DetectControllerV2.py 49 KB

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