DevicePushService.py 48 KB

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