DevicePushService.py 71 KB

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