DetectControllerV2.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. import json
  2. import logging
  3. import os
  4. import apns2
  5. import boto3
  6. import botocore
  7. import jpush as jpush
  8. from botocore import client
  9. from django.db import transaction
  10. from django.http import JsonResponse
  11. from django.views.generic.base import View
  12. from pyfcm import FCMNotification
  13. from AnsjerPush.config import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
  14. from AnsjerPush.config import JPUSH_CONFIG, FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE
  15. from Object.RedisObject import RedisObject
  16. from Service.CommonService import CommonService
  17. from Service.DevicePushService import DevicePushService
  18. from Service.PushService import PushObject
  19. # 移动侦测V2接口
  20. class NotificationV2View(View):
  21. def get(self, request, *args, **kwargs):
  22. request.encoding = 'utf-8'
  23. return self.validation(request.GET)
  24. def post(self, request, *args, **kwargs):
  25. request.encoding = 'utf-8'
  26. return self.validation(request.POST)
  27. def validation(self, request_dict):
  28. """
  29. 设备触发报警消息推送
  30. @param request_dict:uidToken 加密uid
  31. @param request_dict:etk 加密uid
  32. @param request_dict:channel 设备通道号
  33. @param request_dict:n_time 设备触发报警时间
  34. @param request_dict:event_type 设备事件类型
  35. @param request_dict:is_st 文件类型(0:无,1:图片,2:视频)
  36. @param request_dict:region 文件存储区域(1:国外,2国内)
  37. @param request_dict:electricity 电量值
  38. """
  39. logger = logging.getLogger('info')
  40. logger.info('移动侦测V2接口参数:{}'.format(request_dict))
  41. uidToken = request_dict.get('uidToken', None)
  42. etk = request_dict.get('etk', None)
  43. channel = request_dict.get('channel', '1')
  44. n_time = request_dict.get('n_time', None)
  45. event_type = request_dict.get('event_type', None)
  46. is_st = request_dict.get('is_st', None)
  47. region = request_dict.get('region', None)
  48. electricity = request_dict.get('electricity', '')
  49. time_token = request_dict.get('time_token', None)
  50. uid = request_dict.get('uid', None)
  51. if not all([channel, n_time]):
  52. return JsonResponse(status=200, data={
  53. 'code': 444,
  54. 'msg': 'param is wrong'})
  55. if not region or not is_st:
  56. return JsonResponse(status=200, data={'code': 404, 'msg': 'no region or is_st'})
  57. # 时间戳token校验
  58. if time_token:
  59. if not CommonService.check_time_stamp_token(time_token, n_time):
  60. return JsonResponse(status=200, data={'code': 13, 'msg': 'Timestamp token verification failed'})
  61. try:
  62. is_st = int(is_st)
  63. region = int(region)
  64. event_type = int(event_type)
  65. if not uid:
  66. uid = DevicePushService.decode_uid(etk, uidToken) # 解密uid
  67. if len(uid) != 20 and len(uid) != 14:
  68. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong uid'})
  69. req_limiting = '{uid}_{channel}_{event_type}_ptl' \
  70. .format(uid=uid, channel=channel, event_type=event_type)
  71. is_sys_msg = self.is_sys_msg(int(event_type)) # 判断事件类型是否是系统消息
  72. if is_sys_msg:
  73. push_interval = '{uid}_{channel}_{event_type}_flag' \
  74. .format(uid=uid, channel=channel, event_type=event_type)
  75. else:
  76. push_interval = '{uid}_{channel}_flag'.format(uid=uid, channel=channel)
  77. redisObj = RedisObject(db=6)
  78. cache_req_limiting = redisObj.get_data(key=req_limiting) # 获取请求限流缓存数据
  79. cache_app_push = redisObj.get_data(key=push_interval) # 获取APP推送消息时间间隔缓存数据
  80. logger.info('消息推送- 限流key: {}, 推送间隔key: {}'.
  81. format(cache_req_limiting, cache_app_push))
  82. if event_type != 606:
  83. if cache_req_limiting: # 限流存在则直接返回
  84. return JsonResponse(status=200, data={'code': 0, 'msg': 'Push again in one minute'})
  85. redisObj.set_data(key=req_limiting, val=1, expire=60) # 当缓存不存在限流数据 重新设置一分钟请求一次
  86. uid_push_qs = DevicePushService.query_uid_push(uid, event_type) # 查询uid_set与push数据列表
  87. if not uid_push_qs.exists():
  88. logger.info('消息推送-uid_push 数据不存在')
  89. return JsonResponse(status=200, data={'code': 176, 'msg': 'no uid_push data'})
  90. ai_type = uid_push_qs.first()['uid_set__ai_type']
  91. event_type = self.get_combo_msg_type(ai_type, event_type) # 解析消息事件类型看是否多类型组合
  92. # 将uid_set以及uid_push 转数组列表
  93. uid_set_push_list = DevicePushService.cache_uid_push(uid_push_qs)
  94. nickname = uid_set_push_list[0]['uid_set__nickname']
  95. nickname = uid if not nickname else nickname
  96. # APP消息提醒推送间隔
  97. detect_interval = uid_set_push_list[0]['uid_set__detect_interval']
  98. if event_type != 606:
  99. if not cache_app_push:
  100. # 缓存APP提醒推送间隔 默认1分钟提醒一次
  101. DevicePushService.cache_push_detect_interval(redisObj, push_interval, detect_interval,
  102. uid_set_push_list[0]['uid_set__new_detect_interval'])
  103. bucket = ''
  104. aws_s3_client = ''
  105. if is_st == 1 or is_st == 3: # 使用aws s3
  106. aws_s3_client = s3_client(region=region)
  107. bucket = 'foreignpush' if region == 1 else 'push'
  108. kwag_args = {
  109. 'uid': uid,
  110. 'channel': channel,
  111. 'event_type': event_type,
  112. 'n_time': n_time,
  113. }
  114. params = {'nickname': nickname, 'uid': uid, 'kwag_args': kwag_args, 'is_st': is_st, 'region': region,
  115. 'is_sys_msg': is_sys_msg, 'channel': channel, 'event_type': event_type, 'n_time': n_time,
  116. 'electricity': electricity, 'bucket': bucket, 'aws_s3_client': aws_s3_client,
  117. 'app_push': cache_app_push, 'storage_location': 2}
  118. logger.info('已创建s3对象,推送数据为:{}'.format(params))
  119. # APP消息推送与获取报警消息数据列表
  120. result = DevicePushService.save_msg_push(uid_set_push_list, **params)
  121. # 批量系统消息&报警消息数据存库
  122. DevicePushService.save_sys_msg(is_sys_msg, result['local_date_time'],
  123. result['sys_msg_list'], result['new_device_info_list'])
  124. params['aws_s3_client'] = aws_s3_client
  125. params['uid_set_push_list'] = uid_set_push_list
  126. params['code_dict'] = result
  127. result_dict = DevicePushService.get_push_url(**params) # 获取S3对象上传链接
  128. return JsonResponse(status=200, data=result_dict)
  129. except Exception as e:
  130. logger.info('消息推送-异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  131. data = {
  132. 'errLine': e.__traceback__.tb_lineno,
  133. 'errMsg': repr(e),
  134. }
  135. return JsonResponse(status=200, data=json.dumps(data), safe=False)
  136. @classmethod
  137. def get_combo_msg_type(cls, ai_type, event_type):
  138. """
  139. 获取组合类型,ai_type == 47 支持算法小店,需判断组合类型
  140. """
  141. logger = logging.getLogger('info')
  142. try:
  143. if ai_type != 47:
  144. return event_type
  145. logger.info('LOG------算法小店组合类型十进制值:{}'.format(event_type))
  146. # 如触发一个事件,则匹配已用类型 1替换后变成51代表移动侦测 1:移动侦测,2:人形,4:车型,8:人脸
  147. event_dict = {
  148. 1: 51,
  149. 2: 57,
  150. 4: 58,
  151. 16: 59,
  152. 8: 60,
  153. 32: 61
  154. }
  155. event_val = event_dict.get(event_type, 0)
  156. # event_val == 0 没有匹配到单个值则认为组合类型
  157. # 如是3,则转为二进制11,代表(1+2)触发了移动侦测+人形侦测
  158. if event_val == 0:
  159. val = cls.dec_to_bin(event_type)
  160. return int(val)
  161. else:
  162. return int(event_val)
  163. except Exception as e:
  164. logger.info('推送错误异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  165. return event_type
  166. @staticmethod
  167. def dec_to_bin(num):
  168. """
  169. 十进制转二进制
  170. """
  171. result = ""
  172. while num != 0:
  173. ret = num % 2
  174. num //= 2
  175. result = str(ret) + result
  176. return result
  177. def push_thread_test(self, push_type, aws_s3_client, bucket, key, uid, appBundleId, token_val, event_type, n_time,
  178. msg_title, msg_text, channel):
  179. logger = logging.getLogger('info')
  180. logger.info('推送图片测试:{} {} {} {} {} {} {} {}'.format(push_type, uid, appBundleId, token_val, event_type, n_time,
  181. msg_title, msg_text))
  182. try:
  183. image_url = aws_s3_client.generate_presigned_url('get_object', Params={'Bucket': bucket, 'Key': key},
  184. ExpiresIn=300)
  185. logger.info('推送图片url:{}'.format(image_url))
  186. if push_type == 0:
  187. PushObject.ios_apns_push(uid, appBundleId, token_val, n_time, event_type, msg_title, msg_text,
  188. uid, channel, image_url)
  189. elif push_type == 1:
  190. PushObject.android_fcm_push(uid, appBundleId, token_val, n_time, event_type, msg_title,
  191. msg_text, uid, channel, image_url)
  192. except Exception as e:
  193. logger.info('推送图片测试异常:{}'.format(e))
  194. @staticmethod
  195. def is_sys_msg(event_type):
  196. """
  197. 判断是否属于系统消息
  198. @return: True | False
  199. """
  200. event_type_list = [702, 703, 704]
  201. if event_type in event_type_list:
  202. return True
  203. return False
  204. def get_msg_text(self, channel, n_time, lang, tz, event_type, electricity='', is_sys=0):
  205. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  206. etype = int(event_type)
  207. if lang == 'cn':
  208. if etype == 704:
  209. msg_type = '剩余电量 ' + electricity
  210. elif etype == 702:
  211. msg_type = '摄像头休眠'
  212. elif etype == 703:
  213. msg_type = '摄像头唤醒'
  214. else:
  215. msg_type = ''
  216. if is_sys:
  217. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  218. else:
  219. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  220. else:
  221. if etype == 704:
  222. msg_type = 'Battery remaining ' + electricity
  223. elif etype == 702:
  224. msg_type = 'Camera sleep'
  225. elif etype == 703:
  226. msg_type = 'Camera wake'
  227. else:
  228. msg_type = ''
  229. if is_sys:
  230. send_text = '{msg_type} channel:{channel}'. \
  231. format(msg_type=msg_type, channel=channel)
  232. else:
  233. send_text = '{msg_type} channel:{channel} date:{date}'. \
  234. format(msg_type=msg_type, channel=channel, date=n_date)
  235. return send_text
  236. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
  237. msg_title, msg_text):
  238. app_key = JPUSH_CONFIG[appBundleId]['Key']
  239. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  240. _jpush = jpush.JPush(app_key, master_secret)
  241. push = _jpush.create_push()
  242. push.audience = jpush.registration_id(token_val)
  243. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  244. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  245. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  246. big_text=msg_text, title=msg_title,
  247. extras=push_data)
  248. push.notification = jpush.notification(android=android)
  249. push.platform = jpush.all_
  250. res = push.send()
  251. print(res)
  252. return res.status_code
  253. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  254. logger = logging.getLogger('info')
  255. try:
  256. serverKey = FCM_CONFIG[appBundleId]
  257. except Exception as e:
  258. logger.info('------fcm_error:{}'.format(repr(e)))
  259. return 'serverKey abnormal'
  260. push_service = FCMNotification(api_key=serverKey)
  261. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  262. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  263. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  264. message_body=msg_text, data_message=data,
  265. extra_kwargs={
  266. 'default_vibrate_timings': True,
  267. 'default_sound': True,
  268. 'default_light_settings': True
  269. })
  270. return result
  271. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  272. msg_text):
  273. logger = logging.getLogger('info')
  274. logger.info("进来do_apns函数了")
  275. logger.info(token_val)
  276. logger.info(APNS_MODE)
  277. logger.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  278. try:
  279. cli = apns2.APNSClient(mode=APNS_MODE,
  280. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  281. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  282. "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
  283. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  284. payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
  285. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  286. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  287. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  288. print(res.status_code)
  289. logger.info("apns_推送状态:")
  290. logger.info(res.status_code)
  291. if res.status_code == 200:
  292. return res.status_code
  293. else:
  294. print('apns push fail')
  295. print(res.reason)
  296. logger.info('apns push fail')
  297. logger.info(res.reason)
  298. return res.status_code
  299. except (ValueError, ArithmeticError):
  300. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  301. except Exception as e:
  302. print(repr(e))
  303. print('do_apns函数错误行号', e.__traceback__.tb_lineno)
  304. logger.info('do_apns错误:{}'.format(repr(e)))
  305. return repr(e)
  306. def s3_client(region):
  307. if region == 2: # 国内
  308. aws_s3_client = boto3.client(
  309. 's3',
  310. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  311. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  312. config=botocore.client.Config(signature_version='s3v4'),
  313. region_name='cn-northwest-1'
  314. )
  315. else: # 国外
  316. aws_s3_client = boto3.client(
  317. 's3',
  318. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  319. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  320. config=botocore.client.Config(signature_version='s3v4'),
  321. region_name='us-east-1'
  322. )
  323. return aws_s3_client