DevicePushService.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : DevicePushService.py
  4. @Time : 2022/11/23 11:40
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import logging
  10. import os
  11. import threading
  12. import time
  13. import apns2
  14. import jpush as jpush
  15. from pyfcm import FCMNotification
  16. from AnsjerPush.config import JPUSH_CONFIG, FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE
  17. from AnsjerPush.config import SERVER_TYPE
  18. from Model.models import UidPushModel, SysMsgModel
  19. from Object.ETkObject import ETkObject
  20. from Object.UidTokenObject import UidTokenObject
  21. from Object.utils import LocalDateTimeUtil
  22. from Service.CommonService import CommonService
  23. from Service.EquipmentInfoService import EquipmentInfoService
  24. from Service.GatewayService import GatewayPushService
  25. LOGGING = logging.getLogger('info')
  26. class DevicePushService:
  27. @staticmethod
  28. def decode_uid(etk, uidToken):
  29. """
  30. 解密UID,优先解密etk 否则判断uidToken
  31. """
  32. # 解密获取uid
  33. if etk:
  34. eto = ETkObject(etk)
  35. uid = eto.uid
  36. else:
  37. uto = UidTokenObject(uidToken)
  38. uid = uto.UID
  39. LOGGING.info('消息推送-当前UID:{}'.format(uid))
  40. return uid
  41. @classmethod
  42. def query_uid_push(cls, uid):
  43. """
  44. 查询uid_set与push数据列表
  45. """
  46. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  47. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
  48. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  49. 'uid_set__channel', 'uid_set__ai_type', 'uid_set__new_detect_interval')
  50. return uid_push_qs
  51. @staticmethod
  52. def cache_uid_push(uid_push_qs):
  53. """
  54. 将uid_push 信息进行缓存
  55. @param uid_push_qs: uid_set & uid_push 列表对象
  56. @return: uid_set_list
  57. """
  58. uid_set_list = []
  59. for qs in uid_push_qs:
  60. uid_set_list.append(qs)
  61. # redis_obj.set_data(key=name, val=str(redis_list), expire=expire)
  62. return uid_set_list
  63. @staticmethod
  64. def cache_push_detect_interval(redis_obj, name, detect_interval, new_detect_interval):
  65. """
  66. 缓存设置推送消息的时间间隔
  67. @param redis_obj: redis对象
  68. @param name: redis key
  69. @param detect_interval: 原推送时间间隔
  70. @param new_detect_interval: 新推送时间间隔
  71. """
  72. if SERVER_TYPE != 'Ansjer.cn_formal_settings':
  73. detect_interval = new_detect_interval if new_detect_interval > 0 else detect_interval
  74. detect_interval = 60 if detect_interval < 60 else detect_interval
  75. redis_obj.set_data(key=name, val=1, expire=detect_interval - 5)
  76. LOGGING.info('消息推送-缓存设置APP推送间隔:{}s'.format(detect_interval))
  77. @classmethod
  78. def save_msg_push(cls, uid_set_push_list, **params):
  79. """
  80. APP消息推送以及报警消息存库
  81. @nickname 设备名称
  82. @channel 通道
  83. @event_type 事件类型
  84. """
  85. new_device_info_list = []
  86. sys_msg_list = []
  87. userID_ids = []
  88. kwag_args = params['kwag_args']
  89. code_data = {'do_apns_code': '', 'do_fcm_code': '', 'do_jpush_code': ''}
  90. local_date_time = ''
  91. for up in uid_set_push_list:
  92. appBundleId = up['appBundleId']
  93. token_val = up['token_val']
  94. lang = up['lang']
  95. tz = up['tz']
  96. if tz is None or tz == '':
  97. tz = 0
  98. # 发送标题
  99. msg_title = cls.get_msg_title(appBundleId=appBundleId, nickname=params['nickname'])
  100. # 发送内容
  101. msg_text = cls.get_msg_text(channel=params['channel'], n_time=params['n_time'], lang=lang,
  102. tz=tz, event_type=params['event_type'],
  103. electricity=params['electricity'])
  104. kwag_args['appBundleId'] = appBundleId
  105. kwag_args['token_val'] = token_val
  106. kwag_args['msg_title'] = msg_title
  107. kwag_args['msg_text'] = msg_text
  108. LOGGING.info('推送要的数据: {}'.format(kwag_args))
  109. local_date_time = CommonService.get_now_time_str(n_time=params['n_time'], tz=tz, lang='cn')
  110. LOGGING.info('<<<<<根据时区计算后日期={},时区={}'.format(local_date_time, tz))
  111. local_date_time = local_date_time[0:10]
  112. LOGGING.info('<<<<<切片后的日期={}'.format(local_date_time))
  113. # 以下是存库
  114. userID_id = up["userID_id"]
  115. if userID_id not in userID_ids:
  116. now_time = int(time.time())
  117. if params['is_sys_msg']:
  118. sys_msg_text = cls.get_msg_text(channel=params['channel'], n_time=params['n_time'], lang=lang,
  119. tz=tz,
  120. event_type=params['event_type'], electricity=params['electricity'],
  121. is_sys=1)
  122. sys_msg_list.append(SysMsgModel(userID_id=userID_id, msg=sys_msg_text, addTime=now_time,
  123. updTime=now_time, uid=params['uid'],
  124. eventType=params['event_type']))
  125. else:
  126. LOGGING.info('分表存数据start------')
  127. params['userID_id'] = userID_id
  128. new_device_info_list.append(cls.created_device_vo(local_date_time, **params))
  129. userID_ids.append(userID_id)
  130. params['appBundleId'] = appBundleId
  131. params['token_val'] = token_val
  132. params['lang'] = lang
  133. params['tz'] = tz
  134. params['kwag_args'] = kwag_args
  135. code_data = cls.send_app_msg_push(up['push_type'], **params)
  136. return {'code_date': code_data, 'new_device_info_list': new_device_info_list, 'sys_msg_list': sys_msg_list,
  137. 'local_date_time': local_date_time}
  138. @classmethod
  139. def send_app_msg_push(cls, push_type, **param):
  140. """
  141. 发送app消息推送
  142. """
  143. try:
  144. kwag_args = param['kwag_args']
  145. result = {'do_apns_code': '', 'do_fcm_code': '', 'do_jpush_code': ''}
  146. # 判断是否进行APP消息推送,如app_push不为空,则不进行推送
  147. if not param['app_push']:
  148. LOGGING.info('APP准备推送:{}, {}'.format(param['uid'], param))
  149. if (param['is_st'] == 1 or param['is_st'] == 3) and (push_type == 0 or push_type == 1): # 推送显示图片
  150. if param['is_st'] == 1:
  151. key = '{}/{}/{}.jpeg'.format(param['uid'], param['channel'], param['n_time'])
  152. else:
  153. key = '{}/{}/{}_0.jpeg'.format(param['uid'], param['channel'], param['n_time'])
  154. push_thread = threading.Thread(target=cls.async_send_picture_push, args=(
  155. push_type, param['aws_s3_client'], param['bucket'], key, param['uid'], param['appBundleId'],
  156. param['token_val'], param['event_type'], param['n_time'],
  157. param['msg_title'], param['msg_text'], param['channel']))
  158. push_thread.start()
  159. else:
  160. if push_type == 0: # ios apns
  161. result['do_apns_code'] = cls.do_apns(**kwag_args)
  162. elif push_type == 1: # android gcm
  163. result['do_fcm_code'] = cls.do_fcm(**kwag_args)
  164. elif push_type == 2: # android jpush
  165. result['do_jpush_code'] = cls.do_jpush(**kwag_args)
  166. return result
  167. except Exception as e:
  168. LOGGING.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  169. return None
  170. @classmethod
  171. def save_sys_msg(cls, is_sys_msg, local_date_time, sys_msg_list, new_device_info_list):
  172. """
  173. 保存系统消息&设备推送消息存库
  174. """
  175. if is_sys_msg:
  176. SysMsgModel.objects.bulk_create(sys_msg_list)
  177. else:
  178. # new 分表批量存储 设备信息
  179. if new_device_info_list and len(new_device_info_list) > 0:
  180. # 根据日期获得星期几
  181. week = LocalDateTimeUtil.date_to_week(local_date_time)
  182. EquipmentInfoService.equipment_info_bulk_create(week, new_device_info_list)
  183. LOGGING.info('设备信息分表批量保存end------')
  184. return True
  185. @classmethod
  186. def created_device_vo(cls, local_date_time, **params):
  187. """
  188. 获取设备推送表对象
  189. """
  190. return EquipmentInfoService.get_equipment_info_obj(
  191. local_date_time,
  192. device_user_id=params['userID_id'],
  193. event_time=params['n_time'],
  194. event_type=params['event_type'],
  195. device_uid=params['uid'],
  196. device_nick_name=params['nickname'],
  197. channel=params['channel'],
  198. alarm='Motion \tChannel:{channel}'.format(channel=params['channel']),
  199. is_st=params['is_st'],
  200. receive_time=params['n_time'],
  201. add_time=int(time.time()),
  202. storage_location=2,
  203. border_coords='',
  204. )
  205. @staticmethod
  206. def get_msg_title(appBundleId, nickname):
  207. """
  208. 获取消息标题
  209. """""
  210. package_title_config = {
  211. 'com.ansjer.customizedd_a': 'DVS',
  212. 'com.ansjer.zccloud_a': 'ZosiSmart',
  213. 'com.ansjer.zccloud_ab': '周视',
  214. 'com.ansjer.adcloud_a': 'ADCloud',
  215. 'com.ansjer.adcloud_ab': 'ADCloud',
  216. 'com.ansjer.accloud_a': 'ACCloud',
  217. 'com.ansjer.loocamccloud_a': 'Loocam',
  218. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  219. 'com.ansjer.customizedb_a': 'COCOONHD',
  220. 'com.ansjer.customizeda_a': 'Guardian365',
  221. 'com.ansjer.customizedc_a': 'PatrolSecure',
  222. }
  223. if appBundleId in package_title_config.keys():
  224. return package_title_config[appBundleId] + '(' + nickname + ')'
  225. else:
  226. return nickname
  227. @staticmethod
  228. def get_msg_text(channel, n_time, lang, tz, event_type, electricity='', is_sys=0):
  229. """
  230. 获取消息文本
  231. """
  232. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  233. etype = int(event_type)
  234. if lang == 'cn':
  235. if etype == 704:
  236. msg_type = '剩余电量:' + electricity
  237. elif etype == 702:
  238. msg_type = '摄像头休眠'
  239. elif etype == 703:
  240. msg_type = '摄像头唤醒'
  241. else:
  242. msg_type = ''
  243. if is_sys:
  244. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  245. else:
  246. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  247. else:
  248. if etype == 704:
  249. msg_type = 'Battery remaining:' + electricity
  250. elif etype == 702:
  251. msg_type = 'Camera sleep'
  252. elif etype == 703:
  253. msg_type = 'Camera wake'
  254. else:
  255. msg_type = ''
  256. if is_sys:
  257. send_text = '{msg_type} channel:{channel}'. \
  258. format(msg_type=msg_type, channel=channel)
  259. else:
  260. send_text = '{msg_type} channel:{channel} date:{date}'. \
  261. format(msg_type=msg_type, channel=channel, date=n_date)
  262. return send_text
  263. @staticmethod
  264. def do_jpush(uid, channel, appBundleId, token_val, event_type, n_time,
  265. msg_title, msg_text):
  266. """
  267. android 国内极光APP消息提醒推送
  268. """
  269. app_key = JPUSH_CONFIG[appBundleId]['Key']
  270. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  271. _jpush = jpush.JPush(app_key, master_secret)
  272. push = _jpush.create_push()
  273. push.audience = jpush.registration_id(token_val)
  274. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  275. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  276. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  277. big_text=msg_text, title=msg_title,
  278. extras=push_data)
  279. push.notification = jpush.notification(android=android)
  280. push.platform = jpush.all_
  281. res = push.send()
  282. print(res)
  283. return res.status_code
  284. @staticmethod
  285. def do_fcm(uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  286. """
  287. android 谷歌APP消息提醒推送
  288. """
  289. try:
  290. serverKey = FCM_CONFIG[appBundleId]
  291. except Exception as e:
  292. LOGGING.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  293. return 'serverKey abnormal'
  294. push_service = FCMNotification(api_key=serverKey)
  295. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  296. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  297. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  298. message_body=msg_text, data_message=data,
  299. extra_kwargs={
  300. 'default_vibrate_timings': True,
  301. 'default_sound': True,
  302. 'default_light_settings': True
  303. })
  304. return result
  305. @staticmethod
  306. def do_apns(uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  307. msg_text):
  308. """
  309. ios 消息提醒推送
  310. """
  311. LOGGING.info("进来do_apns函数了")
  312. LOGGING.info(token_val)
  313. LOGGING.info(APNS_MODE)
  314. LOGGING.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  315. try:
  316. cli = apns2.APNSClient(
  317. mode=APNS_MODE, client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  318. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  319. "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
  320. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  321. payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
  322. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  323. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  324. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  325. print(res.status_code)
  326. LOGGING.info("apns_推送状态:")
  327. LOGGING.info(res.status_code)
  328. if res.status_code == 200:
  329. return res.status_code
  330. else:
  331. print('apns push fail')
  332. print(res.reason)
  333. LOGGING.info('apns push fail')
  334. LOGGING.info(res.reason)
  335. return res.status_code
  336. except (ValueError, ArithmeticError):
  337. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  338. except Exception as e:
  339. print(repr(e))
  340. print('do_apns函数错误行号', e.__traceback__.tb_lineno)
  341. LOGGING.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  342. return repr(e)
  343. @classmethod
  344. def async_send_picture_push(cls, push_type, aws_s3_client, bucket, key, uid, appBundleId,
  345. token_val, event_type, n_time, msg_title, msg_text, channel):
  346. """
  347. 异步APP图片推送
  348. """
  349. try:
  350. image_url = aws_s3_client.generate_presigned_url('get_object', Params={'Bucket': bucket, 'Key': key},
  351. ExpiresIn=300)
  352. LOGGING.info('推送图片url:{}'.format(image_url))
  353. if push_type == 0:
  354. GatewayPushService.ios_apns_push(uid, appBundleId, token_val, n_time, event_type, msg_title, msg_text,
  355. uid, channel, image_url)
  356. elif push_type == 1:
  357. GatewayPushService.android_fcm_push(uid, appBundleId, token_val, n_time, event_type, msg_title,
  358. msg_text, uid, channel, image_url)
  359. except Exception as e:
  360. LOGGING.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  361. @staticmethod
  362. def get_push_url(**params):
  363. """
  364. 获取推送URL,设备根本当前返回结果进行数据上传
  365. @return: re_data
  366. """
  367. re_data = {'code': 0, 'msg': 'success'}
  368. if params['is_st'] == 0 or params['is_st'] == 2:
  369. re_data['msg'] = 'success 0 or 2'
  370. for up in params['uid_set_push_list']:
  371. if up['push_type'] == 0: # ios apns
  372. up['do_apns_code'] = params['code_dict']['do_apns_code']
  373. elif up['push_type'] == 1: # android gcm
  374. up['do_fcm_code'] = params['code_dict']['do_fcm_code']
  375. elif up['push_type'] == 2: # android jpush
  376. up['do_jpush_code'] = params['code_dict']['do_jpush_code']
  377. del up['push_type']
  378. del up['userID_id']
  379. del up['userID__NickName']
  380. del up['lang']
  381. del up['tz']
  382. del up['uid_set__nickname']
  383. del up['uid_set__detect_interval']
  384. del up['uid_set__detect_group']
  385. re_data['re_list'] = params['uid_set_push_list']
  386. elif params['is_st'] == 1:
  387. key_name = '{uid}/{channel}/{filename}.jpeg' \
  388. .format(uid=params['uid'], channel=params['channel'], filename=params['n_time'])
  389. re_args = {'Key': key_name}
  390. if params['region'] == 2: # 2:国内
  391. re_args['Bucket'] = 'push'
  392. else: # 1:国外
  393. re_args['Bucket'] = 'foreignpush'
  394. response_url = DevicePushService.generate_s3_url(params['aws_s3_client'], re_args)
  395. re_data['img_push'] = response_url
  396. elif params['is_st'] == 3:
  397. img_url_list = []
  398. if params['region'] == 2: # 2:国内
  399. re_args = {'Bucket': 'push'}
  400. else: # 1:国外
  401. re_args = {'Bucket': 'foreignpush'}
  402. for i in range(params['is_st']):
  403. key_name = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  404. format(uid=params['uid'], channel=params['channel'], filename=params['n_time'], st=i)
  405. re_args['Key'] = key_name
  406. response_url = DevicePushService.generate_s3_url(params['aws_s3_client'], re_args)
  407. img_url_list.append(response_url)
  408. re_data['img_url_list'] = img_url_list
  409. re_data['msg'] = 'success 3'
  410. return re_data
  411. @staticmethod
  412. def generate_s3_url(aws_s3_client, params):
  413. """
  414. 获取S3对象URL
  415. """
  416. response_url = aws_s3_client.generate_presigned_url(
  417. ClientMethod='put_object',
  418. Params=params,
  419. ExpiresIn=3600
  420. )
  421. return response_url