DevicePushService.py 60 KB

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