DetectController.py 9.8 KB

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