DevicePushService.py 55 KB

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