DetectController.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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, UidSetModel, UidPushModel
  25. from Object.ETkObject import ETkObject
  26. from Object.RedisObject import RedisObject
  27. from Object.ResponseObject import ResponseObject
  28. from Object.UidTokenObject import UidTokenObject
  29. from Service.CommonService import CommonService
  30. # http://test.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  31. # 移动侦测接口
  32. class NotificationView(View):
  33. def get(self, request, *args, **kwargs):
  34. request.encoding = 'utf-8'
  35. # operation = kwargs.get('operation')
  36. return self.validation(request.GET)
  37. def post(self, request, *args, **kwargs):
  38. request.encoding = 'utf-8'
  39. # operation = kwargs.get('operation')
  40. return self.validation(request.POST)
  41. def validation11(self, request_dict):
  42. response = ResponseObject()
  43. uidToken = request_dict.get('uidToken', 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. if not all([uidToken, channel, n_time]):
  49. return JsonResponse(status=200, data={
  50. 'code': 444,
  51. 'msg': 'param is wrong'})
  52. # return response.json(444)
  53. utko = UidTokenObject(uidToken)
  54. uid = utko.UID
  55. redisObj = RedisObject(db=6)
  56. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  57. pkey = '{uid}_ptl'.format(uid=uid)
  58. if redisObj.get_data(key=pkey):
  59. res_data = {'code': 0, 'msg': 'success,!'}
  60. return JsonResponse(status=200, data=res_data)
  61. else:
  62. # 设置推送间隔60秒一次
  63. redisObj.set_data(key=pkey, val=1, expire=60)
  64. uid_set_qs = UidSetModel.objects.filter(uid=uid, detect_status=1)
  65. if uid_set_qs.exists():
  66. uid_set_id = uid_set_qs[0].id
  67. nickname = uid_set_qs[0].nickname
  68. if not nickname:
  69. nickname = uid
  70. uid_push_qs = UidPushModel.objects.filter(uid_set__id=uid_set_id). \
  71. values('token_val', 'app_type', 'appBundleId', 'push_type', 'userID_id', 'userID__NickName', 'lang',
  72. 'tz')
  73. if uid_push_qs.exists():
  74. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  75. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  76. for up in uid_push_qs:
  77. push_type = up['push_type']
  78. # ios apns
  79. print(push_type)
  80. if push_type == 0:
  81. self.do_apns(request_dict, up, response, uid, channel, nickname)
  82. # android gcm
  83. elif push_type == 1:
  84. self.do_fcm(request_dict, up, response, uid, channel, nickname)
  85. # self.do_gmc(request_dict, up, response, uid, channel,nickname)
  86. # android jpush
  87. elif push_type == 2:
  88. self.do_jpush(request_dict, up, response, uid, channel, nickname)
  89. # self.do_save_equipment_info(ua, n_time, channel, event_type, is_st)
  90. # 需求不一样,所以这么做的
  91. self.do_bulk_create_info(uid_push_qs, n_time, channel, event_type, is_st, uid)
  92. if is_st == '0' or is_st == '2':
  93. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  94. elif is_st == '1':
  95. # Endpoint以杭州为例,其它Region请按实际情况填写。
  96. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  97. # 设置此签名URL在60秒内有效。
  98. url = bucket.sign_url('PUT', obj, 7200)
  99. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  100. return JsonResponse(status=200, data=res_data)
  101. elif is_st == '3':
  102. # 人形检测带动图
  103. # Endpoint以杭州为例,其它Region请按实际情况填写。
  104. img_url_list = []
  105. for i in range(int(is_st)):
  106. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  107. format(uid=uid, channel=channel, filename=n_time, st=i)
  108. # 设置此签名URL在60秒内有效。
  109. url = bucket.sign_url('PUT', obj, 7200)
  110. img_url_list.append(url)
  111. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  112. return JsonResponse(status=200, data=res_data)
  113. else:
  114. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  115. else:
  116. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  117. def validation(self, request_dict):
  118. response = ResponseObject()
  119. uidToken = request_dict.get('uidToken', None)
  120. channel = request_dict.get('channel', '1')
  121. n_time = request_dict.get('n_time', None)
  122. event_type = request_dict.get('event_type', None)
  123. is_st = request_dict.get('is_st', None)
  124. if not all([uidToken, channel, n_time]):
  125. return JsonResponse(status=200, data={
  126. 'code': 444,
  127. 'msg': 'param is wrong'})
  128. # return response.json(444)
  129. utko = UidTokenObject(uidToken)
  130. uid = utko.UID
  131. redisObj = RedisObject(db=6)
  132. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  133. pkey = '{uid}_ptl'.format(uid=uid)
  134. if redisObj.get_data(key=pkey):
  135. res_data = {'code': 0, 'msg': 'success,!'}
  136. return JsonResponse(status=200, data=res_data)
  137. else:
  138. # 设置推送间隔60秒一次
  139. redisObj.set_data(key=pkey, val=1, expire=60)
  140. # uid_set_id = uid_set_qs[0].id
  141. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid). \
  142. values('token_val', 'app_type', 'appBundleId',
  143. 'push_type', 'userID_id', 'userID__NickName',
  144. 'lang', 'tz','uid_set__nickname')
  145. if uid_push_qs.exists():
  146. nickname = uid_push_qs[0]['uid_set__nickname']
  147. if not nickname:
  148. nickname = uid
  149. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  150. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  151. for up in uid_push_qs:
  152. push_type = up['push_type']
  153. # ios apns
  154. print(push_type)
  155. if push_type == 0:
  156. self.do_apns(request_dict, up, response, uid, channel, nickname)
  157. # android gcm
  158. elif push_type == 1:
  159. self.do_fcm(request_dict, up, response, uid, channel, nickname)
  160. # self.do_gmc(request_dict, up, response, uid, channel,nickname)
  161. # android jpush
  162. elif push_type == 2:
  163. self.do_jpush(request_dict, up, response, uid, channel, nickname)
  164. # self.do_save_equipment_info(ua, n_time, channel, event_type, is_st)
  165. # 需求不一样,所以这么做的
  166. self.do_bulk_create_info(uid_push_qs, n_time, channel, event_type, is_st, uid)
  167. if is_st == '0' or is_st == '2':
  168. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  169. elif is_st == '1':
  170. # Endpoint以杭州为例,其它Region请按实际情况填写。
  171. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  172. # 设置此签名URL在60秒内有效。
  173. url = bucket.sign_url('PUT', obj, 7200)
  174. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  175. return JsonResponse(status=200, data=res_data)
  176. elif is_st == '3':
  177. # 人形检测带动图
  178. # Endpoint以杭州为例,其它Region请按实际情况填写。
  179. img_url_list = []
  180. for i in range(int(is_st)):
  181. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  182. format(uid=uid, channel=channel, filename=n_time, st=i)
  183. # 设置此签名URL在60秒内有效。
  184. url = bucket.sign_url('PUT', obj, 7200)
  185. img_url_list.append(url)
  186. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  187. return JsonResponse(status=200, data=res_data)
  188. else:
  189. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  190. def do_jpush(self, request_dict, uaql, response, uid, channel, nickname):
  191. event_type = request_dict.get('event_type', None)
  192. n_time = request_dict.get('n_time', None)
  193. appBundleId = uaql['appBundleId']
  194. token_val = uaql['token_val']
  195. lang = uaql['lang']
  196. tz = uaql['tz']
  197. response = ResponseObject()
  198. app_key = JPUSH_CONFIG[appBundleId]['Key']
  199. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  200. # 此处换成各自的app_key和master_secre
  201. _jpush = jpush.JPush(app_key, master_secret)
  202. push = _jpush.create_push()
  203. # if you set the logging level to "DEBUG",it will show the debug logging.
  204. _jpush.set_logging("DEBUG")
  205. # push.audience = jpush.all_
  206. push.audience = jpush.registration_id(token_val)
  207. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  208. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  209. message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
  210. send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)
  211. android = jpush.android(alert=send_text, priority=1, style=1, alert_type=7,
  212. big_text=send_text, title=message_title,
  213. extras=push_data)
  214. push.notification = jpush.notification(android=android)
  215. push.platform = jpush.all_
  216. try:
  217. res = push.send()
  218. print(res)
  219. except Exception as e:
  220. print("Exception")
  221. print(repr(e))
  222. return response.json(10, repr(e))
  223. else:
  224. return response.json(0)
  225. def get_message_title(self, appBundleId, nickname):
  226. package_title_config = {
  227. 'com.ansjer.customizedd_a': 'DVS',
  228. 'com.ansjer.zccloud_a': 'ZosiSmart',
  229. 'com.ansjer.zccloud_ab': '周视',
  230. 'com.ansjer.adcloud_a': 'ADCloud',
  231. 'com.ansjer.adcloud_ab': 'ADCloud',
  232. 'com.ansjer.accloud_a': 'ACCloud',
  233. 'com.ansjer.loocamccloud_a': 'Loocam',
  234. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  235. 'com.ansjer.customizedb_a': 'COCOONHD',
  236. 'com.ansjer.customizeda_a': 'Guardian365',
  237. 'com.ansjer.customizedc_a': 'PatrolSecure',
  238. }
  239. if appBundleId in package_title_config.keys():
  240. return package_title_config[appBundleId] + '(' + nickname + ')'
  241. else:
  242. return nickname
  243. def get_send_text(self, channel, n_time, lang, tz, event_type):
  244. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  245. msg_type = ''
  246. if int(event_type) == 704:
  247. msg_type = 'battery is too low'
  248. if lang == 'cn':
  249. msg_type = '电池电量过低'
  250. send_text = '{msg_type}channel:{channel} date:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  251. if lang == 'cn':
  252. send_text = '{msg_type}通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  253. return send_text
  254. def do_fcm(self, request_dict, uaql, response, uid, channel, nickname):
  255. n_time = request_dict.get('n_time')
  256. appBundleId = uaql['appBundleId']
  257. token_val = uaql['token_val']
  258. lang = uaql['lang']
  259. tz = uaql['tz']
  260. try:
  261. serverKey = FCM_CONFIG[appBundleId]
  262. except Exception as e:
  263. return response.json(404)
  264. event_type = request_dict.get('event_type', None)
  265. push_service = FCMNotification(api_key=serverKey)
  266. registration_id = token_val
  267. message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
  268. send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)
  269. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  270. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  271. result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title,
  272. message_body=send_text, data_message=data,
  273. extra_kwargs={
  274. 'default_vibrate_timings': True,
  275. 'default_sound': True,
  276. 'default_light_settings': True
  277. })
  278. response = ResponseObject()
  279. return response.json(0, result)
  280. def do_apns(self, request_dict, uaql, response, uid, channel, nickname):
  281. event_type = request_dict.get('event_type', None)
  282. token_val = uaql['token_val']
  283. lang = uaql['lang']
  284. n_time = request_dict.get('n_time')
  285. appBundleId = uaql['appBundleId']
  286. tz = uaql['tz']
  287. message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
  288. send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)
  289. try:
  290. print('---')
  291. cli = apns2.APNSClient(mode=APNS_MODE,
  292. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  293. # password=APNS_CONFIG[appBundleId]['password'])
  294. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  295. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  296. # body = json.dumps(push_data)
  297. alert = apns2.PayloadAlert(body=send_text, title=message_title)
  298. payload = apns2.Payload(alert=alert, custom=push_data)
  299. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  300. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  301. # assert res.status_code == 200, res.reason
  302. # assert res.apns_id
  303. print('========')
  304. print(res.status_code)
  305. if res.status_code == 200:
  306. return response.json(0)
  307. else:
  308. return response.json(404, res.reason)
  309. except Exception as e:
  310. print(repr(e))
  311. return response.json(10, repr(e))
  312. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  313. #
  314. qs_list = []
  315. nowTime = int(time.time())
  316. # 设备昵称
  317. userID_ids = []
  318. for dv in uaqs:
  319. userID_id = dv["userID_id"]
  320. if userID_id not in userID_ids:
  321. add_data = {
  322. 'userID_id': dv["userID_id"],
  323. 'eventTime': n_time,
  324. 'eventType': event_type,
  325. 'devUid': uid,
  326. 'devNickName': uid,
  327. 'Channel': channel,
  328. 'alarm': 'Motion \tChannel:{channel}'.format(channel=channel),
  329. 'is_st': int(is_st),
  330. 'receiveTime': n_time,
  331. 'addTime': nowTime
  332. }
  333. qs_list.append(Equipment_Info(**add_data))
  334. userID_ids.append(userID_id)
  335. if qs_list:
  336. print(1)
  337. Equipment_Info.objects.bulk_create(qs_list)
  338. return True
  339. else:
  340. return False
  341. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  342. # 移动侦测接口
  343. class PushNotificationView(View):
  344. def get(self, request, *args, **kwargs):
  345. request.encoding = 'utf-8'
  346. # operation = kwargs.get('operation')
  347. return self.validation(request.GET)
  348. def post(self, request, *args, **kwargs):
  349. request.encoding = 'utf-8'
  350. # operation = kwargs.get('operation')
  351. return self.validation(request.POST)
  352. def validation(self, request_dict):
  353. etk = request_dict.get('etk', None)
  354. channel = request_dict.get('channel', '1')
  355. n_time = request_dict.get('n_time', None)
  356. event_type = request_dict.get('event_type', None)
  357. is_st = request_dict.get('is_st', None)
  358. eto = ETkObject(etk)
  359. uid = eto.uid
  360. if len(uid) == 20:
  361. redisObj = RedisObject(db=6)
  362. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  363. pkey = '{uid}_ptl'.format(uid=uid)
  364. # 推送时间限制
  365. if redisObj.get_data(key=pkey):
  366. res_data = {'code': 0, 'msg': 'success,!'}
  367. return JsonResponse(status=200, data=res_data)
  368. else:
  369. redisObj.set_data(key=pkey, val=1, expire=60)
  370. uid_set_qs = UidSetModel.objects.filter(uid=uid, detect_status=1)
  371. if uid_set_qs.exists():
  372. uid_set_id = uid_set_qs[0].id
  373. uid_push_qs = UidPushModel.objects.filter(uid_set__id=uid_set_id). \
  374. values('token_val', 'app_type', 'appBundleId', 'push_type',
  375. 'userID_id', 'userID__NickName', 'lang', 'tz')
  376. if uid_set_qs.exists():
  377. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  378. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  379. self.do_bulk_create_info(uid_push_qs, n_time, channel, event_type, is_st, uid)
  380. if is_st == '0' or is_st == '2':
  381. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  382. elif is_st == '1':
  383. # Endpoint以杭州为例,其它Region请按实际情况填写。
  384. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  385. # 设置此签名URL在60秒内有效。
  386. url = bucket.sign_url('PUT', obj, 7200)
  387. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  388. return JsonResponse(status=200, data=res_data)
  389. elif is_st == '3':
  390. # 人形检测带动图
  391. img_url_list = []
  392. for i in range(int(is_st)):
  393. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  394. format(uid=uid, channel=channel, filename=n_time, st=i)
  395. # 设置此签名URL在60秒内有效。
  396. url = bucket.sign_url('PUT', obj, 7200)
  397. img_url_list.append(url)
  398. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  399. return JsonResponse(status=200, data=res_data)
  400. else:
  401. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  402. else:
  403. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  404. else:
  405. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  406. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  407. #
  408. qs_list = []
  409. nowTime = int(time.time())
  410. # 设备昵称
  411. userID_ids = []
  412. for dv in uaqs:
  413. userID_id = dv["userID_id"]
  414. if userID_id not in userID_ids:
  415. add_data = {
  416. 'userID_id': dv["userID_id"],
  417. 'eventTime': n_time,
  418. 'eventType': event_type,
  419. 'devUid': uid,
  420. 'devNickName': uid,
  421. 'Channel': channel,
  422. 'alarm': 'Motion \tChannel:{channel}'.format(channel=channel),
  423. 'is_st': int(is_st),
  424. 'receiveTime': n_time,
  425. 'addTime': nowTime
  426. }
  427. qs_list.append(Equipment_Info(**add_data))
  428. userID_ids.append(userID_id)
  429. if qs_list:
  430. print(1)
  431. Equipment_Info.objects.bulk_create(qs_list)
  432. return True
  433. else:
  434. return False