DetectController.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @AUTHOR: ASJRD018
  6. @NAME: AnsjerFormal
  7. @software: PyCharm
  8. @DATE: 2019/1/14 15:57
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: DetectController.py
  12. @Contact: chanjunkai@163.com
  13. """
  14. import logging
  15. import os
  16. import time
  17. import apns2
  18. import jpush as jpush
  19. import oss2
  20. from django.http import JsonResponse
  21. from django.views.generic.base import View
  22. from pyfcm import FCMNotification
  23. from AnsjerPush.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, JPUSH_CONFIG, FCM_CONFIG, \
  24. APNS_CONFIG, BASE_DIR, APNS_MODE
  25. from Model.models import UidPushModel, SysMsgModel
  26. from Object.ETkObject import ETkObject
  27. from Object.RedisObject import RedisObject
  28. from Object.UidTokenObject import UidTokenObject
  29. from Object.utils import LocalDateTimeUtil
  30. from Service.CommonService import CommonService
  31. from Service.EquipmentInfoService import EquipmentInfoService
  32. # 旧移动侦测接口
  33. class NotificationView(View):
  34. def get(self, request, *args, **kwargs):
  35. request.encoding = 'utf-8'
  36. return self.validation(request.GET)
  37. def post(self, request, *args, **kwargs):
  38. request.encoding = 'utf-8'
  39. return self.validation(request.POST)
  40. def validation(self, request_dict):
  41. logger = logging.getLogger('info')
  42. logger.info("旧移动侦测接口参数:{}".format(request_dict))
  43. uidToken = request_dict.get('uidToken', None)
  44. etk = request_dict.get('etk', None)
  45. channel = request_dict.get('channel', '1')
  46. n_time = request_dict.get('n_time', None)
  47. event_type = request_dict.get('event_type', None)
  48. is_st = request_dict.get('is_st', None)
  49. if not all([channel, n_time]):
  50. return JsonResponse(status=200, data={'code': 444, 'msg': 'error channel or n_time'})
  51. if etk:
  52. eto = ETkObject(etk)
  53. uid = eto.uid
  54. if len(uid) != 20:
  55. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  56. else:
  57. utko = UidTokenObject(uidToken)
  58. uid = utko.UID
  59. logger.info("旧移动侦测接口的uid:{}".format(uid))
  60. pkey = '{uid}_{channel}_{event_type}_ptl'.format(uid=uid, event_type=event_type, channel=channel)
  61. ykey = '{uid}_redis_qs'.format(uid=uid)
  62. is_sys_msg = self.is_sys_msg(int(event_type))
  63. if is_sys_msg is True:
  64. dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
  65. else:
  66. dkey = '{uid}_{channel}_flag'.format(uid=uid, channel=channel)
  67. redisObj = RedisObject(db=6)
  68. have_ykey = redisObj.get_data(key=ykey) # uid_set 数据库缓存
  69. have_pkey = redisObj.get_data(key=pkey) # 一分钟限制key
  70. have_dkey = redisObj.get_data(key=dkey) # 推送类型限制
  71. # 一分钟外,推送开启状态
  72. detect_med_type = 0 # 0推送旧机制 1存库不推送,2推送存库
  73. # 暂时注销
  74. if have_pkey:
  75. res_data = {'code': 0, 'msg': 'Push it once a minute'}
  76. return JsonResponse(status=200, data=res_data)
  77. # 数据库读取数据
  78. if have_ykey:
  79. uid_push_list = eval(redisObj.get_data(key=ykey))
  80. else:
  81. # 从数据库查询出来
  82. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  83. values('token_val', 'app_type', 'appBundleId', 'm_code',
  84. 'push_type', 'userID_id', 'userID__NickName',
  85. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  86. 'uid_set__channel')
  87. uid_push_list = []
  88. for qs in uid_push_qs:
  89. uid_push_list.append(qs)
  90. # 修改redis数据,并设置过期时间为10分钟
  91. redisObj.set_data(key=ykey, val=str(uid_push_list), expire=600)
  92. if not uid_push_list:
  93. res_data = {'code': 404, 'msg': 'error !'}
  94. return JsonResponse(status=200, data=res_data)
  95. if not uid_push_list:
  96. res_data = {'code': 0, 'msg': 'uid_push_list not exist'}
  97. return JsonResponse(status=200, data=res_data)
  98. nickname = uid_push_list[0]['uid_set__nickname']
  99. detect_interval = uid_push_list[0]['uid_set__detect_interval']
  100. detect_group = uid_push_list[0]['uid_set__detect_group']
  101. now_time = int(time.time())
  102. if not nickname:
  103. nickname = uid
  104. if detect_group is not None:
  105. if have_dkey:
  106. detect_med_type = 1 # 1为存库不推送
  107. else:
  108. detect_med_type = 2 # 为2的话,既推送,又存库
  109. # detect_group=0允许全部推送的时候
  110. if detect_group == '0' or detect_group == '':
  111. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  112. else:
  113. detect_group_list = detect_group.split(',')
  114. if event_type in detect_group_list:
  115. if detect_interval < 60:
  116. detect_interval = 60
  117. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  118. redisObj.set_data(key=pkey, val=1, expire=60)
  119. # 旧模式并且没有pkey,重新创建一个
  120. if not detect_group and not have_pkey:
  121. redisObj.set_data(key=pkey, val=1, expire=60)
  122. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  123. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  124. kwag_args = {
  125. 'uid': uid,
  126. 'channel': channel,
  127. 'event_type': event_type,
  128. 'n_time': n_time,
  129. }
  130. sys_msg_list = []
  131. userID_ids = []
  132. do_apns_code = ''
  133. do_fcm_code = ''
  134. do_jpush_code = ''
  135. new_device_info_list = []
  136. local_date_time = ''
  137. for up in uid_push_list:
  138. push_type = up['push_type']
  139. appBundleId = up['appBundleId']
  140. token_val = up['token_val']
  141. lang = up['lang']
  142. tz = up['tz']
  143. if tz is None or tz == '':
  144. tz = 0
  145. # 发送标题
  146. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  147. # 发送内容
  148. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  149. event_type=event_type)
  150. kwag_args['appBundleId'] = appBundleId
  151. kwag_args['token_val'] = token_val
  152. kwag_args['msg_title'] = msg_title
  153. kwag_args['msg_text'] = msg_text
  154. logger.info('推送要的数据:')
  155. logger.info(kwag_args)
  156. logger.info(detect_med_type)
  157. local_date_time = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang='cn')
  158. logger.info('<<<<<旧的接口,根据时区计算后日期={},时区={}'.format(local_date_time, tz))
  159. local_date_time = local_date_time[0:10]
  160. logger.info('<<<<<旧的接口,日期={}'.format(local_date_time))
  161. # 以下是存库
  162. userID_id = up["userID_id"]
  163. if userID_id not in userID_ids:
  164. if is_sys_msg:
  165. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  166. event_type=event_type, is_sys=1)
  167. sys_msg_list.append(SysMsgModel(
  168. userID_id=userID_id,
  169. msg=sys_msg_text,
  170. addTime=now_time,
  171. updTime=now_time,
  172. uid=uid,
  173. eventType=event_type))
  174. else:
  175. logger.info('----《旧接口》start------')
  176. new_device_info_list.append(EquipmentInfoService.get_equipment_info_obj(
  177. local_date_time,
  178. device_user_id=userID_id,
  179. event_time=n_time,
  180. event_type=event_type,
  181. device_uid=uid,
  182. device_nick_name=nickname,
  183. channel=channel,
  184. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  185. is_st=is_st,
  186. receive_time=n_time,
  187. add_time=now_time,
  188. storage_location=1,
  189. border_coords='',
  190. ))
  191. userID_ids.append(userID_id)
  192. # 推送
  193. if detect_med_type == 2 or detect_med_type == 0:
  194. try:
  195. if push_type == 0: # ios apns
  196. do_apns_code = self.do_apns(**kwag_args)
  197. elif push_type == 1: # android gcm
  198. print('do_fcm')
  199. do_fcm_code = self.do_fcm(**kwag_args)
  200. elif push_type == 2: # android jpush
  201. print('do_jpush')
  202. do_jpush_code = self.do_jpush(**kwag_args)
  203. except Exception as e:
  204. logger.info("errLine={errLine}, errMsg={errMsg}".format(errLine=e.__traceback__.tb_lineno,
  205. errMsg=repr(e)))
  206. continue
  207. if detect_med_type == 1:
  208. do_apns_code = '只存库不推送'
  209. do_fcm_code = '只存库不推送'
  210. do_jpush_code = '只存库不推送'
  211. if is_sys_msg:
  212. SysMsgModel.objects.bulk_create(sys_msg_list)
  213. else:
  214. if new_device_info_list and len(new_device_info_list) > 0:
  215. # 根据日期获得星期几
  216. week = LocalDateTimeUtil.date_to_week(local_date_time)
  217. EquipmentInfoService.equipment_info_bulk_create(week, new_device_info_list)
  218. logger.info('----《旧接口》设备信息分表批量保存end')
  219. if is_st == '0' or is_st == '2':
  220. print("is_st=0or2")
  221. for up in uid_push_list:
  222. if up['push_type'] == 0: # ios apns
  223. up['do_apns_code'] = do_apns_code
  224. elif up['push_type'] == 1: # android gcm
  225. up['do_fcm_code'] = do_fcm_code
  226. elif up['push_type'] == 2: # android jpush
  227. up['do_jpush_code'] = do_jpush_code
  228. del up['push_type']
  229. del up['userID_id']
  230. del up['userID__NickName']
  231. del up['lang']
  232. del up['tz']
  233. del up['uid_set__nickname']
  234. del up['uid_set__detect_interval']
  235. del up['uid_set__detect_group']
  236. return JsonResponse(status=200, data={'code': 0, 'msg': 'success 0 or 2'})
  237. elif is_st == '1':
  238. print("is_st=1")
  239. # Endpoint以杭州为例,其它Region请按实际情况填写。
  240. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  241. # 设置此签名URL在60秒内有效。
  242. url = bucket.sign_url('PUT', obj, 7200)
  243. for up in uid_push_list:
  244. up['do_apns_code'] = do_apns_code
  245. up['do_fcm_code'] = do_fcm_code
  246. up['do_jpush_code'] = do_jpush_code
  247. del up['push_type']
  248. del up['userID_id']
  249. del up['userID__NickName']
  250. del up['lang']
  251. del up['tz']
  252. del up['uid_set__nickname']
  253. del up['uid_set__detect_interval']
  254. del up['uid_set__detect_group']
  255. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  256. return JsonResponse(status=200, data=res_data)
  257. elif is_st == '3':
  258. print("is_st=3")
  259. # 人形检测带动图
  260. # Endpoint以杭州为例,其它Region请按实际情况填写。
  261. img_url_list = []
  262. for i in range(int(is_st)):
  263. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  264. format(uid=uid, channel=channel, filename=n_time, st=i)
  265. # 设置此签名URL在60秒内有效。
  266. url = bucket.sign_url('PUT', obj, 7200)
  267. img_url_list.append(url)
  268. for up in uid_push_list:
  269. up['do_apns_code'] = do_apns_code
  270. up['do_fcm_code'] = do_fcm_code
  271. up['do_jpush_code'] = do_jpush_code
  272. del up['push_type']
  273. del up['userID_id']
  274. del up['userID__NickName']
  275. del up['lang']
  276. del up['tz']
  277. del up['uid_set__nickname']
  278. del up['uid_set__detect_interval']
  279. del up['uid_set__detect_group']
  280. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
  281. return JsonResponse(status=200, data=res_data)
  282. def get_msg_title(self, appBundleId, nickname):
  283. package_title_config = {
  284. 'com.ansjer.customizedd_a': 'DVS',
  285. 'com.ansjer.zccloud_a': 'ZosiSmart',
  286. 'com.ansjer.zccloud_ab': '周视',
  287. 'com.ansjer.adcloud_a': 'ADCloud',
  288. 'com.ansjer.adcloud_ab': 'ADCloud',
  289. 'com.ansjer.accloud_a': 'ACCloud',
  290. 'com.ansjer.loocamccloud_a': 'Loocam',
  291. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  292. 'com.ansjer.customizedb_a': 'COCOONHD',
  293. 'com.ansjer.customizeda_a': 'Guardian365',
  294. 'com.ansjer.customizedc_a': 'PatrolSecure',
  295. }
  296. if appBundleId in package_title_config.keys():
  297. return package_title_config[appBundleId] + '(' + nickname + ')'
  298. else:
  299. return nickname
  300. def is_sys_msg(self, event_type):
  301. event_type_list = [702, 703, 704]
  302. if event_type in event_type_list:
  303. return True
  304. return False
  305. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  306. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  307. etype = int(event_type)
  308. if lang == 'cn':
  309. if etype == 704:
  310. msg_type = '电量过低'
  311. elif etype == 702:
  312. msg_type = '摄像头休眠'
  313. elif etype == 703:
  314. msg_type = '摄像头唤醒'
  315. else:
  316. msg_type = ''
  317. if is_sys:
  318. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  319. else:
  320. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  321. else:
  322. if etype == 704:
  323. msg_type = 'Low battery'
  324. elif etype == 702:
  325. msg_type = 'Camera sleep'
  326. elif etype == 703:
  327. msg_type = 'Camera wake'
  328. else:
  329. msg_type = ''
  330. if is_sys:
  331. send_text = '{msg_type} channel:{channel}'. \
  332. format(msg_type=msg_type, channel=channel)
  333. else:
  334. send_text = '{msg_type} channel:{channel} date:{date}'. \
  335. format(msg_type=msg_type, channel=channel, date=n_date)
  336. return send_text
  337. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  338. app_key = JPUSH_CONFIG[appBundleId]['Key']
  339. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  340. _jpush = jpush.JPush(app_key, master_secret)
  341. push = _jpush.create_push()
  342. push.audience = jpush.registration_id(token_val)
  343. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  344. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  345. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  346. big_text=msg_text, title=msg_title,
  347. extras=push_data)
  348. push.notification = jpush.notification(android=android)
  349. push.platform = jpush.all_
  350. try:
  351. res = push.send()
  352. print(res)
  353. status_code = res.status_code
  354. except Exception as e:
  355. logger = logging.getLogger('info')
  356. logger.info(e)
  357. status_code = 100
  358. return status_code
  359. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  360. try:
  361. serverKey = FCM_CONFIG[appBundleId]
  362. except Exception as e:
  363. return 'serverKey abnormal'
  364. push_service = FCMNotification(api_key=serverKey)
  365. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  366. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  367. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  368. message_body=msg_text, data_message=data,
  369. extra_kwargs={
  370. 'default_vibrate_timings': True,
  371. 'default_sound': True,
  372. 'default_light_settings': True
  373. })
  374. return result
  375. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  376. try:
  377. cli = apns2.APNSClient(mode=APNS_MODE,
  378. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  379. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  380. "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
  381. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  382. payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
  383. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  384. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  385. if res.status_code == 200:
  386. return res.status_code
  387. else:
  388. return res.status_code
  389. except (ValueError, ArithmeticError):
  390. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  391. except Exception as e:
  392. return repr(e)