DevicePushService.py 56 KB

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