DetectControllerV2.py 51 KB

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