DevicePushService.py 45 KB

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