DevicePushService.py 40 KB

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