DetectController.py 18 KB

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