DevicePushService.py 33 KB

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