DevicePushService.py 26 KB

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