DetectControllerV2.py 49 KB

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