DevicePushService.py 50 KB

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