DetectControllerV2.py 44 KB

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