DetectControllerV2.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @AUTHOR: ASJRD018
  6. @NAME: AnsjerFormal
  7. @software: PyCharm
  8. @DATE: 2019/1/14 15:57
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: DetectController.py
  12. @Contact: chanjunkai@163.com
  13. """
  14. import datetime
  15. import json
  16. import logging
  17. import os
  18. import time
  19. import apns2
  20. import boto3
  21. import botocore
  22. import jpush as jpush
  23. from botocore import client
  24. from django.http import JsonResponse
  25. from django.views.generic.base import View
  26. from pyfcm import FCMNotification
  27. from AnsjerPush.config import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
  28. from AnsjerPush.config import JPUSH_CONFIG, FCM_CONFIG, \
  29. APNS_CONFIG, BASE_DIR, APNS_MODE
  30. from AnsjerPush.config import SERVER_TYPE
  31. from Model.models import Equipment_Info, UidPushModel, SysMsgModel
  32. from Object.ETkObject import ETkObject
  33. from Object.RedisObject import RedisObject
  34. from Object.UidTokenObject import UidTokenObject
  35. from Object.utils import LocalDateTimeUtil
  36. from Service.CommonService import CommonService
  37. from Service.EquipmentInfoService import EquipmentInfoService
  38. '''
  39. http://push.dvema.com/notify/push?etk=Y2lTRXhMTjBWS01sWlpURTVJU0ZWTlJ6RXhNVUU9T3o=&n_time=1526845794&channel=1&event_type=704&is_st=0
  40. http://push.dvema.com/deviceShadow/generateUTK?username=debug_user&password=debug_password&uid=VVDHCVBYDKFMJRWA111A
  41. '''
  42. # 移动侦测接口
  43. class NotificationView(View):
  44. def get(self, request, *args, **kwargs):
  45. request.encoding = 'utf-8'
  46. return self.validation(request.GET)
  47. def post(self, request, *args, **kwargs):
  48. request.encoding = 'utf-8'
  49. operation = kwargs.get('operation')
  50. if operation == 'test_apns':
  51. return self.test_apns(request.POST)
  52. return self.validation(request.POST)
  53. def validation(self, request_dict):
  54. logger = logging.getLogger('info')
  55. logger.info("进来推送接口了")
  56. logger.info(request_dict)
  57. logger.info('使用配置: {}'.format(SERVER_TYPE))
  58. uidToken = request_dict.get('uidToken', None)
  59. etk = request_dict.get('etk', None)
  60. channel = request_dict.get('channel', '1')
  61. n_time = request_dict.get('n_time', None)
  62. event_type = request_dict.get('event_type', None)
  63. is_st = request_dict.get('is_st', None)
  64. company_secrete = request_dict.get('company_secrete', None)
  65. region = request_dict.get('region', None)
  66. electricity = request_dict.get('electricity', '')
  67. if not all([channel, n_time]):
  68. return JsonResponse(status=200, data={
  69. 'code': 444,
  70. 'msg': 'param is wrong'})
  71. if not region or not is_st:
  72. return JsonResponse(status=200, data={'code': 404, 'msg': 'no region or is_st'})
  73. try:
  74. is_st = int(is_st)
  75. region = int(region)
  76. # 解密获取uid
  77. if etk:
  78. eto = ETkObject(etk)
  79. uid = eto.uid
  80. else:
  81. uto = UidTokenObject(uidToken)
  82. uid = uto.UID
  83. # uid = request_dict.get('uid', None) # 调试
  84. # 判断uid长度
  85. if len(uid) != 20 and len(uid) != 14:
  86. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong uid'})
  87. logger.info('调用推送接口的uid:{}'.format(uid))
  88. pkey = '{uid}_{channel}_{event_type}_ptl'.format(uid=uid, channel=channel, event_type=event_type)
  89. ykey = '{uid}_redis_qs'.format(uid=uid)
  90. is_sys_msg = self.is_sys_msg(int(event_type))
  91. if is_sys_msg:
  92. dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, channel=channel, event_type=event_type)
  93. else:
  94. dkey = '{uid}_{channel}_flag'.format(uid=uid, channel=channel)
  95. redisObj = RedisObject(db=6)
  96. have_ykey = redisObj.get_data(key=ykey) # uid_set 数据库缓存
  97. have_pkey = redisObj.get_data(key=pkey) # 一分钟限制key
  98. have_dkey = redisObj.get_data(key=dkey) # 推送消息时间间隔
  99. logger.info('ykey:{}, pkey: {}, dkey: {},'.format(have_ykey, have_pkey, have_dkey))
  100. # 一分钟内不推送
  101. if have_pkey:
  102. return JsonResponse(status=200, data={'code': 0, 'msg': 'Push again in one minute'})
  103. redisObj.set_data(key=pkey, val=1, expire=60)
  104. # 查询推送数据
  105. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  106. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
  107. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  108. 'uid_set__channel')
  109. if not uid_push_qs.exists():
  110. logger.info('uid_push 数据不存在')
  111. return JsonResponse(status=200, data={'code': 176, 'msg': 'no uid_push data'})
  112. redis_list = []
  113. for qs in uid_push_qs:
  114. redis_list.append(qs)
  115. # 修改redis数据,并设置过期时间为10分钟
  116. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  117. nickname = redis_list[0]['uid_set__nickname']
  118. detect_interval = redis_list[0]['uid_set__detect_interval']
  119. detect_group = redis_list[0]['uid_set__detect_group']
  120. if not nickname:
  121. nickname = uid
  122. if not have_dkey:
  123. # 设置推送消息的时间间隔
  124. if detect_group == '0' or detect_group == '':
  125. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  126. else:
  127. detect_group_list = detect_group.split(',')
  128. if event_type in detect_group_list:
  129. if detect_interval < 60:
  130. detect_interval = 60
  131. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  132. if is_st == 1 or is_st == 3: # 使用aws s3
  133. aws_s3_client = s3_client(region=region)
  134. kwag_args = {
  135. 'uid': uid,
  136. 'channel': channel,
  137. 'event_type': event_type,
  138. 'n_time': n_time,
  139. }
  140. eq_list = []
  141. sys_msg_list = []
  142. userID_ids = []
  143. do_apns_code = ''
  144. do_fcm_code = ''
  145. do_jpush_code = ''
  146. logger.info('进入手机推送------')
  147. logger.info('uid={}'.format(uid))
  148. logger.info(redis_list)
  149. new_device_info_list = []
  150. local_date_now = str(datetime.datetime.fromtimestamp(int(n_time)).date())
  151. timeArray = time.localtime(n_time)
  152. str_time = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
  153. logging.info('设备格式化后时间{},设备时间戳{}'.format(str_time, n_time))
  154. logger.info('日期{},时间戳{}'.format(local_date_now, n_time))
  155. for up in redis_list:
  156. push_type = up['push_type']
  157. appBundleId = up['appBundleId']
  158. token_val = up['token_val']
  159. lang = up['lang']
  160. tz = up['tz']
  161. if tz is None or tz == '':
  162. tz = 0
  163. # 发送标题
  164. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  165. # 发送内容
  166. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  167. event_type=event_type, electricity=electricity)
  168. kwag_args['appBundleId'] = appBundleId
  169. kwag_args['token_val'] = token_val
  170. kwag_args['msg_title'] = msg_title
  171. kwag_args['msg_text'] = msg_text
  172. logger.info('推送要的数据: {}'.format(kwag_args))
  173. # 以下是存库
  174. userID_id = up["userID_id"]
  175. if userID_id not in userID_ids:
  176. now_time = int(time.time())
  177. if is_sys_msg:
  178. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  179. event_type=event_type, electricity=electricity, is_sys=1)
  180. sys_msg_list.append(SysMsgModel(
  181. userID_id=userID_id,
  182. msg=sys_msg_text,
  183. addTime=now_time,
  184. updTime=now_time,
  185. uid=uid,
  186. eventType=event_type))
  187. else:
  188. # eq_list.append(Equipment_Info(
  189. # userID_id=userID_id,
  190. # eventTime=n_time,
  191. # eventType=event_type,
  192. # devUid=uid,
  193. # devNickName=nickname,
  194. # Channel=channel,
  195. # alarm='Motion \tChannel:{channel}'.format(channel=channel),
  196. # is_st=is_st,
  197. # receiveTime=n_time,
  198. # addTime=now_time,
  199. # storage_location=2,
  200. # borderCoords='',
  201. # ))
  202. # start 根据设备侦测时间为准进行分表存储数据
  203. logger.info('分表存数据start------')
  204. new_device_info_list.append(EquipmentInfoService.get_equipment_info_obj(
  205. local_date_now,
  206. device_user_id=userID_id,
  207. event_time=n_time,
  208. event_type=event_type,
  209. device_uid=uid,
  210. device_nick_name=nickname,
  211. channel=channel,
  212. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  213. is_st=is_st,
  214. receive_time=n_time,
  215. add_time=now_time,
  216. storage_location=2,
  217. border_coords='',
  218. ))
  219. # end
  220. userID_ids.append(userID_id)
  221. try:
  222. # 推送消息
  223. if not have_dkey:
  224. if push_type == 0: # ios apns
  225. do_apns_code = self.do_apns(**kwag_args)
  226. logger.info('进入do_apns,uid={}'.format(uid))
  227. logger.info('do_apns_code===={}'.format(do_apns_code))
  228. elif push_type == 1: # android gcm
  229. do_fcm_code = self.do_fcm(**kwag_args)
  230. elif push_type == 2: # android jpush
  231. do_jpush_code = self.do_jpush(**kwag_args)
  232. except Exception as e:
  233. logger.info(
  234. "errLine={errLine}, errMsg={errMsg}".format(errLine=e.__traceback__.tb_lineno, errMsg=repr(e)))
  235. continue
  236. if is_sys_msg:
  237. SysMsgModel.objects.bulk_create(sys_msg_list)
  238. else:
  239. # Equipment_Info.objects.bulk_create(eq_list)
  240. # new 分表批量存储 设备信息
  241. if new_device_info_list and len(new_device_info_list) > 0:
  242. # 根据日期获得星期几
  243. week = LocalDateTimeUtil.date_to_week(local_date_now)
  244. EquipmentInfoService.equipment_info_bulk_create(week, new_device_info_list)
  245. logger.info('设备信息分表批量保存end------')
  246. if is_st == 0 or is_st == 2:
  247. for up in redis_list:
  248. if up['push_type'] == 0: # ios apns
  249. up['do_apns_code'] = do_apns_code
  250. elif up['push_type'] == 1: # android gcm
  251. up['do_fcm_code'] = do_fcm_code
  252. elif up['push_type'] == 2: # android jpush
  253. up['do_jpush_code'] = do_jpush_code
  254. up['test_or_www'] = SERVER_TYPE
  255. del up['push_type']
  256. del up['userID_id']
  257. del up['userID__NickName']
  258. del up['lang']
  259. del up['tz']
  260. del up['uid_set__nickname']
  261. del up['uid_set__detect_interval']
  262. del up['uid_set__detect_group']
  263. return JsonResponse(status=200, data={'code': 0, 'msg': 'success 0 or 2', 're_list': redis_list})
  264. elif is_st == 1:
  265. thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  266. Params = {'Key': thumbspng}
  267. if region == 2: # 2:国内
  268. Params['Bucket'] = 'push'
  269. else: # 1:国外
  270. Params['Bucket'] = 'foreignpush'
  271. response_url = generate_s3_url(aws_s3_client, Params)
  272. for up in redis_list:
  273. up['do_apns_code'] = do_apns_code
  274. up['do_fcm_code'] = do_fcm_code
  275. up['do_jpush_code'] = do_jpush_code
  276. up['test_or_www'] = SERVER_TYPE
  277. del up['push_type']
  278. del up['userID_id']
  279. del up['userID__NickName']
  280. del up['lang']
  281. del up['tz']
  282. del up['uid_set__nickname']
  283. del up['uid_set__detect_interval']
  284. del up['uid_set__detect_group']
  285. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
  286. return JsonResponse(status=200, data=res_data)
  287. elif is_st == 3:
  288. img_url_list = []
  289. if region == 2: # 2:国内
  290. Params = {'Bucket': 'push'}
  291. else: # 1:国外
  292. Params = {'Bucket': 'foreignpush'}
  293. for i in range(is_st):
  294. thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  295. format(uid=uid, channel=channel, filename=n_time, st=i)
  296. Params['Key'] = thumbspng
  297. response_url = generate_s3_url(aws_s3_client, Params)
  298. img_url_list.append(response_url)
  299. for up in redis_list:
  300. up['do_apns_code'] = do_apns_code
  301. up['do_fcm_code'] = do_fcm_code
  302. up['do_jpush_code'] = do_jpush_code
  303. up['test_or_www'] = SERVER_TYPE
  304. del up['push_type']
  305. del up['userID_id']
  306. del up['userID__NickName']
  307. del up['lang']
  308. del up['tz']
  309. del up['uid_set__nickname']
  310. del up['uid_set__detect_interval']
  311. del up['uid_set__detect_group']
  312. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
  313. return JsonResponse(status=200, data=res_data)
  314. except Exception as e:
  315. logger.info('移动侦测接口异常: {}'.format(e))
  316. logger.info('错误文件', e.__traceback__.tb_frame.f_globals['__file__'])
  317. logger.info('错误行号', e.__traceback__.tb_lineno)
  318. data = {
  319. 'errLine': e.__traceback__.tb_lineno,
  320. 'errMsg': repr(e),
  321. }
  322. return JsonResponse(status=200, data=json.dumps(data), safe=False)
  323. def test_apns(self, request_dict):
  324. kwag_args = {
  325. 'uid': request_dict.get('uid', None),
  326. 'channel': request_dict.get('channel', None),
  327. 'event_type': request_dict.get('event_type', None),
  328. 'n_time': request_dict.get('n_time', None),
  329. 'appBundleId': request_dict.get('appBundleId', None),
  330. 'token_val': request_dict.get('token_val', None),
  331. 'msg_title': request_dict.get('msg_title', None),
  332. 'msg_text': request_dict.get('msg_text', None),
  333. }
  334. do_apns_code = self.do_apns(**kwag_args)
  335. return JsonResponse(status=500, data={'do_apns_code': do_apns_code})
  336. def get_msg_title(self, appBundleId, nickname):
  337. package_title_config = {
  338. 'com.ansjer.customizedd_a': 'DVS',
  339. 'com.ansjer.zccloud_a': 'ZosiSmart',
  340. 'com.ansjer.zccloud_ab': '周视',
  341. 'com.ansjer.adcloud_a': 'ADCloud',
  342. 'com.ansjer.adcloud_ab': 'ADCloud',
  343. 'com.ansjer.accloud_a': 'ACCloud',
  344. 'com.ansjer.loocamccloud_a': 'Loocam',
  345. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  346. 'com.ansjer.customizedb_a': 'COCOONHD',
  347. 'com.ansjer.customizeda_a': 'Guardian365',
  348. 'com.ansjer.customizedc_a': 'PatrolSecure',
  349. }
  350. if appBundleId in package_title_config.keys():
  351. return package_title_config[appBundleId] + '(' + nickname + ')'
  352. else:
  353. return nickname
  354. def is_sys_msg(self, event_type):
  355. event_type_list = [702, 703, 704]
  356. if event_type in event_type_list:
  357. return True
  358. return False
  359. def get_msg_text(self, channel, n_time, lang, tz, event_type, electricity='', is_sys=0):
  360. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  361. etype = int(event_type)
  362. if lang == 'cn':
  363. if etype == 704:
  364. msg_type = '剩余电量:' + electricity
  365. elif etype == 702:
  366. msg_type = '摄像头休眠'
  367. elif etype == 703:
  368. msg_type = '摄像头唤醒'
  369. else:
  370. msg_type = ''
  371. if is_sys:
  372. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  373. else:
  374. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  375. # send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  376. else:
  377. if etype == 704:
  378. msg_type = 'Battery remaining:' + electricity
  379. elif etype == 702:
  380. msg_type = 'Camera sleep'
  381. elif etype == 703:
  382. msg_type = 'Camera wake'
  383. else:
  384. msg_type = ''
  385. if is_sys:
  386. send_text = '{msg_type} channel:{channel}'. \
  387. format(msg_type=msg_type, channel=channel)
  388. else:
  389. send_text = '{msg_type} channel:{channel} date:{date}'. \
  390. format(msg_type=msg_type, channel=channel, date=n_date)
  391. return send_text
  392. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
  393. msg_title, msg_text):
  394. app_key = JPUSH_CONFIG[appBundleId]['Key']
  395. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  396. # 此处换成各自的app_key和master_secre
  397. _jpush = jpush.JPush(app_key, master_secret)
  398. push = _jpush.create_push()
  399. # if you set the logging level to "DEBUG",it will show the debug logging.
  400. # _jpush.set_logging("DEBUG")
  401. # push.audience = jpush.all_
  402. push.audience = jpush.registration_id(token_val)
  403. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  404. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  405. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  406. big_text=msg_text, title=msg_title,
  407. extras=push_data)
  408. push.notification = jpush.notification(android=android)
  409. push.platform = jpush.all_
  410. res = push.send()
  411. print(res)
  412. return res.status_code
  413. # try:
  414. # res = push.send()
  415. # print(res)
  416. # except Exception as e:
  417. # print("jpush fail")
  418. # print("Exception")
  419. # print(repr(e))
  420. # return
  421. # else:
  422. # print("jpush success")
  423. # return
  424. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  425. logger = logging.getLogger('info')
  426. try:
  427. serverKey = FCM_CONFIG[appBundleId]
  428. except Exception as e:
  429. logger.info('------fcm_error:{}'.format(repr(e)))
  430. return 'serverKey abnormal'
  431. push_service = FCMNotification(api_key=serverKey)
  432. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  433. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  434. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  435. message_body=msg_text, data_message=data,
  436. extra_kwargs={
  437. 'default_vibrate_timings': True,
  438. 'default_sound': True,
  439. 'default_light_settings': True
  440. })
  441. logger.info('------fcm_status:')
  442. logger.info(result)
  443. print('fcm push ing')
  444. print(result)
  445. return result
  446. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  447. msg_text):
  448. logger = logging.getLogger('info')
  449. logger.info("进来do_apns函数了")
  450. logger.info(token_val)
  451. logger.info(APNS_MODE)
  452. logger.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  453. try:
  454. cli = apns2.APNSClient(mode=APNS_MODE,
  455. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  456. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  457. "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
  458. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  459. payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
  460. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  461. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  462. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  463. print(res.status_code)
  464. logger.info("apns_推送状态:")
  465. logger.info(res.status_code)
  466. # 200, 推送成功。
  467. #   400, 请求有问题。
  468. #   403, 证书或Token有问题。
  469. #   405, 请求方式不正确, 只支持POST请求
  470. #   410, 设备的Token与证书不一致
  471. if res.status_code == 200:
  472. return res.status_code
  473. else:
  474. print('apns push fail')
  475. print(res.reason)
  476. logger.info('apns push fail')
  477. logger.info(res.reason)
  478. return res.status_code
  479. except (ValueError, ArithmeticError):
  480. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  481. except Exception as e:
  482. print(repr(e))
  483. print('do_apns函数错误行号', e.__traceback__.tb_lineno)
  484. logger.info('do_apns错误:{}'.format(repr(e)))
  485. return repr(e)
  486. def do_update_detect_interval(self, uid, channel, redisObject, detect_interval):
  487. if channel == 0:
  488. channel = 17
  489. else:
  490. channel += 1
  491. for i in range(1, channel):
  492. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=51, channel=i)
  493. if tmpDKey is not False:
  494. llt = redisObject.get_ttl(tmpDKey)
  495. if llt > detect_interval:
  496. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  497. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=54, channel=i)
  498. if tmpDKey is not False:
  499. llt = redisObject.get_ttl(tmpDKey)
  500. if llt > detect_interval:
  501. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  502. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  503. # 移动侦测接口
  504. class PushNotificationView(View):
  505. def get(self, request, *args, **kwargs):
  506. request.encoding = 'utf-8'
  507. # operation = kwargs.get('operation')
  508. return self.validation(request.GET)
  509. def post(self, request, *args, **kwargs):
  510. request.encoding = 'utf-8'
  511. # operation = kwargs.get('operation')
  512. return self.validation(request.POST)
  513. def validation(self, request_dict):
  514. etk = request_dict.get('etk', None)
  515. channel = request_dict.get('channel', '1')
  516. n_time = request_dict.get('n_time', None)
  517. event_type = request_dict.get('event_type', None)
  518. is_st = request_dict.get('is_st', None)
  519. region = request_dict.get('region', '2')
  520. region = int(region)
  521. eto = ETkObject(etk)
  522. uid = eto.uid
  523. if len(uid) == 20:
  524. redisObj = RedisObject(db=6)
  525. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  526. pkey = '{uid}_ptl'.format(uid=uid)
  527. ykey = '{uid}_redis_qs'.format(uid=uid)
  528. if redisObj.get_data(key=pkey):
  529. res_data = {'code': 0, 'msg': 'success,!33333333333'}
  530. return JsonResponse(status=200, data=res_data)
  531. else:
  532. redisObj.set_data(key=pkey, val=1, expire=60)
  533. ##############
  534. redis_data = redisObj.get_data(key=ykey)
  535. if redis_data:
  536. redis_list = eval(redis_data)
  537. else:
  538. # 设置推送时间为60秒一次
  539. redisObj.set_data(key=pkey, val=1, expire=60)
  540. print("从数据库查到数据")
  541. # 从数据库查询出来
  542. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  543. values('token_val', 'app_type', 'appBundleId',
  544. 'push_type', 'userID_id', 'lang', 'm_code',
  545. 'tz', 'uid_set__nickname')
  546. # 新建一个list接收数据
  547. redis_list = []
  548. # 把数据库数据追加进redis_list
  549. for qs in uid_push_qs:
  550. redis_list.append(qs)
  551. # 修改redis数据,并设置过期时间为10分钟
  552. if redis_list:
  553. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  554. # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  555. # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  556. aws_s3_guonei = boto3.client(
  557. 's3',
  558. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  559. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  560. config=botocore.client.Config(signature_version='s3v4'),
  561. region_name='cn-northwest-1'
  562. )
  563. aws_s3_guowai = boto3.client(
  564. 's3',
  565. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  566. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  567. config=botocore.client.Config(signature_version='s3v4'),
  568. region_name='us-east-1'
  569. )
  570. self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
  571. if is_st == '0' or is_st == '2':
  572. return JsonResponse(status=200, data={'code': 0, 'msg': 'success44444444444444444'})
  573. elif is_st == '1':
  574. # Endpoint以杭州为例,其它Region请按实际情况填写。
  575. # obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  576. # 设置此签名URL在60秒内有效。
  577. # url = bucket.sign_url('PUT', obj, 7200)
  578. thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  579. if region == 2: # 2:国内
  580. response_url = aws_s3_guonei.generate_presigned_url(
  581. ClientMethod='put_object',
  582. Params={
  583. 'Bucket': 'push',
  584. 'Key': thumbspng
  585. },
  586. ExpiresIn=3600
  587. )
  588. else: # 1:国外
  589. response_url = aws_s3_guowai.generate_presigned_url(
  590. ClientMethod='put_object',
  591. Params={
  592. 'Bucket': 'foreignpush',
  593. 'Key': thumbspng
  594. },
  595. ExpiresIn=3600
  596. )
  597. # res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  598. # response_url = response_url[:4] + response_url[5:]
  599. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
  600. return JsonResponse(status=200, data=res_data)
  601. elif is_st == '3':
  602. # 人形检测带动图
  603. img_url_list = []
  604. for i in range(int(is_st)):
  605. # obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  606. # format(uid=uid, channel=channel, filename=n_time, st=i)
  607. # 设置此签名URL在60秒内有效。
  608. # url = bucket.sign_url('PUT', obj, 7200)
  609. thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  610. format(uid=uid, channel=channel, filename=n_time, st=i)
  611. if region == 2: # 2:国内
  612. response_url = aws_s3_guonei.generate_presigned_url(
  613. ClientMethod='put_object',
  614. Params={
  615. 'Bucket': 'push',
  616. 'Key': thumbspng
  617. },
  618. ExpiresIn=3600
  619. )
  620. else: # 1:国外
  621. response_url = aws_s3_guowai.generate_presigned_url(
  622. ClientMethod='put_object',
  623. Params={
  624. 'Bucket': 'foreignpush',
  625. 'Key': thumbspng
  626. },
  627. ExpiresIn=3600
  628. )
  629. # response_url = response_url[:4] + response_url[5:]
  630. img_url_list.append(response_url)
  631. # img_url_list.append(url)
  632. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  633. return JsonResponse(status=200, data=res_data)
  634. else:
  635. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  636. else:
  637. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  638. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  639. now_time = int(time.time())
  640. # 设备昵称
  641. userID_ids = []
  642. sys_msg_list = []
  643. is_sys_msg = self.is_sys_msg(int(event_type))
  644. is_st = int(is_st)
  645. eq_list = []
  646. nickname = uaqs[0]['uid_set__nickname']
  647. if not nickname:
  648. nickname = uid
  649. for ua in uaqs:
  650. lang = ua['lang']
  651. tz = ua['tz']
  652. userID_id = ua["userID_id"]
  653. if userID_id not in userID_ids:
  654. if is_sys_msg:
  655. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  656. event_type=event_type, is_sys=1)
  657. sys_msg_list.append(SysMsgModel(
  658. userID_id=userID_id,
  659. msg=sys_msg_text,
  660. addTime=now_time,
  661. updTime=now_time,
  662. uid=uid,
  663. eventType=event_type))
  664. else:
  665. eq_list.append(Equipment_Info(
  666. userID_id=userID_id,
  667. eventTime=n_time,
  668. eventType=event_type,
  669. devUid=uid,
  670. devNickName=nickname,
  671. Channel=channel,
  672. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  673. is_st=is_st,
  674. receiveTime=n_time,
  675. addTime=now_time,
  676. storage_location=2,
  677. borderCoords='',
  678. ))
  679. if eq_list:
  680. print('eq_list')
  681. Equipment_Info.objects.bulk_create(eq_list)
  682. if is_sys_msg:
  683. print('sys_msg')
  684. SysMsgModel.objects.bulk_create(sys_msg_list)
  685. return True
  686. def is_sys_msg(self, event_type):
  687. event_type_list = [702, 703, 704]
  688. if event_type in event_type_list:
  689. return True
  690. return False
  691. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  692. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  693. etype = int(event_type)
  694. if lang == 'cn':
  695. if etype == 704:
  696. msg_type = '剩余电量:'
  697. elif etype == 702:
  698. msg_type = '摄像头休眠'
  699. elif etype == 703:
  700. msg_type = '摄像头唤醒'
  701. else:
  702. msg_type = ''
  703. if is_sys:
  704. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  705. else:
  706. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  707. else:
  708. if etype == 704:
  709. msg_type = 'Battery remaining:'
  710. elif etype == 702:
  711. msg_type = 'Camera sleep'
  712. elif etype == 703:
  713. msg_type = 'Camera wake'
  714. else:
  715. msg_type = ''
  716. if is_sys:
  717. send_text = '{msg_type} channel:{channel}'. \
  718. format(msg_type=msg_type, channel=channel)
  719. else:
  720. send_text = '{msg_type} channel:{channel} date:{date}'. \
  721. format(msg_type=msg_type, channel=channel, date=n_date)
  722. return send_text
  723. # 低电量推送接口
  724. class PWnotificationView(View):
  725. def get(self, request, *args, **kwargs):
  726. request.encoding = 'utf-8'
  727. return self.validation(request.GET)
  728. def post(self, request, *args, **kwargs):
  729. request.encoding = 'utf-8'
  730. return self.validation(request.POST)
  731. def validation(self, request_dict):
  732. logger = logging.getLogger('info')
  733. uid = request_dict.get('uid', None)
  734. channel = request_dict.get('channel', None)
  735. electricity = request_dict.get('electricity', None)
  736. logger.info('调用低电量推送接口的uid: {},electricity: {}'.format(uid, electricity))
  737. try:
  738. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid). \
  739. values('token_val', 'app_type', 'appBundleId', 'm_code',
  740. 'push_type', 'userID_id', 'userID__NickName',
  741. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  742. 'uid_set__channel')
  743. if not uid_push_qs.exists():
  744. res_data = {'code': 173, 'msg': 'uid push data not exit!'}
  745. return JsonResponse(status=200, data=res_data)
  746. print(uid_push_qs)
  747. # 新建一个list接收数据
  748. redis_list = []
  749. # 把数据库数据追加进redis_list
  750. for qs in uid_push_qs:
  751. redis_list.append(qs)
  752. if not redis_list:
  753. res_data = {'code': 0, 'msg': 'no redis_list success!'}
  754. return JsonResponse(status=200, data=res_data)
  755. nickname = redis_list[0]['uid_set__nickname']
  756. if not nickname:
  757. nickname = uid
  758. now_time = int(time.time())
  759. channel = channel
  760. event_type = 704
  761. sys_msg_list = []
  762. userID_ids = []
  763. kwag_args = {
  764. 'uid': uid,
  765. 'channel': channel,
  766. 'event_type': event_type,
  767. 'n_time': now_time,
  768. }
  769. for up in redis_list:
  770. push_type = up['push_type']
  771. appBundleId = up['appBundleId']
  772. token_val = up['token_val']
  773. lang = up['lang']
  774. tz = up['tz']
  775. if tz is None or tz == '':
  776. tz = 0
  777. # 发送标题
  778. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  779. # 发送内容
  780. msg_text = self.get_msg_text(channel=channel, n_time=now_time, lang=lang, tz=tz,
  781. event_type=event_type, electricity=electricity)
  782. kwag_args['appBundleId'] = appBundleId
  783. kwag_args['token_val'] = token_val
  784. kwag_args['msg_title'] = msg_title
  785. kwag_args['msg_text'] = msg_text
  786. if push_type == 0: # ios apns
  787. do_apns_code = self.do_apns(**kwag_args)
  788. elif push_type == 1: # android gcm
  789. print('do_fcm')
  790. do_fcm_code = self.do_fcm(**kwag_args)
  791. elif push_type == 2: # android jpush
  792. print('do_jpush')
  793. do_jpush_code = self.do_jpush(**kwag_args)
  794. # 以下是存库
  795. userID_id = up["userID_id"]
  796. if userID_id not in userID_ids:
  797. sys_msg_text = self.get_msg_text(channel=channel, n_time=now_time, lang=lang, tz=tz,
  798. event_type=event_type, is_sys=1, electricity=electricity)
  799. sys_msg_list.append(SysMsgModel(
  800. userID_id=userID_id,
  801. msg=sys_msg_text,
  802. addTime=now_time,
  803. updTime=now_time,
  804. uid=uid,
  805. eventType=event_type,
  806. ))
  807. userID_ids.append(userID_id)
  808. SysMsgModel.objects.bulk_create(sys_msg_list)
  809. return JsonResponse(status=200, data={'code': 0})
  810. except Exception as e:
  811. logger.info('低电量推送接口异常: {}'.format(e))
  812. return JsonResponse(status=500)
  813. def get_msg_title(self, appBundleId, nickname):
  814. package_title_config = {
  815. 'com.ansjer.customizedd_a': 'DVS',
  816. 'com.ansjer.zccloud_a': 'ZosiSmart',
  817. 'com.ansjer.zccloud_ab': '周视',
  818. 'com.ansjer.adcloud_a': 'ADCloud',
  819. 'com.ansjer.adcloud_ab': 'ADCloud',
  820. 'com.ansjer.accloud_a': 'ACCloud',
  821. 'com.ansjer.loocamccloud_a': 'Loocam',
  822. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  823. 'com.ansjer.customizedb_a': 'COCOONHD',
  824. 'com.ansjer.customizeda_a': 'Guardian365',
  825. 'com.ansjer.customizedc_a': 'PatrolSecure',
  826. }
  827. if appBundleId in package_title_config.keys():
  828. return package_title_config[appBundleId] + '(' + nickname + ')'
  829. else:
  830. return nickname
  831. def is_sys_msg(self, event_type):
  832. event_type_list = [702, 703, 704]
  833. if event_type in event_type_list:
  834. return True
  835. return False
  836. def get_msg_text(self, channel, n_time, lang, tz, event_type, electricity, is_sys=0):
  837. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  838. etype = int(event_type)
  839. if lang == 'cn':
  840. if etype == 704:
  841. msg_type = '剩余电量:' + electricity
  842. elif etype == 702:
  843. msg_type = '摄像头休眠'
  844. elif etype == 703:
  845. msg_type = '摄像头唤醒'
  846. else:
  847. msg_type = ''
  848. if is_sys:
  849. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  850. else:
  851. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  852. # send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  853. else:
  854. if etype == 704:
  855. msg_type = 'Battery remaining:' + electricity
  856. elif etype == 702:
  857. msg_type = 'Camera sleep'
  858. elif etype == 703:
  859. msg_type = 'Camera wake'
  860. else:
  861. msg_type = ''
  862. if is_sys:
  863. send_text = '{msg_type} channel:{channel}'. \
  864. format(msg_type=msg_type, channel=channel)
  865. else:
  866. send_text = '{msg_type} channel:{channel} date:{date}'. \
  867. format(msg_type=msg_type, channel=channel, date=n_date)
  868. return send_text
  869. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
  870. msg_title, msg_text):
  871. app_key = JPUSH_CONFIG[appBundleId]['Key']
  872. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  873. # 此处换成各自的app_key和master_secre
  874. _jpush = jpush.JPush(app_key, master_secret)
  875. push = _jpush.create_push()
  876. # if you set the logging level to "DEBUG",it will show the debug logging.
  877. # _jpush.set_logging("DEBUG")
  878. # push.audience = jpush.all_
  879. push.audience = jpush.registration_id(token_val)
  880. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  881. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  882. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  883. big_text=msg_text, title=msg_title,
  884. extras=push_data)
  885. push.notification = jpush.notification(android=android)
  886. push.platform = jpush.all_
  887. res = push.send()
  888. print(res)
  889. return res.status_code
  890. # try:
  891. # res = push.send()
  892. # print(res)
  893. # except Exception as e:
  894. # print("jpush fail")
  895. # print("Exception")
  896. # print(repr(e))
  897. # return
  898. # else:
  899. # print("jpush success")
  900. # return
  901. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  902. try:
  903. serverKey = FCM_CONFIG[appBundleId]
  904. except Exception as e:
  905. return 'serverKey abnormal'
  906. push_service = FCMNotification(api_key=serverKey)
  907. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  908. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  909. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  910. message_body=msg_text, data_message=data,
  911. extra_kwargs={
  912. 'default_vibrate_timings': True,
  913. 'default_sound': True,
  914. 'default_light_settings': True
  915. })
  916. print('fcm push ing')
  917. print(result)
  918. return result
  919. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  920. msg_text):
  921. logger = logging.getLogger('info')
  922. logger.info("进来do_apns函数了")
  923. logger.info(token_val)
  924. logger.info(APNS_MODE)
  925. logger.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  926. try:
  927. cli = apns2.APNSClient(mode=APNS_MODE,
  928. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  929. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  930. "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
  931. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  932. payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
  933. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  934. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  935. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  936. print(res.status_code)
  937. logger.info("推送状态:")
  938. logger.info(res.status_code)
  939. # 200, 推送成功。
  940. #   400, 请求有问题。
  941. #   403, 证书或Token有问题。
  942. #   405, 请求方式不正确, 只支持POST请求
  943. #   410, 设备的Token与证书不一致
  944. if res.status_code == 200:
  945. return res.status_code
  946. else:
  947. print('apns push fail')
  948. print(res.reason)
  949. logger.info('apns push fail')
  950. logger.info(res.reason)
  951. return res.status_code
  952. except (ValueError, ArithmeticError):
  953. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  954. except Exception as e:
  955. print(repr(e))
  956. logger.info(repr(e))
  957. return repr(e)
  958. def do_update_detect_interval(self, uid, channel, redisObject, detect_interval):
  959. if channel == 0:
  960. channel = 17
  961. else:
  962. channel += 1
  963. for i in range(1, channel):
  964. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=51, channel=i)
  965. if tmpDKey is not False:
  966. llt = redisObject.get_ttl(tmpDKey)
  967. if llt > detect_interval:
  968. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  969. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=54, channel=i)
  970. if tmpDKey is not False:
  971. llt = redisObject.get_ttl(tmpDKey)
  972. if llt > detect_interval:
  973. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  974. def s3_client(region):
  975. if region == 2: # 国内
  976. aws_s3_client = boto3.client(
  977. 's3',
  978. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  979. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  980. config=botocore.client.Config(signature_version='s3v4'),
  981. region_name='cn-northwest-1'
  982. )
  983. else: # 国外
  984. aws_s3_client = boto3.client(
  985. 's3',
  986. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  987. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  988. config=botocore.client.Config(signature_version='s3v4'),
  989. region_name='us-east-1'
  990. )
  991. return aws_s3_client
  992. def generate_s3_url(aws_s3_client, Params):
  993. response_url = aws_s3_client.generate_presigned_url(
  994. ClientMethod='put_object',
  995. Params=Params,
  996. ExpiresIn=3600
  997. )
  998. return response_url