DetectControllerV2.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. import datetime
  2. import json
  3. import time
  4. import boto3
  5. import botocore
  6. import oss2
  7. import redis
  8. from botocore import client
  9. from django.http import JsonResponse
  10. from django.views.generic.base import View
  11. from obs import ObsClient
  12. from Ansjer.config import DETECT_PUSH_DOMAIN, DETECT_PUSH_DOMAINS, DETECT_PUSH_DOMAIN_JIUAN, DETECT_PUSH_DOMAINS_JIUAN, \
  13. OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, LOGGER, ALGORITHM_COMBO_TYPES, \
  14. HUAWEICLOUD_AK, HUAWEICLOUD_SK, HUAWEICLOUD_OBS_SERVER, HUAWEICLOUD_PUSH_BUKET
  15. from Ansjer.config import PUSH_BUCKET, CONFIG_INFO, CONFIG_CN, CONFIG_EUR, CONFIG_US
  16. from Ansjer.config import PUSH_REDIS_ADDRESS
  17. from Model.models import Device_Info, Equipment_Info, UidSetModel, UidPushModel, CompanyModel, SysMsgModel, \
  18. AiService, VodBucketModel
  19. from Object.ETkObject import ETkObject
  20. from Object.OCIObjectStorage import OCIObjectStorage
  21. from Object.RedisObject import RedisObject
  22. from Object.ResponseObject import ResponseObject
  23. from Object.TokenObject import TokenObject
  24. from Object.utils import LocalDateTimeUtil
  25. from Service.CommonService import CommonService
  26. from Service.EquipmentInfoService import EquipmentInfoService
  27. from Service.VodHlsService import SplitVodHlsObject
  28. class DetectControllerViewV2(View):
  29. def get(self, request, *args, **kwargs):
  30. request.encoding = 'utf-8'
  31. operation = kwargs.get('operation')
  32. api_version = kwargs.get('apiVersion')
  33. # self.ip = CommonService.get_ip_address(request)
  34. return self.validation(request, request.GET, operation, api_version)
  35. def post(self, request, *args, **kwargs):
  36. request.encoding = 'utf-8'
  37. operation = kwargs.get('operation')
  38. api_version = kwargs.get('apiVersion')
  39. # self.ip = CommonService.get_ip_address(request)
  40. return self.validation(request, request.POST, operation, api_version)
  41. def validation(self, request, request_dict, operation, api_version):
  42. response = ResponseObject()
  43. if operation is None:
  44. return response.json(444, 'error path')
  45. token = request_dict.get('token', None)
  46. lang = request_dict.get('lang', None)
  47. if lang:
  48. response = ResponseObject(lang)
  49. tko = TokenObject(token)
  50. if tko.code == 0:
  51. userID = tko.userID
  52. # 修改推送设置
  53. if operation == 'changeStatus':
  54. return self.do_change_status(userID, request_dict, response)
  55. # 查询推送信息
  56. elif operation == 'queryInfo':
  57. return self.do_query(request_dict, response, userID)
  58. # 点击推送信息跳转到列表信息
  59. elif operation == 'transferInfo':
  60. return self.do_transfer(request_dict, response, userID)
  61. # 更新推送延迟
  62. elif operation == 'updateInterval':
  63. return self.do_update_interval(userID, request_dict, response)
  64. # 消息提醒配置
  65. elif operation == 'messageNotificationSet':
  66. return self.message_notification_set(api_version, request_dict, response)
  67. else:
  68. return response.json(414)
  69. else:
  70. return response.json(tko.code)
  71. @classmethod
  72. def message_notification_set(cls, api_version, request_dict, response):
  73. """
  74. 消息提醒设置
  75. @param api_version: 版本号
  76. @param request_dict: 参数json格式
  77. @param response: 响应数据
  78. """
  79. try:
  80. msg_data = request_dict.get('msgData', None)
  81. uid = request_dict.get('uid', None)
  82. channel = int(request_dict.get('channel', 0))
  83. is_nvr = int(request_dict.get('isNVR', 0))
  84. event_types = request_dict.get('eventTypes', None)
  85. LOGGER.info('*****DetectControllerViewV2.message_notification_set*****api_version:{},uid:{}'
  86. .format(api_version, uid))
  87. if not all([msg_data, uid]):
  88. return response.json(444)
  89. data = json.loads(msg_data)
  90. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  91. if not uid_set_qs.exists():
  92. return response.json(173)
  93. data = cls.update_nvr_app_msg(channel, is_nvr, uid_set_qs[0].msg_notify, data, event_types)
  94. uid_set_qs.update(msg_notify=data, updTime=int(time.time()))
  95. return response.json(0)
  96. except Exception as e:
  97. LOGGER.error('*****DetectControllerViewV2.message_notification_set:errLine:{}, errMsg:{}'
  98. .format(e.__traceback__.tb_lineno, repr(e)))
  99. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  100. @classmethod
  101. def update_nvr_app_msg(cls, channel, is_nvr, msg_notify, data, event_types):
  102. try:
  103. # 检查是否是 NVR 且通道大于 0
  104. if is_nvr == 1 and channel > 0:
  105. # 构建目标键,例如 'channel1' 或 'channel2'
  106. target_key = f'channel{channel}'
  107. # 使用条件表达式构建 new_data
  108. new_data = {target_key: list(map(int, event_types.split(','))) if event_types else []}
  109. # 获取 nvr 列表并准备标志
  110. nvr_list = msg_notify.get('nvr', [])
  111. # 尝试在 nvr 列表中找到匹配的通道
  112. for item in nvr_list:
  113. if target_key in item:
  114. item[target_key] = new_data[target_key]
  115. return msg_notify # 找到匹配后直接返回
  116. # 如果没有找到匹配,添加 new_data
  117. nvr_list.append(new_data)
  118. msg_notify['nvr'] = nvr_list
  119. return msg_notify
  120. elif is_nvr == 0:
  121. # 检查 data 中是否存在 nvr 键,如果存在则删除
  122. if 'nvr' in data:
  123. del data['nvr'] # 删除 nvr 键
  124. return data # 返回更新后的 data
  125. except Exception as e:
  126. # 记录异常信息
  127. LOGGER.error('修改消息提醒params: {}: errLine: {}, errMsg: {}'.format(
  128. data, e.__traceback__.tb_lineno, repr(e)))
  129. return data
  130. def do_change_status(self, userID, request_dict, response):
  131. token_val = request_dict.get('token_val', None)
  132. jg_token_val = request_dict.get('jg_token_val', '')
  133. appBundleId = request_dict.get('appBundleId', None)
  134. app_type = request_dict.get('app_type', None)
  135. push_type = request_dict.get('push_type', None)
  136. status = request_dict.get('status', None)
  137. m_code = request_dict.get('m_code', None)
  138. uid = request_dict.get('uid', None)
  139. lang = request_dict.get('lang', 'en')
  140. tz = request_dict.get('tz', '0')
  141. company_secrete = request_dict.get('company_secrete', None)
  142. region = request_dict.get('region', None) # app必须传:1:国外,2:国内
  143. electricity_status = request_dict.get('electricity_status', None)
  144. domain_name = request_dict.get('domain_name', None)
  145. is_nvr = int(request_dict.get('isNVR', 0))
  146. if not region:
  147. return response.json(444, 'region')
  148. region = int(region)
  149. # 消息提醒功能新增
  150. # 如果传空上来,就默认为0
  151. if tz == '':
  152. tz = 0
  153. else:
  154. tz = tz.replace("GMT", "")
  155. detect_group = request_dict.get('detect_group', None)
  156. interval = request_dict.get('interval', None)
  157. if not status and not electricity_status:
  158. return response.json(444, 'status and electricity_status')
  159. if not company_secrete:
  160. return response.json(444, 'company_secrete')
  161. company = CompanyModel.objects.filter(secret=company_secrete)
  162. if not company.exists():
  163. return response.json(444, 'company_secrete')
  164. # 关闭推送
  165. if not all([appBundleId, app_type, token_val, uid, m_code]):
  166. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  167. try:
  168. # 判断用户是否拥有设备
  169. device_info_qs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  170. if not device_info_qs.exists():
  171. device_info_qs = Device_Info.objects.filter(userID_id=userID, serial_number=uid)
  172. if not device_info_qs.exists():
  173. return response.json(14)
  174. # 更新或创建uid_set数据
  175. nowTime = int(time.time())
  176. uid_set_data = {
  177. 'device_type': device_info_qs[0].Type
  178. }
  179. # 设置开关状态,0:关闭,1:开启
  180. if status:
  181. status = int(status)
  182. uid_set_data['detect_status'] = status
  183. device_info_qs.update(NotificationMode=status)
  184. # 检测类型
  185. if detect_group:
  186. uid_set_data['detect_group'] = detect_group
  187. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  188. # 设置消息推送间隔
  189. if interval:
  190. interval = int(interval)
  191. if uid_set_qs.exists() and status == 1 and uid_set_qs.first().detect_status == 0:
  192. interval = 60
  193. uid_set_data['detect_interval'] = interval
  194. # 开通了ai服务的设备,通过mqtt通知设备修改消息推送间隔
  195. ai_service_qs = AiService.objects.filter(uid=uid, use_status=1, endTime__gte=nowTime)
  196. if ai_service_qs.exists():
  197. topic_name = 'ansjer/generic/{}'.format(uid)
  198. msg = {
  199. 'commandType': 'AIState',
  200. 'payload': {
  201. 'IntervalTime': interval
  202. }
  203. }
  204. CommonService.req_publish_mqtt_msg(uid, topic_name, msg)
  205. if uid_set_qs.exists():
  206. msg_data = uid_set_qs.first().msg_notify
  207. if status == 0 and msg_data:
  208. msg_data['appPush'] = -1
  209. uid_set_data['msg_notify'] = msg_data
  210. elif status == 1 and uid_set_qs.first().detect_status == 0:
  211. uid_set_data['detect_interval'] = 60
  212. types = ALGORITHM_COMBO_TYPES
  213. device_type = device_info_qs[0].Type
  214. ai_type = uid_set_qs.first().ai_type
  215. # IPC默认关闭移动侦测APP通知
  216. if ai_type > 0 and device_type and device_type not in [1, 2, 3, 4, 10001]:
  217. types = [x for x in types if x != 51]
  218. msg_data = {'appPush': 1,
  219. 'pushTime': {'allDay': 1, 'repeat': 127, 'endTime': 0, 'timeZone': '+08.00',
  220. 'startTime': 0},
  221. 'eventTypes': {'device': types, 'aiCloud': 1}
  222. }
  223. if is_nvr == 1: # 检查NVR版本是否存在
  224. # 确定通道数量,如果channel大于0则使用其值,否则默认使用4
  225. channel_count = uid_set_qs[0].channel if uid_set_qs[0].channel > 0 else 4
  226. # 生成通道的列表,每个频道对应一个字典,格式为 "channelX": [types]
  227. channel_list = [{f'channel{index + 1}': ALGORITHM_COMBO_TYPES} for index in range(channel_count)]
  228. # 将NVR字典赋值给msg_data中的'nvr'键
  229. msg_data['nvr'] = channel_list
  230. msg_data['eventTypes']['device'] = [] # 将IPC允许推送类型设为空
  231. uid_set_data['msg_notify'] = msg_data
  232. uid_set_id = uid_set_qs[0].id
  233. uid_set_data['updTime'] = nowTime
  234. uid_set_qs.update(**uid_set_data)
  235. else:
  236. uid_set_data['uid'] = uid
  237. uid_set_data['addTime'] = nowTime
  238. uid_set_data['updTime'] = nowTime
  239. uid_set_qs = UidSetModel.objects.create(**uid_set_data)
  240. uid_set_id = uid_set_qs.id
  241. # 初始化UidPushModel推送表
  242. if electricity_status:
  243. if m_code != 0 and m_code != '0':
  244. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  245. if uid_push_qs.exists():
  246. uid_push_update_dict = {
  247. 'appBundleId': appBundleId,
  248. 'app_type': app_type,
  249. 'push_type': push_type,
  250. 'token_val': token_val,
  251. 'jg_token_val': jg_token_val,
  252. 'updTime': nowTime,
  253. 'lang': lang,
  254. 'tz': tz
  255. }
  256. uid_push_qs.update(**uid_push_update_dict)
  257. else:
  258. uid_push_create_dict = {
  259. 'uid_set_id': uid_set_id,
  260. 'userID_id': userID,
  261. 'appBundleId': appBundleId,
  262. 'app_type': app_type,
  263. 'push_type': push_type,
  264. 'token_val': token_val,
  265. 'jg_token_val': jg_token_val,
  266. 'm_code': m_code,
  267. 'addTime': nowTime,
  268. 'updTime': nowTime,
  269. 'lang': lang,
  270. 'tz': tz
  271. }
  272. # 绑定设备推送
  273. UidPushModel.objects.create(**uid_push_create_dict)
  274. return response.json(0)
  275. if status == 0:
  276. # 状态为0的时候删除redis缓存数据
  277. self.do_delete_redis(uid)
  278. return response.json(0)
  279. elif status == 1:
  280. if m_code != 0 and m_code != '0':
  281. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  282. if uid_push_qs.exists():
  283. uid_push_update_dict = {
  284. 'appBundleId': appBundleId,
  285. 'app_type': app_type,
  286. 'push_type': push_type,
  287. 'token_val': token_val,
  288. 'jg_token_val': jg_token_val,
  289. 'updTime': nowTime,
  290. 'lang': lang,
  291. 'tz': tz
  292. }
  293. uid_push_qs.update(**uid_push_update_dict)
  294. else:
  295. uid_push_create_dict = {
  296. 'uid_set_id': uid_set_id,
  297. 'userID_id': userID,
  298. 'appBundleId': appBundleId,
  299. 'app_type': app_type,
  300. 'push_type': push_type,
  301. 'token_val': token_val,
  302. 'jg_token_val': jg_token_val,
  303. 'm_code': m_code,
  304. 'addTime': nowTime,
  305. 'updTime': nowTime,
  306. 'lang': lang,
  307. 'tz': tz
  308. }
  309. # 绑定设备推送
  310. UidPushModel.objects.create(**uid_push_create_dict)
  311. if interval:
  312. self.do_delete_redis(uid, interval)
  313. else:
  314. self.do_delete_redis(uid)
  315. etkObj = ETkObject(etk='')
  316. etk = etkObj.encrypt(uid)
  317. if company_secrete == 'MTEyMTNB':
  318. d_type = device_info_qs[0].Type
  319. url = DETECT_PUSH_DOMAIN
  320. if d_type in [103, 26]:
  321. url = DETECT_PUSH_DOMAINS
  322. urls = DETECT_PUSH_DOMAINS
  323. else:
  324. url = DETECT_PUSH_DOMAIN_JIUAN
  325. urls = DETECT_PUSH_DOMAINS_JIUAN
  326. if domain_name in ['api.zositeche.com', 'api.loocam3.com', 'common.neutral3.com']:
  327. url = 'http://push.zositeche.com/'
  328. urls = 'https://push.zositeche.com/'
  329. detectUrl = "{DETECT_PUSH_DOMAIN}notifyV2/push?etk={etk}&company_secrete={company_secrete}&region={region}". \
  330. format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN=url, region=region)
  331. detectUrls = "{DETECT_PUSH_DOMAIN_V2}notifyV2/push?etk={etk}&company_secrete={company_secrete}&region={region}". \
  332. format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN_V2=urls, region=region)
  333. return response.json(0, {'detectUrl': detectUrl, 'detectUrls': detectUrls})
  334. else:
  335. return response.json(173)
  336. except Exception as e:
  337. LOGGER.info('消息推送设置error,uid:{},line:{},msg:{}'.format(uid, e.__traceback__.tb_lineno, repr(e)))
  338. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  339. def do_delete_redis(self, uid, detect_interval=0):
  340. keyPattern = '{uid}*'.format(uid=uid)
  341. redisObj = RedisObject(host=PUSH_REDIS_ADDRESS)
  342. keys = redisObj.get_keys(keyPattern)
  343. if keys:
  344. for key in keys:
  345. key = key.decode()
  346. if detect_interval == 0:
  347. redisObj.del_data(key=key)
  348. elif key.find('plt') != -1:
  349. continue
  350. elif key.find('flag') != -1:
  351. redisObj.set_data(key=key, val=1, expire=detect_interval)
  352. else:
  353. redisObj.del_data(key=key)
  354. def do_query(self, request_dict, response, userID):
  355. page = int(request_dict.get('page', None))
  356. line = int(request_dict.get('line', None))
  357. start_time = request_dict.get('startTime', None)
  358. end_time = request_dict.get('endTime', None)
  359. event_type = request_dict.get('eventType', None)
  360. region = int(request_dict.get('region', None))
  361. uids = request_dict.get('uids', None)
  362. channel = request_dict.get('channel', None)
  363. try:
  364. uid_list = []
  365. if uids:
  366. uid_list = uids.split(',')
  367. if not start_time and not end_time:
  368. # 默认查询近七天内数据
  369. end_time = int(time.time())
  370. start_time = LocalDateTimeUtil.get_before_days_timestamp(end_time, 7)
  371. equipment_info_qs, count = EquipmentInfoService. \
  372. union_equipment_info(userID, uid_list, event_type, start_time, end_time, page, line, channel=channel)
  373. # 查询设备类型,昵称
  374. if uid_list:
  375. dvqs = Device_Info.objects.filter(UID__in=uid_list, userID_id=userID).values('UID', 'Type', 'NickName')
  376. uid_type_dict = {}
  377. for dv in dvqs:
  378. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  379. else:
  380. dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
  381. uid_type_dict = {}
  382. for dv in dvqs:
  383. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  384. # 没有推送数据返回空列表
  385. if count == 0:
  386. return response.json(0, {'datas': [], 'count': 0})
  387. res = []
  388. # 华为云
  389. obs_client = ObsClient(
  390. access_key_id=HUAWEICLOUD_AK, secret_access_key=HUAWEICLOUD_SK, server=HUAWEICLOUD_OBS_SERVER)
  391. # 阿里云
  392. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  393. oss_img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  394. # aws
  395. aws_s3 = boto3.client(
  396. 's3',
  397. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  398. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  399. config=botocore.client.Config(signature_version='s3v4'),
  400. region_name='us-east-1'
  401. )
  402. aws_s3_cn = boto3.client(
  403. 's3',
  404. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  405. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  406. config=botocore.client.Config(signature_version='s3v4'),
  407. region_name='cn-northwest-1'
  408. )
  409. # oci
  410. # 国内生产环境默认不实例OCI对象
  411. oci = self.get_oci_client()
  412. redis_obj = RedisObject(3)
  413. # ai消息标识所有组合标签
  414. ai_all_event_type = EquipmentInfoService.get_all_comb_event_type()
  415. for equipment_info in equipment_info_qs:
  416. uid = equipment_info['devUid']
  417. event_time = equipment_info['eventTime']
  418. channel = equipment_info['Channel']
  419. storage_location = equipment_info['storage_location']
  420. border_coords = equipment_info['borderCoords']
  421. event_type = equipment_info['eventType']
  422. event_tag = equipment_info['eventTag']
  423. if equipment_info['is_st'] == 1:
  424. thumbspng = '{}/{}/{}.jpeg'.format(uid, channel, event_time)
  425. if storage_location == 1: # 阿里云oss
  426. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  427. elif storage_location == 5: # 华为云
  428. create_res = obs_client.createSignedUrl(
  429. method='GET', bucketName=HUAWEICLOUD_PUSH_BUKET, objectKey=thumbspng, expires=300)
  430. img_url = create_res.signedUrl
  431. elif storage_location in [3, 4]:
  432. prefix_name = f'{uid}/'
  433. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  434. if img_url:
  435. img_url = img_url + thumbspng
  436. else:
  437. params = {'Key': thumbspng}
  438. if region == 1: # AWS国外
  439. params['Bucket'] = 'foreignpush'
  440. img_url = aws_s3.generate_presigned_url(
  441. 'get_object', Params=params, ExpiresIn=300)
  442. else: # AWS国内
  443. params['Bucket'] = 'push'
  444. img_url = aws_s3_cn.generate_presigned_url(
  445. 'get_object', Params=params, ExpiresIn=300)
  446. equipment_info['img'] = img_url
  447. equipment_info['img_list'] = [img_url]
  448. elif equipment_info['is_st'] == 2:
  449. # 列表装载回放时间戳标记
  450. split_vod_hls_obj = SplitVodHlsObject()
  451. vodqs = split_vod_hls_obj.get_vod_hls_data(
  452. uid=uid, channel=channel, start_time=int(event_time)).values('bucket_id')
  453. if not vodqs.exists():
  454. return response.json(173)
  455. vod_bucket_qs = VodBucketModel.objects.filter(id=vodqs[0]['bucket_id']).values('bucket', 'endpoint')
  456. if not vod_bucket_qs.exists():
  457. return response.json(173)
  458. bucket_name = vod_bucket_qs[0]['bucket']
  459. endpoint = vod_bucket_qs[0]['endpoint']
  460. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  461. ts = '{}/vod{}/{}/ts0.ts'.format(uid, channel, event_time)
  462. if storage_location == 1: # 阿里云oss
  463. thumb0 = bucket.sign_url('GET', ts, 3600,
  464. params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  465. thumb1 = bucket.sign_url('GET', ts, 3600,
  466. params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  467. thumb2 = bucket.sign_url('GET', ts, 3600,
  468. params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  469. equipment_info['img_list'] = [thumb0, thumb1, thumb2]
  470. else:
  471. params = {'Key': ts}
  472. if region == 1: # AWS国外
  473. params['Bucket'] = 'foreignpush'
  474. img_url = aws_s3.generate_presigned_url(
  475. 'get_object', Params=params, ExpiresIn=300)
  476. else: # AWS国内
  477. params['Bucket'] = 'push'
  478. img_url = aws_s3_cn.generate_presigned_url(
  479. 'get_object', Params=params, ExpiresIn=300)
  480. equipment_info['img_list'] = [img_url]
  481. elif equipment_info['is_st'] == 3 or equipment_info['is_st'] == 4:
  482. # 列表装载回放时间戳标记
  483. equipment_info['img_list'] = []
  484. for i in range(equipment_info['is_st']):
  485. thumbspng = '{}/{}/{}_{}.jpeg'.format(uid, channel, event_time, i)
  486. if storage_location == 1: # 阿里云oss
  487. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  488. elif storage_location == 5: # 华为云
  489. create_res = obs_client.createSignedUrl(
  490. method='GET', bucketName=HUAWEICLOUD_PUSH_BUKET, objectKey=thumbspng, expires=300)
  491. img_url = create_res.signedUrl
  492. elif storage_location in [3, 4]: # 国外OCI云
  493. prefix_name = f'{uid}/'
  494. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  495. if img_url:
  496. img_url = img_url + thumbspng
  497. else:
  498. params = {'Key': thumbspng}
  499. if region == 1: # 国外AWS
  500. params['Bucket'] = 'foreignpush'
  501. img_url = aws_s3.generate_presigned_url(
  502. 'get_object', Params=params, ExpiresIn=300)
  503. else: # 国内AWS
  504. params['Bucket'] = 'push'
  505. img_url = aws_s3_cn.generate_presigned_url(
  506. 'get_object', Params=params, ExpiresIn=300)
  507. equipment_info['img_list'].append(img_url)
  508. if uid in uid_type_dict.keys():
  509. equipment_info['uid_type'] = uid_type_dict[uid]['type']
  510. equipment_info['devNickName'] = uid_type_dict[uid]['NickName']
  511. else:
  512. equipment_info['uid_type'] = ''
  513. equipment_info['borderCoords'] = '' if border_coords == '' else eval(border_coords) # ai消息坐标信息
  514. equipment_info['ai_event_type_list'] = []
  515. # 如果是ai消息类型,则分解eventType, 如:123 -> [1,2,3]
  516. if border_coords and event_type in ai_all_event_type:
  517. equipment_info['ai_event_type_list'] = list(map(int, str(event_type)))
  518. if EquipmentInfoService.is_combo_tag(event_type, event_tag):
  519. equipment_info['ai_event_type_list'] += EquipmentInfoService.get_combo_types(event_type, event_tag)
  520. equipment_info['alarm'] = 'Motion \tChannel:{channel}'.format(channel=channel)
  521. res.append(equipment_info)
  522. return response.json(0, {'datas': res, 'count': count})
  523. except Exception as e:
  524. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  525. @staticmethod
  526. def get_oci_client():
  527. """
  528. 获取所在区域客户端
  529. @return:
  530. """
  531. if CONFIG_INFO == CONFIG_CN:
  532. return None
  533. oci = OCIObjectStorage(CONFIG_EUR) if CONFIG_INFO == CONFIG_EUR else OCIObjectStorage(CONFIG_US)
  534. return oci
  535. @staticmethod
  536. def oci_object_url(oci, redis_obj, uid, obj_name):
  537. """
  538. 获取OCI对象存储URL 有效期5分钟
  539. @param uid: 设备UID
  540. @param redis_obj: 缓存客户端
  541. @param oci: oci客户端
  542. @param obj_name: 对象名称或前缀
  543. @return: url
  544. """
  545. try:
  546. if not oci:
  547. return ''
  548. uid_key = f'PUSH:MSG:OCI:URL:{uid}'
  549. oci_url = redis_obj.get_data(uid_key)
  550. if oci_url:
  551. return oci_url
  552. time_expires = datetime.datetime.utcnow() + datetime.timedelta(minutes=60)
  553. result = oci.get_preauthenticated_request_url(PUSH_BUCKET, 'ociPush', obj_name, time_expires,
  554. 'AnyObjectRead') # 授权到指定uid文件夹
  555. full_url = result.full_path if result else ''
  556. redis_obj.set_data(uid_key, full_url, 3580)
  557. return full_url
  558. except Exception as e:
  559. LOGGER.error('oci查询消息列表异常error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  560. return
  561. # redis_obj,is_st,storage_location,uid,channel,event_type,event_time,event_tag)
  562. def get_redis_url(self, **params):
  563. try:
  564. oss_img_bucket = params['oss_img_bucket']
  565. # 国内生产环境默认不实例OCI对象
  566. oci = self.get_oci_client()
  567. # 华为云
  568. obs_client = ObsClient(
  569. access_key_id=HUAWEICLOUD_AK, secret_access_key=HUAWEICLOUD_SK, server=HUAWEICLOUD_OBS_SERVER)
  570. uid = params['uid']
  571. is_st = params['is_st']
  572. storage_location = params['storage_location']
  573. region = params['region']
  574. aws_s3 = params['aws_s3']
  575. aws_s3_cn = params['aws_s3_cn']
  576. redis_obj = params['redis_obj']
  577. channel = params['channel']
  578. event_time = params['event_time']
  579. event_type = int(params['event_type'])
  580. event_tag = params['event_tag']
  581. img_list = []
  582. img_url = ''
  583. if is_st == 1:
  584. thumbspng = '{}/{}/{}.jpeg'.format(uid, channel, event_time)
  585. if storage_location == 1: # 阿里云oss
  586. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  587. elif storage_location == 5: # 华为云
  588. create_res = obs_client.createSignedUrl(
  589. method='GET', bucketName=HUAWEICLOUD_PUSH_BUKET, objectKey=thumbspng, expires=300)
  590. img_url = create_res.signedUrl
  591. elif storage_location in [3, 4]:
  592. prefix_name = f'{uid}/'
  593. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  594. if img_url:
  595. img_url = img_url + thumbspng
  596. else:
  597. params = {'Key': thumbspng}
  598. if region == 1: # AWS国外
  599. params['Bucket'] = 'foreignpush'
  600. img_url = aws_s3.generate_presigned_url(
  601. 'get_object', Params=params, ExpiresIn=300)
  602. else: # AWS国内
  603. params['Bucket'] = 'push'
  604. img_url = aws_s3_cn.generate_presigned_url(
  605. 'get_object', Params=params, ExpiresIn=300)
  606. img_list = [img_url]
  607. elif is_st == 3 or is_st == 4:
  608. # 列表装载回放时间戳标记
  609. img_list = []
  610. for i in range(is_st):
  611. thumbspng = '{}/{}/{}_{}.jpeg'.format(uid, channel, event_time, i)
  612. if storage_location == 1: # 阿里云oss
  613. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  614. elif storage_location == 5: # 华为云
  615. create_res = obs_client.createSignedUrl(
  616. method='GET', bucketName=HUAWEICLOUD_PUSH_BUKET, objectKey=thumbspng, expires=300)
  617. img_url = create_res.signedUrl
  618. elif storage_location in [3, 4]:
  619. prefix_name = f'{uid}/'
  620. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  621. if img_url:
  622. img_url = img_url + thumbspng
  623. else:
  624. params = {'Key': thumbspng}
  625. if region == 1: # 国外AWS
  626. params['Bucket'] = 'foreignpush'
  627. img_url = aws_s3.generate_presigned_url(
  628. 'get_object', Params=params, ExpiresIn=300)
  629. else: # 国内AWS
  630. params['Bucket'] = 'push'
  631. img_url = aws_s3_cn.generate_presigned_url(
  632. 'get_object', Params=params, ExpiresIn=300)
  633. img_list.append(img_url)
  634. ai_event_type_list = EquipmentInfoService.get_combo_types(event_type, event_tag)
  635. msg_data = {
  636. "id": "",
  637. "status": False,
  638. "answer_status": False,
  639. "alarm": "",
  640. "is_st": is_st,
  641. "storage_location": storage_location,
  642. "devUid": uid,
  643. "devNickName": "",
  644. "Channel": channel,
  645. "eventType": event_type,
  646. "eventTime": event_time,
  647. "receiveTime": 0,
  648. "addTime": 0,
  649. "borderCoords": "",
  650. "eventTag": event_tag,
  651. "img": img_url,
  652. "img_list": img_list,
  653. "uid_type": 0,
  654. "ai_event_type_list": ai_event_type_list
  655. }
  656. datas = [msg_data]
  657. return datas
  658. except Exception as e:
  659. LOGGER.error('消息跳转异常:, errLine:{}, errMsg:{}'
  660. .format(e.__traceback__.tb_lineno, repr(e)))
  661. return []
  662. def do_transfer(self, request_dict, response, userID):
  663. event_time = request_dict.get('eventTime', None)
  664. event_type = request_dict.get('eventType', None)
  665. region = int(request_dict.get('region', None))
  666. channel = int(request_dict.get('channel', 1))
  667. uid = request_dict.get('uid', None)
  668. if not all([event_time, region, uid]):
  669. return response.json(444)
  670. try:
  671. msg_key = 'PUSH:MSG:IMAGE:{}:{}:{}'.format(uid, channel, event_time)
  672. redis_client = redis.Redis(connection_pool=redis.ConnectionPool(host=PUSH_REDIS_ADDRESS, port=6379, db=3))
  673. msg_data = redis_client.get(msg_key)
  674. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  675. oss_img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  676. aws_s3 = boto3.client(
  677. 's3',
  678. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  679. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  680. config=botocore.client.Config(signature_version='s3v4'),
  681. region_name='us-east-1'
  682. )
  683. aws_s3_cn = boto3.client(
  684. 's3',
  685. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  686. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  687. config=botocore.client.Config(signature_version='s3v4'),
  688. region_name='cn-northwest-1'
  689. )
  690. # 国内生产环境默认不实例OCI对象
  691. oci = self.get_oci_client()
  692. # 华为云
  693. obs_client = ObsClient(
  694. access_key_id=HUAWEICLOUD_AK, secret_access_key=HUAWEICLOUD_SK, server=HUAWEICLOUD_OBS_SERVER)
  695. redis_obj = RedisObject(3)
  696. if msg_data:
  697. msg_dict = json.loads(msg_data)
  698. LOGGER.info(f'缓存数据:{msg_dict}')
  699. params = {'redis_obj': redis_obj, 'is_st': msg_dict['is_st'], 'region': region, 'aws_s3': aws_s3,
  700. 'storage_location': msg_dict['storage_location'], 'aws_s3_cn': aws_s3_cn,
  701. 'uid': uid, 'channel': channel, 'event_type': event_type, 'oss_img_bucket': oss_img_bucket,
  702. 'event_time': event_time, 'event_tag': msg_dict['event_tag']}
  703. res = self.get_redis_url(**params)
  704. return response.json(0, {'datas': res, 'count': 1})
  705. kwargs = {'device_user_id': userID, 'device_uid': uid, 'event_time': event_time, 'event_type': event_type}
  706. equipment_info_qs, count = EquipmentInfoService.get_equipment_info(**kwargs)
  707. # 查询设备类型,昵称
  708. dvqs = Device_Info.objects.filter(UID=uid, userID_id=userID).values('UID', 'Type', 'NickName')
  709. uid_type_dict = {}
  710. for dv in dvqs:
  711. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  712. # 没有推送数据返回空列表
  713. if count == 0:
  714. return response.json(0, {'datas': [], 'count': 0})
  715. res = []
  716. # ai消息标识所有组合标签
  717. ai_all_event_type = EquipmentInfoService.get_all_comb_event_type()
  718. for equipment_info in equipment_info_qs:
  719. uid = equipment_info['devUid']
  720. event_time = equipment_info['eventTime']
  721. channel = equipment_info['Channel']
  722. storage_location = equipment_info['storage_location']
  723. border_coords = equipment_info['borderCoords']
  724. event_type = equipment_info['eventType']
  725. event_tag = equipment_info['eventTag']
  726. if equipment_info['is_st'] == 1:
  727. thumbspng = '{}/{}/{}.jpeg'.format(uid, channel, event_time)
  728. if storage_location == 1: # 阿里云oss
  729. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  730. elif storage_location == 5: # 华为云
  731. create_res = obs_client.createSignedUrl(
  732. method='GET', bucketName=HUAWEICLOUD_PUSH_BUKET, objectKey=thumbspng, expires=300)
  733. img_url = create_res.signedUrl
  734. elif storage_location in [3, 4]:
  735. prefix_name = f'{uid}/'
  736. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  737. if img_url:
  738. img_url = img_url + thumbspng
  739. else:
  740. params = {'Key': thumbspng}
  741. if region == 1: # AWS国外
  742. params['Bucket'] = 'foreignpush'
  743. img_url = aws_s3.generate_presigned_url(
  744. 'get_object', Params=params, ExpiresIn=300)
  745. else: # AWS国内
  746. params['Bucket'] = 'push'
  747. img_url = aws_s3_cn.generate_presigned_url(
  748. 'get_object', Params=params, ExpiresIn=300)
  749. equipment_info['img'] = img_url
  750. equipment_info['img_list'] = [img_url]
  751. elif equipment_info['is_st'] == 2:
  752. # 列表装载回放时间戳标记
  753. split_vod_hls_obj = SplitVodHlsObject()
  754. vodqs = split_vod_hls_obj.get_vod_hls_data(
  755. uid=uid, channel=channel, start_time=int(event_time)).values('bucket_id')
  756. if not vodqs.exists():
  757. return response.json(173)
  758. vod_bucket_qs = VodBucketModel.objects.filter(id=vodqs[0]['bucket_id']).values('bucket', 'endpoint')
  759. if not vod_bucket_qs.exists():
  760. return response.json(173)
  761. bucket_name = vod_bucket_qs[0]['bucket']
  762. endpoint = vod_bucket_qs[0]['endpoint']
  763. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  764. ts = '{}/vod{}/{}/ts0.ts'.format(uid, channel, event_time)
  765. if storage_location == 1: # 阿里云oss
  766. thumb0 = bucket.sign_url('GET', ts, 3600,
  767. params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  768. thumb1 = bucket.sign_url('GET', ts, 3600,
  769. params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  770. thumb2 = bucket.sign_url('GET', ts, 3600,
  771. params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  772. equipment_info['img_list'] = [thumb0, thumb1, thumb2]
  773. else:
  774. params = {'Key': ts}
  775. if region == 1: # AWS国外
  776. params['Bucket'] = 'foreignpush'
  777. img_url = aws_s3.generate_presigned_url(
  778. 'get_object', Params=params, ExpiresIn=300)
  779. else: # AWS国内
  780. params['Bucket'] = 'push'
  781. img_url = aws_s3_cn.generate_presigned_url(
  782. 'get_object', Params=params, ExpiresIn=300)
  783. equipment_info['img_list'] = [img_url]
  784. elif equipment_info['is_st'] == 3 or equipment_info['is_st'] == 4:
  785. # 列表装载回放时间戳标记
  786. equipment_info['img_list'] = []
  787. for i in range(equipment_info['is_st']):
  788. thumbspng = '{}/{}/{}_{}.jpeg'.format(uid, channel, event_time, i)
  789. if storage_location == 1: # 阿里云oss
  790. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  791. elif storage_location == 5: # 华为云
  792. create_res = obs_client.createSignedUrl(
  793. method='GET', bucketName=HUAWEICLOUD_PUSH_BUKET, objectKey=thumbspng, expires=300)
  794. img_url = create_res.signedUrl
  795. elif storage_location in [3, 4]:
  796. prefix_name = f'{uid}/'
  797. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  798. if img_url:
  799. img_url = img_url + thumbspng
  800. else:
  801. params = {'Key': thumbspng}
  802. if region == 1: # 国外AWS
  803. params['Bucket'] = 'foreignpush'
  804. img_url = aws_s3.generate_presigned_url(
  805. 'get_object', Params=params, ExpiresIn=300)
  806. else: # 国内AWS
  807. params['Bucket'] = 'push'
  808. img_url = aws_s3_cn.generate_presigned_url(
  809. 'get_object', Params=params, ExpiresIn=300)
  810. equipment_info['img_list'].append(img_url)
  811. if uid in uid_type_dict.keys():
  812. equipment_info['uid_type'] = uid_type_dict[uid]['type']
  813. equipment_info['devNickName'] = uid_type_dict[uid]['NickName']
  814. else:
  815. equipment_info['uid_type'] = ''
  816. equipment_info['borderCoords'] = '' if border_coords == '' else eval(border_coords) # ai消息坐标信息
  817. equipment_info['ai_event_type_list'] = []
  818. # 如果是ai消息类型,则分解eventType, 如:123 -> [1,2,3]
  819. if border_coords and event_type in ai_all_event_type:
  820. equipment_info['ai_event_type_list'] = list(map(int, str(event_type)))
  821. if EquipmentInfoService.is_combo_tag(event_type, event_tag):
  822. equipment_info['ai_event_type_list'] += EquipmentInfoService.get_combo_types(event_type, event_tag)
  823. res.append(equipment_info)
  824. return response.json(0, {'datas': res, 'count': count})
  825. except Exception as e:
  826. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  827. def do_update_interval(self, userID, request_dict, response):
  828. uid = request_dict.get('uid', None)
  829. interval = request_dict.get('interval', None)
  830. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  831. if dvqs.exists():
  832. uid_set_qs = UidSetModel.objects. \
  833. filter(uid=uid, uidpushmodel__userID_id=userID)
  834. if uid_set_qs.exists():
  835. uid_set_qs.update(detect_interval=int(interval))
  836. else:
  837. return response.json(173)
  838. else:
  839. return response.json(0)
  840. # 这个接口没有调用过,不敢动
  841. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  842. # 移动侦测接口
  843. class PushNotificationView(View):
  844. def get(self, request, *args, **kwargs):
  845. request.encoding = 'utf-8'
  846. # operation = kwargs.get('operation')
  847. return self.validation(request.GET)
  848. def post(self, request, *args, **kwargs):
  849. request.encoding = 'utf-8'
  850. # operation = kwargs.get('operation')
  851. return self.validation(request.POST)
  852. def validation(self, request_dict):
  853. etk = request_dict.get('etk', None)
  854. channel = request_dict.get('channel', '1')
  855. n_time = request_dict.get('n_time', None)
  856. event_type = request_dict.get('event_type', None)
  857. is_st = request_dict.get('is_st', None)
  858. region = request_dict.get('region', '2')
  859. region = int(region)
  860. eto = ETkObject(etk)
  861. uid = eto.uid
  862. if len(uid) == 20:
  863. redisObj = RedisObject()
  864. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  865. pkey = '{uid}_ptl'.format(uid=uid)
  866. ykey = '{uid}_redis_qs'.format(uid=uid)
  867. if redisObj.get_data(key=pkey):
  868. res_data = {'code': 0, 'msg': 'success,!33333333333'}
  869. return JsonResponse(status=200, data=res_data)
  870. else:
  871. redisObj.set_data(key=pkey, val=1, expire=60)
  872. ##############
  873. redis_data = redisObj.get_data(key=ykey)
  874. if redis_data:
  875. redis_list = eval(redis_data)
  876. else:
  877. # 设置推送时间为60秒一次
  878. redisObj.set_data(key=pkey, val=1, expire=60)
  879. print("从数据库查到数据")
  880. # 从数据库查询出来
  881. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  882. values('token_val', 'app_type', 'appBundleId',
  883. 'push_type', 'userID_id', 'lang', 'm_code',
  884. 'tz', 'uid_set__nickname')
  885. # 新建一个list接收数据
  886. redis_list = []
  887. # 把数据库数据追加进redis_list
  888. for qs in uid_push_qs:
  889. redis_list.append(qs)
  890. # 修改redis数据,并设置过期时间为10分钟
  891. if redis_list:
  892. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  893. # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  894. # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  895. aws_s3_guonei = boto3.client(
  896. 's3',
  897. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  898. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  899. config=botocore.client.Config(signature_version='s3v4'),
  900. region_name='cn-northwest-1'
  901. )
  902. aws_s3_guowai = boto3.client(
  903. 's3',
  904. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  905. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  906. config=botocore.client.Config(signature_version='s3v4'),
  907. region_name='us-east-1'
  908. )
  909. self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
  910. if is_st == '0' or is_st == '2':
  911. return JsonResponse(status=200, data={'code': 0, 'msg': 'success44444444444444444'})
  912. elif is_st == '1':
  913. # Endpoint以杭州为例,其它Region请按实际情况填写。
  914. # obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  915. # 设置此签名URL在60秒内有效。
  916. # url = bucket.sign_url('PUT', obj, 7200)
  917. thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  918. if region == 2: # 2:国内
  919. response_url = aws_s3_guonei.generate_presigned_url(
  920. ClientMethod='put_object',
  921. Params={
  922. 'Bucket': 'push',
  923. 'Key': thumbspng
  924. },
  925. ExpiresIn=3600
  926. )
  927. else: # 1:国外
  928. response_url = aws_s3_guowai.generate_presigned_url(
  929. ClientMethod='put_object',
  930. Params={
  931. 'Bucket': 'foreignpush',
  932. 'Key': thumbspng
  933. },
  934. ExpiresIn=3600
  935. )
  936. # res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  937. # response_url = response_url[:4] + response_url[5:]
  938. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
  939. return JsonResponse(status=200, data=res_data)
  940. elif is_st == '3':
  941. # 人形检测带动图
  942. img_url_list = []
  943. for i in range(int(is_st)):
  944. # obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  945. # format(uid=uid, channel=channel, filename=n_time, st=i)
  946. # 设置此签名URL在60秒内有效。
  947. # url = bucket.sign_url('PUT', obj, 7200)
  948. thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  949. format(uid=uid, channel=channel, filename=n_time, st=i)
  950. if region == 2: # 2:国内
  951. response_url = aws_s3_guonei.generate_presigned_url(
  952. ClientMethod='put_object',
  953. Params={
  954. 'Bucket': 'push',
  955. 'Key': thumbspng
  956. },
  957. ExpiresIn=3600
  958. )
  959. else: # 1:国外
  960. response_url = aws_s3_guowai.generate_presigned_url(
  961. ClientMethod='put_object',
  962. Params={
  963. 'Bucket': 'foreignpush',
  964. 'Key': thumbspng
  965. },
  966. ExpiresIn=3600
  967. )
  968. # response_url = response_url[:4] + response_url[5:]
  969. img_url_list.append(response_url)
  970. # img_url_list.append(url)
  971. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  972. return JsonResponse(status=200, data=res_data)
  973. else:
  974. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  975. else:
  976. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  977. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  978. now_time = int(time.time())
  979. # 设备昵称
  980. userID_ids = []
  981. sys_msg_list = []
  982. is_sys_msg = self.is_sys_msg(int(event_type))
  983. is_st = int(is_st)
  984. eq_list = []
  985. nickname = uaqs[0]['uid_set__nickname']
  986. if not nickname:
  987. nickname = uid
  988. for ua in uaqs:
  989. lang = ua['lang']
  990. tz = ua['tz']
  991. userID_id = ua["userID_id"]
  992. if userID_id not in userID_ids:
  993. eq_list.append(Equipment_Info(
  994. userID_id=userID_id,
  995. eventTime=n_time,
  996. eventType=event_type,
  997. devUid=uid,
  998. devNickName=nickname,
  999. Channel=channel,
  1000. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  1001. is_st=is_st,
  1002. receiveTime=n_time,
  1003. addTime=now_time,
  1004. storage_location=2
  1005. ))
  1006. if is_sys_msg:
  1007. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  1008. event_type=event_type, is_sys=1)
  1009. sys_msg_list.append(SysMsgModel(
  1010. userID_id=userID_id,
  1011. msg=sys_msg_text,
  1012. addTime=now_time,
  1013. updTime=now_time,
  1014. uid=uid,
  1015. eventType=event_type))
  1016. if eq_list:
  1017. print('eq_list')
  1018. Equipment_Info.objects.bulk_create(eq_list)
  1019. if is_sys_msg:
  1020. print('sys_msg')
  1021. SysMsgModel.objects.bulk_create(sys_msg_list)
  1022. return True
  1023. def is_sys_msg(self, event_type):
  1024. event_type_list = [702, 703, 704]
  1025. if event_type in event_type_list:
  1026. return True
  1027. return False
  1028. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  1029. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  1030. etype = int(event_type)
  1031. if lang == 'cn':
  1032. if etype == 704:
  1033. msg_type = '电量过低'
  1034. elif etype == 702:
  1035. msg_type = '摄像头休眠'
  1036. elif etype == 703:
  1037. msg_type = '摄像头唤醒'
  1038. else:
  1039. msg_type = ''
  1040. if is_sys:
  1041. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  1042. else:
  1043. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  1044. else:
  1045. if etype == 704:
  1046. msg_type = 'Low battery'
  1047. elif etype == 702:
  1048. msg_type = 'Camera sleep'
  1049. elif etype == 703:
  1050. msg_type = 'Camera wake'
  1051. else:
  1052. msg_type = ''
  1053. if is_sys:
  1054. send_text = '{msg_type} channel:{channel}'. \
  1055. format(msg_type=msg_type, channel=channel)
  1056. else:
  1057. send_text = '{msg_type} channel:{channel} date:{date}'. \
  1058. format(msg_type=msg_type, channel=channel, date=n_date)
  1059. return send_text