DevicePushService.py 49 KB

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