DevicePushService.py 33 KB

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