DevicePushService.py 44 KB

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