DetectControllerV2.py 50 KB

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