DevicePushService.py 52 KB

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