DevicePushService.py 50 KB

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