DetectControllerV2.py 50 KB

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