DevicePushService.py 53 KB

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