DevicePushService.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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 datetime
  10. import hashlib
  11. import json
  12. import logging
  13. import threading
  14. import time
  15. import boto3
  16. import botocore
  17. import oss2
  18. import requests
  19. from obs import ObsClient
  20. from AnsjerPush.Config.aiConfig import DEVICE_EVENT_TYPE, ALGORITHM_COMBO_TYPES
  21. from AnsjerPush.config import CONFIG_INFO, CONFIG_CN, MULTI_CHANNEL_TYPE_LIST, SYS_EVENT_TYPE_LIST, AWS_ACCESS_KEY_ID, \
  22. AWS_SECRET_ACCESS_KEY, EVENT_DICT, EVENT_DICT_CN, CONFIG_TEST, HUAWEICLOUD_AK, HUAWEICLOUD_SK, \
  23. HUAWEICLOUD_OBS_SERVER, HUAWEICLOUD_PUSH_BUKET, OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET
  24. from AnsjerPush.config import XMPUSH_CONFIG, OPPOPUSH_CONFIG, XM_PUSH_CHANNEL_ID, XM_PUSH_CHANNEL_DICT
  25. from Model.models import UidPushModel, SysMsgModel, DeviceSharePermission, DeviceChannelUserSet, \
  26. DeviceChannelUserPermission, UidSetModel, Device_Info, UserAudioVideoPush, PushLog
  27. from Object.ETkObject import ETkObject
  28. from Object.OCIObjectStorage import OCIObjectStorage
  29. from Object.UidTokenObject import UidTokenObject
  30. from Object.enums.ConstantEnum import ConstantEnum
  31. from Object.enums.EventTypeEnum import EventTypeEnumObj
  32. from Object.utils import LocalDateTimeUtil
  33. from Service.CommonService import CommonService
  34. from Service.EquipmentInfoService import EquipmentInfoService, EQUIPMENT_INFO_DICT
  35. from Service.HuaweiPushService.HuaweiPushService import HuaweiPushObject
  36. from Service.PushService import PushObject
  37. from django.db import close_old_connections
  38. from Service.VSeesHuaweiPushService.VseesHuaweiPushObject import VseesHuaweiPushObject
  39. LOGGING = logging.getLogger('info')
  40. TIME_LOGGER = logging.getLogger('time')
  41. ERROR_INFO_LOGGER = logging.getLogger('error_info')
  42. class DevicePushService:
  43. @staticmethod
  44. def decode_uid(etk, uidToken):
  45. """
  46. 解密UID,优先解密etk 否则判断uidToken
  47. """
  48. # 解密获取uid
  49. if etk:
  50. eto = ETkObject(etk)
  51. uid = eto.uid
  52. else:
  53. uto = UidTokenObject(uidToken)
  54. uid = uto.UID
  55. return uid
  56. @staticmethod
  57. def judge_sys_msg(event_type):
  58. """
  59. 判断是否属于系统消息
  60. @param event_type: 事件类型
  61. @return: bool
  62. """
  63. if event_type in SYS_EVENT_TYPE_LIST:
  64. return True
  65. return False
  66. @staticmethod
  67. def get_s3_client(region):
  68. """
  69. 根据地区获取S3 client
  70. @param region: 地区,1:国外, 2:国内
  71. @return: aws_s3_client
  72. """
  73. if int(region) == 1:
  74. aws_s3_client = boto3.client(
  75. 's3',
  76. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  77. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  78. config=botocore.client.Config(signature_version='s3v4'),
  79. region_name='us-east-1'
  80. )
  81. else:
  82. aws_s3_client = boto3.client(
  83. 's3',
  84. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  85. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  86. config=botocore.client.Config(signature_version='s3v4'),
  87. region_name='cn-northwest-1'
  88. )
  89. return aws_s3_client
  90. @classmethod
  91. def query_uid_push(cls, uid, event_type, button='1'):
  92. """
  93. 查询uid_push和uid_set数据
  94. @param uid: uid
  95. @param event_type: 事件类型
  96. @param button: 按钮
  97. @return: uid_push_qs
  98. """
  99. if event_type not in [606, 607]:
  100. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1) \
  101. .exclude(token_val='0'). \
  102. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
  103. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  104. 'uid_set__channel', 'uid_set__ai_type', 'uid_set__device_type', 'uid_set__new_detect_interval',
  105. 'uid_set__msg_notify')
  106. else:
  107. # 一键通话只推主用户
  108. device_info_qs = Device_Info.objects.filter(UID=uid).values('vodPrimaryUserID')
  109. primary_user_id = device_info_qs[0]['vodPrimaryUserID']
  110. if event_type == 607: # 音视频通话根据用户按钮来推送
  111. button_qs = UserAudioVideoPush.objects.filter(uid=uid).values('buttonUser1', 'buttonUser2')
  112. if button_qs.exists():
  113. primary_user_id = button_qs[0]['buttonUser1'] if button == '1' else button_qs[0]['buttonUser2']
  114. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, userID_id=primary_user_id) \
  115. .exclude(token_val='0'). \
  116. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
  117. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  118. 'uid_set__channel', 'uid_set__ai_type', 'uid_set__device_type', 'uid_set__new_detect_interval',
  119. 'uid_set__msg_notify', 'jg_token_val')
  120. return uid_push_qs
  121. @classmethod
  122. def get_uid_push_by_uid(cls, uid):
  123. """
  124. 根据uid获取设备推送(目前仅用在OZI定制客户)
  125. """
  126. device_info_qs = Device_Info.objects.filter(UID=uid).values('vodPrimaryUserID')
  127. primary_user_id = device_info_qs[0]['vodPrimaryUserID']
  128. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, userID_id=primary_user_id) \
  129. .exclude(token_val='0'). \
  130. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
  131. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  132. 'uid_set__channel', 'uid_set__ai_type', 'uid_set__device_type', 'uid_set__new_detect_interval',
  133. 'uid_set__msg_notify', 'jg_token_val')
  134. return uid_push_qs
  135. @staticmethod
  136. def qs_to_list(qs):
  137. """
  138. qs对象转存列表
  139. @param qs: query set对象
  140. @return: qs_list
  141. """
  142. qs_list = []
  143. for i in qs:
  144. qs_list.append(i)
  145. return qs_list
  146. @staticmethod
  147. def cache_push_detect_interval(redis_obj, name, detect_interval, new_detect_interval):
  148. """
  149. 缓存设置推送消息的时间间隔
  150. @param redis_obj: redis对象
  151. @param name: redis key
  152. @param detect_interval: 原推送时间间隔
  153. @param new_detect_interval: 新推送时间间隔
  154. """
  155. if CONFIG_INFO != CONFIG_CN:
  156. detect_interval = new_detect_interval if new_detect_interval > 0 else detect_interval
  157. detect_interval = 60 if detect_interval < 60 else detect_interval
  158. else: # 国内推送兼容问题,有值并且大于旧消息间隔则使用new_detect_interval
  159. detect_interval = new_detect_interval if new_detect_interval > detect_interval else detect_interval
  160. redis_obj.set_data(key=name, val=1, expire=detect_interval - 5)
  161. @classmethod
  162. def push_msg(cls, **params):
  163. """
  164. 推送消息
  165. @param params: 推送参数
  166. @return: bool
  167. """
  168. try:
  169. uid = params['uid']
  170. params['event_tag'] = cls.get_event_tag(params['ai_type'], params['event_type'], params['detection'])
  171. is_app_push = True if params['event_type'] in [606, 607] else \
  172. cls.is_send_app_push(
  173. params['event_type'], params['event_tag'], params['app_push_config'], params['app_push'],
  174. uid, params['channel'])
  175. # 低功耗产品推送,休眠702,低电量704提醒,1023 ozi, 并且detection=0,0标识单事件类型,1标识多事件类型
  176. is_app_push = True if params['event_type'] in [702, 704, 1022, 1023] and params[
  177. 'detection'] == 0 else is_app_push
  178. redis_obj = params['redis_obj']
  179. # 推送
  180. if is_app_push:
  181. msg_key = 'PUSH:MSG:IMAGE:{}:{}:{}'.format(params['uid'], params['channel'], params['n_time'])
  182. d_params = {'is_st': params['is_st'], 'storage_location': params['storage_location'],
  183. 'event_tag': params['event_tag'], 'event_type': params['event_type']}
  184. redis_obj.set_data(msg_key, json.dumps(d_params), 60)
  185. push_kwargs = params['push_kwargs']
  186. push_token_list = []
  187. for up in params['uid_set_push_list']:
  188. push_type = up['push_type']
  189. lang = up['lang']
  190. tz = up['tz']
  191. if tz is None or tz == '':
  192. tz = 0
  193. if params['event_type'] in [606, 607] and push_type in [5, 6]:
  194. process_token = up['jg_token_val']
  195. push_kwargs['jg_token_val'] = up['jg_token_val']
  196. else:
  197. process_token = up['token_val']
  198. if 'jg_token_val' in push_kwargs:
  199. push_kwargs.pop('jg_token_val')
  200. appBundleId = up['appBundleId']
  201. token_val = up['token_val']
  202. if process_token in push_token_list:
  203. LOGGING.info("uid:{}, 重复token_val{},".format(uid, token_val))
  204. continue
  205. # 发送标题
  206. msg_title = cls.get_msg_title(nickname=params['nickname'])
  207. # 发送内容
  208. msg_text = cls.get_msg_text(channel=params['channel'], n_time=params['n_time'], lang=lang, tz=tz,
  209. event_type=params['event_type'], ai_type=params['ai_type'],
  210. device_type=params['device_type'], electricity=params['electricity'],
  211. dealings_type=params['dealings_type'], event_tag=params['event_tag']
  212. )
  213. # 补齐推送参数
  214. push_kwargs['appBundleId'] = appBundleId
  215. push_kwargs['token_val'] = token_val
  216. push_kwargs['msg_title'] = msg_title
  217. push_kwargs['msg_text'] = msg_text
  218. params['push_kwargs'] = push_kwargs
  219. params['appBundleId'] = appBundleId
  220. params['token_val'] = token_val
  221. params['lang'] = lang
  222. params['tz'] = tz
  223. params['push_type'] = push_type
  224. params['redis_obj'] = redis_obj
  225. # GlobalThreadPool().submit(cls.send_app_msg_push, **params)
  226. push_thread = threading.Thread(
  227. target=cls.send_app_msg_push,
  228. kwargs=params
  229. )
  230. push_thread.start()
  231. # 过滤相同的token_val
  232. push_token_list.append(process_token)
  233. except Exception as e:
  234. ERROR_INFO_LOGGER.info(
  235. '推送消息线程异常,uid:{},error_line:{},error_msg:{}'
  236. .format(params['uid'], e.__traceback__.tb_lineno, repr(e)))
  237. @classmethod
  238. def save_msg_push(cls, **params):
  239. """
  240. 保存推送数据和推送消息
  241. @param params: 推送参数
  242. @return: bool
  243. """
  244. sys_msg_list = []
  245. saved_user_id_list = []
  246. uid = params['uid']
  247. now_time = int(time.time())
  248. redis_obj = params['redis_obj']
  249. try:
  250. params['event_tag'] = cls.get_event_tag(params['ai_type'], params['event_type'], params['detection'])
  251. save_equipment_info = False
  252. equipment_info_key = EquipmentInfoService.randoms_choice_equipment_info_key()
  253. for up in params['uid_set_push_list']:
  254. lang = up['lang']
  255. tz = up['tz']
  256. if tz is None or tz == '':
  257. tz = 0
  258. # 保存系统消息或推送消息数据
  259. user_id = up['userID_id']
  260. if user_id not in saved_user_id_list: # 防止同一用户重复写入数据
  261. # 系统消息
  262. if params['is_sys_msg']:
  263. sys_msg_text = cls.get_msg_text(channel=params['channel'], n_time=params['n_time'], lang=lang,
  264. tz=tz, is_sys=1, device_type=params['device_type'],
  265. event_type=params['event_type'],
  266. electricity=params['electricity'])
  267. sys_msg_list.append(SysMsgModel(userID_id=user_id, msg=sys_msg_text, addTime=now_time,
  268. updTime=now_time, uid=uid, eventType=params['event_type']))
  269. # 保存推送消息
  270. else:
  271. if not save_equipment_info:
  272. save_equipment_info = True
  273. params['userID_id'] = user_id
  274. answer_status = 1 if params['dealings_type'] == 1 else 0
  275. equipment_info_kwargs = {
  276. 'device_user_id': params['userID_id'],
  277. 'event_time': params['n_time'],
  278. 'event_type': params['event_type'],
  279. 'device_uid': params['uid'],
  280. 'device_nick_name': params['nickname'],
  281. 'channel': params['channel'],
  282. 'alarm': 'Motion \tChannel:{}'.format(params['channel']),
  283. 'is_st': params['is_st'],
  284. 'add_time': int(time.time()),
  285. 'storage_location': params['storage_location'],
  286. 'event_tag': params['event_tag'],
  287. 'answer_status': answer_status
  288. }
  289. # 保存到redis列表
  290. equipment_info_value = json.dumps(equipment_info_kwargs)
  291. redis_obj.rpush(equipment_info_key, equipment_info_value)
  292. saved_user_id_list.append(user_id)
  293. close_old_connections()
  294. # 写入系统消息
  295. if sys_msg_list:
  296. SysMsgModel.objects.bulk_create(sys_msg_list)
  297. if save_equipment_info:
  298. equipment_info_list = []
  299. equipment_info_model = EQUIPMENT_INFO_DICT[equipment_info_key]
  300. # 一键通话和视频通话需要实时写入数据
  301. # 正式服通过定时任务批量写入数据
  302. if params['event_type'] in [606, 607] or CONFIG_INFO == CONFIG_TEST:
  303. end = 0
  304. # 缓存数据多于100条,批量保存前100条,否则保存全部
  305. equipment_info_len = redis_obj.llen(equipment_info_key)
  306. end = 99 if equipment_info_len > 100 else equipment_info_len - 1
  307. if end != 0:
  308. equipment_info_redis_list = redis_obj.lrange(equipment_info_key, 0, end)
  309. redis_obj.ltrim(equipment_info_key, end + 1, -1)
  310. for equipment_info in equipment_info_redis_list:
  311. equipment_info_data = eval(equipment_info)
  312. # 设备昵称存在表情,解码utf-8
  313. if equipment_info_data.get('device_nick_name') is not None:
  314. equipment_info_data['device_nick_name'] = equipment_info_data['device_nick_name']. \
  315. encode('UTF-8', 'ignore').decode('UTF-8')
  316. equipment_info_list.append(equipment_info_model(**equipment_info_data))
  317. equipment_info_model.objects.bulk_create(equipment_info_list)
  318. return True
  319. except Exception as e:
  320. ERROR_INFO_LOGGER.info(
  321. '保存推送数据和推送消息线程异常,uid:{}, error_line:{}, error_msg:{}'.
  322. format(uid, e.__traceback__.tb_lineno, repr(e)))
  323. return False
  324. @classmethod
  325. def get_event_tag(cls, ai_type, event_type, detection=0):
  326. """
  327. 获取事件标签
  328. """
  329. algorithm = False
  330. if ai_type > 0 and detection == 1:
  331. algorithm = True
  332. elif (ai_type == 7 and event_type <= 7) or (ai_type == 47 and event_type <= 47) or (detection == 1):
  333. algorithm = True
  334. if not algorithm:
  335. return ',' + str(event_type) + ','
  336. event_res = DEVICE_EVENT_TYPE.get(event_type, 0)
  337. if event_res > 0:
  338. return ',' + str(event_res) + ','
  339. event_type = cls.dec_to_bin(event_type)
  340. types = cls.get_combo_types(event_type)
  341. res = ','.join(types) + ','
  342. return ',' + res
  343. @classmethod
  344. def get_combo_types(cls, event_type):
  345. """
  346. 获取设备算法组合类型
  347. 51:移动侦测,52:传感器报警,53:影像遗失,54:PIR,55:门磁报警,56:外部发报,57:人型报警(提示:有人出现),58:车型,59:宠物,60:人脸,61:异响,
  348. 62:区域闯入,63:区域闯出,64:长时间无人检测,65:长时间无人检测,66:往来检测,67:哭声检测,68:手势检测,69:火焰检测
  349. 0:代表空字符,702:摄像头休眠,703:摄像头唤醒,704:电量过低
  350. AWS AI识别 1:人形,2:车型,3:宠物,4:包裹。云端AI类型
  351. """
  352. try:
  353. types = []
  354. event_type = str(event_type)
  355. len_type = len(event_type)
  356. for i in range(len_type):
  357. e_type = event_type[len_type - 1 - i]
  358. if e_type == '1':
  359. types.append(str(ALGORITHM_COMBO_TYPES[i]))
  360. return types
  361. except Exception as e:
  362. LOGGING.info('推送错误异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  363. return event_type
  364. @staticmethod
  365. def dec_to_bin(num):
  366. """
  367. 十进制转二进制
  368. """
  369. result = ""
  370. while num != 0:
  371. ret = num % 2
  372. num //= 2
  373. result = str(ret) + result
  374. return result
  375. @classmethod
  376. def send_app_msg_push(cls, **kwargs):
  377. """
  378. 发送推送
  379. @kwargs :
  380. @return push_result: bool
  381. """
  382. try:
  383. push_type = kwargs['push_type']
  384. push_kwargs = kwargs['push_kwargs']
  385. push_result = False
  386. uid = kwargs['uid']
  387. # is_st为1或3,且推送类型为apns,gcm,华为,异步推送图片
  388. if (kwargs['is_st'] == 1 or kwargs['is_st'] == 3) and \
  389. (push_type == 0 or push_type == 1 or push_type == 3):
  390. if kwargs['is_st'] == 1:
  391. key = '{}/{}/{}.jpeg'.format(kwargs['uid'], kwargs['channel'], kwargs['n_time'])
  392. else:
  393. key = '{}/{}/{}_0.jpeg'.format(kwargs['uid'], kwargs['channel'], kwargs['n_time'])
  394. # 开始异步推送图片
  395. # thread_pool = GlobalThreadPool()
  396. # thread_pool.submit(cls.async_send_picture_push, (
  397. # push_type, kwargs['aws_s3_client'], kwargs['bucket'], key,
  398. # kwargs['uid'], kwargs['appBundleId'], kwargs['token_val'], kwargs['event_type'], kwargs['n_time'],
  399. # push_kwargs['msg_title'], push_kwargs['msg_text'], kwargs['channel'], kwargs['storage_location']))
  400. push_thread = threading.Thread(target=cls.async_send_picture_push, args=(
  401. push_type, kwargs['aws_s3_client'], kwargs['bucket'], key,
  402. kwargs['uid'], kwargs['appBundleId'], kwargs['token_val'], kwargs['event_type'], kwargs['n_time'],
  403. push_kwargs['msg_title'], push_kwargs['msg_text'], kwargs['channel'], kwargs['storage_location'],
  404. kwargs['redis_obj']))
  405. push_thread.start()
  406. push_result = True
  407. # 不推图
  408. else:
  409. if push_type in [0, 1, 2]:
  410. kwargs = {
  411. 'nickname': kwargs['uid'],
  412. 'app_bundle_id': kwargs['appBundleId'],
  413. 'token_val': kwargs['token_val'],
  414. 'n_time': kwargs['n_time'],
  415. 'event_type': kwargs['event_type'],
  416. 'msg_title': push_kwargs['msg_title'],
  417. 'msg_text': push_kwargs['msg_text'],
  418. 'uid': kwargs['uid'],
  419. 'channel': kwargs['channel']
  420. }
  421. if push_type == 0: # ios apns
  422. push_result = PushObject.ios_apns_push(**kwargs)
  423. elif push_type == 1: # android gcm
  424. push_result = PushObject.android_fcm_push_v1(**kwargs)
  425. elif push_type == 2: # android jpush
  426. kwargs.pop('uid')
  427. push_result = PushObject.android_jpush(**kwargs)
  428. elif push_type == 3:
  429. if kwargs["appBundleId"] == ConstantEnum.ZOSI_APP_BUNDLE_ID.value:
  430. huawei_push_object = HuaweiPushObject()
  431. huawei_push_object.send_push_notify_message(**push_kwargs)
  432. elif kwargs["appBundleId"] == ConstantEnum.VSEES_APP_BUNDLE_ID.value:
  433. vsees_huawei_push_object = VseesHuaweiPushObject()
  434. vsees_huawei_push_object.send_push_notify_message(**push_kwargs)
  435. elif push_type == 4: # android xmpush
  436. if kwargs['event_type'] in EventTypeEnumObj.DATA_PUSH_EVENT_TYPE_LIST.value:
  437. push_channel = 'push_to_talk'
  438. else:
  439. push_channel = 'device_reminder'
  440. channel_id = XM_PUSH_CHANNEL_DICT[kwargs['appBundleId']][push_channel]
  441. push_result = cls.do_xmpush(channel_id=channel_id, **push_kwargs)
  442. elif push_type == 5: # android vivopush
  443. push_result = PushObject.android_vivopush(**push_kwargs)
  444. elif push_type == 6: # android oppopush
  445. channel_id = 'DEVICE_REMINDER'
  446. push_result = cls.do_oppopush(channel_id=channel_id, **push_kwargs)
  447. elif push_type == 7: # android meizupush
  448. push_result = PushObject.android_meizupush(**push_kwargs)
  449. elif push_type == 8: # android honorpush
  450. push_result = PushObject.android_honorpush(**push_kwargs)
  451. if kwargs['event_type'] in [606, 607]:
  452. close_old_connections()
  453. # 写入日志表
  454. PushLog.objects.create(uid=uid, event_type=kwargs['event_type'], created_time=int(time.time()),
  455. content=push_kwargs, push_result=push_result, push_type=push_type)
  456. return push_result
  457. except Exception as e:
  458. ERROR_INFO_LOGGER.info('发送推送线程异常uid:{},type:{},error_line:{},error_msg:{}'
  459. .format(kwargs['uid'], kwargs['push_type'], e.__traceback__.tb_lineno, repr(e)))
  460. return False
  461. @staticmethod
  462. def get_msg_title(nickname):
  463. """
  464. 获取消息标题
  465. """""
  466. return nickname
  467. @staticmethod
  468. def get_event_type_text(lang, event_type, dealings_type):
  469. """
  470. 事件类型文案键值查找
  471. """
  472. if lang == 'cn':
  473. if event_type in EVENT_DICT_CN:
  474. if isinstance(EVENT_DICT_CN[event_type], dict):
  475. msg_type = EVENT_DICT_CN[event_type][dealings_type]
  476. else:
  477. msg_type = EVENT_DICT_CN[event_type]
  478. else:
  479. msg_type = '未知事件类型 '
  480. return msg_type
  481. else:
  482. if event_type in EVENT_DICT:
  483. if isinstance(EVENT_DICT[event_type], dict):
  484. msg_type = EVENT_DICT[event_type][dealings_type]
  485. else:
  486. msg_type = EVENT_DICT[event_type]
  487. else:
  488. msg_type = 'Unknown event type'
  489. return msg_type
  490. @staticmethod
  491. def get_msg_text(channel, n_time, lang, tz, event_type, electricity='', is_sys=0, dealings_type=0, ai_type=0,
  492. device_type=0, event_tag=''):
  493. """
  494. 获取消息文本
  495. @param: channel 通道号
  496. @param: n_time 触发事件
  497. @param: lang 语言
  498. @param: tz 时区
  499. @param: event_type 事件类型
  500. @param: electricity 电量
  501. @param: is_sys 是否系统消息
  502. @param: dealings_type 往来类型 1 进 1 离开
  503. @param: ai_type 设备本地AI只能算法 事件类型
  504. @param: device_type 设备类型
  505. @param: event_tag 设备算法事件标签
  506. """
  507. msg_type = ''
  508. event_type = int(event_type)
  509. device_type = int(device_type)
  510. event_list = []
  511. if event_tag:
  512. event_list = [int(event) for event in event_tag.split(',') if event]
  513. events_to_remove = [702, 703, 704]
  514. for event in events_to_remove:
  515. if event in event_list:
  516. event_list.remove(event)
  517. if lang == 'cn':
  518. if event_type == 51:
  519. msg_type = '检测到画面变化'
  520. elif event_type == 52:
  521. msg_type = '传感器报警'
  522. elif event_type == 53:
  523. msg_type = '影像遗失'
  524. elif event_type == 54:
  525. msg_type = 'PIR'
  526. elif event_type == 55:
  527. msg_type = '门磁报警'
  528. elif event_type == 56:
  529. msg_type = '外部发报'
  530. elif event_type == 57:
  531. msg_type = '有人出现'
  532. elif event_type == 58:
  533. msg_type = '有车出现'
  534. elif event_type == 59:
  535. msg_type = '有宠物出现'
  536. elif event_type == 60:
  537. msg_type = '发现人脸'
  538. elif event_type == 61:
  539. msg_type = '有异响'
  540. elif event_type == 62:
  541. msg_type = '区域闯入'
  542. elif event_type == 63:
  543. msg_type = '区域闯出'
  544. elif event_type == 64:
  545. msg_type = '有人徘徊'
  546. elif event_type == 65:
  547. msg_type = '长时间无人出现'
  548. elif event_type == 1022:
  549. msg_type = '有人按下门铃'
  550. elif event_type == 1023:
  551. msg_type = '儿童保护模式开启'
  552. elif event_type == 704:
  553. msg_type = '电量低'
  554. elif event_type == 702:
  555. msg_type = '摄像头休眠'
  556. elif event_type == 703:
  557. msg_type = '摄像头唤醒'
  558. elif event_type in [606, 607]:
  559. msg_type = '有人呼叫,请点击查看'
  560. if event_type not in [606, 607, 1022] and ai_type > 0 and event_list:
  561. msg_type = ''.join([DevicePushService.get_event_type_text(lang, item, dealings_type)
  562. for item in event_list])
  563. if is_sys:
  564. if device_type in MULTI_CHANNEL_TYPE_LIST:
  565. send_text = '{} 通道:{}'.format(msg_type, channel)
  566. else:
  567. send_text = msg_type
  568. else:
  569. if device_type in MULTI_CHANNEL_TYPE_LIST:
  570. send_text = '{} 通道:{}'.format(msg_type, channel)
  571. else:
  572. send_text = '{}'.format(msg_type)
  573. else:
  574. if event_type == 51:
  575. msg_type = 'Screen change detected'
  576. elif event_type == 52:
  577. msg_type = 'Sensor alarms'
  578. elif event_type == 53:
  579. msg_type = 'Lost images'
  580. elif event_type == 54:
  581. msg_type = 'PIR'
  582. elif event_type == 55:
  583. msg_type = 'Door magnetic alarm'
  584. elif event_type == 56:
  585. msg_type = 'External reporting'
  586. elif event_type == 57:
  587. msg_type = 'Person detected'
  588. elif event_type == 58:
  589. msg_type = 'Vehicle detected'
  590. elif event_type == 59:
  591. msg_type = 'Pet detected'
  592. elif event_type == 60:
  593. msg_type = 'Human face detected'
  594. elif event_type == 61:
  595. msg_type = 'Abnormal sound detected'
  596. elif event_type == 62:
  597. msg_type = 'Intrusion detected in the area'
  598. elif event_type == 63:
  599. msg_type = 'Area vacated'
  600. elif event_type == 64:
  601. msg_type = 'Loitering detected'
  602. elif event_type == 65:
  603. msg_type = 'No appearance for a long time'
  604. elif event_type == 1022:
  605. msg_type = 'Someone rang the doorbell'
  606. elif event_type == 1023:
  607. msg_type = 'Child protection mode is enabled'
  608. elif event_type == 704:
  609. msg_type = 'low battery'
  610. elif event_type == 702:
  611. msg_type = 'Camera sleep'
  612. elif event_type == 703:
  613. msg_type = 'Camera wake'
  614. elif event_type in [606, 607]:
  615. msg_type = 'Someone is calling, please click to view'
  616. if event_type not in [606, 607, 1022] and ai_type > 0 and event_list:
  617. msg_type = ''.join([DevicePushService.get_event_type_text(lang, item, dealings_type)
  618. for item in event_list])
  619. if is_sys:
  620. if device_type in MULTI_CHANNEL_TYPE_LIST:
  621. send_text = '{} channel:{}'.format(msg_type, channel)
  622. else:
  623. send_text = msg_type
  624. else:
  625. if device_type in MULTI_CHANNEL_TYPE_LIST:
  626. send_text = '{} channel:{}'.format(msg_type, channel)
  627. else:
  628. send_text = '{}'.format(msg_type)
  629. return send_text
  630. @staticmethod
  631. def do_xmpush(channel_id, uid, channel, appBundleId, token_val, event_type, n_time,
  632. msg_title, msg_text):
  633. """
  634. android 国内小米APP消息提醒推送
  635. """
  636. try:
  637. url = 'https://api.xmpush.xiaomi.com/v3/message/regid'
  638. app_secret = XMPUSH_CONFIG[appBundleId]
  639. # payload = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  640. # 'received_at': n_time, 'event_time': n_time, 'event_type': event_type,
  641. # 'uid': uid, 'channel': channel
  642. # }
  643. data = {
  644. 'title': msg_title,
  645. 'description': msg_text,
  646. 'payload': 'payload',
  647. 'restricted_package_name': appBundleId,
  648. 'registration_id': token_val,
  649. 'extra.channel_id': channel_id,
  650. 'extra.alert': 'Motion',
  651. 'extra.msg': '',
  652. 'extra.sound': 'sound.aif',
  653. 'extra.zpush': '1',
  654. 'extra.received_at': n_time,
  655. 'extra.event_time': n_time,
  656. 'extra.event_type': event_type,
  657. 'extra.uid': uid,
  658. 'extra.channel': channel,
  659. }
  660. if event_type in [606, 607]:
  661. data['extra.sound_uri'] = 'android.resource://com.ansjer.zccloud_ab/raw/phone_call'
  662. headers = {
  663. 'Authorization': 'key={}'.format(app_secret)
  664. }
  665. response = requests.post(url, data=data, headers=headers)
  666. LOGGING.info('uid:{},时间:{}小米推送参数:{}'.format(uid, n_time, data))
  667. if response.status_code == 200:
  668. LOGGING.info('uid:{},时间:{}小米推送结果:{}'.format(uid, n_time, response.json()))
  669. return True
  670. ERROR_INFO_LOGGER.info('小米推送异常,uid:{},状态码{},时间:{},结果:{},'
  671. .format(uid, response.status_code, n_time, response.json()))
  672. return False
  673. except Exception as e:
  674. ERROR_INFO_LOGGER.info('小米推送异常,uid:{},时间:{},error_line:{},error_msg:{}'.
  675. format(uid, n_time, e.__traceback__.tb_lineno, repr(e)))
  676. return False
  677. @staticmethod
  678. def do_oppopush(channel_id, uid, channel, appBundleId, token_val, event_type, n_time,
  679. msg_title, msg_text, jg_token_val=''):
  680. """
  681. android 国内oppo APP消息提醒推送
  682. """
  683. try:
  684. if event_type in [606, 607]:
  685. channel_id = XM_PUSH_CHANNEL_ID['push_to_talk']
  686. app_key = OPPOPUSH_CONFIG[appBundleId]['Key']
  687. master_secret = OPPOPUSH_CONFIG[appBundleId]['Secret']
  688. url = 'https://api.push.oppomobile.com/'
  689. now_time = str(round(time.time() * 1000))
  690. # 1、实例化一个sha256对象
  691. sha256 = hashlib.sha256()
  692. # 2、调用update方法进行加密
  693. sha256.update((app_key + now_time + master_secret).encode('utf-8'))
  694. # 3、调用hexdigest方法,获取加密结果
  695. sign = sha256.hexdigest()
  696. # 获取auth_token
  697. get_token_url = url + 'server/v1/auth'
  698. post_data = {
  699. 'app_key': app_key,
  700. 'sign': sign,
  701. 'timestamp': now_time
  702. }
  703. headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  704. response = requests.post(get_token_url, data=post_data, headers=headers)
  705. result = response.json()
  706. # 发送推送
  707. push_url = url + 'server/v1/message/notification/unicast'
  708. extra_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  709. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type,
  710. 'uid': uid, 'channel': channel}
  711. message = {
  712. "target_type": 2,
  713. "target_value": token_val,
  714. "notification": {
  715. "title": msg_title,
  716. "content": msg_text,
  717. 'channel_id': channel_id,
  718. 'action_parameters': extra_data,
  719. 'click_action_type': 4,
  720. 'click_action_activity': OPPOPUSH_CONFIG[appBundleId]['click_action_activity']
  721. }
  722. }
  723. push_data = {
  724. 'auth_token': result['data']['auth_token'],
  725. 'message': json.dumps(message)
  726. }
  727. response = requests.post(push_url, data=push_data, headers=headers)
  728. if response.status_code == 200:
  729. if event_type in [606, 607]:
  730. PushObject.jpush_transparent_transmission(msg_title, msg_text, appBundleId, jg_token_val,
  731. extra_data)
  732. return True
  733. return False
  734. except Exception as e:
  735. ERROR_INFO_LOGGER.info('oppo推送异常,uid:{},time:{},error_line:{},error_msg:{}'.
  736. format(uid, n_time, e.__traceback__.tb_lineno, repr(e)))
  737. return False
  738. @classmethod
  739. def async_send_picture_push(cls, push_type, aws_s3_client, bucket, key, uid, appBundleId, token_val,
  740. event_type, n_time, msg_title, msg_text, channel, storage_reg, redis_obj):
  741. """
  742. 异步推送图片
  743. """
  744. try:
  745. if storage_reg == 1:
  746. # 阿里云
  747. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  748. oss_img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  749. image_url = oss_img_bucket.sign_url('GET', key, 300)
  750. elif storage_reg in [3, 4]:
  751. image_url = DevicePushService.oci_object_url(uid, redis_obj, storage_reg, bucket, key)
  752. elif storage_reg == 5:
  753. image_url = DevicePushService.create_obs_signed_url(key, 'GET')
  754. else:
  755. image_url = aws_s3_client.generate_presigned_url(
  756. 'get_object', Params={'Bucket': bucket, 'Key': key}, ExpiresIn=3600)
  757. push_result = False
  758. if push_type == 0:
  759. push_result = PushObject.ios_apns_push(
  760. uid, appBundleId, token_val, n_time, event_type, msg_title, msg_text, uid, channel, image_url)
  761. elif push_type == 1:
  762. push_result = PushObject.android_fcm_push_v1(
  763. uid, appBundleId, token_val, n_time, event_type, msg_title, msg_text, uid, channel, image_url)
  764. elif push_type == 3:
  765. if appBundleId == ConstantEnum.ZOSI_APP_BUNDLE_ID.value:
  766. huawei_push_object = HuaweiPushObject()
  767. push_result = huawei_push_object.send_push_notify_message(
  768. token_val=token_val, msg_title=msg_title, msg_text=msg_text, uid=uid, event_type=event_type,
  769. n_time=n_time, image_url=image_url, channel=channel)
  770. elif appBundleId == ConstantEnum.VSEES_APP_BUNDLE_ID.value:
  771. vsees_huawei_push_object = VseesHuaweiPushObject()
  772. push_result = vsees_huawei_push_object.send_push_notify_message(
  773. token_val=token_val, msg_title=msg_title, msg_text=msg_text, uid=uid, event_type=event_type,
  774. n_time=n_time, image_url=image_url, channel=channel)
  775. TIME_LOGGER.info('{}推送图片,push_type:{},推送结果:{}'.format(uid, push_type, push_result))
  776. except Exception as e:
  777. ERROR_INFO_LOGGER.error(
  778. '异步推送图片异常,error_line:{},error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  779. @staticmethod
  780. def oci_object_url(uid, redis_obj, storage_location, bucket, obj_name):
  781. """
  782. 获取OCI对象存储URL 有效期5分钟
  783. @param uid: uid
  784. @param redis_obj: 缓存客户端
  785. @param storage_location: 存储区域
  786. @param bucket: 存储桶
  787. @param obj_name: 对象名称
  788. @return: url
  789. """
  790. try:
  791. uid_key = f'PUSH:PICTURE:OCI:URL:{uid}'
  792. oci_url = redis_obj.get_data(uid_key)
  793. if oci_url:
  794. return oci_url + obj_name
  795. oci = OCIObjectStorage('eur' if storage_location == 4 else 'us')
  796. prefix_name = f'{uid}/'
  797. time_expires = datetime.datetime.utcnow() + datetime.timedelta(minutes=60)
  798. result = oci.get_preauthenticated_request_url(bucket, 'ociPush', prefix_name, time_expires,
  799. 'AnyObjectRead') # 授权到指定uid文件夹
  800. full_url = result.full_path if result else ''
  801. redis_obj.set_data(uid_key, full_url, 3580)
  802. return full_url + obj_name
  803. except Exception as e:
  804. LOGGING.error('oci查询消息列表异常error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  805. return ''
  806. @staticmethod
  807. def create_oci_req_url(storage_location, bucket, obj_name, oci=None):
  808. """
  809. 创建oci预认证请求url
  810. """
  811. if not oci:
  812. region = 'eur' if storage_location == 4 else 'us'
  813. oci = OCIObjectStorage(region)
  814. time_expires = datetime.datetime.utcnow() + datetime.timedelta(minutes=60)
  815. result = oci.create_ereauthenticated_request(bucket, 'ociPush', obj_name, time_expires)
  816. if not result:
  817. return ''
  818. return result.full_path + result.object_name
  819. @staticmethod
  820. def get_res_data(**kwargs):
  821. """
  822. 获取响应数据
  823. @return: res_data
  824. """
  825. res_data = {'code': 0, 'msg': 'success'}
  826. is_st = kwargs['is_st']
  827. storage_location = kwargs['storage_location']
  828. if is_st == 0 or is_st == 2:
  829. res_data['msg'] = 'success 0 or 2'
  830. elif is_st == 1:
  831. key_name = '{}/{}/{}.jpeg'.format(kwargs['uid'], kwargs['channel'], kwargs['n_time'])
  832. params = {'Key': key_name}
  833. if kwargs['region'] == 2: # 2:国内
  834. params['Bucket'] = 'push'
  835. else: # 1:国外
  836. params['Bucket'] = 'foreignpush'
  837. # 根据存储区域返回链接
  838. if storage_location in [3, 4]:
  839. # OCI
  840. img_url = DevicePushService.create_oci_req_url(storage_location, params['Bucket'], key_name)
  841. res_data['img_push'] = img_url
  842. res_data['msg'] = 'success 1'
  843. elif storage_location == 2:
  844. # AWS
  845. img_url = DevicePushService.generate_s3_url(kwargs['aws_s3_client'], params)
  846. res_data['img_push'] = img_url
  847. else:
  848. # 华为云
  849. img_url = DevicePushService.create_obs_signed_url(key_name, 'PUT')
  850. res_data['img_push'] = img_url
  851. res_data['msg'] = 'success 1'
  852. elif is_st == 3:
  853. img_url_list = []
  854. if kwargs['region'] == 2: # 2:国内
  855. params = {'Bucket': 'push'}
  856. else: # 1:国外
  857. params = {'Bucket': 'foreignpush'}
  858. oci_client = None
  859. if storage_location in [3, 4]: # 三张图的时候提前获取实例化OCI
  860. region = 'eur' if storage_location == 4 else 'us'
  861. oci_client = OCIObjectStorage(region)
  862. for i in range(kwargs['is_st']):
  863. key_name = '{}/{}/{}_{}.jpeg'.format(kwargs['uid'], kwargs['channel'], kwargs['n_time'], i)
  864. params['Key'] = key_name
  865. if storage_location in [3, 4]:
  866. # OCI
  867. img_url = DevicePushService.create_oci_req_url(
  868. storage_location, params['Bucket'], key_name, oci_client)
  869. elif storage_location == 2:
  870. # AWS
  871. img_url = DevicePushService.generate_s3_url(kwargs['aws_s3_client'], params)
  872. else:
  873. # 华为云
  874. img_url = DevicePushService.create_obs_signed_url(key_name, 'PUT')
  875. img_url_list.append(img_url)
  876. res_data['img_url_list'] = img_url_list
  877. res_data['msg'] = 'success 3'
  878. return res_data
  879. @staticmethod
  880. def generate_s3_url(aws_s3_client, params):
  881. """
  882. 获取S3对象URL
  883. """
  884. response_url = aws_s3_client.generate_presigned_url(
  885. ClientMethod='put_object',
  886. Params=params,
  887. ExpiresIn=3600
  888. )
  889. return response_url
  890. @staticmethod
  891. def create_obs_signed_url(key_name, method):
  892. """
  893. 生成对象存储预签名URL
  894. @param key_name: 对象名称
  895. @param method: 方法
  896. @return: 预签名URL
  897. """
  898. obs_client = ObsClient(
  899. access_key_id=HUAWEICLOUD_AK, secret_access_key=HUAWEICLOUD_SK, server=HUAWEICLOUD_OBS_SERVER)
  900. res = obs_client.createSignedUrl(
  901. method=method, bucketName=HUAWEICLOUD_PUSH_BUKET, objectKey=key_name, expires=3600)
  902. return res.signedUrl
  903. @staticmethod
  904. def check_share_permission(user_id, channel, uid):
  905. """
  906. 检查用户是否有权限接收设备报警推送
  907. """
  908. user_permission_qs = DeviceChannelUserSet.objects.filter(user_id=user_id, uid=uid) \
  909. .values('id', 'channels')
  910. # 根据当前用户与uid查询是否设置过通道权限,不存在则不是分享设备
  911. if not user_permission_qs.exists():
  912. return True
  913. up_id = user_permission_qs[0]['id']
  914. channels = user_permission_qs[0]['channels']
  915. channels_list = [int(val) for val in channels.split(',')]
  916. # 当前uid是属于分享设备并且设置了权限
  917. # 判断通道是否设置了权限,不存在则当前通道没有权限接受消息推送
  918. if int(channel) not in channels_list:
  919. return False
  920. permission_qs = DeviceSharePermission.objects.filter(code='AlarmMessages').values('id')
  921. p_id = permission_qs[0]['id']
  922. # 当前通道存在设置则查看是否有 消息推送权限
  923. channel_permission_qs = DeviceChannelUserPermission.objects \
  924. .filter(channel_user_id=up_id, permission_id=p_id) \
  925. .values('permission_id', 'channel_user_id')
  926. if not channel_permission_qs.exists():
  927. return False
  928. return True
  929. @classmethod
  930. def is_algorithm_type(cls, uid, event_type):
  931. """
  932. 判断是否是算法类型 62、63、64、65、66不限制推送
  933. """
  934. uid_set_qs = UidSetModel.objects.filter(uid=uid).values('ai_type')
  935. if not uid_set_qs.exists():
  936. return False
  937. if uid_set_qs[0]['ai_type'] == 0:
  938. return False
  939. event_types = [62, 63, 64, 65, 66]
  940. event_res = DEVICE_EVENT_TYPE.get(event_type, 0)
  941. if event_res in event_types:
  942. return True
  943. event_types2 = cls.get_combo_types(event_type)
  944. if not event_types2:
  945. return False
  946. c = [x for x in event_types if x in event_types2]
  947. return True if c else False
  948. @staticmethod
  949. def is_send_app_push(event_type, event_tag, app_push_config, msg_interval=None, uid=None, channel=1):
  950. """
  951. 是否进行APP消息提醒
  952. @return: True|False
  953. """
  954. try:
  955. if not app_push_config:
  956. return True
  957. is_push = app_push_config['appPush']
  958. if is_push != 1: # 1:进行APP提醒,其它则不执行APP提醒
  959. return False
  960. if msg_interval: # 存在消息间隔数据缓存 不推送APP消息
  961. return False
  962. if 'nvr' in app_push_config:
  963. push = DevicePushService.is_msg_push_nvr(event_type, int(channel), app_push_config)
  964. TIME_LOGGER.info(f'uid:{uid}NVR推送结果:{push}')
  965. return push
  966. all_day = app_push_config['pushTime']['allDay']
  967. # 允许设备类型APP提醒列表
  968. app_event_types = app_push_config['eventTypes']['device']
  969. if all_day == 0: # 1:全天提醒,0:自定义时间提醒
  970. push_time_config = app_push_config['pushTime']
  971. # 计算当前时间是否在自定义消息提醒范围内
  972. if not DevicePushService.is_push_notify_allowed_now(push_time_config):
  973. return False
  974. # APP接收提醒,判断识别类型是否勾选提醒
  975. push_result = DevicePushService.is_type_push(event_type, event_tag, app_event_types)
  976. return push_result
  977. except Exception as e:
  978. LOGGING.info(
  979. '{}判断是否执行APP推送异常,errLine:{}, errMsg:{}'.format(uid, e.__traceback__.tb_lineno, repr(e)))
  980. return True
  981. @staticmethod
  982. def is_msg_push_nvr(event_type, channel, config):
  983. try:
  984. # 获取 NVR 配置中记录,默认为空列表
  985. nvr_entries = config.get('nvr', [])
  986. # 构建通道键,例如 'channel1' 或 'channel2'
  987. channel_key = f'channel{channel}'
  988. if not nvr_entries:
  989. return True
  990. # 查找给定通道
  991. matching_entry = next((entry for entry in nvr_entries if channel_key in entry), None)
  992. # 如果没有找到匹配项,返回 True,表示可以推送
  993. if not matching_entry:
  994. return True
  995. # 获取与 channel_key 对应的 event_types
  996. event_types = matching_entry[channel_key] if channel_key in matching_entry else []
  997. # 调用 is_type_push 方法检查事件类型是否可以推送
  998. return DevicePushService.is_type_push(event_type, None, event_types)
  999. except Exception as e:
  1000. # 记录异常信息并返回 False
  1001. ERROR_INFO_LOGGER.error(
  1002. 'NVRAPP推送异常, errLine: {}, errMsg: {}'.format(e.__traceback__.tb_lineno, repr(e)))
  1003. return False
  1004. @staticmethod
  1005. def is_type_push(event_type, event_tag, app_event_types):
  1006. # 检查事件标签和应用事件类型是否都存在
  1007. if event_tag and app_event_types:
  1008. # 将事件标签按逗号分割成列表,并转换为整数类型
  1009. tag_list = [int(event) for event in event_tag.split(',') if event]
  1010. # 判断是否有任一标签允许应用提醒
  1011. return any(item in app_event_types for item in tag_list)
  1012. # 检查事件类型和用户所选事件类型是否都存在,并判断事件类型在用户所选事件类型列表中
  1013. return event_type and app_event_types and event_type in app_event_types
  1014. @staticmethod
  1015. def is_push_notify_allowed_now(push_time_config):
  1016. """
  1017. 判断当前时间是否在允许APP推送提醒
  1018. """
  1019. now_time = int(time.time())
  1020. start_time = push_time_config['startTime']
  1021. end_time = push_time_config['endTime']
  1022. repeat = push_time_config['repeat']
  1023. tz = push_time_config['timeZone']
  1024. # 获取当前日期和周几
  1025. now_date, week = DevicePushService.get_now_date_and_week(now_time, tz)
  1026. # 判断是否在重复日范围内
  1027. if not DevicePushService.is_repeated(week, repeat):
  1028. return False
  1029. # 计算当前日期在一天中的秒数
  1030. seconds = LocalDateTimeUtil.convert_time_to_seconds(now_date)
  1031. # 判断是否在APP推送提醒范围内
  1032. return DevicePushService.is_in_effect(start_time, end_time, seconds)
  1033. @staticmethod
  1034. def is_in_effect(start, end, now_seconds):
  1035. """
  1036. 判断是否在提醒时间范围内
  1037. @params: 开始时间秒
  1038. @params: 结束时间秒
  1039. @params: 当前时间秒
  1040. @return: 当前时间是在范围内返回True 否则False
  1041. """
  1042. if start < end:
  1043. return start <= now_seconds <= end
  1044. else:
  1045. return start <= now_seconds or now_seconds <= end
  1046. @staticmethod
  1047. def is_repeated(week_day, repeat_day):
  1048. """
  1049. 判断是否重复日
  1050. @params: week_day 周几
  1051. @params: 重复日1-127
  1052. @return: 如果当前日期在重复日则返回True否则False
  1053. """
  1054. # 判断对应位置上的值是否为 1
  1055. is_repeat = (repeat_day >> (week_day - 1)) & 1 == 1
  1056. return is_repeat
  1057. @staticmethod
  1058. def get_now_date_and_week(now_time, tz):
  1059. now_data = CommonService.get_now_time_str(now_time, tz, 'cn')
  1060. week = LocalDateTimeUtil.date_to_week(now_data)
  1061. return now_data, week