DetectController.py 18 KB

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