DetectController.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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 os
  15. import time
  16. import apns2
  17. import jpush as jpush
  18. import oss2
  19. from django.http import JsonResponse
  20. from django.views.generic.base import View
  21. from pyfcm import FCMNotification
  22. from AnsjerPush.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, DETECT_PUSH_DOMAIN, JPUSH_CONFIG, \
  23. FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE
  24. from Model.models import Equipment_Info, UidPushModel, SysMsgModel
  25. from Object.ETkObject import ETkObject
  26. from Object.RedisObject import RedisObject
  27. from Object.UidTokenObject import UidTokenObject
  28. from Service.CommonService import CommonService
  29. '''
  30. http://push.dvema.com/notify/push?etk=Y2lTRXhMTjBWS01sWlpURTVJU0ZWTlJ6RXhNVUU9T3o=&n_time=1526845794&channel=1&event_type=704&is_st=0
  31. http://push.dvema.com/deviceShadow/generateUTK?username=debug_user&password=debug_password&uid=VVDHCVBYDKFMJRWA111A
  32. '''
  33. # 移动侦测接口
  34. class NotificationView(View):
  35. def get(self, request, *args, **kwargs):
  36. request.encoding = 'utf-8'
  37. return self.validation(request.GET)
  38. def post(self, request, *args, **kwargs):
  39. request.encoding = 'utf-8'
  40. return self.validation(request.POST)
  41. def validation(self, request_dict):
  42. uidToken = request_dict.get('uidToken', None)
  43. etk = request_dict.get('etk', None)
  44. channel = request_dict.get('channel', '1')
  45. n_time = request_dict.get('n_time', None)
  46. event_type = request_dict.get('event_type', None)
  47. is_st = request_dict.get('is_st', None)
  48. # print("aaa")
  49. # return JsonResponse(0,safe=False)
  50. if not all([channel, n_time]):
  51. return JsonResponse(status=200, data={
  52. 'code': 444,
  53. 'msg': 'param is wrong'})
  54. if etk:
  55. eto = ETkObject(etk)
  56. uid = eto.uid
  57. if len(uid) != 20:
  58. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  59. else:
  60. utko = UidTokenObject(uidToken)
  61. uid = utko.UID
  62. pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  63. ykey = '{uid}_{channel}_redis_qs'.format(uid=uid, channel=channel)
  64. dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
  65. # 判断redisObj.get_data(key=pkey):不为空
  66. redisObj = RedisObject(db=6)
  67. have_ykey = redisObj.get_data(key=ykey) # uid_set 数据库缓存
  68. have_pkey = redisObj.get_data(key=pkey) # 一分钟限制key
  69. have_dkey = redisObj.get_data(key=dkey) # 推送类型限制
  70. # 一分钟外,推送开启状态
  71. detect_med_type = 0 # 0推送旧机制 1存库不推送,2推送存库
  72. if have_pkey:
  73. res_data = {'code': 0, 'msg': 'success!'}
  74. return JsonResponse(status=200, data=res_data)
  75. # 数据库读取数据
  76. if have_ykey:
  77. redis_list = eval(redisObj.get_data(key=ykey))
  78. else:
  79. # 从数据库查询出来
  80. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid,uid_set__detect_status=1). \
  81. values('token_val', 'app_type', 'appBundleId',
  82. 'push_type', 'userID_id', 'userID__NickName',
  83. 'lang', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group')
  84. # 新建一个list接收数据
  85. redis_list = []
  86. # 把数据库数据追加进redis_list
  87. for qs in uid_push_qs:
  88. redis_list.append(qs)
  89. # 修改redis数据,并设置过期时间为10分钟
  90. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  91. if not redis_list:
  92. print("没有redi_list")
  93. res_data = {'code': 0, 'msg': 'success!'}
  94. return JsonResponse(status=200, data=res_data)
  95. is_sys_msg = self.is_sys_msg(int(event_type))
  96. nickname = redis_list[0]['uid_set__nickname']
  97. detect_interval = redis_list[0]['uid_set__detect_interval']
  98. detect_group = redis_list[0]['uid_set__detect_group']
  99. now_time = int(time.time())
  100. if not nickname:
  101. nickname = uid
  102. if detect_group:
  103. if have_dkey:
  104. detect_med_type = 1
  105. else:
  106. detect_med_type = 2
  107. detect_group_list = detect_group.split(',')
  108. if event_type in detect_group_list:
  109. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  110. redisObj.set_data(key=pkey, val=1, expire=60)
  111. # 旧模式并且没有pkey,重新创建一个
  112. if not detect_group and not have_pkey:
  113. # 设置推送时间为60秒一次
  114. redisObj.set_data(key=pkey, val=1, expire=60)
  115. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  116. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  117. kwag_args = {
  118. 'uid': uid,
  119. 'channel': channel,
  120. 'event_type': event_type,
  121. 'n_time': n_time,
  122. # 'appBundleId': appBundleId,
  123. # 'token_val': token_val,
  124. # 'msg_title': msg_title,
  125. # 'msg_text': msg_text
  126. }
  127. eq_list = []
  128. sys_msg_list = []
  129. userID_ids = []
  130. for up in redis_list:
  131. push_type = up['push_type']
  132. appBundleId = up['appBundleId']
  133. token_val = up['token_val']
  134. lang = up['lang']
  135. tz = up['tz']
  136. # 发送标题
  137. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  138. # 发送内容
  139. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  140. event_type=event_type)
  141. kwag_args['appBundleId'] = appBundleId
  142. kwag_args['token_val'] = token_val
  143. kwag_args['msg_title'] = msg_title
  144. kwag_args['msg_text'] = msg_text
  145. #推送
  146. if detect_med_type == 2 or detect_med_type == 0:
  147. if push_type == 0: # ios apns
  148. self.do_apns(**kwag_args)
  149. elif push_type == 1: # android gcm
  150. self.do_fcm(**kwag_args)
  151. elif push_type == 2: # android jpush
  152. self.do_jpush(**kwag_args)
  153. # 以下是存库
  154. userID_id = up["userID_id"]
  155. int_is_st = int(is_st)
  156. if userID_id not in userID_ids:
  157. eq_list.append(Equipment_Info(
  158. userID_id=userID_id,
  159. eventTime=n_time,
  160. eventType=event_type,
  161. devUid=uid,
  162. devNickName=nickname,
  163. Channel=channel,
  164. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  165. is_st=int_is_st,
  166. receiveTime=n_time,
  167. addTime=now_time
  168. ))
  169. if is_sys_msg:
  170. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  171. event_type=event_type, is_sys=1)
  172. sys_msg_list.append(SysMsgModel(
  173. userID_id=userID_id,
  174. msg=sys_msg_text,
  175. addTime=now_time,
  176. updTime=now_time,
  177. uid=uid,
  178. eventType=event_type))
  179. userID_ids.append(userID_id)
  180. if is_sys_msg:
  181. SysMsgModel.objects.bulk_create(sys_msg_list)
  182. Equipment_Info.objects.bulk_create(eq_list)
  183. if is_st == '0' or is_st == '2':
  184. print("is_st=0or2")
  185. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  186. elif is_st == '1':
  187. print("is_st=1")
  188. # Endpoint以杭州为例,其它Region请按实际情况填写。
  189. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  190. # 设置此签名URL在60秒内有效。
  191. url = bucket.sign_url('PUT', obj, 7200)
  192. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  193. return JsonResponse(status=200, data=res_data)
  194. elif is_st == '3':
  195. print("is_st=3")
  196. # 人形检测带动图
  197. # Endpoint以杭州为例,其它Region请按实际情况填写。
  198. img_url_list = []
  199. for i in range(int(is_st)):
  200. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  201. format(uid=uid, channel=channel, filename=n_time, st=i)
  202. # 设置此签名URL在60秒内有效。
  203. url = bucket.sign_url('PUT', obj, 7200)
  204. img_url_list.append(url)
  205. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  206. return JsonResponse(status=200, data=res_data)
  207. def get_msg_title(self, appBundleId, nickname):
  208. package_title_config = {
  209. 'com.ansjer.customizedd_a': 'DVS',
  210. 'com.ansjer.zccloud_a': 'ZosiSmart',
  211. 'com.ansjer.zccloud_ab': '周视',
  212. 'com.ansjer.adcloud_a': 'ADCloud',
  213. 'com.ansjer.adcloud_ab': 'ADCloud',
  214. 'com.ansjer.accloud_a': 'ACCloud',
  215. 'com.ansjer.loocamccloud_a': 'Loocam',
  216. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  217. 'com.ansjer.customizedb_a': 'COCOONHD',
  218. 'com.ansjer.customizeda_a': 'Guardian365',
  219. 'com.ansjer.customizedc_a': 'PatrolSecure',
  220. }
  221. if appBundleId in package_title_config.keys():
  222. return package_title_config[appBundleId] + '(' + nickname + ')'
  223. else:
  224. return nickname
  225. def is_sys_msg(self, event_type):
  226. event_type_list = [702, 703, 704]
  227. if event_type in event_type_list:
  228. return True
  229. return False
  230. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  231. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  232. etype = int(event_type)
  233. if lang == 'cn':
  234. if etype == 704:
  235. msg_type = '电量过低'
  236. elif etype == 702:
  237. msg_type = '摄像头休眠'
  238. elif etype == 703:
  239. msg_type = '摄像头唤醒'
  240. else:
  241. msg_type = ''
  242. if is_sys:
  243. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  244. else:
  245. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  246. # send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  247. else:
  248. if etype == 704:
  249. msg_type = 'Low battery'
  250. elif etype == 702:
  251. msg_type = 'Camera sleep'
  252. elif etype == 703:
  253. msg_type = 'Camera wake'
  254. else:
  255. msg_type = ''
  256. if is_sys:
  257. send_text = '{msg_type} channel:{channel}'. \
  258. format(msg_type=msg_type, channel=channel)
  259. else:
  260. send_text = '{msg_type} channel:{channel} date:{date}'. \
  261. format(msg_type=msg_type, channel=channel, date=n_date)
  262. return send_text
  263. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
  264. msg_title, msg_text):
  265. app_key = JPUSH_CONFIG[appBundleId]['Key']
  266. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  267. # 此处换成各自的app_key和master_secre
  268. _jpush = jpush.JPush(app_key, master_secret)
  269. push = _jpush.create_push()
  270. # if you set the logging level to "DEBUG",it will show the debug logging.
  271. # _jpush.set_logging("DEBUG")
  272. # push.audience = jpush.all_
  273. push.audience = jpush.registration_id(token_val)
  274. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  275. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  276. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  277. big_text=msg_text, title=msg_title,
  278. extras=push_data)
  279. push.notification = jpush.notification(android=android)
  280. push.platform = jpush.all_
  281. try:
  282. res = push.send()
  283. print(res)
  284. except Exception as e:
  285. print("jpush fail")
  286. print("Exception")
  287. print(repr(e))
  288. return
  289. else:
  290. print("jpush success")
  291. return
  292. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  293. try:
  294. serverKey = FCM_CONFIG[appBundleId]
  295. except Exception as e:
  296. return
  297. push_service = FCMNotification(api_key=serverKey)
  298. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  299. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  300. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  301. message_body=msg_text, data_message=data,
  302. extra_kwargs={
  303. 'default_vibrate_timings': True,
  304. 'default_sound': True,
  305. 'default_light_settings': True
  306. })
  307. print('fcm push ing')
  308. print(result)
  309. return
  310. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  311. msg_text):
  312. try:
  313. cli = apns2.APNSClient(mode=APNS_MODE,
  314. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  315. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  316. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  317. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  318. payload = apns2.Payload(alert=alert, custom=push_data)
  319. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  320. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  321. print(res.status_code)
  322. if res.status_code == 200:
  323. print('apns push success')
  324. return
  325. else:
  326. print('apns push fail')
  327. print(res.reason)
  328. return
  329. except Exception as e:
  330. print(repr(e))
  331. return
  332. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  333. # 移动侦测接口
  334. class PushNotificationView(View):
  335. def get(self, request, *args, **kwargs):
  336. request.encoding = 'utf-8'
  337. # operation = kwargs.get('operation')
  338. return self.validation(request.GET)
  339. def post(self, request, *args, **kwargs):
  340. request.encoding = 'utf-8'
  341. # operation = kwargs.get('operation')
  342. return self.validation(request.POST)
  343. def validation(self, request_dict):
  344. etk = request_dict.get('etk', None)
  345. channel = request_dict.get('channel', '1')
  346. n_time = request_dict.get('n_time', None)
  347. event_type = request_dict.get('event_type', None)
  348. is_st = request_dict.get('is_st', None)
  349. eto = ETkObject(etk)
  350. uid = eto.uid
  351. if len(uid) == 20:
  352. redisObj = RedisObject(db=6)
  353. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  354. pkey = '{uid}_ptl'.format(uid=uid)
  355. ykey = '{uid}_redis_qs'.format(uid=uid)
  356. if redisObj.get_data(key=pkey):
  357. res_data = {'code': 0, 'msg': 'success,!'}
  358. return JsonResponse(status=200, data=res_data)
  359. else:
  360. redisObj.set_data(key=pkey, val=1, expire=60)
  361. ##############
  362. redis_data = redisObj.get_data(key=ykey)
  363. if redis_data:
  364. redis_list = eval(redis_data)
  365. else:
  366. # 设置推送时间为60秒一次
  367. redisObj.set_data(key=pkey, val=1, expire=60)
  368. print("从数据库查到数据")
  369. # 从数据库查询出来
  370. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  371. values('token_val', 'app_type', 'appBundleId',
  372. 'push_type', 'userID_id', 'lang',
  373. 'tz', 'uid_set__nickname')
  374. # 新建一个list接收数据
  375. redis_list = []
  376. # 把数据库数据追加进redis_list
  377. for qs in uid_push_qs:
  378. redis_list.append(qs)
  379. # 修改redis数据,并设置过期时间为10分钟
  380. if redis_list:
  381. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  382. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  383. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  384. self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
  385. if is_st == '0' or is_st == '2':
  386. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  387. elif is_st == '1':
  388. # Endpoint以杭州为例,其它Region请按实际情况填写。
  389. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  390. # 设置此签名URL在60秒内有效。
  391. url = bucket.sign_url('PUT', obj, 7200)
  392. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  393. return JsonResponse(status=200, data=res_data)
  394. elif is_st == '3':
  395. # 人形检测带动图
  396. img_url_list = []
  397. for i in range(int(is_st)):
  398. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  399. format(uid=uid, channel=channel, filename=n_time, st=i)
  400. # 设置此签名URL在60秒内有效。
  401. url = bucket.sign_url('PUT', obj, 7200)
  402. img_url_list.append(url)
  403. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  404. return JsonResponse(status=200, data=res_data)
  405. else:
  406. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  407. else:
  408. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  409. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  410. now_time = int(time.time())
  411. # 设备昵称
  412. userID_ids = []
  413. sys_msg_list = []
  414. is_sys_msg = self.is_sys_msg(int(event_type))
  415. is_st = int(is_st)
  416. eq_list = []
  417. nickname = uaqs[0]['uid_set__nickname']
  418. if not nickname:
  419. nickname = uid
  420. for ua in uaqs:
  421. lang = ua['lang']
  422. tz = ua['tz']
  423. userID_id = ua["userID_id"]
  424. if userID_id not in userID_ids:
  425. eq_list.append(Equipment_Info(
  426. userID_id=userID_id,
  427. eventTime=n_time,
  428. eventType=event_type,
  429. devUid=uid,
  430. devNickName=nickname,
  431. Channel=channel,
  432. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  433. is_st=is_st,
  434. receiveTime=n_time,
  435. addTime=now_time
  436. ))
  437. if is_sys_msg:
  438. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  439. event_type=event_type, is_sys=1)
  440. sys_msg_list.append(SysMsgModel(
  441. userID_id=userID_id,
  442. msg=sys_msg_text,
  443. addTime=now_time,
  444. updTime=now_time,
  445. uid=uid,
  446. eventType=event_type))
  447. if eq_list:
  448. print('eq_list')
  449. Equipment_Info.objects.bulk_create(eq_list)
  450. if is_sys_msg:
  451. print('sys_msg')
  452. SysMsgModel.objects.bulk_create(sys_msg_list)
  453. return True
  454. def is_sys_msg(self, event_type):
  455. event_type_list = [702, 703, 704]
  456. if event_type in event_type_list:
  457. return True
  458. return False
  459. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  460. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  461. etype = int(event_type)
  462. if lang == 'cn':
  463. if etype == 704:
  464. msg_type = '电量过低'
  465. elif etype == 702:
  466. msg_type = '摄像头休眠'
  467. elif etype == 703:
  468. msg_type = '摄像头唤醒'
  469. else:
  470. msg_type = ''
  471. if is_sys:
  472. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  473. else:
  474. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  475. else:
  476. if etype == 704:
  477. msg_type = 'Low battery'
  478. elif etype == 702:
  479. msg_type = 'Camera sleep'
  480. elif etype == 703:
  481. msg_type = 'Camera wake'
  482. else:
  483. msg_type = ''
  484. if is_sys:
  485. send_text = '{msg_type} channel:{channel}'. \
  486. format(msg_type=msg_type, channel=channel)
  487. else:
  488. send_text = '{msg_type} channel:{channel} date:{date}'. \
  489. format(msg_type=msg_type, channel=channel, date=n_date)
  490. return send_text