DevicePushService.py 39 KB

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