DevicePushService.py 49 KB

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