DevicePushService.py 46 KB

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