DetectController.py 12 KB

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