DevicePushService.py 45 KB

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