DevicePushService.py 43 KB

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