DetectControllerV2.py 56 KB

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