DevicePushService.py 33 KB

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