DevicePushService.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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 threading
  13. import time
  14. import boto3
  15. import botocore
  16. import requests
  17. from AnsjerPush.Config.aiConfig import DEVICE_EVENT_TYPE, ALGORITHM_COMBO_TYPES
  18. from AnsjerPush.config import CONFIG_INFO, CONFIG_CN, MULTI_CHANNEL_TYPE_LIST, SYS_EVENT_TYPE_LIST, AWS_ACCESS_KEY_ID, \
  19. AWS_SECRET_ACCESS_KEY, EVENT_DICT, EVENT_DICT_CN
  20. from AnsjerPush.config import XMPUSH_CONFIG, OPPOPUSH_CONFIG
  21. from Model.models import UidPushModel, SysMsgModel, DeviceSharePermission, DeviceChannelUserSet, \
  22. DeviceChannelUserPermission, UidSetModel, Device_Info
  23. from Object.ETkObject import ETkObject
  24. from Object.UidTokenObject import UidTokenObject
  25. from Object.utils import LocalDateTimeUtil
  26. from Service.CommonService import CommonService
  27. from Service.EquipmentInfoService import EquipmentInfoService
  28. from Service.HuaweiPushService.HuaweiPushService import HuaweiPushObject
  29. from Service.PushService import PushObject
  30. LOGGING = logging.getLogger('info')
  31. class DevicePushService:
  32. @staticmethod
  33. def decode_uid(etk, uidToken):
  34. """
  35. 解密UID,优先解密etk 否则判断uidToken
  36. """
  37. # 解密获取uid
  38. if etk:
  39. eto = ETkObject(etk)
  40. uid = eto.uid
  41. else:
  42. uto = UidTokenObject(uidToken)
  43. uid = uto.UID
  44. LOGGING.info('消息推送-当前UID:{}'.format(uid))
  45. return uid
  46. @staticmethod
  47. def judge_sys_msg(event_type):
  48. """
  49. 判断是否属于系统消息
  50. @param event_type: 事件类型
  51. @return: bool
  52. """
  53. if event_type in SYS_EVENT_TYPE_LIST:
  54. return True
  55. return False
  56. @staticmethod
  57. def get_s3_client(region):
  58. """
  59. 根据地区获取S3 client
  60. @param region: 地区,1:国外, 2:国内
  61. @return: aws_s3_client
  62. """
  63. if int(region) == 1:
  64. aws_s3_client = boto3.client(
  65. 's3',
  66. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  67. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  68. config=botocore.client.Config(signature_version='s3v4'),
  69. region_name='us-east-1'
  70. )
  71. else:
  72. aws_s3_client = boto3.client(
  73. 's3',
  74. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  75. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  76. config=botocore.client.Config(signature_version='s3v4'),
  77. region_name='cn-northwest-1'
  78. )
  79. return aws_s3_client
  80. @classmethod
  81. def query_uid_push(cls, uid, event_type):
  82. """
  83. 查询uid_push和uid_set数据
  84. @param uid: uid
  85. @param event_type: 事件类型
  86. @return: uid_push_qs
  87. """
  88. if event_type not in [606, 607]:
  89. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  90. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
  91. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  92. 'uid_set__channel', 'uid_set__ai_type', 'uid_set__device_type', 'uid_set__new_detect_interval',
  93. 'uid_set__msg_notify')
  94. else:
  95. # 一键通话只推主用户
  96. device_info_qs = Device_Info.objects.filter(UID=uid).values('vodPrimaryUserID')
  97. primary_user_id = device_info_qs[0]['vodPrimaryUserID']
  98. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, userID_id=primary_user_id). \
  99. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
  100. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  101. 'uid_set__channel', 'uid_set__ai_type', 'uid_set__device_type', 'uid_set__new_detect_interval',
  102. 'uid_set__msg_notify', 'jg_token_val')
  103. return uid_push_qs
  104. @staticmethod
  105. def qs_to_list(qs):
  106. """
  107. qs对象转存列表
  108. @param qs: query set对象
  109. @return: qs_list
  110. """
  111. qs_list = []
  112. for i in qs:
  113. qs_list.append(i)
  114. return qs_list
  115. @staticmethod
  116. def cache_push_detect_interval(redis_obj, name, detect_interval, new_detect_interval):
  117. """
  118. 缓存设置推送消息的时间间隔
  119. @param redis_obj: redis对象
  120. @param name: redis key
  121. @param detect_interval: 原推送时间间隔
  122. @param new_detect_interval: 新推送时间间隔
  123. """
  124. if CONFIG_INFO != CONFIG_CN:
  125. detect_interval = new_detect_interval if new_detect_interval > 0 else detect_interval
  126. detect_interval = 60 if detect_interval < 60 else detect_interval
  127. redis_obj.set_data(key=name, val=1, expire=detect_interval - 5)
  128. @classmethod
  129. def save_msg_push(cls, uid_set_push_list, **params):
  130. """
  131. 推送消息,返回推送数据列表
  132. @param uid_set_push_list: redis对象
  133. @param params: 推送参数
  134. @return: dict
  135. """
  136. LOGGING.info('uid_set_push_list:{}'.format(uid_set_push_list))
  137. new_device_info_list = []
  138. sys_msg_list = []
  139. userID_ids = []
  140. kwag_args = params['kwag_args']
  141. code_data = {'do_apns_code': '', 'do_fcm_code': '', 'do_jpush_code': ''}
  142. local_date_time = ''
  143. # push_permission = True
  144. try:
  145. params['event_tag'] = cls.get_event_tag(params['ai_type'], params['event_type'], params['detection'])
  146. is_app_push = True if params['event_tag'] in [606, 607] else \
  147. cls.is_send_app_push(params['event_type'], params['event_tag'], params['app_push_config'])
  148. for up in uid_set_push_list:
  149. appBundleId = up['appBundleId']
  150. token_val = up['token_val']
  151. lang = up['lang']
  152. tz = up['tz']
  153. if tz is None or tz == '':
  154. tz = 0
  155. # 发送标题
  156. msg_title = cls.get_msg_title(nickname=params['nickname'])
  157. # 发送内容
  158. msg_text = cls.get_msg_text(channel=params['channel'], n_time=params['n_time'], lang=lang, tz=tz,
  159. event_type=params['event_type'], ai_type=params['ai_type'],
  160. device_type=params['device_type'], electricity=params['electricity'],
  161. dealings_type=params['dealings_type'], event_tag=params['event_tag']
  162. )
  163. kwag_args['appBundleId'] = appBundleId
  164. kwag_args['token_val'] = token_val
  165. kwag_args['msg_title'] = msg_title
  166. kwag_args['msg_text'] = msg_text
  167. if params['event_type'] in [606, 607] and up['push_type'] in [5, 6]:
  168. kwag_args['jg_token_val'] = up['jg_token_val']
  169. else:
  170. if 'jg_token_val' in kwag_args:
  171. kwag_args.pop('jg_token_val')
  172. local_date_time = CommonService.get_now_time_str(n_time=params['n_time'], tz=tz, lang='cn')
  173. local_date_time = local_date_time[0:10]
  174. # 以下是存库
  175. userID_id = up["userID_id"]
  176. if userID_id not in userID_ids:
  177. now_time = int(time.time())
  178. if params['is_sys_msg']:
  179. sys_msg_text = cls.get_msg_text(channel=params['channel'], n_time=params['n_time'], lang=lang,
  180. tz=tz, is_sys=1, device_type=params['device_type'],
  181. event_type=params['event_type'],
  182. electricity=params['electricity'],
  183. )
  184. sys_msg_list.append(SysMsgModel(userID_id=userID_id, msg=sys_msg_text, addTime=now_time,
  185. updTime=now_time, uid=params['uid'],
  186. eventType=params['event_type']))
  187. else:
  188. params['userID_id'] = userID_id
  189. # push_permission = DevicePushService.check_share_permission(userID_id,
  190. # params['channel'],params['uid'])
  191. new_device_info_list.append(cls.created_device_vo(local_date_time, **params))
  192. userID_ids.append(userID_id)
  193. params['appBundleId'] = appBundleId
  194. params['token_val'] = token_val
  195. params['lang'] = lang
  196. params['tz'] = tz
  197. params['kwag_args'] = kwag_args
  198. code_data = cls.send_app_msg_push(up['push_type'], **params) if is_app_push else code_data
  199. return {'code_date': code_data, 'new_device_info_list': new_device_info_list, 'sys_msg_list': sys_msg_list,
  200. 'local_date_time': local_date_time}
  201. except Exception as e:
  202. LOGGING.info('推送消息或存表异常: errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  203. @classmethod
  204. def get_event_tag(cls, ai_type, event_type, detection=0):
  205. """
  206. 获取事件标签
  207. """
  208. algorithm = False
  209. if ai_type > 0 and detection == 1:
  210. algorithm = True
  211. elif (ai_type == 7 and event_type <= 7) or (ai_type == 47 and event_type <= 47) or (detection == 1):
  212. algorithm = True
  213. if not algorithm:
  214. return ',' + str(event_type) + ','
  215. event_res = DEVICE_EVENT_TYPE.get(event_type, 0)
  216. if event_res > 0:
  217. return ',' + str(event_res) + ','
  218. event_type = cls.dec_to_bin(event_type)
  219. types = cls.get_combo_types(event_type)
  220. res = ','.join(types) + ','
  221. return ',' + res
  222. @classmethod
  223. def get_combo_types(cls, event_type):
  224. """
  225. 获取设备算法组合类型
  226. 51:移动侦测,52:传感器报警,53:影像遗失,54:PIR,55:门磁报警,56:外部发报,57:人型报警(提示:有人出现),58:车型,59:宠物,60:人脸,61:异响,
  227. 62:区域闯入,63:区域闯出,64:长时间无人检测,65:长时间无人检测,66:往来检测,67:哭声检测,68:手势检测,69:火焰检测
  228. 0:代表空字符,702:摄像头休眠,703:摄像头唤醒,704:电量过低
  229. AWS AI识别 1:人形,2:车型,3:宠物,4:包裹。云端AI类型
  230. """
  231. try:
  232. types = []
  233. event_type = str(event_type)
  234. len_type = len(event_type)
  235. for i in range(len_type):
  236. e_type = event_type[len_type - 1 - i]
  237. if e_type == '1':
  238. types.append(str(ALGORITHM_COMBO_TYPES[i]))
  239. LOGGING.info('算法对照打印:{}'.format(ALGORITHM_COMBO_TYPES))
  240. return types
  241. except Exception as e:
  242. print('推送错误异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  243. return event_type
  244. @staticmethod
  245. def dec_to_bin(num):
  246. """
  247. 十进制转二进制
  248. """
  249. result = ""
  250. while num != 0:
  251. ret = num % 2
  252. num //= 2
  253. result = str(ret) + result
  254. return result
  255. @classmethod
  256. def send_app_msg_push(cls, push_type, **param):
  257. """
  258. 发送app消息推送
  259. """
  260. try:
  261. kwargs = param['kwag_args']
  262. result = {'do_apns_code': '', 'do_fcm_code': '', 'do_jpush_code': '', 'do_xmpush_code': '',
  263. 'do_vivopush_code': '', 'do_meizupush_code': '', 'do_oppopush_code': ''}
  264. # 判断是否进行APP消息推送,如app_push不为空,则不进行推送
  265. if not param['app_push']:
  266. LOGGING.info('APP准备推送:{}, {}'.format(param['uid'], param))
  267. # is_st为1或3,且推送类型为apns,gcm,华为,异步推送图片
  268. if (param['is_st'] == 1 or param['is_st'] == 3) and \
  269. (push_type == 0 or push_type == 1 or push_type == 3):
  270. if param['is_st'] == 1:
  271. key = '{}/{}/{}.jpeg'.format(param['uid'], param['channel'], param['n_time'])
  272. else:
  273. key = '{}/{}/{}_0.jpeg'.format(param['uid'], param['channel'], param['n_time'])
  274. push_thread = threading.Thread(target=cls.async_send_picture_push, args=(
  275. push_type, param['aws_s3_client'], param['bucket'], key,
  276. param['uid'], param['appBundleId'], param['token_val'], param['event_type'], param['n_time'],
  277. param['kwag_args']['msg_title'], param['kwag_args']['msg_text'], param['channel']))
  278. push_thread.start()
  279. # 不推图
  280. else:
  281. if push_type == 0: # ios apns
  282. result['do_apns_code'] = PushObject.ios_apns_push(param['uid'], param['appBundleId'],
  283. param['token_val'], param['n_time'],
  284. param['event_type'],
  285. param['kwag_args']['msg_title'],
  286. param['kwag_args']['msg_text'],
  287. param['uid'], param['channel'])
  288. elif push_type == 1: # android gcm
  289. result['do_fcm_code'] = PushObject.android_fcm_push(param['uid'], param['appBundleId'],
  290. param['token_val'], param['n_time'],
  291. param['event_type'],
  292. param['kwag_args']['msg_title'],
  293. param['kwag_args']['msg_text'],
  294. param['uid'], param['channel'])
  295. elif push_type == 2: # android jpush
  296. result['do_jpush_code'] = PushObject.android_jpush(param['uid'], param['appBundleId'],
  297. param['token_val'], param['n_time'],
  298. param['event_type'],
  299. param['kwag_args']['msg_title'],
  300. param['kwag_args']['msg_text'])
  301. elif push_type == 3:
  302. huawei_push_object = HuaweiPushObject()
  303. huawei_push_object.send_push_notify_message(**kwargs)
  304. elif push_type == 4: # android xmpush
  305. channel_id = 104551
  306. result['do_xmpush_code'] = cls.do_xmpush(channel_id=channel_id, **kwargs)
  307. elif push_type == 5: # android vivopush
  308. result['do_vivopush_code'] = PushObject.android_vivopush(**kwargs)
  309. elif push_type == 6: # android oppopush
  310. channel_id = 'DEVICE_REMINDER'
  311. result['do_oppopush_code'] = cls.do_oppopush(channel_id=channel_id, **kwargs)
  312. elif push_type == 7: # android meizupush
  313. result['do_meizupush_code'] = PushObject.android_meizupush(**kwargs)
  314. return result
  315. except Exception as e:
  316. LOGGING.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  317. return None
  318. @classmethod
  319. def save_sys_msg(cls, is_sys_msg, local_date_time, sys_msg_list, new_device_info_list):
  320. """
  321. 保存系统消息&设备推送消息存库
  322. """
  323. if is_sys_msg:
  324. SysMsgModel.objects.bulk_create(sys_msg_list)
  325. else:
  326. # new 分表批量存储 设备信息
  327. if new_device_info_list and len(new_device_info_list) > 0:
  328. # 根据日期获得星期几
  329. week = LocalDateTimeUtil.date_to_week(local_date_time)
  330. EquipmentInfoService.equipment_info_bulk_create(week, new_device_info_list)
  331. return True
  332. @classmethod
  333. def created_device_vo(cls, local_date_time, **params):
  334. """
  335. 获取设备推送表对象
  336. """
  337. return EquipmentInfoService.get_equipment_info_obj(
  338. local_date_time,
  339. device_user_id=params['userID_id'],
  340. event_time=params['n_time'],
  341. event_type=params['event_type'],
  342. device_uid=params['uid'],
  343. device_nick_name=params['nickname'],
  344. channel=params['channel'],
  345. alarm='Motion \tChannel:{channel}'.format(channel=params['channel']),
  346. is_st=params['is_st'],
  347. receive_time=params['n_time'],
  348. add_time=int(time.time()),
  349. storage_location=params['storage_location'],
  350. border_coords='',
  351. event_tag=params['event_tag'],
  352. answer_status=True if params['dealings_type'] == 1 else False
  353. )
  354. @staticmethod
  355. def get_msg_title(nickname):
  356. """
  357. 获取消息标题
  358. """""
  359. return nickname
  360. @staticmethod
  361. def get_event_type_text(lang, event_type, dealings_type):
  362. """
  363. 事件类型文案键值查找
  364. """
  365. if lang == 'cn':
  366. if event_type in EVENT_DICT_CN:
  367. if isinstance(EVENT_DICT_CN[event_type], dict):
  368. msg_type = EVENT_DICT_CN[event_type][dealings_type]
  369. else:
  370. msg_type = EVENT_DICT_CN[event_type]
  371. else:
  372. msg_type = '未知事件类型 '
  373. return msg_type
  374. else:
  375. if event_type in EVENT_DICT:
  376. if isinstance(EVENT_DICT[event_type], dict):
  377. msg_type = EVENT_DICT[event_type][dealings_type]
  378. else:
  379. msg_type = EVENT_DICT[event_type]
  380. else:
  381. msg_type = 'Unknown event type'
  382. return msg_type
  383. @staticmethod
  384. def get_msg_text(channel, n_time, lang, tz, event_type, electricity='', is_sys=0, dealings_type=0, ai_type=0,
  385. device_type=0, event_tag=''):
  386. """
  387. 获取消息文本
  388. @param: channel 通道号
  389. @param: n_time 触发事件
  390. @param: lang 语言
  391. @param: tz 时区
  392. @param: event_type 事件类型
  393. @param: electricity 电量
  394. @param: is_sys 是否系统消息
  395. @param: dealings_type 往来类型 1 进 1 离开
  396. @param: ai_type 设备本地AI只能算法 事件类型
  397. @param: device_type 设备类型
  398. @param: event_tag 设备算法事件标签
  399. """
  400. msg_type = ''
  401. event_type = int(event_type)
  402. device_type = int(device_type)
  403. event_list = []
  404. if event_tag:
  405. event_list = [int(event) for event in event_tag.split(',') if event]
  406. if lang == 'cn':
  407. if event_type == 51:
  408. msg_type = '检测到画面变化'
  409. elif event_type == 57:
  410. msg_type = '有人出现'
  411. elif event_type == 58:
  412. msg_type = '有车出现'
  413. elif event_type == 59:
  414. msg_type = '有宠物出现'
  415. elif event_type == 60:
  416. msg_type = '发现人脸'
  417. elif event_type == 61:
  418. msg_type = '有异响'
  419. elif event_type == 62:
  420. msg_type = '区域闯入'
  421. elif event_type == 63:
  422. msg_type = '区域闯出'
  423. elif event_type == 64:
  424. msg_type = '有人徘徊'
  425. elif event_type == 65:
  426. msg_type = '长时间无人出现'
  427. elif event_type == 704:
  428. msg_type = '剩余电量 ' + electricity
  429. elif event_type == 702:
  430. msg_type = '摄像头休眠'
  431. elif event_type == 703:
  432. msg_type = '摄像头唤醒'
  433. elif event_type == 606:
  434. msg_type = '有人呼叫,请点击查看'
  435. elif ai_type > 0 and event_list:
  436. msg_type = ''.join([DevicePushService.get_event_type_text(lang, item, dealings_type)
  437. for item in event_list])
  438. if is_sys:
  439. if device_type in MULTI_CHANNEL_TYPE_LIST:
  440. send_text = '{} 通道:{}'.format(msg_type, channel)
  441. else:
  442. send_text = msg_type
  443. else:
  444. if device_type in MULTI_CHANNEL_TYPE_LIST:
  445. send_text = '{} 通道:{}'.format(msg_type, channel)
  446. else:
  447. send_text = '{}'.format(msg_type)
  448. else:
  449. if event_type == 51:
  450. msg_type = 'Screen change detected'
  451. elif event_type == 57:
  452. msg_type = 'Person detected'
  453. elif event_type == 58:
  454. msg_type = 'Vehicle detected'
  455. elif event_type == 59:
  456. msg_type = 'Pet detected'
  457. elif event_type == 60:
  458. msg_type = 'Human face detected'
  459. elif event_type == 61:
  460. msg_type = 'Abnormal sound detected'
  461. elif event_type == 62:
  462. msg_type = 'Intrusion detected in the area'
  463. elif event_type == 63:
  464. msg_type = 'Area vacated'
  465. elif event_type == 64:
  466. msg_type = 'Loitering detected'
  467. elif event_type == 65:
  468. msg_type = 'No appearance for a long time'
  469. elif event_type == 704:
  470. msg_type = 'Battery remaining ' + electricity
  471. elif event_type == 702:
  472. msg_type = 'Camera sleep'
  473. elif event_type == 703:
  474. msg_type = 'Camera wake'
  475. elif event_type == 606:
  476. msg_type = 'Someone is calling, please click to view'
  477. elif ai_type > 0 and event_list:
  478. msg_type = ''.join([DevicePushService.get_event_type_text(lang, item, dealings_type)
  479. for item in event_list])
  480. if is_sys:
  481. if device_type in MULTI_CHANNEL_TYPE_LIST:
  482. send_text = '{} channel:{}'.format(msg_type, channel)
  483. else:
  484. send_text = msg_type
  485. else:
  486. if device_type in MULTI_CHANNEL_TYPE_LIST:
  487. send_text = '{} channel:{}'.format(msg_type, channel)
  488. else:
  489. send_text = '{}'.format(msg_type)
  490. return send_text
  491. @staticmethod
  492. def do_xmpush(channel_id, uid, channel, appBundleId, token_val, event_type, n_time,
  493. msg_title, msg_text):
  494. """
  495. android 国内小米APP消息提醒推送
  496. """
  497. url = 'https://api.xmpush.xiaomi.com/v3/message/regid'
  498. app_secret = XMPUSH_CONFIG[appBundleId]
  499. # payload = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  500. # 'received_at': n_time, 'event_time': n_time, 'event_type': event_type,
  501. # 'uid': uid, 'channel': channel
  502. # }
  503. data = {
  504. 'title': msg_title,
  505. 'description': msg_text,
  506. 'payload': 'payload',
  507. 'restricted_package_name': appBundleId,
  508. 'registration_id': token_val,
  509. 'extra.channel_id': channel_id,
  510. 'extra.alert': 'Motion',
  511. 'extra.msg': '',
  512. 'extra.sound': 'sound.aif',
  513. 'extra.zpush': '1',
  514. 'extra.received_at': n_time,
  515. 'extra.event_time': n_time,
  516. 'extra.event_type': event_type,
  517. 'extra.uid': uid,
  518. 'extra.channel': channel,
  519. }
  520. headers = {
  521. 'Authorization': 'key={}'.format(app_secret)
  522. }
  523. response = requests.post(url, data=data, headers=headers)
  524. if response.status_code == 200:
  525. LOGGING.info('uid为{},小米推送结果:{}'.format(uid, response.json()))
  526. return response.json()
  527. @staticmethod
  528. def do_oppopush(channel_id, uid, channel, appBundleId, token_val, event_type, n_time,
  529. msg_title, msg_text, jg_token_val=''):
  530. """
  531. android 国内oppo APP消息提醒推送
  532. """
  533. app_key = OPPOPUSH_CONFIG[appBundleId]['Key']
  534. master_secret = OPPOPUSH_CONFIG[appBundleId]['Secret']
  535. url = 'https://api.push.oppomobile.com/'
  536. now_time = str(round(time.time() * 1000))
  537. # 1、实例化一个sha256对象
  538. sha256 = hashlib.sha256()
  539. # 2、调用update方法进行加密
  540. sha256.update((app_key + now_time + master_secret).encode('utf-8'))
  541. # 3、调用hexdigest方法,获取加密结果
  542. sign = sha256.hexdigest()
  543. # 获取auth_token
  544. get_token_url = url + 'server/v1/auth'
  545. post_data = {
  546. 'app_key': app_key,
  547. 'sign': sign,
  548. 'timestamp': now_time
  549. }
  550. headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  551. response = requests.post(get_token_url, data=post_data, headers=headers)
  552. result = response.json()
  553. # 发送推送
  554. push_url = url + 'server/v1/message/notification/unicast'
  555. extra_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  556. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type,
  557. 'uid': uid, 'channel': channel}
  558. message = {
  559. "target_type": 2,
  560. "target_value": token_val,
  561. "notification": {
  562. "title": msg_title,
  563. "content": msg_text,
  564. 'channel_id': channel_id,
  565. 'action_parameters': extra_data,
  566. 'click_action_type': 4,
  567. 'click_action_activity': 'com.ansjer.zccloud_a.AJ_MainView.AJ_Home.AJMainActivity'
  568. }
  569. }
  570. push_data = {
  571. 'auth_token': result['data']['auth_token'],
  572. 'message': json.dumps(message)
  573. }
  574. response = requests.post(push_url, data=push_data, headers=headers)
  575. if response.status_code == 200:
  576. LOGGING.info("oppo推送返回值:{},uid:{},time:{},event:{}".format(response.json(), uid, now_time, event_type))
  577. if event_type == 606 or event_type == '606':
  578. PushObject.jpush_transparent_transmission(msg_title, msg_text, appBundleId, jg_token_val, extra_data)
  579. return response.json()
  580. @classmethod
  581. def async_send_picture_push(cls, push_type, aws_s3_client, bucket, key, uid, appBundleId,
  582. token_val, event_type, n_time, msg_title, msg_text, channel):
  583. """
  584. 异步APP图片推送
  585. """
  586. try:
  587. image_url = aws_s3_client.generate_presigned_url('get_object',
  588. Params={'Bucket': bucket, 'Key': key},
  589. ExpiresIn=3600)
  590. LOGGING.info('推送图片url:{}'.format(image_url))
  591. if push_type == 0:
  592. PushObject.ios_apns_push(uid, appBundleId, token_val, n_time, event_type, msg_title, msg_text,
  593. uid, channel, image_url)
  594. elif push_type == 1:
  595. PushObject.android_fcm_push(uid, appBundleId, token_val, n_time, event_type, msg_title,
  596. msg_text, uid, channel, image_url)
  597. elif push_type == 3:
  598. huawei_push_object = HuaweiPushObject()
  599. huawei_push_object.send_push_notify_message(token_val=token_val, msg_title=msg_title, msg_text=msg_text,
  600. uid=uid, event_type=event_type, n_time=n_time,
  601. image_url=image_url)
  602. except Exception as e:
  603. LOGGING.info('图片推送异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  604. @staticmethod
  605. def get_push_url(**params):
  606. """
  607. 获取推送URL,设备根本当前返回结果进行数据上传
  608. @return: re_data
  609. """
  610. re_data = {'code': 0, 'msg': 'success'}
  611. if params['is_st'] == 0 or params['is_st'] == 2:
  612. re_data['msg'] = 'success 0 or 2'
  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
  695. @staticmethod
  696. def is_send_app_push(event_type, event_tag, app_push_config):
  697. """
  698. 是否进行APP消息提醒
  699. @return: True|False
  700. """
  701. try:
  702. if not app_push_config:
  703. return True
  704. is_push = app_push_config['appPush']
  705. if is_push != 1: # 1:进行APP提醒,其它则不执行APP提醒
  706. return False
  707. all_day = app_push_config['pushTime']['allDay']
  708. # 允许设备类型APP提醒列表
  709. app_event_types = app_push_config['eventTypes']['device']
  710. if all_day == 0: # 1:全天提醒,0:自定义时间提醒
  711. push_time_config = app_push_config['pushTime']
  712. # 计算当前时间是否在自定义消息提醒范围内
  713. if not DevicePushService.is_push_notify_allowed_now(push_time_config):
  714. LOGGING.info('APP推送提醒不在自定义时间内:{}'.format(push_time_config))
  715. return False
  716. # APP接收提醒,判断识别类型是否勾选提醒
  717. push_result = DevicePushService.is_type_push(event_type, event_tag, app_event_types)
  718. LOGGING.info('APP推送提醒是否执行:{}'.format(push_result))
  719. return push_result
  720. except Exception as e:
  721. LOGGING.info('判断是否执行APP推送异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  722. return True
  723. @staticmethod
  724. def is_type_push(event_type, event_tag, app_event_types):
  725. # 检查事件标签和应用事件类型是否都存在
  726. if event_tag and app_event_types:
  727. # 将事件标签按逗号分割成列表,并转换为整数类型
  728. tag_list = [int(event) for event in event_tag.split(',') if event]
  729. # 判断是否有任一标签允许应用提醒
  730. return any(item in app_event_types for item in tag_list)
  731. # 检查事件类型和用户所选事件类型是否都存在,并判断事件类型在用户所选事件类型列表中
  732. return event_type and app_event_types and event_type in app_event_types
  733. @staticmethod
  734. def is_push_notify_allowed_now(push_time_config):
  735. """
  736. 判断当前时间是否在允许APP推送提醒
  737. """
  738. now_time = int(time.time())
  739. start_time = push_time_config['startTime']
  740. end_time = push_time_config['endTime']
  741. repeat = push_time_config['repeat']
  742. tz = push_time_config['timeZone']
  743. # 获取当前日期和周几
  744. now_date, week = DevicePushService.get_now_date_and_week(now_time, tz)
  745. # 判断是否在重复日范围内
  746. if not DevicePushService.is_repeated(week, repeat):
  747. return False
  748. # 计算当前日期在一天中的秒数
  749. seconds = LocalDateTimeUtil.convert_time_to_seconds(now_date)
  750. # 判断是否在APP推送提醒范围内
  751. return DevicePushService.is_in_effect(start_time, end_time, seconds)
  752. @staticmethod
  753. def is_in_effect(start, end, now_seconds):
  754. """
  755. 判断是否在提醒时间范围内
  756. @params: 开始时间秒
  757. @params: 结束时间秒
  758. @params: 当前时间秒
  759. @return: 当前时间是在范围内返回True 否则False
  760. """
  761. if start < end:
  762. return start <= now_seconds <= end
  763. else:
  764. return start <= now_seconds or now_seconds <= end
  765. @staticmethod
  766. def is_repeated(week_day, repeat_day):
  767. """
  768. 判断是否重复日
  769. @params: week_day 周几
  770. @params: 重复日1-127
  771. @return: 如果当前日期在重复日则返回True否则False
  772. """
  773. # 判断对应位置上的值是否为 1
  774. is_repeat = (repeat_day >> (week_day - 1)) & 1 == 1
  775. return is_repeat
  776. @staticmethod
  777. def get_now_date_and_week(now_time, tz):
  778. now_data = CommonService.get_now_time_str(now_time, tz, 'cn')
  779. week = LocalDateTimeUtil.date_to_week(now_data)
  780. return now_data, week