DetectControllerV2.py 46 KB

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