DevicePushService.py 56 KB

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