DetectController.py 18 KB

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