DevicePushService.py 44 KB

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