DetectControllerV2.py 49 KB

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