DetectController.py 18 KB

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