DetectController.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. from django.utils.decorators import method_decorator
  15. from django.views.decorators.csrf import csrf_exempt
  16. from django.views.generic.base import View
  17. import time
  18. import apns2
  19. from Object.ResponseObject import ResponseObject
  20. import os
  21. from Ansjer.config import BASE_DIR
  22. from Object.TokenObject import TokenObject
  23. import jpush as jpush
  24. from Model.models import Device_User, Device_Info, Equipment_Info, App_Info, UID_App
  25. from Object.UidTokenObject import UidTokenObject
  26. from Ansjer.config import SERVER_DOMAIN
  27. import json
  28. import requests
  29. from Model.models import Equipment_Info
  30. # http://192.168.136.40:8077/detect/changeStatus?uid=JW3684H8BSHG9TTM111A&token_val=18071adc03536302f34&appBundleId=com.ansjer.zccloud_ab&push_type=2&token=local&status=1
  31. class DetectControllerView(View):
  32. @method_decorator(csrf_exempt)
  33. def dispatch(self, *args, **kwargs):
  34. return super(DetectControllerView, self).dispatch(*args, **kwargs)
  35. def get(self, request, *args, **kwargs):
  36. request.encoding = 'utf-8'
  37. operation = kwargs.get('operation')
  38. return self.validation(request.GET, operation)
  39. def post(self, request, *args, **kwargs):
  40. request.encoding = 'utf-8'
  41. operation = kwargs.get('operation')
  42. return self.validation(request.POST, operation)
  43. def validation(self, request_dict, operation):
  44. response = ResponseObject()
  45. if operation is None:
  46. return response.json(444, 'error path')
  47. token = request_dict.get('token', None)
  48. tko = TokenObject(token)
  49. if tko.code == 0:
  50. userID = tko.userID
  51. if operation == 'changeStatus':
  52. return self.do_change_status(userID, request_dict, response)
  53. else:
  54. return response.json(414)
  55. else:
  56. return response.json(tko.code)
  57. def do_change_status(self, userID, request_dict, response):
  58. uid = request_dict.get('uid', None)
  59. token_val = request_dict.get('token_val', None)
  60. appBundleId = request_dict.get('appBundleId', None)
  61. push_type = request_dict.get('push_type', None)
  62. status = request_dict.get('status', None)
  63. print('status')
  64. print(status)
  65. if status == '0':
  66. UID_App.objects.filter(appBundleId=appBundleId, userID_id=userID, token_val=token_val, uid=uid).delete()
  67. return response.json(0)
  68. elif status == '1':
  69. # return response.json(10)
  70. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  71. aiqs = App_Info.objects.filter(appBundleId=appBundleId).values('app_type')
  72. print(dvqs)
  73. print(aiqs)
  74. if dvqs.exists() and aiqs.exists():
  75. now_time = int(time.time())
  76. try:
  77. UID_App.objects.create(
  78. uid=uid,
  79. userID_id=userID,
  80. appBundleId=appBundleId,
  81. app_type=aiqs[0]['app_type'],
  82. push_type=push_type,
  83. token_val=token_val,
  84. addTime=now_time,
  85. updTime=now_time)
  86. except Exception as e:
  87. print(repr(e))
  88. return response.json(10,repr(e))
  89. else:
  90. utko = UidTokenObject()
  91. utko.generate(data={'uid': uid})
  92. detectUrl = "{SERVER_DOMAIN}notify/push?uidToken={uidToken}". \
  93. format(uidToken=utko.token, SERVER_DOMAIN=SERVER_DOMAIN)
  94. return response.json(0, {'detectUrl': detectUrl})
  95. else:
  96. return response.json(173)
  97. # 移动侦测接口
  98. class NotificationView(View):
  99. def get(self, request, *args, **kwargs):
  100. request.encoding = 'utf-8'
  101. # operation = kwargs.get('operation')
  102. return self.validation(request.GET)
  103. def post(self, request, *args, **kwargs):
  104. request.encoding = 'utf-8'
  105. # operation = kwargs.get('operation')
  106. return self.validation(request.POST)
  107. def validation(self, request_dict):
  108. response = ResponseObject()
  109. uidToken = request_dict.get('uidToken', None)
  110. utko = UidTokenObject(uidToken)
  111. uid = utko.UID
  112. uaqs = UID_App.objects.filter(uid=uid). \
  113. values('token_val', 'app_type', 'appBundleId', 'push_type', 'uid', 'userID_id', 'userID__NickName')
  114. if uaqs.exists():
  115. for ua in uaqs:
  116. push_type = ua['push_type']
  117. # ios apns
  118. if push_type == 0:
  119. self.do_apns(request_dict, ua, response)
  120. # android gcm
  121. elif push_type == 1:
  122. self.do_gmc(request_dict, ua, response)
  123. # android jpush
  124. elif push_type == 2:
  125. self.do_jpush(request_dict, ua, response)
  126. n_time = request_dict.get('n_time')
  127. self.do_save_equipment_info(ua, n_time)
  128. return response.json(0)
  129. else:
  130. return response.json(173)
  131. def do_jpush(self, request_dict, uaql, response):
  132. jpush_config = {
  133. 'com.ansjer.accloud_ab': {
  134. 'Key': 'f0dc047e5e53fd14199de5b0',
  135. 'Secret': 'aa7f7db33e9f0a7f3871aa1c'},
  136. 'com.ansjer.adcloud_ab': {
  137. 'Key': '76d97b535185114985608234',
  138. 'Secret': 'c9a92b301043cc9c52778692'},
  139. 'com.ansjer.zccloud_ab': {
  140. 'Key': 'd9924f56d3cc7c6017965130',
  141. 'Secret': '869d832d126a232f158b5987'},
  142. 'com.ansjer.loocamccloud_ab': {
  143. 'Key': 'd1cc44797b4642b0e05304fe',
  144. 'Secret': 'c3e8b4ca8c576de61401e56a'},
  145. 'com.ansjer.loocamdcloud_ab': {
  146. 'Key': '76d97b535185114985608234',
  147. 'Secret': 'c9a92b301043cc9c52778692'},
  148. 'com.ansjer.zccloud_a': {
  149. 'Key': '57de2a80d68bf270fd6bdf5a',
  150. 'Secret': '3d354eb6a0b49c2610decf42'},
  151. 'com.ansjer.accloud_a': {
  152. 'Key': 'ff95ee685f49c0dc4013347b',
  153. 'Secret': 'de2c20959f5516fdeeafe78e'},
  154. 'com.ansjer.adcloud_a': {
  155. 'Key': '2e47eb1aee9b164460df3668',
  156. 'Secret': 'b9137d8d684bc248f1809b6d'},
  157. 'com.ansjer.loocamccloud_a': {
  158. 'Key': '23c9213215c7ca0ec945629b',
  159. 'Secret': '81e4b1e859cc8387e2e6c431'},
  160. 'com.ansjer.loocamdcloud_a': {
  161. 'Key': '1dbdd60a16e9892d6f68a073',
  162. 'Secret': '80a97690e7e043109059b403'},
  163. 'com.ansjer.customizedb_a': {
  164. 'Key': '9d79630aa49adfa291fe2568',
  165. 'Secret': '4d8ff52f88136561875a0212'},
  166. }
  167. n_time = request_dict.get('n_time', None)
  168. appBundleId = uaql['appBundleId']
  169. token_val = uaql['token_val']
  170. uid = uaql['uid']
  171. response = ResponseObject()
  172. app_key = jpush_config[appBundleId]['Key']
  173. master_secret = jpush_config[appBundleId]['Secret']
  174. # 此处换成各自的app_key和master_secret
  175. _jpush = jpush.JPush(app_key, master_secret)
  176. push = _jpush.create_push()
  177. # if you set the logging level to "DEBUG",it will show the debug logging.
  178. _jpush.set_logging("DEBUG")
  179. # push.audience = jpush.all_
  180. push.audience = jpush.registration_id(token_val)
  181. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": "51", "msg": "",
  182. "received_at": n_time, "sound": "sound.aif", "uid": uid}
  183. push_msg = json.dumps(push_data)
  184. # push.notification = jpush.notification(alert="hello jpush api")
  185. # push.notification = jpush.notification(alert=push_msg)
  186. # android = jpush.android(alert="Hello, Android msg",extras=push_data)
  187. # push.notification = jpush.notification(alert="Hello, JPush!", android=android)
  188. # push.notification = jpush.message(msg_content=push_data, extras=push_data)
  189. push.message = jpush.message('Motion', extras=push_data, title='KPNS', content_type='text')
  190. push.platform = jpush.all_
  191. try:
  192. res = push.send()
  193. print(res)
  194. except Exception as e:
  195. print("Exception")
  196. print(repr(e))
  197. return response.json(10, repr(e))
  198. else:
  199. return response.json(0)
  200. def do_gmc(self, request_dict, uaql, response):
  201. n_time = request_dict.get('n_time')
  202. appBundleId = uaql['appBundleId']
  203. token_val = uaql['token_val']
  204. uid = uaql['uid']
  205. gcm_config = {
  206. 'com.ansjer.zccloud_a': 'AAAAb9YP3rk:APA91bHu8u-CTpcd0g6lKPo0WNVqCi8jZub1cPPbSAY9AucT1HxlF65ZDUko9iG8q2ch17bwu9YWHpK1xI1gHSRXCslLvZlXEmHZC0AG3JKg15XuUvlFKACIajUFV-pOeGRT8tM6-31I',
  207. 'com.ansjer.loocamccloud_a': 'AAAAb9YP3rk:APA91bFCgd-kbVmpK4EVpfdHH_PJZQCYTkOGnTZdIuBWEz2r7aMRsJYHOH3sB-rwcbaRWgnufTyjX9nGQxb6KxQbWVk4ah_H-M3IqGh6Mb60WQQAuR33V6g_Jes5pGL6ViuIxGHqVMaR',
  208. 'com.ansjer.loocamdcloud_a': 'AAAAb9YP3rk:APA91bGw2I2KMD4i-5T7nZO_wB8kuAOuqgyqe5rxmY-W5qkpYEx9IL2IfmC_qf6B_xOyjIDDSjckvMo-RauN__SEoxvAkis7042GRkoKpw7cjZ_H8lC-d50PC0GclPzccrOGFusyKbFY',
  209. 'com.ansjer.customizedb_a': 'AAAAb9YP3rk:APA91bE7kI4vcm-9h_CJNFlOZfc-xwP4Btn6AnjOrwoKV6fgYN7fdarkO76sYxVZiAbDnxsFfOJyP7vQfwyan6mdjuyD5iHdt_XgO22VqniC0vA1V4GJiCS8Tp7LxIX8JVKZl9I_Powt',
  210. 'com.ansjer.customizeda_a': 'AAAAb9YP3rk:APA91bF0HzizVWDc6dKzobY9fsaKDK4veqkOZehDXshVXs8pEEvNWjR_YWbhP60wsRYCHCal8fWN5cECVOWNMMzDsfU88Ty2AUl8S5FtZsmeDTkoGntQOswBr8Ln7Fm_LAp1VqTf9CpM',
  211. }
  212. serverKey = gcm_config[appBundleId]
  213. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": "51", "msg": "",
  214. "received_at": n_time, "sound": "sound.aif", "uid": uid}
  215. json_data = {
  216. "collapse_key": "WhatYouWant",
  217. "data": push_data,
  218. "delay_while_idle": False,
  219. "time_to_live": 3600,
  220. "registration_ids": [token_val]
  221. }
  222. url = 'https://android.googleapis.com/gcm/send'
  223. # serverKey = "AAAAb9YP3rk:APA91bHu8u-CTpcd0g6lKPo0WNVqCi8jZub1cPPbSAY9AucT1HxlF65ZDUko9iG8q2ch17bwu9YWHpK1xI1gHSRXCslLvZlXEmHZC0AG3JKg15XuUvlFKACIajUFV-pOeGRT8tM6-31I"
  224. data = json.dumps(json_data).encode('utf-8')
  225. headers = {'Content-Type': 'application/json', 'Authorization': 'key=%s' % serverKey}
  226. req = requests.post(url, data, headers=headers)
  227. return response.json(0)
  228. def do_apns(self, request_dict, uaql, response):
  229. token_val = uaql['token_val']
  230. n_time = request_dict.get('n_time')
  231. appBundleId = uaql['appBundleId']
  232. uid = uaql['uid']
  233. apns_config = {
  234. 'appbundleId': {'pem_path': 'xxxx', 'topic': 'topic', 'password': 'password'}
  235. }
  236. try:
  237. # daytime = time.strftime("%Y%m%d%H%M", time.localtime(1547256103))
  238. # print(daytime)
  239. pem_path = os.path.join(BASE_DIR, apns_config[appBundleId]['topic'])
  240. # pem_path = os.path.join(BASE_DIR, 'Ansjer/file/apns-dev.pem')
  241. cli = apns2.APNSClient(mode="dev", client_cert=pem_path, password='111111')
  242. body = json.dumps({'uid': uid, 'n_time': n_time})
  243. alert = apns2.PayloadAlert(body="body!", title="title!")
  244. payload = apns2.Payload(alert=alert)
  245. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  246. res = cli.push(n=n, device_token=token_val, topic=apns_config[appBundleId]['pem_path'])
  247. # assert res.status_code == 200, res.reason
  248. # assert res.apns_id
  249. if res.status_code == 200:
  250. # self.do_save_equipment_info(uaql, n_time)
  251. return response.json(0)
  252. else:
  253. return response.json(404, res.reason)
  254. except Exception as e:
  255. return response.json(10, repr(e))
  256. def do_save_equipment_info(self, uaql, n_time):
  257. Equipment_Info.objects.create(
  258. userID_id=uaql['userID_id'],
  259. eventTime=n_time,
  260. eventType=1,
  261. devUid=uaql['uid'],
  262. devNickName=uaql['userID__NickName'],
  263. Channel='0',
  264. alarm='0',
  265. receiveTime=n_time)