DevicePushService.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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 hashlib
  10. import json
  11. import logging
  12. import os
  13. import threading
  14. import time
  15. import apns2
  16. import jpush as jpush
  17. import requests
  18. from pyfcm import FCMNotification
  19. from AnsjerPush.Config.aiConfig import DEVICE_EVENT_TYPE
  20. from AnsjerPush.config import CONFIG_INFO, CONFIG_CN
  21. from AnsjerPush.config import JPUSH_CONFIG, FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE, XMPUSH_CONFIG, OPPOPUSH_CONFIG
  22. from Model.models import UidPushModel, SysMsgModel, DeviceSharePermission, DeviceChannelUserSet, \
  23. DeviceChannelUserPermission, UidSetModel
  24. from Object.ETkObject import ETkObject
  25. from Object.UidTokenObject import UidTokenObject
  26. from Object.utils import LocalDateTimeUtil
  27. from Service.CommonService import CommonService
  28. from Service.EquipmentInfoService import EquipmentInfoService
  29. from Service.HuaweiPushService.HuaweiPushService import HuaweiPushObject
  30. from Service.PushService import PushObject
  31. LOGGING = logging.getLogger('info')
  32. class DevicePushService:
  33. @staticmethod
  34. def decode_uid(etk, uidToken):
  35. """
  36. 解密UID,优先解密etk 否则判断uidToken
  37. """
  38. # 解密获取uid
  39. if etk:
  40. eto = ETkObject(etk)
  41. uid = eto.uid
  42. else:
  43. uto = UidTokenObject(uidToken)
  44. uid = uto.UID
  45. LOGGING.info('消息推送-当前UID:{}'.format(uid))
  46. return uid
  47. @classmethod
  48. def query_uid_push(cls, uid, event_type):
  49. """
  50. 查询uid_set与push数据列表
  51. """
  52. if event_type != 606:
  53. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  54. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
  55. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  56. 'uid_set__channel', 'uid_set__ai_type', 'uid_set__new_detect_interval')
  57. else:
  58. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid). \
  59. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
  60. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  61. 'uid_set__channel', 'uid_set__ai_type', 'uid_set__new_detect_interval')
  62. return uid_push_qs
  63. @staticmethod
  64. def cache_uid_push(uid_push_qs):
  65. """
  66. 将uid_push 信息进行缓存
  67. @param uid_push_qs: uid_set & uid_push 列表对象
  68. @return: uid_set_list
  69. """
  70. uid_set_list = []
  71. for qs in uid_push_qs:
  72. uid_set_list.append(qs)
  73. # redis_obj.set_data(key=name, val=str(redis_list), expire=expire)
  74. return uid_set_list
  75. @staticmethod
  76. def cache_push_detect_interval(redis_obj, name, detect_interval, new_detect_interval):
  77. """
  78. 缓存设置推送消息的时间间隔
  79. @param redis_obj: redis对象
  80. @param name: redis key
  81. @param detect_interval: 原推送时间间隔
  82. @param new_detect_interval: 新推送时间间隔
  83. """
  84. if CONFIG_INFO != CONFIG_CN:
  85. detect_interval = new_detect_interval if new_detect_interval > 0 else detect_interval
  86. detect_interval = 60 if detect_interval < 60 else detect_interval
  87. redis_obj.set_data(key=name, val=1, expire=detect_interval - 5)
  88. LOGGING.info('消息推送-缓存设置APP推送间隔:{}s'.format(detect_interval))
  89. @classmethod
  90. def save_msg_push(cls, uid_set_push_list, **params):
  91. """
  92. APP消息推送以及报警消息存库
  93. @nickname 设备名称
  94. @channel 通道
  95. @event_type 事件类型
  96. """
  97. new_device_info_list = []
  98. sys_msg_list = []
  99. userID_ids = []
  100. kwag_args = params['kwag_args']
  101. code_data = {'do_apns_code': '', 'do_fcm_code': '', 'do_jpush_code': ''}
  102. local_date_time = ''
  103. push_permission = True
  104. try:
  105. params['event_tag'] = cls.get_event_tag(params['ai_type'], params['event_type'])
  106. for up in uid_set_push_list:
  107. appBundleId = up['appBundleId']
  108. token_val = up['token_val']
  109. lang = up['lang']
  110. tz = up['tz']
  111. if tz is None or tz == '':
  112. tz = 0
  113. # 发送标题
  114. msg_title = cls.get_msg_title(nickname=params['nickname'])
  115. # 发送内容
  116. msg_text = cls.get_msg_text(channel=params['channel'], n_time=params['n_time'], lang=lang,
  117. tz=tz, event_type=params['event_type'],
  118. electricity=params['electricity'], dealings_type=params['dealings_type'],
  119. ai_type=params['ai_type'])
  120. kwag_args['appBundleId'] = appBundleId
  121. kwag_args['token_val'] = token_val
  122. kwag_args['msg_title'] = msg_title
  123. kwag_args['msg_text'] = msg_text
  124. LOGGING.info('推送要的数据: {}'.format(kwag_args))
  125. local_date_time = CommonService.get_now_time_str(n_time=params['n_time'], tz=tz, lang='cn')
  126. LOGGING.info('<<<<<根据时区计算后日期={},时区={}'.format(local_date_time, tz))
  127. local_date_time = local_date_time[0:10]
  128. LOGGING.info('<<<<<切片后的日期={}'.format(local_date_time))
  129. # 以下是存库
  130. userID_id = up["userID_id"]
  131. if userID_id not in userID_ids:
  132. now_time = int(time.time())
  133. if params['is_sys_msg']:
  134. sys_msg_text = cls.get_msg_text(channel=params['channel'], n_time=params['n_time'], lang=lang,
  135. tz=tz,
  136. event_type=params['event_type'],
  137. electricity=params['electricity'],
  138. is_sys=1)
  139. sys_msg_list.append(SysMsgModel(userID_id=userID_id, msg=sys_msg_text, addTime=now_time,
  140. updTime=now_time, uid=params['uid'],
  141. eventType=params['event_type']))
  142. else:
  143. LOGGING.info('分表存数据start------')
  144. params['userID_id'] = userID_id
  145. # push_permission = DevicePushService.check_share_permission(userID_id,
  146. # params['channel'],params['uid'])
  147. new_device_info_list.append(cls.created_device_vo(local_date_time, **params))
  148. userID_ids.append(userID_id)
  149. params['appBundleId'] = appBundleId
  150. params['token_val'] = token_val
  151. params['lang'] = lang
  152. params['tz'] = tz
  153. params['kwag_args'] = kwag_args
  154. code_data = cls.send_app_msg_push(up['push_type'], **params)
  155. return {'code_date': code_data, 'new_device_info_list': new_device_info_list, 'sys_msg_list': sys_msg_list,
  156. 'local_date_time': local_date_time}
  157. except Exception as e:
  158. LOGGING.info('推送消息或存表异常: errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  159. @classmethod
  160. def get_event_tag(cls, ai_type, event_type):
  161. """
  162. 获取事件标签
  163. """
  164. if ai_type > 0:
  165. event_res = DEVICE_EVENT_TYPE.get(event_type, 0)
  166. if event_res > 0:
  167. return ',' + str(event_res) + ','
  168. event_type = cls.dec_to_bin(event_type)
  169. types = cls.get_combo_types(event_type)
  170. res = ','.join(types) + ','
  171. return ',' + res
  172. return ',' + str(event_type) + ','
  173. @classmethod
  174. def get_combo_types(cls, event_type):
  175. """
  176. 获取设备算法组合类型
  177. 51:移动侦测,52:传感器报警,53:影像遗失,54:PIR,55:门磁报警,56:外部发报,57:人型报警(提示:有人出现),58:车型,59:宠物,60:人脸,61:异响,
  178. 62:区域闯入,63:区域闯出,64:长时间无人检测,65:长时间无人检测,66:往来检测
  179. 0:代表空字符,702:摄像头休眠,703:摄像头唤醒,704:电量过低
  180. AWS AI识别 1:人形,2:车型,3:宠物,4:包裹。云端AI类型
  181. @param event_type:
  182. @return:
  183. """
  184. try:
  185. types = []
  186. combo_types = [51, 57, 58, 59, 60, 61,
  187. 62, 63, 64, 65, 66]
  188. event_type = str(event_type)
  189. len_type = len(event_type)
  190. for i in range(0, len_type):
  191. e_type = int(event_type[len_type - 1 - i])
  192. if e_type == 1:
  193. types.append(str(combo_types[i]))
  194. LOGGING.info('算法对照打印:{}'.format(combo_types))
  195. return types
  196. except Exception as e:
  197. print('推送错误异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  198. return event_type
  199. @staticmethod
  200. def dec_to_bin(num):
  201. """
  202. 十进制转二进制
  203. """
  204. result = ""
  205. while num != 0:
  206. ret = num % 2
  207. num //= 2
  208. result = str(ret) + result
  209. return result
  210. @classmethod
  211. def send_app_msg_push(cls, push_type, **param):
  212. """
  213. 发送app消息推送
  214. """
  215. try:
  216. kwargs = param['kwag_args']
  217. result = {'do_apns_code': '', 'do_fcm_code': '', 'do_jpush_code': '', 'do_xmpush_code': '',
  218. 'do_vivopush_code': '', 'do_meizupush_code': '', 'do_oppopush_code': ''}
  219. # 判断是否进行APP消息推送,如app_push不为空,则不进行推送
  220. if not param['app_push']:
  221. LOGGING.info('APP准备推送:{}, {}'.format(param['uid'], param))
  222. # 推送显示图片
  223. if (param['is_st'] == 1 or param['is_st'] == 3) and \
  224. (push_type == 0 or push_type == 1 or push_type == 3):
  225. if param['is_st'] == 1:
  226. key = '{}/{}/{}.jpeg'.format(param['uid'], param['channel'], param['n_time'])
  227. else:
  228. key = '{}/{}/{}_0.jpeg'.format(param['uid'], param['channel'], param['n_time'])
  229. push_thread = threading.Thread(target=cls.async_send_picture_push, args=(
  230. push_type, param['aws_s3_client'], param['bucket'], key, param['uid'], param['appBundleId'],
  231. param['token_val'], param['event_type'], param['n_time'],
  232. param['kwag_args']['msg_title'], param['kwag_args']['msg_text'], param['channel']))
  233. push_thread.start()
  234. else:
  235. if push_type == 0: # ios apns
  236. result['do_apns_code'] = cls.do_apns(**kwargs)
  237. elif push_type == 1: # android gcm
  238. result['do_fcm_code'] = cls.do_fcm(**kwargs)
  239. elif push_type == 2: # android jpush
  240. result['do_jpush_code'] = cls.do_jpush(**kwargs)
  241. elif push_type == 3:
  242. huawei_push_object = HuaweiPushObject()
  243. huawei_push_object.send_push_notify_message(**kwargs)
  244. elif push_type == 4: # android xmpush
  245. channel_id = 104551
  246. result['do_xmpush_code'] = cls.do_xmpush(channel_id=channel_id, **kwargs)
  247. elif push_type == 5: # android vivopush
  248. result['do_vivopush_code'] = PushObject.android_vivopush(**kwargs)
  249. elif push_type == 6: # android oppopush
  250. channel_id = 'DEVICE_REMINDER'
  251. result['do_oppopush_code'] = cls.do_oppopush(channel_id=channel_id, **kwargs)
  252. elif push_type == 7: # android meizupush
  253. result['do_meizupush_code'] = PushObject.android_meizupush(**kwargs)
  254. return result
  255. except Exception as e:
  256. LOGGING.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  257. return None
  258. @classmethod
  259. def save_sys_msg(cls, is_sys_msg, local_date_time, sys_msg_list, new_device_info_list):
  260. """
  261. 保存系统消息&设备推送消息存库
  262. """
  263. if is_sys_msg:
  264. SysMsgModel.objects.bulk_create(sys_msg_list)
  265. else:
  266. # new 分表批量存储 设备信息
  267. if new_device_info_list and len(new_device_info_list) > 0:
  268. # 根据日期获得星期几
  269. week = LocalDateTimeUtil.date_to_week(local_date_time)
  270. EquipmentInfoService.equipment_info_bulk_create(week, new_device_info_list)
  271. LOGGING.info('设备信息分表批量保存end------')
  272. return True
  273. @classmethod
  274. def created_device_vo(cls, local_date_time, **params):
  275. """
  276. 获取设备推送表对象
  277. """
  278. return EquipmentInfoService.get_equipment_info_obj(
  279. local_date_time,
  280. device_user_id=params['userID_id'],
  281. event_time=params['n_time'],
  282. event_type=params['event_type'],
  283. device_uid=params['uid'],
  284. device_nick_name=params['nickname'],
  285. channel=params['channel'],
  286. alarm='Motion \tChannel:{channel}'.format(channel=params['channel']),
  287. is_st=params['is_st'],
  288. receive_time=params['n_time'],
  289. add_time=int(time.time()),
  290. storage_location=params['storage_location'],
  291. border_coords='',
  292. event_tag=params['event_tag'],
  293. answer_status=True if params['dealings_type'] == 1 else False
  294. )
  295. @staticmethod
  296. def get_msg_title(nickname):
  297. """
  298. 获取消息标题
  299. """""
  300. return nickname
  301. @staticmethod
  302. def get_msg_text(channel, n_time, lang, tz, event_type, electricity='', is_sys=0, dealings_type=0,
  303. ai_type=0):
  304. """
  305. 获取消息文本
  306. """
  307. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  308. etype = int(event_type)
  309. if lang == 'cn':
  310. if etype == 704:
  311. msg_type = '剩余电量 ' + electricity
  312. elif etype == 702:
  313. msg_type = '摄像头休眠'
  314. elif etype == 703:
  315. msg_type = '摄像头唤醒'
  316. elif etype == 606:
  317. msg_type = '有人呼叫,请点击查看'
  318. elif ai_type > 0:
  319. if etype == 1024 and dealings_type == 1:
  320. msg_type = '有人进入'
  321. elif etype == 1024 and dealings_type == 2:
  322. msg_type = '有人离开'
  323. elif etype == 512:
  324. msg_type = '长时间无人出现'
  325. elif etype == 256:
  326. msg_type = '有人徘徊'
  327. elif etype == 128:
  328. msg_type = '区域离开'
  329. elif etype == 64:
  330. msg_type = '区域闯入'
  331. else:
  332. msg_type = ''
  333. else:
  334. msg_type = ''
  335. if is_sys:
  336. send_text = '{} 通道:{}'.format(msg_type, channel)
  337. else:
  338. send_text = '{} 通道:{} 日期:{}'.format(msg_type, channel, n_date)
  339. else:
  340. if etype == 704:
  341. msg_type = 'Battery remaining ' + electricity
  342. elif etype == 702:
  343. msg_type = 'Camera sleep'
  344. elif etype == 703:
  345. msg_type = 'Camera wake'
  346. elif etype == 606:
  347. msg_type = 'Someone is calling, please click to view'
  348. elif ai_type > 0:
  349. if etype == 1024 and int(dealings_type) == 1:
  350. msg_type = 'Someone entered'
  351. elif etype == 1024 and int(dealings_type) == 2:
  352. msg_type = 'Someone left'
  353. elif etype == 512:
  354. msg_type = 'No one shows up for a long time'
  355. elif etype == 256:
  356. msg_type = 'Someone wanders'
  357. elif etype == 128:
  358. msg_type = 'Area departure'
  359. elif etype == 64:
  360. msg_type = 'Area break-in'
  361. else:
  362. msg_type = ''
  363. else:
  364. msg_type = ''
  365. if is_sys:
  366. send_text = '{} channel:{}'.format(msg_type, channel)
  367. else:
  368. send_text = '{} channel:{} date:{}'.format(msg_type, channel, n_date)
  369. return send_text
  370. @staticmethod
  371. def do_jpush(uid, channel, appBundleId, token_val, event_type, n_time,
  372. msg_title, msg_text):
  373. """
  374. android 国内极光APP消息提醒推送
  375. """
  376. app_key = JPUSH_CONFIG[appBundleId]['Key']
  377. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  378. _jpush = jpush.JPush(app_key, master_secret)
  379. push = _jpush.create_push()
  380. push.audience = jpush.registration_id(token_val)
  381. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  382. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  383. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  384. big_text=msg_text, title=msg_title,
  385. extras=push_data)
  386. push.notification = jpush.notification(android=android)
  387. push.platform = jpush.all_
  388. res = push.send()
  389. print(res)
  390. return res.status_code
  391. @staticmethod
  392. def do_fcm(uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  393. """
  394. android 谷歌APP消息提醒推送
  395. """
  396. try:
  397. serverKey = FCM_CONFIG[appBundleId]
  398. except Exception as e:
  399. LOGGING.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  400. return 'serverKey abnormal'
  401. push_service = FCMNotification(api_key=serverKey)
  402. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  403. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  404. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  405. message_body=msg_text, data_message=data,
  406. extra_kwargs={
  407. 'default_vibrate_timings': True,
  408. 'default_sound': True,
  409. 'default_light_settings': True
  410. })
  411. return result
  412. @staticmethod
  413. def do_apns(uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  414. msg_text):
  415. """
  416. ios 消息提醒推送
  417. """
  418. LOGGING.info("进来do_apns函数了")
  419. LOGGING.info(token_val)
  420. LOGGING.info(APNS_MODE)
  421. LOGGING.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  422. try:
  423. cli = apns2.APNSClient(
  424. mode=APNS_MODE, client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  425. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  426. "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
  427. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  428. payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
  429. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  430. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  431. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  432. print(res.status_code)
  433. LOGGING.info("apns_推送状态:")
  434. LOGGING.info(res.status_code)
  435. if res.status_code == 200:
  436. return res.status_code
  437. else:
  438. print('apns push fail')
  439. print(res.reason)
  440. LOGGING.info('apns push fail')
  441. LOGGING.info(res.reason)
  442. return res.status_code
  443. except (ValueError, ArithmeticError):
  444. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  445. except Exception as e:
  446. print(repr(e))
  447. print('do_apns函数错误行号', e.__traceback__.tb_lineno)
  448. LOGGING.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  449. return repr(e)
  450. @staticmethod
  451. def do_xmpush(channel_id, uid, channel, appBundleId, token_val, event_type, n_time,
  452. msg_title, msg_text):
  453. """
  454. android 国内小米APP消息提醒推送
  455. """
  456. url = 'https://api.xmpush.xiaomi.com/v3/message/regid'
  457. app_secret = XMPUSH_CONFIG[appBundleId]
  458. # payload = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  459. # 'received_at': n_time, 'event_time': n_time, 'event_type': event_type,
  460. # 'uid': uid, 'channel': channel
  461. # }
  462. data = {
  463. 'title': msg_title,
  464. 'description': msg_text,
  465. 'payload': 'payload',
  466. 'restricted_package_name': appBundleId,
  467. 'registration_id': token_val,
  468. 'extra.channel_id': channel_id,
  469. 'extra.alert': 'Motion',
  470. 'extra.msg': '',
  471. 'extra.sound': 'sound.aif',
  472. 'extra.zpush': '1',
  473. 'extra.received_at': n_time,
  474. 'extra.event_time': n_time,
  475. 'extra.event_type': event_type,
  476. 'extra.uid': uid,
  477. 'extra.channel': channel,
  478. }
  479. headers = {
  480. 'Authorization': 'key={}'.format(app_secret)
  481. }
  482. response = requests.post(url, data=data, headers=headers)
  483. if response.status_code == 200:
  484. LOGGING.info('小米推送结果:{}'.format(response.json()))
  485. return response.json()
  486. @staticmethod
  487. def do_oppopush(channel_id, uid, channel, appBundleId, token_val, event_type, n_time,
  488. msg_title, msg_text):
  489. """
  490. android 国内oppo APP消息提醒推送
  491. """
  492. app_key = OPPOPUSH_CONFIG[appBundleId]['Key']
  493. master_secret = OPPOPUSH_CONFIG[appBundleId]['Secret']
  494. url = 'https://api.push.oppomobile.com/'
  495. now_time = str(round(time.time() * 1000))
  496. # 1、实例化一个sha256对象
  497. sha256 = hashlib.sha256()
  498. # 2、调用update方法进行加密
  499. sha256.update((app_key + now_time + master_secret).encode('utf-8'))
  500. # 3、调用hexdigest方法,获取加密结果
  501. sign = sha256.hexdigest()
  502. # 获取auth_token
  503. get_token_url = url + 'server/v1/auth'
  504. post_data = {
  505. 'app_key': app_key,
  506. 'sign': sign,
  507. 'timestamp': now_time
  508. }
  509. headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  510. response = requests.post(get_token_url, data=post_data, headers=headers)
  511. result = response.json()
  512. # 发送推送
  513. push_url = url + 'server/v1/message/notification/unicast'
  514. extra_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  515. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type,
  516. 'uid': uid, 'channel': channel}
  517. message = {
  518. "target_type": 2,
  519. "target_value": token_val,
  520. "notification": {
  521. "title": msg_title,
  522. "content": msg_text,
  523. 'channel_id': channel_id,
  524. 'action_parameters': extra_data,
  525. 'click_action_type': 1,
  526. 'click_action_activity': 'com.ansjer.zccloud_a.AJ_MainView.AJ_Home.AJMainActivity'
  527. }
  528. }
  529. push_data = {
  530. 'auth_token': result['data']['auth_token'],
  531. 'message': json.dumps(message)
  532. }
  533. response = requests.post(push_url, data=push_data, headers=headers)
  534. if response.status_code == 200:
  535. LOGGING.info("oppo推送返回值:{}".format(response.json()))
  536. return response.json()
  537. @classmethod
  538. def async_send_picture_push(cls, push_type, aws_s3_client, bucket, key, uid, appBundleId,
  539. token_val, event_type, n_time, msg_title, msg_text, channel):
  540. """
  541. 异步APP图片推送
  542. """
  543. try:
  544. image_url = aws_s3_client.generate_presigned_url('get_object',
  545. Params={'Bucket': bucket, 'Key': key},
  546. ExpiresIn=3600)
  547. LOGGING.info('推送图片url:{}'.format(image_url))
  548. if push_type == 0:
  549. PushObject.ios_apns_push(uid, appBundleId, token_val, n_time, event_type, msg_title, msg_text,
  550. uid, channel, image_url)
  551. elif push_type == 1:
  552. PushObject.android_fcm_push(uid, appBundleId, token_val, n_time, event_type, msg_title,
  553. msg_text, uid, channel, image_url)
  554. elif push_type == 3:
  555. huawei_push_object = HuaweiPushObject()
  556. huawei_push_object.send_push_notify_message(token_val=token_val, msg_title=msg_title, msg_text=msg_text,
  557. image_url=image_url)
  558. except Exception as e:
  559. LOGGING.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  560. @staticmethod
  561. def get_push_url(**params):
  562. """
  563. 获取推送URL,设备根本当前返回结果进行数据上传
  564. @return: re_data
  565. """
  566. re_data = {'code': 0, 'msg': 'success'}
  567. if params['is_st'] == 0 or params['is_st'] == 2:
  568. re_data['msg'] = 'success 0 or 2'
  569. for up in params['uid_set_push_list']:
  570. if up['push_type'] == 0: # ios apns
  571. up['do_apns_code'] = params['code_dict']['code_date']['do_apns_code']
  572. elif up['push_type'] == 1: # android gcm
  573. up['do_fcm_code'] = params['code_dict']['code_date']['do_fcm_code']
  574. elif up['push_type'] == 2: # android jpush
  575. up['do_jpush_code'] = params['code_dict']['code_date']['do_jpush_code']
  576. elif up['push_type'] == 4: # android jpush
  577. up['do_xmpush_code'] = params['code_dict']['code_date']['do_xmpush_code']
  578. elif up['push_type'] == 5: # android jpush
  579. up['do_vivopush_code'] = params['code_dict']['code_date']['do_vivopush_code']
  580. elif up['push_type'] == 7: # android jpush
  581. up['do_meizupush_code'] = params['code_dict']['code_date']['do_meizupush_code']
  582. del up['push_type']
  583. del up['userID_id']
  584. del up['userID__NickName']
  585. del up['lang']
  586. del up['tz']
  587. del up['uid_set__nickname']
  588. del up['uid_set__detect_interval']
  589. del up['uid_set__detect_group']
  590. re_data['re_list'] = params['uid_set_push_list']
  591. elif params['is_st'] == 1:
  592. key_name = '{uid}/{channel}/{filename}.jpeg' \
  593. .format(uid=params['uid'], channel=params['channel'], filename=params['n_time'])
  594. re_args = {'Key': key_name}
  595. if params['region'] == 2: # 2:国内
  596. re_args['Bucket'] = 'push'
  597. else: # 1:国外
  598. re_args['Bucket'] = 'foreignpush'
  599. response_url = DevicePushService.generate_s3_url(params['aws_s3_client'], re_args)
  600. re_data['img_push'] = response_url
  601. elif params['is_st'] == 3:
  602. img_url_list = []
  603. if params['region'] == 2: # 2:国内
  604. re_args = {'Bucket': 'push'}
  605. else: # 1:国外
  606. re_args = {'Bucket': 'foreignpush'}
  607. for i in range(params['is_st']):
  608. key_name = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  609. format(uid=params['uid'], channel=params['channel'], filename=params['n_time'], st=i)
  610. re_args['Key'] = key_name
  611. response_url = DevicePushService.generate_s3_url(params['aws_s3_client'], re_args)
  612. img_url_list.append(response_url)
  613. re_data['img_url_list'] = img_url_list
  614. re_data['msg'] = 'success 3'
  615. return re_data
  616. @staticmethod
  617. def generate_s3_url(aws_s3_client, params):
  618. """
  619. 获取S3对象URL
  620. """
  621. response_url = aws_s3_client.generate_presigned_url(
  622. ClientMethod='put_object',
  623. Params=params,
  624. ExpiresIn=3600
  625. )
  626. return response_url
  627. @staticmethod
  628. def check_share_permission(user_id, channel, uid):
  629. """
  630. 检查用户是否有权限接收设备报警推送
  631. """
  632. user_permission_qs = DeviceChannelUserSet.objects.filter(user_id=user_id, uid=uid) \
  633. .values('id', 'channels')
  634. # 根据当前用户与uid查询是否设置过通道权限,不存在则不是分享设备
  635. if not user_permission_qs.exists():
  636. return True
  637. up_id = user_permission_qs[0]['id']
  638. channels = user_permission_qs[0]['channels']
  639. channels_list = [int(val) for val in channels.split(',')]
  640. # 当前uid是属于分享设备并且设置了权限
  641. # 判断通道是否设置了权限,不存在则当前通道没有权限接受消息推送
  642. if int(channel) not in channels_list:
  643. return False
  644. permission_qs = DeviceSharePermission.objects.filter(code='AlarmMessages').values('id')
  645. p_id = permission_qs[0]['id']
  646. # 当前通道存在设置则查看是否有 消息推送权限
  647. channel_permission_qs = DeviceChannelUserPermission.objects \
  648. .filter(channel_user_id=up_id, permission_id=p_id) \
  649. .values('permission_id', 'channel_user_id')
  650. if not channel_permission_qs.exists():
  651. return False
  652. return True
  653. @classmethod
  654. def is_algorithm_type(cls, uid, event_type):
  655. """
  656. 判断是否是算法类型 62、63、64、65、66不限制推送
  657. """
  658. uid_set_qs = UidSetModel.objects.filter(uid=uid).values('ai_type')
  659. if not uid_set_qs.exists():
  660. return False
  661. if uid_set_qs[0]['ai_type'] == 0:
  662. return False
  663. event_types = [62, 63, 64, 65, 66]
  664. event_res = DEVICE_EVENT_TYPE.get(event_type, 0)
  665. if event_res in event_types:
  666. return True
  667. event_types2 = cls.get_combo_types(event_type)
  668. if not event_types2:
  669. return False
  670. c = [x for x in event_types if x in event_types2]
  671. return True if c else False