DetectController.py 11 KB

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