DetectControllerV2.py 48 KB

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