DetectController.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 json
  15. import os
  16. import time
  17. import urllib
  18. import apns2
  19. import jpush as jpush
  20. import oss2
  21. import requests
  22. from django.utils.decorators import method_decorator
  23. from django.views.decorators.csrf import csrf_exempt
  24. from django.views.generic.base import View
  25. from AnsjerPush.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, SERVER_DOMAIN, BASE_DIR, DETECT_PUSH_DOMAIN
  26. from Model.models import Equipment_Info, UidSetModel, UidPushModel
  27. from Object.ResponseObject import ResponseObject
  28. from Object.UidTokenObject import UidTokenObject
  29. from django.http import JsonResponse
  30. from Object.RedisObject import RedisObject
  31. from django.db import transaction
  32. # http://192.168.136.40:8077/notify/push?uidToken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJUTjdNUEUzMjExVUU3NkFQMTExQSJ9.k501567VdnhFpn_ygzGRDat3Kqlz5CsEA9jAC2dDk_g&obj=12341234&n_time=1234561234
  33. # http://test.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  34. # 移动侦测接口
  35. class NotificationView(View):
  36. def get(self, request, *args, **kwargs):
  37. request.encoding = 'utf-8'
  38. # operation = kwargs.get('operation')
  39. return self.validation(request.GET)
  40. def post(self, request, *args, **kwargs):
  41. request.encoding = 'utf-8'
  42. # operation = kwargs.get('operation')
  43. return self.validation(request.POST)
  44. def validation(self, request_dict):
  45. response = ResponseObject()
  46. uidToken = request_dict.get('uidToken', None)
  47. channel = request_dict.get('channel', None)
  48. n_time = request_dict.get('n_time', None)
  49. event_type = request_dict.get('event_type', None)
  50. is_st = request_dict.get('is_st', None)
  51. if not all([uidToken, channel, n_time]):
  52. return JsonResponse(status=200, data={
  53. 'code': 444,
  54. 'msg': 'param is wrong'})
  55. # return response.json(444)
  56. utko = UidTokenObject(uidToken)
  57. uid = utko.UID
  58. uid_set_qs = UidSetModel.objects.filter(uid=uid, detect_status=1)
  59. if uid_set_qs.exists():
  60. uid_set_id = uid_set_qs[0].id
  61. uid_push_qs = UidPushModel.objects.filter(uid_set__id=uid_set_id). \
  62. values('token_val', 'app_type', 'appBundleId', 'push_type', 'userID_id', 'userID__NickName')
  63. if uid_set_qs.exists():
  64. redisObj = RedisObject(db=6)
  65. pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  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. detect_interval = uid_set_qs[0].detect_interval
  71. if detect_interval:
  72. redisObj.set_data(key=pkey, val=1, expire=detect_interval)
  73. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  74. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  75. for up in uid_push_qs:
  76. push_type = up['push_type']
  77. # ios apns
  78. if push_type == 0:
  79. self.do_apns(request_dict, up, response, uid)
  80. # android gcm
  81. elif push_type == 1:
  82. self.do_gmc(request_dict, up, response, uid)
  83. # android jpush
  84. elif push_type == 2:
  85. self.do_jpush(request_dict, up, response, uid)
  86. # self.do_save_equipment_info(ua, n_time, channel, event_type, is_st)
  87. # 需求不一样,所以这么做的
  88. self.do_bulk_create_info(uid_push_qs, n_time, channel, event_type, is_st, uid)
  89. if is_st == '0' or is_st == '2':
  90. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  91. else:
  92. # Endpoint以杭州为例,其它Region请按实际情况填写。
  93. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  94. # 设置此签名URL在60秒内有效。
  95. url = bucket.sign_url('PUT', obj, 7200)
  96. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  97. return JsonResponse(status=200, data=res_data)
  98. else:
  99. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  100. else:
  101. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  102. def do_jpush(self, request_dict, uaql, response, uid):
  103. event_type = request_dict.get('event_type', None)
  104. jpush_config = {
  105. 'com.ansjer.accloud_ab': {
  106. 'Key': 'f0dc047e5e53fd14199de5b0',
  107. 'Secret': 'aa7f7db33e9f0a7f3871aa1c'},
  108. 'com.ansjer.adcloud_ab': {
  109. 'Key': '76d97b535185114985608234',
  110. 'Secret': 'c9a92b301043cc9c52778692'},
  111. 'com.ansjer.zccloud_ab': {
  112. 'Key': 'd9924f56d3cc7c6017965130',
  113. 'Secret': '869d832d126a232f158b5987'},
  114. 'com.ansjer.loocamccloud_ab': {
  115. 'Key': 'd1cc44797b4642b0e05304fe',
  116. 'Secret': 'c3e8b4ca8c576de61401e56a'},
  117. 'com.ansjer.loocamdcloud_ab': {
  118. 'Key': '76d97b535185114985608234',
  119. 'Secret': 'c9a92b301043cc9c52778692'},
  120. 'com.ansjer.zccloud_a': {
  121. 'Key': '57de2a80d68bf270fd6bdf5a',
  122. 'Secret': '3d354eb6a0b49c2610decf42'},
  123. 'com.ansjer.accloud_a': {
  124. 'Key': 'ff95ee685f49c0dc4013347b',
  125. 'Secret': 'de2c20959f5516fdeeafe78e'},
  126. 'com.ansjer.adcloud_a': {
  127. 'Key': '2e47eb1aee9b164460df3668',
  128. 'Secret': 'b9137d8d684bc248f1809b6d'},
  129. 'com.ansjer.loocamccloud_a': {
  130. 'Key': '23c9213215c7ca0ec945629b',
  131. 'Secret': '81e4b1e859cc8387e2e6c431'},
  132. 'com.ansjer.loocamdcloud_a': {
  133. 'Key': '1dbdd60a16e9892d6f68a073',
  134. 'Secret': '80a97690e7e043109059b403'},
  135. 'com.ansjer.customizedb_a': {
  136. 'Key': '9d79630aa49adfa291fe2568',
  137. 'Secret': '4d8ff52f88136561875a0212'},
  138. }
  139. n_time = request_dict.get('n_time', None)
  140. appBundleId = uaql['appBundleId']
  141. token_val = uaql['token_val']
  142. response = ResponseObject()
  143. app_key = jpush_config[appBundleId]['Key']
  144. master_secret = jpush_config[appBundleId]['Secret']
  145. # 此处换成各自的app_key和master_secre
  146. _jpush = jpush.JPush(app_key, master_secret)
  147. push = _jpush.create_push()
  148. # if you set the logging level to "DEBUG",it will show the debug logging.
  149. _jpush.set_logging("DEBUG")
  150. # push.audience = jpush.all_
  151. push.audience = jpush.registration_id(token_val)
  152. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  153. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1"}
  154. push.message = jpush.message('Motion', extras=push_data, title='KPNS', content_type='text')
  155. push.platform = jpush.all_
  156. try:
  157. res = push.send()
  158. print(res)
  159. except Exception as e:
  160. print("Exception")
  161. print(repr(e))
  162. return response.json(10, repr(e))
  163. else:
  164. return response.json(0)
  165. def do_gmc(self, request_dict, uaql, response, uid):
  166. n_time = request_dict.get('n_time')
  167. appBundleId = uaql['appBundleId']
  168. token_val = uaql['token_val']
  169. gcm_config = {
  170. 'com.ansjer.zccloud_a': 'AAAAb9YP3rk:APA91bHu8u-CTpcd0g6lKPo0WNVqCi8jZub1cPPbSAY9AucT1HxlF65ZDUko9iG8q2ch17bwu9YWHpK1xI1gHSRXCslLvZlXEmHZC0AG3JKg15XuUvlFKACIajUFV-pOeGRT8tM6-31I',
  171. 'com.ansjer.loocamccloud_a': 'AAAAb9YP3rk:APA91bFCgd-kbVmpK4EVpfdHH_PJZQCYTkOGnTZdIuBWEz2r7aMRsJYHOH3sB-rwcbaRWgnufTyjX9nGQxb6KxQbWVk4ah_H-M3IqGh6Mb60WQQAuR33V6g_Jes5pGL6ViuIxGHqVMaR',
  172. 'com.ansjer.loocamdcloud_a': 'AAAAb9YP3rk:APA91bGw2I2KMD4i-5T7nZO_wB8kuAOuqgyqe5rxmY-W5qkpYEx9IL2IfmC_qf6B_xOyjIDDSjckvMo-RauN__SEoxvAkis7042GRkoKpw7cjZ_H8lC-d50PC0GclPzccrOGFusyKbFY',
  173. 'com.ansjer.customizedb_a': 'AAAAb9YP3rk:APA91bE7kI4vcm-9h_CJNFlOZfc-xwP4Btn6AnjOrwoKV6fgYN7fdarkO76sYxVZiAbDnxsFfOJyP7vQfwyan6mdjuyD5iHdt_XgO22VqniC0vA1V4GJiCS8Tp7LxIX8JVKZl9I_Powt',
  174. 'com.ansjer.customizeda_a': 'AAAAb9YP3rk:APA91bF0HzizVWDc6dKzobY9fsaKDK4veqkOZehDXshVXs8pEEvNWjR_YWbhP60wsRYCHCal8fWN5cECVOWNMMzDsfU88Ty2AUl8S5FtZsmeDTkoGntQOswBr8Ln7Fm_LAp1VqTf9CpM',
  175. }
  176. serverKey = gcm_config[appBundleId]
  177. event_type = request_dict.get('event_type', None)
  178. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  179. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1"}
  180. json_data = {
  181. "collapse_key": "WhatYouWant",
  182. "data": push_data,
  183. "delay_while_idle": False,
  184. "time_to_live": 3600,
  185. "registration_ids": [token_val]
  186. }
  187. url = 'https://android.googleapis.com/gcm/send'
  188. # serverKey = "AAAAb9YP3rk:APA91bHu8u-CTpcd0g6lKPo0WNVqCi8jZub1cPPbSAY9AucT1HxlF65ZDUko9iG8q2ch17bwu9YWHpK1xI1gHSRXCslLvZlXEmHZC0AG3JKg15XuUvlFKACIajUFV-pOeGRT8tM6-31I"
  189. data = json.dumps(json_data).encode('utf-8')
  190. headers = {'Content-Type': 'application/json', 'Authorization': 'key=%s' % serverKey}
  191. req = requests.post(url, data, headers=headers)
  192. return response.json(0)
  193. def do_apns(self, request_dict, uaql, response, uid):
  194. event_type = request_dict.get('event_type', None)
  195. token_val = uaql['token_val']
  196. n_time = request_dict.get('n_time')
  197. appBundleId = uaql['appBundleId']
  198. apns_config = {
  199. 'com.ansjer.loocamccloud': {
  200. 'pem_path': os.path.join(BASE_DIR, 'Ansjer/file/apns_pem/apns-dev-test.pem'),
  201. 'password': '111111'
  202. }
  203. }
  204. try:
  205. cli = apns2.APNSClient(mode="dev", client_cert=apns_config[appBundleId]['pem_path'],
  206. password=apns_config[appBundleId]['password'])
  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"}
  209. body = json.dumps(push_data)
  210. alert = apns2.PayloadAlert(body=body, title="title!")
  211. payload = apns2.Payload(alert=alert)
  212. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  213. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  214. # assert res.status_code == 200, res.reason
  215. # assert res.apns_id
  216. if res.status_code == 200:
  217. return response.json(0)
  218. else:
  219. return response.json(404, res.reason)
  220. except Exception as e:
  221. return response.json(10, repr(e))
  222. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  223. #
  224. qs_list = []
  225. nowTime = int(time.time())
  226. # 设备昵称
  227. for dv in uaqs:
  228. add_data = {
  229. 'userID_id': dv["userID_id"],
  230. 'eventTime': n_time,
  231. 'eventType': event_type,
  232. 'devUid': uid,
  233. 'devNickName': uid,
  234. 'Channel': channel,
  235. 'alarm': 'Motion \tChannel:{channel}'.format(channel=channel),
  236. 'is_st': int(is_st),
  237. 'receiveTime': n_time,
  238. 'addTime': nowTime
  239. }
  240. qs_list.append(Equipment_Info(**add_data))
  241. if qs_list:
  242. print(1)
  243. Equipment_Info.objects.bulk_create(qs_list)
  244. return True
  245. else:
  246. return False