PowerWarningController.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. # -*- coding: utf-8 -*-
  2. """
  3. @Author : Rocky
  4. @Time : 2022/9/16 10:39
  5. @File :PowerWarningController.py
  6. """
  7. import logging
  8. import os
  9. import time
  10. import apns2
  11. import jpush as jpush
  12. from django.http import JsonResponse
  13. from django.views.generic.base import View
  14. from pyfcm import FCMNotification
  15. from AnsjerPush.config import JPUSH_CONFIG, FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE
  16. from Model.models import UidPushModel, SysMsgModel
  17. from Service.CommonService import CommonService
  18. # 低电量推送接口
  19. class PowerWarningView(View):
  20. def get(self, request, *args, **kwargs):
  21. request.encoding = 'utf-8'
  22. return self.validation(request.GET)
  23. def post(self, request, *args, **kwargs):
  24. request.encoding = 'utf-8'
  25. return self.validation(request.POST)
  26. def validation(self, request_dict):
  27. logger = logging.getLogger('info')
  28. uid = request_dict.get('uid', None)
  29. channel = request_dict.get('channel', None)
  30. electricity = request_dict.get('electricity', None)
  31. logger.info('调用低电量推送接口的uid: {},electricity: {}'.format(uid, electricity))
  32. try:
  33. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid). \
  34. values('token_val', 'app_type', 'appBundleId', 'm_code',
  35. 'push_type', 'userID_id', 'userID__NickName',
  36. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  37. 'uid_set__channel')
  38. if not uid_push_qs.exists():
  39. res_data = {'code': 173, 'msg': 'uid push data not exit!'}
  40. return JsonResponse(status=200, data=res_data)
  41. # 新建一个list接收数据
  42. redis_list = []
  43. # 把数据库数据追加进redis_list
  44. for qs in uid_push_qs:
  45. redis_list.append(qs)
  46. if not redis_list:
  47. res_data = {'code': 0, 'msg': 'no redis_list success!'}
  48. return JsonResponse(status=200, data=res_data)
  49. nickname = redis_list[0]['uid_set__nickname']
  50. if not nickname:
  51. nickname = uid
  52. now_time = int(time.time())
  53. channel = channel
  54. event_type = 704
  55. sys_msg_list = []
  56. userID_ids = []
  57. kwag_args = {
  58. 'uid': uid,
  59. 'channel': channel,
  60. 'event_type': event_type,
  61. 'n_time': now_time,
  62. }
  63. for up in redis_list:
  64. push_type = up['push_type']
  65. appBundleId = up['appBundleId']
  66. token_val = up['token_val']
  67. lang = up['lang']
  68. tz = up['tz']
  69. if tz is None or tz == '':
  70. tz = 0
  71. # 发送标题
  72. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  73. # 发送内容
  74. msg_text = self.get_msg_text(channel=channel, n_time=now_time, lang=lang, tz=tz,
  75. event_type=event_type, electricity=electricity)
  76. kwag_args['appBundleId'] = appBundleId
  77. kwag_args['token_val'] = token_val
  78. kwag_args['msg_title'] = msg_title
  79. kwag_args['msg_text'] = msg_text
  80. if push_type == 0: # ios apns
  81. self.do_apns(**kwag_args)
  82. elif push_type == 1: # android gcm
  83. self.do_fcm(**kwag_args)
  84. elif push_type == 2: # android jpush
  85. self.do_jpush(**kwag_args)
  86. # 以下是存库
  87. userID_id = up["userID_id"]
  88. if userID_id not in userID_ids:
  89. sys_msg_text = self.get_msg_text(channel=channel, n_time=now_time, lang=lang, tz=tz,
  90. event_type=event_type, is_sys=1, electricity=electricity)
  91. sys_msg_list.append(SysMsgModel(
  92. userID_id=userID_id,
  93. msg=sys_msg_text,
  94. addTime=now_time,
  95. updTime=now_time,
  96. uid=uid,
  97. eventType=event_type,
  98. ))
  99. userID_ids.append(userID_id)
  100. SysMsgModel.objects.bulk_create(sys_msg_list)
  101. return JsonResponse(status=200, data={'code': 0})
  102. except Exception as e:
  103. logger.info('低电量推送接口异常: {}'.format(e))
  104. return JsonResponse(status=500, data={'msg': 'power warning error'})
  105. def get_msg_title(self, appBundleId, nickname):
  106. package_title_config = {
  107. 'com.ansjer.customizedd_a': 'DVS',
  108. 'com.ansjer.zccloud_a': 'ZosiSmart',
  109. 'com.ansjer.zccloud_ab': '周视',
  110. 'com.ansjer.adcloud_a': 'ADCloud',
  111. 'com.ansjer.adcloud_ab': 'ADCloud',
  112. 'com.ansjer.accloud_a': 'ACCloud',
  113. 'com.ansjer.loocamccloud_a': 'Loocam',
  114. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  115. 'com.ansjer.customizedb_a': 'COCOONHD',
  116. 'com.ansjer.customizeda_a': 'Guardian365',
  117. 'com.ansjer.customizedc_a': 'PatrolSecure',
  118. }
  119. if appBundleId in package_title_config.keys():
  120. return package_title_config[appBundleId] + '(' + nickname + ')'
  121. else:
  122. return nickname
  123. def is_sys_msg(self, event_type):
  124. event_type_list = [702, 703, 704]
  125. if event_type in event_type_list:
  126. return True
  127. return False
  128. def get_msg_text(self, channel, n_time, lang, tz, event_type, electricity, is_sys=0):
  129. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  130. etype = int(event_type)
  131. if lang == 'cn':
  132. if etype == 704:
  133. msg_type = '剩余电量:' + electricity
  134. elif etype == 702:
  135. msg_type = '摄像头休眠'
  136. elif etype == 703:
  137. msg_type = '摄像头唤醒'
  138. else:
  139. msg_type = ''
  140. if is_sys:
  141. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  142. else:
  143. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  144. else:
  145. if etype == 704:
  146. msg_type = 'Battery remaining:' + electricity
  147. elif etype == 702:
  148. msg_type = 'Camera sleep'
  149. elif etype == 703:
  150. msg_type = 'Camera wake'
  151. else:
  152. msg_type = ''
  153. if is_sys:
  154. send_text = '{msg_type} channel:{channel}'. \
  155. format(msg_type=msg_type, channel=channel)
  156. else:
  157. send_text = '{msg_type} channel:{channel} date:{date}'. \
  158. format(msg_type=msg_type, channel=channel, date=n_date)
  159. return send_text
  160. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  161. app_key = JPUSH_CONFIG[appBundleId]['Key']
  162. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  163. _jpush = jpush.JPush(app_key, master_secret)
  164. push = _jpush.create_push()
  165. push.audience = jpush.registration_id(token_val)
  166. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  167. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  168. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  169. big_text=msg_text, title=msg_title,
  170. extras=push_data)
  171. push.notification = jpush.notification(android=android)
  172. push.platform = jpush.all_
  173. res = push.send()
  174. return res.status_code
  175. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  176. try:
  177. serverKey = FCM_CONFIG[appBundleId]
  178. except Exception as e:
  179. return 'serverKey abnormal'
  180. push_service = FCMNotification(api_key=serverKey)
  181. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  182. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  183. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  184. message_body=msg_text, data_message=data,
  185. extra_kwargs={
  186. 'default_vibrate_timings': True,
  187. 'default_sound': True,
  188. 'default_light_settings': True
  189. })
  190. return result
  191. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  192. try:
  193. cli = apns2.APNSClient(mode=APNS_MODE, client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  194. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  195. "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
  196. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  197. payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
  198. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  199. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  200. if res.status_code == 200:
  201. return res.status_code
  202. else:
  203. return res.status_code
  204. except (ValueError, ArithmeticError):
  205. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  206. except Exception as e:
  207. return repr(e)