DevicePushService.py 50 KB

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