DetectController.py 23 KB

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