DevicePushService.py 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  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, 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. DATA_PUSH_EVENT_TYPE_LIST, PRIMARY_USERS_PUSH_EVENT_TYPE_LIST
  26. from AnsjerPush.config import XMPUSH_CONFIG, OPPOPUSH_CONFIG, XM_PUSH_CHANNEL_ID, XM_PUSH_CHANNEL_DICT
  27. from Model.models import UidPushModel, SysMsgModel, DeviceSharePermission, DeviceChannelUserSet, \
  28. DeviceChannelUserPermission, UidSetModel, Device_Info, UserAudioVideoPush, PushLog
  29. from Object.ETkObject import ETkObject
  30. from Object.OCIObjectStorage import OCIObjectStorage
  31. from Object.RedisObject import RedisObject
  32. from Object.UidTokenObject import UidTokenObject
  33. from Object.enums.ConstantEnum import ConstantEnum
  34. from Object.enums.EventTypeEnum import EventTypeEnumObj
  35. from Object.utils import LocalDateTimeUtil
  36. from Service.CommonService import CommonService
  37. from Service.EquipmentInfoService import EquipmentInfoService, EQUIPMENT_INFO_DICT
  38. from Service.HuaweiPushService.HuaweiPushService import HuaweiPushObject
  39. from Service.PushService import PushObject
  40. from django.db import close_old_connections
  41. from Service.VSeesHuaweiPushService.VseesHuaweiPushObject import VseesHuaweiPushObject
  42. LOGGING = logging.getLogger('info')
  43. TIME_LOGGER = logging.getLogger('time')
  44. ERROR_INFO_LOGGER = logging.getLogger('error_info')
  45. class DevicePushService:
  46. @staticmethod
  47. def decode_uid(etk, uidToken):
  48. """
  49. 解密UID,优先解密etk 否则判断uidToken
  50. """
  51. # 解密获取uid
  52. if etk:
  53. eto = ETkObject(etk)
  54. uid = eto.uid
  55. else:
  56. uto = UidTokenObject(uidToken)
  57. uid = uto.UID
  58. return uid
  59. @staticmethod
  60. def judge_sys_msg(event_type):
  61. """
  62. 判断是否属于系统消息
  63. @param event_type: 事件类型
  64. @return: bool
  65. """
  66. if event_type in SYS_EVENT_TYPE_LIST:
  67. return True
  68. return False
  69. @staticmethod
  70. def get_s3_client(region):
  71. """
  72. 根据地区获取S3 client
  73. @param region: 地区,1:国外, 2:国内
  74. @return: aws_s3_client
  75. """
  76. if int(region) == 1:
  77. aws_s3_client = boto3.client(
  78. 's3',
  79. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  80. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  81. config=botocore.client.Config(signature_version='s3v4'),
  82. region_name='us-east-1'
  83. )
  84. else:
  85. aws_s3_client = boto3.client(
  86. 's3',
  87. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  88. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  89. config=botocore.client.Config(signature_version='s3v4'),
  90. region_name='cn-northwest-1'
  91. )
  92. return aws_s3_client
  93. @classmethod
  94. def query_uid_push(cls, uid, event_type, button='1'):
  95. """
  96. 查询uid_push和uid_set数据
  97. @param uid: uid
  98. @param event_type: 事件类型
  99. @param button: 按钮
  100. @return: uid_push_qs
  101. """
  102. if event_type not in PRIMARY_USERS_PUSH_EVENT_TYPE_LIST:
  103. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1) \
  104. .exclude(token_val='0'). \
  105. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
  106. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  107. 'uid_set__channel', 'uid_set__ai_type', 'uid_set__device_type', 'uid_set__new_detect_interval',
  108. 'uid_set__msg_notify')
  109. else:
  110. # 一键通话,视频通话,按下门铃,SD卡异常 只推主用户
  111. device_info_qs = Device_Info.objects.filter(UID=uid).values('vodPrimaryUserID')
  112. if not device_info_qs.exists():
  113. return None
  114. primary_user_id = device_info_qs[0]['vodPrimaryUserID']
  115. if event_type == 607: # 音视频通话根据用户按钮来推送
  116. button_qs = UserAudioVideoPush.objects.filter(uid=uid).values('buttonUser1', 'buttonUser2')
  117. if button_qs.exists():
  118. primary_user_id = button_qs[0]['buttonUser1'] if button == '1' else button_qs[0]['buttonUser2']
  119. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, userID_id=primary_user_id) \
  120. .exclude(token_val='0'). \
  121. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
  122. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  123. 'uid_set__channel', 'uid_set__ai_type', 'uid_set__device_type', 'uid_set__new_detect_interval',
  124. 'uid_set__msg_notify', 'jg_token_val')
  125. return uid_push_qs
  126. @classmethod
  127. def get_uid_push_by_uid(cls, uid):
  128. """
  129. 根据uid获取设备推送(目前仅用在OZI定制客户)
  130. """
  131. device_info_qs = Device_Info.objects.filter(UID=uid).values('vodPrimaryUserID')
  132. if not device_info_qs.exists():
  133. return None
  134. primary_user_id = device_info_qs[0]['vodPrimaryUserID']
  135. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, userID_id=primary_user_id) \
  136. .exclude(token_val='0'). \
  137. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
  138. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  139. 'uid_set__channel', 'uid_set__ai_type', 'uid_set__device_type', 'uid_set__new_detect_interval',
  140. 'uid_set__msg_notify', 'jg_token_val')
  141. return uid_push_qs
  142. @staticmethod
  143. def qs_to_list(qs):
  144. """
  145. qs对象转存列表
  146. @param qs: query set对象
  147. @return: qs_list
  148. """
  149. qs_list = []
  150. for i in qs:
  151. qs_list.append(i)
  152. return qs_list
  153. @staticmethod
  154. def cache_push_detect_interval(redis_obj, name, detect_interval, new_detect_interval):
  155. """
  156. 缓存设置推送消息的时间间隔
  157. @param redis_obj: redis对象
  158. @param name: redis key
  159. @param detect_interval: 原推送时间间隔
  160. @param new_detect_interval: 新推送时间间隔
  161. """
  162. if CONFIG_INFO != CONFIG_CN:
  163. detect_interval = new_detect_interval if new_detect_interval > 0 else detect_interval
  164. detect_interval = 60 if detect_interval < 60 else detect_interval
  165. else: # 国内推送兼容问题,有值并且大于旧消息间隔则使用new_detect_interval
  166. detect_interval = new_detect_interval if new_detect_interval > detect_interval else detect_interval
  167. redis_obj.set_data(key=name, val=1, expire=detect_interval - 5)
  168. @classmethod
  169. def push_msg(cls, **params):
  170. """
  171. 推送消息
  172. @param params: 推送参数
  173. @return: bool
  174. """
  175. try:
  176. uid = params['uid']
  177. params['event_tag'] = cls.get_event_tag(params['ai_type'], params['event_type'], params['detection'])
  178. is_app_push = True if params['event_type'] in PRIMARY_USERS_PUSH_EVENT_TYPE_LIST \
  179. else cls.is_send_app_push(
  180. params['event_type'], params['event_tag'], params['app_push_config'], params['app_push'],
  181. uid, params['channel'])
  182. # 低功耗产品推送,休眠702,低电量704提醒,1023 ozi, 并且detection=0,0标识单事件类型,1标识多事件类型
  183. is_app_push = True if params['event_type'] in [702, 704, 1022, 1023] and params[
  184. 'detection'] == 0 else is_app_push
  185. redis_obj = params['redis_obj']
  186. # 推送
  187. if is_app_push:
  188. msg_key = 'PUSH:MSG:IMAGE:{}:{}:{}'.format(params['uid'], params['channel'], params['n_time'])
  189. d_params = {'is_st': params['is_st'], 'storage_location': params['storage_location'],
  190. 'event_tag': params['event_tag'], 'event_type': params['event_type']}
  191. redis_obj.set_data(msg_key, json.dumps(d_params), 60)
  192. push_kwargs = params['push_kwargs']
  193. push_token_list = []
  194. for up in params['uid_set_push_list']:
  195. push_type = up['push_type']
  196. lang = up['lang']
  197. tz = up['tz']
  198. if tz is None or tz == '':
  199. tz = 0
  200. if params['event_type'] in DATA_PUSH_EVENT_TYPE_LIST and push_type in [5, 6]:
  201. process_token = up['jg_token_val']
  202. push_kwargs['jg_token_val'] = up['jg_token_val']
  203. else:
  204. process_token = up['token_val']
  205. if 'jg_token_val' in push_kwargs:
  206. push_kwargs.pop('jg_token_val')
  207. appBundleId = up['appBundleId']
  208. token_val = up['token_val']
  209. if process_token in push_token_list:
  210. LOGGING.info("uid:{}, 重复token_val{},".format(uid, token_val))
  211. continue
  212. # 发送标题
  213. msg_title = cls.get_msg_title(nickname=params['nickname'])
  214. # 发送内容
  215. msg_text = cls.get_msg_text_v2(channel=params['channel'], n_time=params['n_time'], lang=lang, tz=tz,
  216. event_type=params['event_type'], ai_type=params['ai_type'],
  217. device_type=params['device_type'], electricity=params['electricity'],
  218. dealings_type=params['dealings_type'], event_tag=params['event_tag'],
  219. redis_obj=params['redis_obj'])
  220. # 补齐推送参数
  221. push_kwargs['appBundleId'] = appBundleId
  222. push_kwargs['token_val'] = token_val
  223. push_kwargs['msg_title'] = msg_title
  224. push_kwargs['msg_text'] = msg_text
  225. params['push_kwargs'] = push_kwargs
  226. params['appBundleId'] = appBundleId
  227. params['token_val'] = token_val
  228. params['lang'] = lang
  229. params['tz'] = tz
  230. params['push_type'] = push_type
  231. params['redis_obj'] = redis_obj
  232. # GlobalThreadPool().submit(cls.send_app_msg_push, **params)
  233. push_thread = threading.Thread(
  234. target=cls.send_app_msg_push,
  235. kwargs=params
  236. )
  237. push_thread.start()
  238. # 过滤相同的token_val
  239. push_token_list.append(process_token)
  240. except Exception as e:
  241. ERROR_INFO_LOGGER.info(
  242. '推送消息线程异常,uid:{},error_line:{},error_msg:{}'
  243. .format(params['uid'], e.__traceback__.tb_lineno, repr(e)))
  244. @classmethod
  245. def save_msg_push(cls, **params):
  246. """
  247. 保存推送数据和推送消息
  248. @param params: 推送参数
  249. @return: bool
  250. """
  251. sys_msg_list = []
  252. saved_user_id_list = []
  253. uid = params['uid']
  254. now_time = int(time.time())
  255. redis_obj = params['redis_obj']
  256. try:
  257. params['event_tag'] = cls.get_event_tag(params['ai_type'], params['event_type'], params['detection'])
  258. save_equipment_info = False
  259. equipment_info_key = EquipmentInfoService.randoms_choice_equipment_info_key()
  260. for up in params['uid_set_push_list']:
  261. lang = up['lang']
  262. tz = up['tz']
  263. if tz is None or tz == '':
  264. tz = 0
  265. # 保存系统消息或推送消息数据
  266. user_id = up['userID_id']
  267. if user_id not in saved_user_id_list: # 防止同一用户重复写入数据
  268. # 系统消息
  269. if params['is_sys_msg']:
  270. sys_msg_text = cls.get_msg_text(channel=params['channel'], n_time=params['n_time'], lang=lang,
  271. tz=tz, is_sys=1, device_type=params['device_type'],
  272. event_type=params['event_type'],
  273. electricity=params['electricity'], is_save_msg=1)
  274. sys_msg_list.append(SysMsgModel(userID_id=user_id, msg=sys_msg_text, addTime=now_time,
  275. updTime=now_time, uid=uid, eventType=params['event_type'],
  276. channel=params['channel']))
  277. # 保存推送消息
  278. else:
  279. if not save_equipment_info:
  280. save_equipment_info = True
  281. params['userID_id'] = user_id
  282. answer_status = 1 if params['dealings_type'] == 1 else 0
  283. equipment_info_kwargs = {
  284. 'device_user_id': params['userID_id'],
  285. 'event_time': params['n_time'],
  286. 'event_type': params['event_type'],
  287. 'device_uid': params['uid'],
  288. 'device_nick_name': params['nickname'],
  289. 'channel': params['channel'],
  290. 'alarm': 'Motion \tChannel:{}'.format(params['channel']),
  291. 'is_st': params['is_st'],
  292. 'add_time': int(time.time()),
  293. 'storage_location': params['storage_location'],
  294. 'event_tag': params['event_tag'],
  295. 'answer_status': answer_status
  296. }
  297. # 保存到redis列表
  298. equipment_info_value = json.dumps(equipment_info_kwargs)
  299. redis_obj.rpush(equipment_info_key, equipment_info_value)
  300. saved_user_id_list.append(user_id)
  301. close_old_connections()
  302. # 写入系统消息
  303. if sys_msg_list:
  304. SysMsgModel.objects.bulk_create(sys_msg_list)
  305. if save_equipment_info:
  306. equipment_info_list = []
  307. equipment_info_model = EQUIPMENT_INFO_DICT[equipment_info_key]
  308. # 一键通话和视频通话需要实时写入数据
  309. # 正式服通过定时任务批量写入数据
  310. if params['event_type'] in DATA_PUSH_EVENT_TYPE_LIST or \
  311. CONFIG_INFO == CONFIG_TEST:
  312. end = 0
  313. # 缓存数据多于100条,批量保存前100条,否则保存全部
  314. equipment_info_len = redis_obj.llen(equipment_info_key)
  315. end = 99 if equipment_info_len > 100 else equipment_info_len - 1
  316. if end != 0:
  317. equipment_info_redis_list = redis_obj.lrange(equipment_info_key, 0, end)
  318. redis_obj.ltrim(equipment_info_key, end + 1, -1)
  319. for equipment_info in equipment_info_redis_list:
  320. equipment_info_data = eval(equipment_info)
  321. # 设备昵称存在表情,解码utf-8
  322. if equipment_info_data.get('device_nick_name') is not None:
  323. equipment_info_data['device_nick_name'] = equipment_info_data['device_nick_name']. \
  324. encode('UTF-8', 'ignore').decode('UTF-8')
  325. equipment_info_list.append(equipment_info_model(**equipment_info_data))
  326. equipment_info_model.objects.bulk_create(equipment_info_list)
  327. return True
  328. except Exception as e:
  329. ERROR_INFO_LOGGER.info(
  330. '保存推送数据和推送消息线程异常,uid:{}, error_line:{}, error_msg:{}'.
  331. format(uid, e.__traceback__.tb_lineno, repr(e)))
  332. return False
  333. @classmethod
  334. def get_event_tag(cls, ai_type, event_type, detection=0):
  335. """
  336. 获取事件标签
  337. """
  338. algorithm = False
  339. if ai_type > 0 and detection == 1:
  340. algorithm = True
  341. elif (ai_type == 7 and event_type <= 7) or (ai_type == 47 and event_type <= 47) or (detection == 1):
  342. algorithm = True
  343. if not algorithm:
  344. return ',' + str(event_type) + ','
  345. event_res = DEVICE_EVENT_TYPE.get(event_type, 0)
  346. if event_res > 0:
  347. return ',' + str(event_res) + ','
  348. event_type = cls.dec_to_bin(event_type)
  349. types = cls.get_combo_types(event_type)
  350. res = ','.join(types) + ','
  351. return ',' + res
  352. @classmethod
  353. def get_combo_types(cls, event_type):
  354. """
  355. 获取设备算法组合类型
  356. 51:移动侦测,52:传感器报警,53:影像遗失,54:PIR,55:门磁报警,56:外部发报,57:人型报警(提示:有人出现),58:车型,59:宠物,60:人脸,61:异响,
  357. 62:区域闯入,63:区域闯出,64:长时间无人检测,65:长时间无人检测,66:往来检测,67:哭声检测,68:手势检测,69:火焰检测
  358. 0:代表空字符,702:摄像头休眠,703:摄像头唤醒,704:电量过低
  359. AWS AI识别 1:人形,2:车型,3:宠物,4:包裹。云端AI类型
  360. """
  361. try:
  362. types = []
  363. event_type = str(event_type)
  364. len_type = len(event_type)
  365. for i in range(len_type):
  366. e_type = event_type[len_type - 1 - i]
  367. if e_type == '1':
  368. types.append(str(ALGORITHM_COMBO_TYPES[i]))
  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 DATA_PUSH_EVENT_TYPE_LIST:
  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 DATA_PUSH_EVENT_TYPE_LIST:
  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 == 706:
  574. msg_type = 'SD卡异常,请重新插拔或格式化SD卡。'
  575. if is_save_msg:
  576. msg_type = 'SD卡异常,请重新插拔或格式化SD卡。如问题仍未解决,请联系在线客服。'
  577. elif event_type in DATA_PUSH_EVENT_TYPE_LIST:
  578. msg_type = '有人呼叫,请点击查看'
  579. if event_type not in DATA_PUSH_EVENT_TYPE_LIST 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 == 706:
  634. msg_type = 'SD card is abnormal. Please re-insert or format the SD card.'
  635. if is_save_msg:
  636. msg_type = 'SD card is abnormal, 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 DATA_PUSH_EVENT_TYPE_LIST:
  639. msg_type = 'Someone is calling, please click to view'
  640. elif event_type not in DATA_PUSH_EVENT_TYPE_LIST 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 get_msg_text_v2(channel, n_time, lang, tz, event_type, electricity='', is_sys=0, dealings_type=0, ai_type=0,
  656. device_type=0, event_tag='', is_save_msg=0, redis_obj=None):
  657. """
  658. 获取消息文案V2
  659. """
  660. msg_type = ''
  661. try:
  662. event_type = int(event_type)
  663. device_type = int(device_type)
  664. event_list = []
  665. # 保持原有event_tag处理逻辑(完全不变)
  666. if event_tag:
  667. event_list = [int(event) for event in event_tag.split(',') if event]
  668. events_to_remove = SYS_EVENT_TYPE_LIST
  669. for event in events_to_remove:
  670. if event in event_list:
  671. event_list.remove(event)
  672. if event_type == 1022:
  673. msg_type = MSG_CONFIG[1022].get(lang, '')
  674. elif event_type == 1023:
  675. msg_type = MSG_CONFIG[1023].get(lang, '')
  676. elif event_type == 702:
  677. msg_type = MSG_CONFIG[702].get(lang, '')
  678. elif event_type == 703:
  679. msg_type = MSG_CONFIG[703].get(lang, '')
  680. elif event_type == 704:
  681. msg_type = MSG_CONFIG[704].get(lang, '')
  682. elif event_type == 706:
  683. if is_save_msg:
  684. msg_type = MSG_CONFIG[706]['save'].get(lang, '')
  685. else:
  686. msg_type = MSG_CONFIG[706]['default'].get(lang, '')
  687. elif event_type in DATA_PUSH_EVENT_TYPE_LIST:
  688. msg_type = MSG_CONFIG['data_push'].get(lang, '')
  689. # 组合事件处理文案
  690. if event_type not in DATA_PUSH_EVENT_TYPE_LIST and ai_type > 0 and event_list:
  691. msg_type = ''.join(
  692. DevicePushService.get_event_type_text_v2(lang, item, dealings_type, redis_obj)
  693. for item in event_list
  694. )
  695. elif not msg_type and event_type not in DATA_PUSH_EVENT_TYPE_LIST:
  696. # --- 新增代码:高频事件拦截 ---
  697. cache_key_tuple = (lang, event_type)
  698. if cache_key_tuple in DevicePushService._HIGH_FREQ_CACHE:
  699. msg_type = DevicePushService._HIGH_FREQ_CACHE[cache_key_tuple]
  700. else:
  701. msg_type = DevicePushService.get_event_type_text_v2(lang, event_type, None, redis_obj)
  702. if is_sys:
  703. if device_type in MULTI_CHANNEL_TYPE_LIST:
  704. send_text = f'{msg_type} 通道:{channel}' if lang == 'cn' else f'{msg_type} channel:{channel}'
  705. else:
  706. send_text = msg_type
  707. else:
  708. if device_type in MULTI_CHANNEL_TYPE_LIST: # NVR多通道文案
  709. channel_dict = {
  710. 'cn': '通道', # 简体中文
  711. 'en': 'Channel', # 英语
  712. 'es': 'Canal', # 西班牙语
  713. 'fr': 'Canal', # 法语
  714. 'de': 'Kanal ', # 德语
  715. 'cn_tw': '通道', # 繁体中文
  716. 'pt': 'Canal', # 葡萄牙语
  717. 'ru': 'Канал', # 俄语
  718. 'ja': 'チャンネル', # 日语
  719. 'it': 'Canale', # 意大利语
  720. 'pl': 'Kanał', # 波兰语
  721. 'nl': 'Kanaal', # 荷兰语
  722. 'ko': '채널', # 韩语
  723. 'ar': 'قناة', # 阿拉伯语
  724. 'vi': 'kênh', # 越南语
  725. 'th': 'ช่องเสียง' # 泰语
  726. }
  727. prefix = channel_dict.get(lang, channel_dict['en'])
  728. send_text = f'{msg_type} {prefix}:{channel}'
  729. else:
  730. send_text = f'{msg_type}'
  731. return send_text
  732. except Exception as e:
  733. ERROR_INFO_LOGGER.error('文案异常time:{},event_tag:{},error行数:{},内容:{}'
  734. .format(n_time, event_tag, e.__traceback__.tb_lineno, repr(e)))
  735. return msg_type
  736. @staticmethod
  737. def get_event_type_text_v2(lang, event_type, dealings_type, redis_obj):
  738. """ 改造后:优先读缓存,无缓存时读配置并写入 """
  739. msg = ''
  740. try:
  741. # 生成缓存键(示例:event_msg:en:66:1)
  742. cache_key = f"event_msg:{lang}:{event_type}"
  743. field = str(dealings_type) if dealings_type else 'default'
  744. # 1. 先尝试从 Redis 读取
  745. cached_msg = redis_obj.hget_data(cache_key, field)
  746. if cached_msg:
  747. return cached_msg
  748. # 2. 缓存未命中,从原配置读取
  749. config = EVENT_CONFIGS.get(lang, EVENT_CONFIGS['en'])
  750. default_msg = DEFAULT_TEXTS.get(lang, DEFAULT_TEXTS['en'])
  751. event_data = config.get(event_type)
  752. # 处理子类型
  753. if isinstance(event_data, dict):
  754. msg = event_data.get(dealings_type, default_msg)
  755. else:
  756. msg = event_data if event_data is not None else default_msg
  757. redis_obj.hset_data(cache_key, field, msg, 3600 * 24 * 7)
  758. return msg
  759. except Exception as e:
  760. ERROR_INFO_LOGGER.error('redis写入文案异常lang:{},event_type:{},error行数:{},内容:{}'
  761. .format(lang, event_type, e.__traceback__.tb_lineno, repr(e)))
  762. return msg
  763. @staticmethod
  764. def do_xmpush(channel_id, uid, channel, appBundleId, token_val, event_type, n_time,
  765. msg_title, msg_text):
  766. """
  767. android 国内小米APP消息提醒推送
  768. """
  769. try:
  770. url = 'https://api.xmpush.xiaomi.com/v3/message/regid'
  771. app_secret = XMPUSH_CONFIG[appBundleId]
  772. # 跳转类型
  773. jump_type = CommonService.get_jump_type(event_type)
  774. data = {
  775. 'title': msg_title,
  776. 'description': msg_text,
  777. 'payload': 'payload',
  778. 'restricted_package_name': appBundleId,
  779. 'registration_id': token_val,
  780. 'extra.channel_id': channel_id,
  781. 'extra.alert': msg_text,
  782. 'extra.msg': '',
  783. 'extra.sound': 'sound.aif',
  784. 'extra.zpush': '1',
  785. 'extra.received_at': n_time,
  786. 'extra.event_time': n_time,
  787. 'extra.event_type': event_type,
  788. 'extra.uid': uid,
  789. 'extra.channel': channel,
  790. 'extra.jump_type': jump_type
  791. }
  792. if event_type in DATA_PUSH_EVENT_TYPE_LIST:
  793. data['extra.sound_uri'] = 'android.resource://com.ansjer.zccloud_ab/raw/phone_call'
  794. headers = {
  795. 'Authorization': 'key={}'.format(app_secret)
  796. }
  797. response = requests.post(url, data=data, headers=headers)
  798. LOGGING.info('uid:{},时间:{}小米推送参数:{}'.format(uid, n_time, data))
  799. if response.status_code == 200:
  800. LOGGING.info('uid:{},时间:{}小米推送结果:{}'.format(uid, n_time, response.json()))
  801. return True
  802. ERROR_INFO_LOGGER.info('小米推送异常,uid:{},状态码{},时间:{},结果:{},'
  803. .format(uid, response.status_code, n_time, response.json()))
  804. return False
  805. except Exception as e:
  806. ERROR_INFO_LOGGER.info('小米推送异常,uid:{},时间:{},error_line:{},error_msg:{}'.
  807. format(uid, n_time, e.__traceback__.tb_lineno, repr(e)))
  808. return False
  809. @staticmethod
  810. def do_oppopush(channel_id, uid, channel, appBundleId, token_val, event_type, n_time,
  811. msg_title, msg_text, jg_token_val=''):
  812. """
  813. android 国内oppo APP消息提醒推送
  814. """
  815. try:
  816. if event_type in DATA_PUSH_EVENT_TYPE_LIST:
  817. channel_id = XM_PUSH_CHANNEL_ID['push_to_talk']
  818. app_key = OPPOPUSH_CONFIG[appBundleId]['Key']
  819. master_secret = OPPOPUSH_CONFIG[appBundleId]['Secret']
  820. url = 'https://api.push.oppomobile.com/'
  821. now_time = str(round(time.time() * 1000))
  822. # 1、实例化一个sha256对象
  823. sha256 = hashlib.sha256()
  824. # 2、调用update方法进行加密
  825. sha256.update((app_key + now_time + master_secret).encode('utf-8'))
  826. # 3、调用hexdigest方法,获取加密结果
  827. sign = sha256.hexdigest()
  828. # 获取auth_token
  829. get_token_url = url + 'server/v1/auth'
  830. post_data = {
  831. 'app_key': app_key,
  832. 'sign': sign,
  833. 'timestamp': now_time
  834. }
  835. headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  836. response = requests.post(get_token_url, data=post_data, headers=headers)
  837. result = response.json()
  838. # 发送推送
  839. push_url = url + 'server/v1/message/notification/unicast'
  840. # 跳转类型
  841. jump_type = CommonService.get_jump_type(event_type)
  842. extra_data = {'alert': msg_text, 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  843. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type,
  844. 'uid': uid, 'channel': channel, 'jump_type': jump_type}
  845. message = {
  846. "target_type": 2,
  847. "target_value": token_val,
  848. "notification": {
  849. "title": msg_title,
  850. "content": msg_text,
  851. 'channel_id': channel_id,
  852. 'action_parameters': extra_data,
  853. 'click_action_type': 4,
  854. 'click_action_activity': OPPOPUSH_CONFIG[appBundleId]['click_action_activity']
  855. }
  856. }
  857. push_data = {
  858. 'auth_token': result['data']['auth_token'],
  859. 'message': json.dumps(message)
  860. }
  861. response = requests.post(push_url, data=push_data, headers=headers)
  862. if response.status_code == 200:
  863. if event_type in DATA_PUSH_EVENT_TYPE_LIST:
  864. PushObject.jpush_transparent_transmission(msg_title, msg_text, appBundleId, jg_token_val,
  865. extra_data)
  866. return True
  867. return False
  868. except Exception as e:
  869. ERROR_INFO_LOGGER.info('oppo推送异常,uid:{},time:{},error_line:{},error_msg:{}'.
  870. format(uid, n_time, e.__traceback__.tb_lineno, repr(e)))
  871. return False
  872. @classmethod
  873. def async_send_picture_push(cls, push_type, aws_s3_client, bucket, key, uid, appBundleId, token_val,
  874. event_type, n_time, msg_title, msg_text, channel, storage_reg, redis_obj):
  875. """
  876. 异步推送图片
  877. """
  878. try:
  879. if storage_reg == 1:
  880. # 阿里云
  881. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  882. oss_img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  883. image_url = oss_img_bucket.sign_url('GET', key, 300)
  884. elif storage_reg in [3, 4]:
  885. image_url = DevicePushService.oci_object_url(uid, redis_obj, storage_reg, bucket, key)
  886. elif storage_reg == 5:
  887. image_url = DevicePushService.create_obs_signed_url(key, 'GET')
  888. else:
  889. image_url = aws_s3_client.generate_presigned_url(
  890. 'get_object', Params={'Bucket': bucket, 'Key': key}, ExpiresIn=3600)
  891. push_result = False
  892. if push_type == 0:
  893. push_result = PushObject.ios_apns_push(
  894. uid, appBundleId, token_val, n_time, event_type, msg_title, msg_text, uid, channel, image_url)
  895. elif push_type == 1:
  896. push_result = PushObject.android_fcm_push_v1(
  897. uid, appBundleId, token_val, n_time, event_type, msg_title, msg_text, uid, channel, image_url)
  898. elif push_type == 3:
  899. if appBundleId == ConstantEnum.ZOSI_APP_BUNDLE_ID.value:
  900. huawei_push_object = HuaweiPushObject()
  901. push_result = huawei_push_object.send_push_notify_message(
  902. token_val=token_val, msg_title=msg_title, msg_text=msg_text, uid=uid, event_type=event_type,
  903. n_time=n_time, image_url=image_url, channel=channel)
  904. elif appBundleId == ConstantEnum.VSEES_APP_BUNDLE_ID.value:
  905. vsees_huawei_push_object = VseesHuaweiPushObject()
  906. push_result = vsees_huawei_push_object.send_push_notify_message(
  907. token_val=token_val, msg_title=msg_title, msg_text=msg_text, uid=uid, event_type=event_type,
  908. n_time=n_time, image_url=image_url, channel=channel)
  909. TIME_LOGGER.info('{}推送图片,push_type:{},推送结果:{}'.format(uid, push_type, push_result))
  910. except Exception as e:
  911. ERROR_INFO_LOGGER.error(
  912. '异步推送图片异常,error_line:{},error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  913. @staticmethod
  914. def oci_object_url(uid, redis_obj, storage_location, bucket, obj_name):
  915. """
  916. 获取OCI对象存储URL 有效期5分钟
  917. @param uid: uid
  918. @param redis_obj: 缓存客户端
  919. @param storage_location: 存储区域
  920. @param bucket: 存储桶
  921. @param obj_name: 对象名称
  922. @return: url
  923. """
  924. try:
  925. uid_key = f'PUSH:PICTURE:OCI:URL:{uid}'
  926. oci_url = redis_obj.get_data(uid_key)
  927. if oci_url:
  928. return oci_url + obj_name
  929. oci = OCIObjectStorage('eur' if storage_location == 4 else 'us')
  930. prefix_name = f'{uid}/'
  931. time_expires = datetime.datetime.utcnow() + datetime.timedelta(minutes=60)
  932. result = oci.get_preauthenticated_request_url(bucket, 'ociPush', prefix_name, time_expires,
  933. 'AnyObjectRead') # 授权到指定uid文件夹
  934. full_url = result.full_path if result else ''
  935. redis_obj.set_data(uid_key, full_url, 3580)
  936. return full_url + obj_name
  937. except Exception as e:
  938. LOGGING.error('oci查询消息列表异常error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  939. return ''
  940. @staticmethod
  941. def create_oci_req_url(storage_location, bucket, obj_name, oci=None):
  942. """
  943. 创建oci预认证请求url
  944. """
  945. if not oci:
  946. region = 'eur' if storage_location == 4 else 'us'
  947. oci = OCIObjectStorage(region)
  948. time_expires = datetime.datetime.utcnow() + datetime.timedelta(minutes=60)
  949. result = oci.create_ereauthenticated_request(bucket, 'ociPush', obj_name, time_expires)
  950. if not result:
  951. return ''
  952. return result.full_path + result.object_name
  953. @staticmethod
  954. def get_res_data(**kwargs):
  955. """
  956. 获取响应数据
  957. @return: res_data
  958. """
  959. res_data = {'code': 0, 'msg': 'success'}
  960. is_st = kwargs['is_st']
  961. storage_location = kwargs['storage_location']
  962. if is_st == 0 or is_st == 2:
  963. res_data['msg'] = 'success 0 or 2'
  964. elif is_st == 1:
  965. key_name = '{}/{}/{}.jpeg'.format(kwargs['uid'], kwargs['channel'], kwargs['n_time'])
  966. params = {'Key': key_name}
  967. if kwargs['region'] == 2: # 2:国内
  968. params['Bucket'] = 'push'
  969. else: # 1:国外
  970. params['Bucket'] = 'foreignpush'
  971. # 根据存储区域返回链接
  972. if storage_location in [3, 4]:
  973. # OCI
  974. img_url = DevicePushService.create_oci_req_url(storage_location, params['Bucket'], key_name)
  975. res_data['img_push'] = img_url
  976. res_data['msg'] = 'success 1'
  977. elif storage_location == 2:
  978. # AWS
  979. img_url = DevicePushService.generate_s3_url(kwargs['aws_s3_client'], params)
  980. res_data['img_push'] = img_url
  981. else:
  982. # 华为云
  983. img_url = DevicePushService.create_obs_signed_url(key_name, 'PUT')
  984. res_data['img_push'] = img_url
  985. res_data['msg'] = 'success 1'
  986. elif is_st == 3:
  987. img_url_list = []
  988. if kwargs['region'] == 2: # 2:国内
  989. params = {'Bucket': 'push'}
  990. else: # 1:国外
  991. params = {'Bucket': 'foreignpush'}
  992. oci_client = None
  993. if storage_location in [3, 4]: # 三张图的时候提前获取实例化OCI
  994. region = 'eur' if storage_location == 4 else 'us'
  995. oci_client = OCIObjectStorage(region)
  996. for i in range(kwargs['is_st']):
  997. key_name = '{}/{}/{}_{}.jpeg'.format(kwargs['uid'], kwargs['channel'], kwargs['n_time'], i)
  998. params['Key'] = key_name
  999. if storage_location in [3, 4]:
  1000. # OCI
  1001. img_url = DevicePushService.create_oci_req_url(
  1002. storage_location, params['Bucket'], key_name, oci_client)
  1003. elif storage_location == 2:
  1004. # AWS
  1005. img_url = DevicePushService.generate_s3_url(kwargs['aws_s3_client'], params)
  1006. else:
  1007. # 华为云
  1008. img_url = DevicePushService.create_obs_signed_url(key_name, 'PUT')
  1009. img_url_list.append(img_url)
  1010. res_data['img_url_list'] = img_url_list
  1011. res_data['msg'] = 'success 3'
  1012. return res_data
  1013. @staticmethod
  1014. def generate_s3_url(aws_s3_client, params):
  1015. """
  1016. 获取S3对象URL
  1017. """
  1018. response_url = aws_s3_client.generate_presigned_url(
  1019. ClientMethod='put_object',
  1020. Params=params,
  1021. ExpiresIn=3600
  1022. )
  1023. return response_url
  1024. @staticmethod
  1025. def create_obs_signed_url(key_name, method):
  1026. """
  1027. 生成对象存储预签名URL
  1028. @param key_name: 对象名称
  1029. @param method: 方法
  1030. @return: 预签名URL
  1031. """
  1032. obs_client = ObsClient(
  1033. access_key_id=HUAWEICLOUD_AK, secret_access_key=HUAWEICLOUD_SK, server=HUAWEICLOUD_OBS_SERVER)
  1034. res = obs_client.createSignedUrl(
  1035. method=method, bucketName=HUAWEICLOUD_PUSH_BUKET, objectKey=key_name, expires=3600)
  1036. return res.signedUrl
  1037. @staticmethod
  1038. def check_share_permission(user_id, channel, uid):
  1039. """
  1040. 检查用户是否有权限接收设备报警推送
  1041. """
  1042. user_permission_qs = DeviceChannelUserSet.objects.filter(user_id=user_id, uid=uid) \
  1043. .values('id', 'channels')
  1044. # 根据当前用户与uid查询是否设置过通道权限,不存在则不是分享设备
  1045. if not user_permission_qs.exists():
  1046. return True
  1047. up_id = user_permission_qs[0]['id']
  1048. channels = user_permission_qs[0]['channels']
  1049. channels_list = [int(val) for val in channels.split(',')]
  1050. # 当前uid是属于分享设备并且设置了权限
  1051. # 判断通道是否设置了权限,不存在则当前通道没有权限接受消息推送
  1052. if int(channel) not in channels_list:
  1053. return False
  1054. permission_qs = DeviceSharePermission.objects.filter(code='AlarmMessages').values('id')
  1055. p_id = permission_qs[0]['id']
  1056. # 当前通道存在设置则查看是否有 消息推送权限
  1057. channel_permission_qs = DeviceChannelUserPermission.objects \
  1058. .filter(channel_user_id=up_id, permission_id=p_id) \
  1059. .values('permission_id', 'channel_user_id')
  1060. if not channel_permission_qs.exists():
  1061. return False
  1062. return True
  1063. @classmethod
  1064. def is_algorithm_type(cls, uid, event_type):
  1065. """
  1066. 判断是否是算法类型 62、63、64、65、66不限制推送
  1067. """
  1068. uid_set_qs = UidSetModel.objects.filter(uid=uid).values('ai_type')
  1069. if not uid_set_qs.exists():
  1070. return False
  1071. if uid_set_qs[0]['ai_type'] == 0:
  1072. return False
  1073. event_types = [62, 63, 64, 65, 66]
  1074. event_res = DEVICE_EVENT_TYPE.get(event_type, 0)
  1075. if event_res in event_types:
  1076. return True
  1077. event_types2 = cls.get_combo_types(event_type)
  1078. if not event_types2:
  1079. return False
  1080. c = [x for x in event_types if x in event_types2]
  1081. return True if c else False
  1082. @staticmethod
  1083. def is_send_app_push(event_type, event_tag, app_push_config, msg_interval=None, uid=None, channel=1):
  1084. """
  1085. 是否进行APP消息提醒
  1086. @return: True|False
  1087. """
  1088. try:
  1089. if not app_push_config:
  1090. return True
  1091. is_push = app_push_config['appPush']
  1092. if is_push != 1: # 1:进行APP提醒,其它则不执行APP提醒
  1093. return False
  1094. if msg_interval: # 存在消息间隔数据缓存 不推送APP消息
  1095. return False
  1096. if 'nvr' in app_push_config:
  1097. push = DevicePushService.is_msg_push_nvr(event_type, int(channel), app_push_config)
  1098. TIME_LOGGER.info(f'uid:{uid}NVR推送结果:{push}')
  1099. return push
  1100. all_day = app_push_config['pushTime']['allDay']
  1101. # 允许设备类型APP提醒列表
  1102. app_event_types = app_push_config['eventTypes']['device']
  1103. if all_day == 0: # 1:全天提醒,0:自定义时间提醒
  1104. push_time_config = app_push_config['pushTime']
  1105. # 计算当前时间是否在自定义消息提醒范围内
  1106. if not DevicePushService.is_push_notify_allowed_now(push_time_config):
  1107. return False
  1108. # APP接收提醒,判断识别类型是否勾选提醒
  1109. push_result = DevicePushService.is_type_push(event_type, event_tag, app_event_types)
  1110. return push_result
  1111. except Exception as e:
  1112. LOGGING.info(
  1113. '{}判断是否执行APP推送异常,errLine:{}, errMsg:{}'.format(uid, e.__traceback__.tb_lineno, repr(e)))
  1114. return True
  1115. @staticmethod
  1116. def is_msg_push_nvr(event_type, channel, config):
  1117. try:
  1118. # 获取 NVR 配置中记录,默认为空列表
  1119. nvr_entries = config.get('nvr', [])
  1120. # 构建通道键,例如 'channel1' 或 'channel2'
  1121. channel_key = f'channel{channel}'
  1122. if not nvr_entries:
  1123. return True
  1124. # 查找给定通道
  1125. matching_entry = next((entry for entry in nvr_entries if channel_key in entry), None)
  1126. # 如果没有找到匹配项,返回 True,表示可以推送
  1127. if not matching_entry:
  1128. return True
  1129. # 获取与 channel_key 对应的 event_types
  1130. event_types = matching_entry[channel_key] if channel_key in matching_entry else []
  1131. # 调用 is_type_push 方法检查事件类型是否可以推送
  1132. return DevicePushService.is_type_push(event_type, None, event_types)
  1133. except Exception as e:
  1134. # 记录异常信息并返回 False
  1135. ERROR_INFO_LOGGER.error(
  1136. 'NVRAPP推送异常, errLine: {}, errMsg: {}'.format(e.__traceback__.tb_lineno, repr(e)))
  1137. return False
  1138. @staticmethod
  1139. def is_type_push(event_type, event_tag, app_event_types):
  1140. # 检查事件标签和应用事件类型是否都存在
  1141. if event_tag and app_event_types:
  1142. # 将事件标签按逗号分割成列表,并转换为整数类型
  1143. tag_list = [int(event) for event in event_tag.split(',') if event]
  1144. # 判断是否有任一标签允许应用提醒
  1145. return any(item in app_event_types for item in tag_list)
  1146. # 检查事件类型和用户所选事件类型是否都存在,并判断事件类型在用户所选事件类型列表中
  1147. return event_type and app_event_types and event_type in app_event_types
  1148. @staticmethod
  1149. def is_push_notify_allowed_now(push_time_config):
  1150. """
  1151. 判断当前时间是否在允许APP推送提醒
  1152. """
  1153. now_time = int(time.time())
  1154. start_time = push_time_config['startTime']
  1155. end_time = push_time_config['endTime']
  1156. repeat = push_time_config['repeat']
  1157. tz = push_time_config['timeZone']
  1158. # 获取当前日期和周几
  1159. now_date, week = DevicePushService.get_now_date_and_week(now_time, tz)
  1160. # 判断是否在重复日范围内
  1161. if not DevicePushService.is_repeated(week, repeat):
  1162. return False
  1163. # 计算当前日期在一天中的秒数
  1164. seconds = LocalDateTimeUtil.convert_time_to_seconds(now_date)
  1165. # 判断是否在APP推送提醒范围内
  1166. return DevicePushService.is_in_effect(start_time, end_time, seconds)
  1167. @staticmethod
  1168. def is_in_effect(start, end, now_seconds):
  1169. """
  1170. 判断是否在提醒时间范围内
  1171. @params: 开始时间秒
  1172. @params: 结束时间秒
  1173. @params: 当前时间秒
  1174. @return: 当前时间是在范围内返回True 否则False
  1175. """
  1176. if start < end:
  1177. return start <= now_seconds <= end
  1178. else:
  1179. return start <= now_seconds or now_seconds <= end
  1180. @staticmethod
  1181. def is_repeated(week_day, repeat_day):
  1182. """
  1183. 判断是否重复日
  1184. @params: week_day 周几
  1185. @params: 重复日1-127
  1186. @return: 如果当前日期在重复日则返回True否则False
  1187. """
  1188. # 判断对应位置上的值是否为 1
  1189. is_repeat = (repeat_day >> (week_day - 1)) & 1 == 1
  1190. return is_repeat
  1191. @staticmethod
  1192. def get_now_date_and_week(now_time, tz):
  1193. now_data = CommonService.get_now_time_str(now_time, tz, 'cn')
  1194. week = LocalDateTimeUtil.date_to_week(now_data)
  1195. return now_data, week
  1196. # 新增内存缓存专用字典(线程安全,无需锁)
  1197. _HIGH_FREQ_CACHE = {
  1198. # 格式: (lang, event_type, dealings_type) : msg
  1199. ('cn', 51): '检测到画面变化',
  1200. ('cn', 57): '有人出现',
  1201. ('en', 51): 'Detected scene change',
  1202. ('en', 57): 'Person detected',
  1203. ('es', 51): 'Cambio de pantalla detectado',
  1204. ('es', 57): 'Persona detectada',
  1205. ('fr', 51): "Changement d'écran détecté",
  1206. ('fr', 57): "Présence d'une personne",
  1207. ('de', 51): "Bildschirmänderung erkannt",
  1208. ('de', 57): "Jemand anwesend",
  1209. ('cn_tw', 51): "檢測到畫面變化",
  1210. ('cn_tw', 57): "有人出現",
  1211. ('pt', 51): "Alteração do ecrã detectada",
  1212. ('pt', 57): "Pessoa detectada",
  1213. ('ru', 51): "Обнаружено изменение сцены",
  1214. ('ru', 57): "Обнаружен человек",
  1215. ('ja', 51): "画面変化を検知",
  1216. ('ja', 57): "人を検知",
  1217. ('it', 51): "Rilevato Cambio di Schermata",
  1218. ('it', 57): "Presenza Umana",
  1219. ('pl', 51): "Wykryto zmianę obrazu",
  1220. ('pl', 57): "Wykryto osobę",
  1221. ('nl', 51): "Schermverandering gedetecteerd",
  1222. ('nl', 57): "Iemand aanwezig",
  1223. ('ko', 51): "화면 변화 감지됨",
  1224. ('ko', 57): "사람 출현",
  1225. ('ar', 51): "تم اكتشاف تغيير في الصورة",
  1226. ('ar', 57): "وجود شخص",
  1227. ('vi', 51): "Phát hiện thay đổi hình ảnh",
  1228. ('vi', 57): "Phát hiện người xuất hiện ",
  1229. ('th', 51): "ตรวจพบการเปลี่ยนแปลงภาพ",
  1230. ('th', 57): "ตรวจพบคนปรากฏตัว",
  1231. }