DevicePushService.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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 hashlib
  10. import json
  11. import logging
  12. import os
  13. import threading
  14. import time
  15. import apns2
  16. import jpush as jpush
  17. import requests
  18. from pyfcm import FCMNotification
  19. from AnsjerPush.config import CONFIG_INFO, CONFIG_CN
  20. from AnsjerPush.config import JPUSH_CONFIG, FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE, XMPUSH_CONFIG, OPPOPUSH_CONFIG
  21. from Model.models import UidPushModel, SysMsgModel, DeviceSharePermission, DeviceChannelUserSet, \
  22. DeviceChannelUserPermission
  23. from Object.ETkObject import ETkObject
  24. from Object.UidTokenObject import UidTokenObject
  25. from Object.utils import LocalDateTimeUtil
  26. from Service.CommonService import CommonService
  27. from Service.EquipmentInfoService import EquipmentInfoService
  28. from Service.HuaweiPushService.HuaweiPushService import HuaweiPushObject
  29. from Service.PushService import PushObject
  30. LOGGING = logging.getLogger('info')
  31. class DevicePushService:
  32. @staticmethod
  33. def decode_uid(etk, uidToken):
  34. """
  35. 解密UID,优先解密etk 否则判断uidToken
  36. """
  37. # 解密获取uid
  38. if etk:
  39. eto = ETkObject(etk)
  40. uid = eto.uid
  41. else:
  42. uto = UidTokenObject(uidToken)
  43. uid = uto.UID
  44. LOGGING.info('消息推送-当前UID:{}'.format(uid))
  45. return uid
  46. @classmethod
  47. def query_uid_push(cls, uid, event_type):
  48. """
  49. 查询uid_set与push数据列表
  50. """
  51. if event_type != 606:
  52. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  53. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
  54. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  55. 'uid_set__channel', 'uid_set__ai_type', 'uid_set__new_detect_interval')
  56. else:
  57. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid). \
  58. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
  59. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  60. 'uid_set__channel', 'uid_set__ai_type', 'uid_set__new_detect_interval')
  61. return uid_push_qs
  62. @staticmethod
  63. def cache_uid_push(uid_push_qs):
  64. """
  65. 将uid_push 信息进行缓存
  66. @param uid_push_qs: uid_set & uid_push 列表对象
  67. @return: uid_set_list
  68. """
  69. uid_set_list = []
  70. for qs in uid_push_qs:
  71. uid_set_list.append(qs)
  72. # redis_obj.set_data(key=name, val=str(redis_list), expire=expire)
  73. return uid_set_list
  74. @staticmethod
  75. def cache_push_detect_interval(redis_obj, name, detect_interval, new_detect_interval):
  76. """
  77. 缓存设置推送消息的时间间隔
  78. @param redis_obj: redis对象
  79. @param name: redis key
  80. @param detect_interval: 原推送时间间隔
  81. @param new_detect_interval: 新推送时间间隔
  82. """
  83. if CONFIG_INFO != CONFIG_CN:
  84. detect_interval = new_detect_interval if new_detect_interval > 0 else detect_interval
  85. detect_interval = 60 if detect_interval < 60 else detect_interval
  86. redis_obj.set_data(key=name, val=1, expire=detect_interval - 5)
  87. LOGGING.info('消息推送-缓存设置APP推送间隔:{}s'.format(detect_interval))
  88. @classmethod
  89. def save_msg_push(cls, uid_set_push_list, **params):
  90. """
  91. APP消息推送以及报警消息存库
  92. @nickname 设备名称
  93. @channel 通道
  94. @event_type 事件类型
  95. """
  96. new_device_info_list = []
  97. sys_msg_list = []
  98. userID_ids = []
  99. kwag_args = params['kwag_args']
  100. code_data = {'do_apns_code': '', 'do_fcm_code': '', 'do_jpush_code': ''}
  101. local_date_time = ''
  102. push_permission = True
  103. try:
  104. for up in uid_set_push_list:
  105. appBundleId = up['appBundleId']
  106. token_val = up['token_val']
  107. lang = up['lang']
  108. tz = up['tz']
  109. if tz is None or tz == '':
  110. tz = 0
  111. # 发送标题
  112. msg_title = cls.get_msg_title(nickname=params['nickname'])
  113. # 发送内容
  114. msg_text = cls.get_msg_text(channel=params['channel'], n_time=params['n_time'], lang=lang,
  115. tz=tz, event_type=params['event_type'],
  116. electricity=params['electricity'])
  117. kwag_args['appBundleId'] = appBundleId
  118. kwag_args['token_val'] = token_val
  119. kwag_args['msg_title'] = msg_title
  120. kwag_args['msg_text'] = msg_text
  121. LOGGING.info('推送要的数据: {}'.format(kwag_args))
  122. local_date_time = CommonService.get_now_time_str(n_time=params['n_time'], tz=tz, lang='cn')
  123. LOGGING.info('<<<<<根据时区计算后日期={},时区={}'.format(local_date_time, tz))
  124. local_date_time = local_date_time[0:10]
  125. LOGGING.info('<<<<<切片后的日期={}'.format(local_date_time))
  126. # 以下是存库
  127. userID_id = up["userID_id"]
  128. if userID_id not in userID_ids:
  129. now_time = int(time.time())
  130. if params['is_sys_msg']:
  131. sys_msg_text = cls.get_msg_text(channel=params['channel'], n_time=params['n_time'], lang=lang,
  132. tz=tz,
  133. event_type=params['event_type'],
  134. electricity=params['electricity'],
  135. is_sys=1)
  136. sys_msg_list.append(SysMsgModel(userID_id=userID_id, msg=sys_msg_text, addTime=now_time,
  137. updTime=now_time, uid=params['uid'],
  138. eventType=params['event_type']))
  139. else:
  140. LOGGING.info('分表存数据start------')
  141. params['userID_id'] = userID_id
  142. push_permission = DevicePushService.check_share_permission(userID_id, params['channel'],
  143. params['uid'])
  144. if push_permission:
  145. new_device_info_list.append(cls.created_device_vo(local_date_time, **params))
  146. userID_ids.append(userID_id)
  147. params['appBundleId'] = appBundleId
  148. params['token_val'] = token_val
  149. params['lang'] = lang
  150. params['tz'] = tz
  151. params['kwag_args'] = kwag_args
  152. code_data = cls.send_app_msg_push(up['push_type'], **params) if push_permission else code_data
  153. return {'code_date': code_data, 'new_device_info_list': new_device_info_list, 'sys_msg_list': sys_msg_list,
  154. 'local_date_time': local_date_time}
  155. except Exception as e:
  156. LOGGING.info('推送消息或存表异常: errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  157. @classmethod
  158. def send_app_msg_push(cls, push_type, **param):
  159. """
  160. 发送app消息推送
  161. """
  162. try:
  163. kwargs = param['kwag_args']
  164. result = {'do_apns_code': '', 'do_fcm_code': '', 'do_jpush_code': '', 'do_xmpush_code': '',
  165. 'do_vivopush_code': '', 'do_meizupush_code': '', 'do_oppopush_code': ''}
  166. # 判断是否进行APP消息推送,如app_push不为空,则不进行推送
  167. if not param['app_push']:
  168. LOGGING.info('APP准备推送:{}, {}'.format(param['uid'], param))
  169. # 推送显示图片
  170. if (param['is_st'] == 1 or param['is_st'] == 3) and \
  171. (push_type == 0 or push_type == 1 or push_type == 3):
  172. if param['is_st'] == 1:
  173. key = '{}/{}/{}.jpeg'.format(param['uid'], param['channel'], param['n_time'])
  174. else:
  175. key = '{}/{}/{}_0.jpeg'.format(param['uid'], param['channel'], param['n_time'])
  176. push_thread = threading.Thread(target=cls.async_send_picture_push, args=(
  177. push_type, param['aws_s3_client'], param['bucket'], key, param['uid'], param['appBundleId'],
  178. param['token_val'], param['event_type'], param['n_time'],
  179. param['kwag_args']['msg_title'], param['kwag_args']['msg_text'], param['channel']))
  180. push_thread.start()
  181. else:
  182. if push_type == 0: # ios apns
  183. result['do_apns_code'] = cls.do_apns(**kwargs)
  184. elif push_type == 1: # android gcm
  185. result['do_fcm_code'] = cls.do_fcm(**kwargs)
  186. elif push_type == 2: # android jpush
  187. result['do_jpush_code'] = cls.do_jpush(**kwargs)
  188. elif push_type == 3:
  189. huawei_push_object = HuaweiPushObject()
  190. huawei_push_object.send_push_notify_message(**kwargs)
  191. elif push_type == 4: # android xmpush
  192. channel_id = 104551
  193. result['do_xmpush_code'] = cls.do_xmpush(channel_id=channel_id, **kwargs)
  194. elif push_type == 5: # android vivopush
  195. result['do_vivopush_code'] = PushObject.android_vivopush(**kwargs)
  196. elif push_type == 6: # android oppopush
  197. channel_id = 'DEVICE_REMINDER'
  198. result['do_oppopush_code'] = cls.do_oppopush(channel_id=channel_id, **kwargs)
  199. elif push_type == 7: # android meizupush
  200. result['do_meizupush_code'] = PushObject.android_meizupush(**kwargs)
  201. return result
  202. except Exception as e:
  203. LOGGING.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  204. return None
  205. @classmethod
  206. def save_sys_msg(cls, is_sys_msg, local_date_time, sys_msg_list, new_device_info_list):
  207. """
  208. 保存系统消息&设备推送消息存库
  209. """
  210. if is_sys_msg:
  211. SysMsgModel.objects.bulk_create(sys_msg_list)
  212. else:
  213. # new 分表批量存储 设备信息
  214. if new_device_info_list and len(new_device_info_list) > 0:
  215. # 根据日期获得星期几
  216. week = LocalDateTimeUtil.date_to_week(local_date_time)
  217. EquipmentInfoService.equipment_info_bulk_create(week, new_device_info_list)
  218. LOGGING.info('设备信息分表批量保存end------')
  219. return True
  220. @classmethod
  221. def created_device_vo(cls, local_date_time, **params):
  222. """
  223. 获取设备推送表对象
  224. """
  225. return EquipmentInfoService.get_equipment_info_obj(
  226. local_date_time,
  227. device_user_id=params['userID_id'],
  228. event_time=params['n_time'],
  229. event_type=params['event_type'],
  230. device_uid=params['uid'],
  231. device_nick_name=params['nickname'],
  232. channel=params['channel'],
  233. alarm='Motion \tChannel:{channel}'.format(channel=params['channel']),
  234. is_st=params['is_st'],
  235. receive_time=params['n_time'],
  236. add_time=int(time.time()),
  237. storage_location=params['storage_location'],
  238. border_coords='',
  239. )
  240. @staticmethod
  241. def get_msg_title(nickname):
  242. """
  243. 获取消息标题
  244. """""
  245. return nickname
  246. @staticmethod
  247. def get_msg_text(channel, n_time, lang, tz, event_type, electricity='', is_sys=0):
  248. """
  249. 获取消息文本
  250. """
  251. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  252. etype = int(event_type)
  253. if lang == 'cn':
  254. if etype == 704:
  255. msg_type = '剩余电量 ' + electricity
  256. elif etype == 702:
  257. msg_type = '摄像头休眠'
  258. elif etype == 703:
  259. msg_type = '摄像头唤醒'
  260. elif etype == 606:
  261. msg_type = '有人呼叫,请点击查看'
  262. else:
  263. msg_type = ''
  264. if is_sys:
  265. send_text = '{} 通道:{}'.format(msg_type, channel)
  266. else:
  267. send_text = '{} 通道:{} 日期:{}'.format(msg_type, channel, n_date)
  268. else:
  269. if etype == 704:
  270. msg_type = 'Battery remaining ' + electricity
  271. elif etype == 702:
  272. msg_type = 'Camera sleep'
  273. elif etype == 703:
  274. msg_type = 'Camera wake'
  275. elif etype == 606:
  276. msg_type = 'Someone is calling, please click to view'
  277. else:
  278. msg_type = ''
  279. if is_sys:
  280. send_text = '{} channel:{}'.format(msg_type, channel)
  281. else:
  282. send_text = '{} channel:{} date:{}'.format(msg_type, channel, n_date)
  283. return send_text
  284. @staticmethod
  285. def do_jpush(uid, channel, appBundleId, token_val, event_type, n_time,
  286. msg_title, msg_text):
  287. """
  288. android 国内极光APP消息提醒推送
  289. """
  290. app_key = JPUSH_CONFIG[appBundleId]['Key']
  291. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  292. _jpush = jpush.JPush(app_key, master_secret)
  293. push = _jpush.create_push()
  294. push.audience = jpush.registration_id(token_val)
  295. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  296. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  297. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  298. big_text=msg_text, title=msg_title,
  299. extras=push_data)
  300. push.notification = jpush.notification(android=android)
  301. push.platform = jpush.all_
  302. res = push.send()
  303. print(res)
  304. return res.status_code
  305. @staticmethod
  306. def do_fcm(uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  307. """
  308. android 谷歌APP消息提醒推送
  309. """
  310. try:
  311. serverKey = FCM_CONFIG[appBundleId]
  312. except Exception as e:
  313. LOGGING.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  314. return 'serverKey abnormal'
  315. push_service = FCMNotification(api_key=serverKey)
  316. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  317. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  318. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  319. message_body=msg_text, data_message=data,
  320. extra_kwargs={
  321. 'default_vibrate_timings': True,
  322. 'default_sound': True,
  323. 'default_light_settings': True
  324. })
  325. return result
  326. @staticmethod
  327. def do_apns(uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  328. msg_text):
  329. """
  330. ios 消息提醒推送
  331. """
  332. LOGGING.info("进来do_apns函数了")
  333. LOGGING.info(token_val)
  334. LOGGING.info(APNS_MODE)
  335. LOGGING.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  336. try:
  337. cli = apns2.APNSClient(
  338. mode=APNS_MODE, client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  339. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  340. "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
  341. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  342. payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
  343. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  344. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  345. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  346. print(res.status_code)
  347. LOGGING.info("apns_推送状态:")
  348. LOGGING.info(res.status_code)
  349. if res.status_code == 200:
  350. return res.status_code
  351. else:
  352. print('apns push fail')
  353. print(res.reason)
  354. LOGGING.info('apns push fail')
  355. LOGGING.info(res.reason)
  356. return res.status_code
  357. except (ValueError, ArithmeticError):
  358. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  359. except Exception as e:
  360. print(repr(e))
  361. print('do_apns函数错误行号', e.__traceback__.tb_lineno)
  362. LOGGING.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  363. return repr(e)
  364. @staticmethod
  365. def do_xmpush(channel_id, uid, channel, appBundleId, token_val, event_type, n_time,
  366. msg_title, msg_text):
  367. """
  368. android 国内小米APP消息提醒推送
  369. """
  370. url = 'https://api.xmpush.xiaomi.com/v3/message/regid'
  371. app_secret = XMPUSH_CONFIG[appBundleId]
  372. # payload = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  373. # 'received_at': n_time, 'event_time': n_time, 'event_type': event_type,
  374. # 'uid': uid, 'channel': channel
  375. # }
  376. data = {
  377. 'title': msg_title,
  378. 'description': msg_text,
  379. 'payload': 'payload',
  380. 'restricted_package_name': appBundleId,
  381. 'registration_id': token_val,
  382. 'extra.channel_id': channel_id,
  383. 'extra.alert': 'Motion',
  384. 'extra.msg': '',
  385. 'extra.sound': 'sound.aif',
  386. 'extra.zpush': '1',
  387. 'extra.received_at': n_time,
  388. 'extra.event_time': n_time,
  389. 'extra.event_type': event_type,
  390. 'extra.uid': uid,
  391. 'extra.channel': channel,
  392. }
  393. headers = {
  394. 'Authorization': 'key={}'.format(app_secret)
  395. }
  396. response = requests.post(url, data=data, headers=headers)
  397. if response.status_code == 200:
  398. return response.json()
  399. @staticmethod
  400. def do_oppopush(channel_id, uid, channel, appBundleId, token_val, event_type, n_time,
  401. msg_title, msg_text):
  402. """
  403. android 国内oppo APP消息提醒推送
  404. """
  405. app_key = OPPOPUSH_CONFIG[appBundleId]['Key']
  406. master_secret = OPPOPUSH_CONFIG[appBundleId]['Secret']
  407. url = 'https://api.push.oppomobile.com/'
  408. now_time = str(round(time.time() * 1000))
  409. # 1、实例化一个sha256对象
  410. sha256 = hashlib.sha256()
  411. # 2、调用update方法进行加密
  412. sha256.update((app_key + now_time + master_secret).encode('utf-8'))
  413. # 3、调用hexdigest方法,获取加密结果
  414. sign = sha256.hexdigest()
  415. # 获取auth_token
  416. get_token_url = url + 'server/v1/auth'
  417. post_data = {
  418. 'app_key': app_key,
  419. 'sign': sign,
  420. 'timestamp': now_time
  421. }
  422. headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  423. response = requests.post(get_token_url, data=post_data, headers=headers)
  424. result = response.json()
  425. # 发送推送
  426. push_url = url + 'server/v1/message/notification/unicast'
  427. extra_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  428. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type,
  429. 'uid': uid, 'channel': channel}
  430. message = {
  431. "target_type": 2,
  432. "target_value": token_val,
  433. "notification": {
  434. "title": msg_title,
  435. "content": msg_text,
  436. 'channel_id': channel_id,
  437. 'action_parameters': extra_data,
  438. 'click_action_type': 1,
  439. 'click_action_activity': 'com.ansjer.zccloud_a.AJ_MainView.AJ_Home.AJMainActivity'
  440. }
  441. }
  442. push_data = {
  443. 'auth_token': result['data']['auth_token'],
  444. 'message': json.dumps(message)
  445. }
  446. response = requests.post(push_url, data=push_data, headers=headers)
  447. if response.status_code == 200:
  448. return response.json()
  449. @classmethod
  450. def async_send_picture_push(cls, push_type, aws_s3_client, bucket, key, uid, appBundleId,
  451. token_val, event_type, n_time, msg_title, msg_text, channel):
  452. """
  453. 异步APP图片推送
  454. """
  455. try:
  456. image_url = aws_s3_client.generate_presigned_url('get_object',
  457. Params={'Bucket': bucket, 'Key': key},
  458. ExpiresIn=3600)
  459. LOGGING.info('推送图片url:{}'.format(image_url))
  460. if push_type == 0:
  461. PushObject.ios_apns_push(uid, appBundleId, token_val, n_time, event_type, msg_title, msg_text,
  462. uid, channel, image_url)
  463. elif push_type == 1:
  464. PushObject.android_fcm_push(uid, appBundleId, token_val, n_time, event_type, msg_title,
  465. msg_text, uid, channel, image_url)
  466. elif push_type == 3:
  467. huawei_push_object = HuaweiPushObject()
  468. huawei_push_object.send_push_notify_message(token_val=token_val, msg_title=msg_title, msg_text=msg_text,
  469. image_url=image_url)
  470. except Exception as e:
  471. LOGGING.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  472. @staticmethod
  473. def get_push_url(**params):
  474. """
  475. 获取推送URL,设备根本当前返回结果进行数据上传
  476. @return: re_data
  477. """
  478. re_data = {'code': 0, 'msg': 'success'}
  479. if params['is_st'] == 0 or params['is_st'] == 2:
  480. re_data['msg'] = 'success 0 or 2'
  481. for up in params['uid_set_push_list']:
  482. if up['push_type'] == 0: # ios apns
  483. up['do_apns_code'] = params['code_dict']['code_date']['do_apns_code']
  484. elif up['push_type'] == 1: # android gcm
  485. up['do_fcm_code'] = params['code_dict']['code_date']['do_fcm_code']
  486. elif up['push_type'] == 2: # android jpush
  487. up['do_jpush_code'] = params['code_dict']['code_date']['do_jpush_code']
  488. elif up['push_type'] == 4: # android jpush
  489. up['do_xmpush_code'] = params['code_dict']['code_date']['do_xmpush_code']
  490. elif up['push_type'] == 5: # android jpush
  491. up['do_vivopush_code'] = params['code_dict']['code_date']['do_vivopush_code']
  492. elif up['push_type'] == 7: # android jpush
  493. up['do_meizupush_code'] = params['code_dict']['code_date']['do_meizupush_code']
  494. del up['push_type']
  495. del up['userID_id']
  496. del up['userID__NickName']
  497. del up['lang']
  498. del up['tz']
  499. del up['uid_set__nickname']
  500. del up['uid_set__detect_interval']
  501. del up['uid_set__detect_group']
  502. re_data['re_list'] = params['uid_set_push_list']
  503. elif params['is_st'] == 1:
  504. key_name = '{uid}/{channel}/{filename}.jpeg' \
  505. .format(uid=params['uid'], channel=params['channel'], filename=params['n_time'])
  506. re_args = {'Key': key_name}
  507. if params['region'] == 2: # 2:国内
  508. re_args['Bucket'] = 'push'
  509. else: # 1:国外
  510. re_args['Bucket'] = 'foreignpush'
  511. response_url = DevicePushService.generate_s3_url(params['aws_s3_client'], re_args)
  512. re_data['img_push'] = response_url
  513. elif params['is_st'] == 3:
  514. img_url_list = []
  515. if params['region'] == 2: # 2:国内
  516. re_args = {'Bucket': 'push'}
  517. else: # 1:国外
  518. re_args = {'Bucket': 'foreignpush'}
  519. for i in range(params['is_st']):
  520. key_name = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  521. format(uid=params['uid'], channel=params['channel'], filename=params['n_time'], st=i)
  522. re_args['Key'] = key_name
  523. response_url = DevicePushService.generate_s3_url(params['aws_s3_client'], re_args)
  524. img_url_list.append(response_url)
  525. re_data['img_url_list'] = img_url_list
  526. re_data['msg'] = 'success 3'
  527. return re_data
  528. @staticmethod
  529. def generate_s3_url(aws_s3_client, params):
  530. """
  531. 获取S3对象URL
  532. """
  533. response_url = aws_s3_client.generate_presigned_url(
  534. ClientMethod='put_object',
  535. Params=params,
  536. ExpiresIn=3600
  537. )
  538. return response_url
  539. @staticmethod
  540. def check_share_permission(user_id, channel, uid):
  541. """
  542. 检查用户是否有权限接收设备报警推送
  543. """
  544. user_permission_qs = DeviceChannelUserSet.objects.filter(user_id=user_id, uid=uid) \
  545. .values('id', 'channels')
  546. # 根据当前用户与uid查询是否设置过通道权限,不存在则不是分享设备
  547. if not user_permission_qs.exists():
  548. return True
  549. up_id = user_permission_qs[0]['id']
  550. channels = user_permission_qs[0]['channels']
  551. channels_list = [int(val) for val in channels.split(',')]
  552. # 当前uid是属于分享设备并且设置了权限
  553. # 判断通道是否设置了权限,不存在则当前通道没有权限接受消息推送
  554. if int(channel) not in channels_list:
  555. return False
  556. permission_qs = DeviceSharePermission.objects.filter(code='AlarmMessages').values('id')
  557. p_id = permission_qs[0]['id']
  558. # 当前通道存在设置则查看是否有 消息推送权限
  559. channel_permission_qs = DeviceChannelUserPermission.objects \
  560. .filter(channel_user_id=up_id, permission_id=p_id) \
  561. .values('permission_id', 'channel_user_id')
  562. if not channel_permission_qs.exists():
  563. return False
  564. return True