DetectController.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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).values('token_val', 'app_type', 'appBundleId', 'push_type', 'uid')
  101. if uaqs.exists():
  102. push_type = uaqs[0]['push_type']
  103. # ios apns
  104. if push_type == 0:
  105. return self.do_apns(request_dict, uaqs[0], response)
  106. # android gcm
  107. elif push_type == 1:
  108. return self.do_gmc(request_dict, uaqs[0], response)
  109. # android jpush
  110. elif push_type == 2:
  111. return self.do_jpush(request_dict, uaqs[0], response)
  112. else:
  113. return response.json(173)
  114. # # 设备主键uid
  115. # if pushType == 'jpush':
  116. # return self.do_jpush(request_dict)
  117. # elif pushType == 'gcm':
  118. # return
  119. # elif pushType == 'apns':
  120. # return
  121. # else:
  122. # return response.json(414)
  123. def do_jpush(self, request_dict, uaql, response):
  124. jpush_config = {
  125. 'com.ansjer.accloud_ab': {
  126. 'Key': 'f0dc047e5e53fd14199de5b0',
  127. 'Secret': 'aa7f7db33e9f0a7f3871aa1c'},
  128. 'com.ansjer.adcloud_ab': {
  129. 'Key': '76d97b535185114985608234',
  130. 'Secret': 'c9a92b301043cc9c52778692'},
  131. 'com.ansjer.zccloud_ab': {
  132. 'Key': 'd9924f56d3cc7c6017965130',
  133. 'Secret': '869d832d126a232f158b5987'},
  134. 'com.ansjer.loocamccloud_ab': {
  135. 'Key': 'd1cc44797b4642b0e05304fe',
  136. 'Secret': 'c3e8b4ca8c576de61401e56a'},
  137. 'com.ansjer.loocamdcloud_ab': {
  138. 'Key': '76d97b535185114985608234',
  139. 'Secret': 'c9a92b301043cc9c52778692'},
  140. 'com.ansjer.zccloud_a': {
  141. 'Key': '57de2a80d68bf270fd6bdf5a',
  142. 'Secret': '3d354eb6a0b49c2610decf42'},
  143. 'com.ansjer.accloud_a': {
  144. 'Key': 'ff95ee685f49c0dc4013347b',
  145. 'Secret': 'de2c20959f5516fdeeafe78e'},
  146. 'com.ansjer.adcloud_a': {
  147. 'Key': '2e47eb1aee9b164460df3668',
  148. 'Secret': 'b9137d8d684bc248f1809b6d'},
  149. 'com.ansjer.loocamccloud_a': {
  150. 'Key': '23c9213215c7ca0ec945629b',
  151. 'Secret': '81e4b1e859cc8387e2e6c431'},
  152. 'com.ansjer.loocamdcloud_a': {
  153. 'Key': '1dbdd60a16e9892d6f68a073',
  154. 'Secret': '80a97690e7e043109059b403'},
  155. 'com.ansjer.customizedb_a': {
  156. 'Key': '9d79630aa49adfa291fe2568',
  157. 'Secret': '4d8ff52f88136561875a0212'},
  158. }
  159. n_time = request_dict.get('n_time', None)
  160. appBundleId = uaql['appBundleId']
  161. token_val = uaql['token_val']
  162. uid = uaql['uid']
  163. response = ResponseObject()
  164. app_key = jpush_config[appBundleId]['Key']
  165. master_secret = jpush_config[appBundleId]['Secret']
  166. # 此处换成各自的app_key和master_secret
  167. _jpush = jpush.JPush(app_key, master_secret)
  168. push = _jpush.create_push()
  169. # if you set the logging level to "DEBUG",it will show the debug logging.
  170. _jpush.set_logging("DEBUG")
  171. # push.audience = jpush.all_
  172. push.audience = jpush.registration_id(token_val)
  173. push_msg = json.dumps({'n_time': n_time, 'uid': uid})
  174. # push.notification = jpush.notification(alert="hello jpush api")
  175. push.notification = jpush.notification(alert=push_msg)
  176. push.platform = jpush.all_
  177. try:
  178. res = push.send()
  179. except Exception as e:
  180. print("Exception")
  181. return response.json(10, repr(e))
  182. else:
  183. return response.json(0)
  184. def do_gmc(self, request_dict, response):
  185. n_time = request_dict.get('n_time')
  186. n_type = request_dict.get('n_type')
  187. msg = {'n_time': n_time, 'n_type': n_type}
  188. json_data = {
  189. "collapse_key": "WhatYouWant",
  190. "data": msg,
  191. "delay_while_idle": False,
  192. "time_to_live": 3600,
  193. "registration_ids": [
  194. 'eSooD4fAARg:APA91bEPenBPnSn5aXIQk56QdLOQ1Mu3hevHsekP_0eDpg458y2ZMBP6By2rVsGYIoxZrXxvkkptPKUE9CmUygBxaZXABddUWB9FyLlznRFerC7RG9X5PsEOH58xK9_aTUdkT7p6Ocld']
  195. }
  196. url = 'https://android.googleapis.com/gcm/send'
  197. serverKey = "AAAAb9YP3rk:APA91bHu8u-CTpcd0g6lKPo0WNVqCi8jZub1cPPbSAY9AucT1HxlF65ZDUko9iG8q2ch17bwu9YWHpK1xI1gHSRXCslLvZlXEmHZC0AG3JKg15XuUvlFKACIajUFV-pOeGRT8tM6-31I"
  198. data = json.dumps(json_data).encode('utf-8')
  199. headers = {'Content-Type': 'application/json', 'Authorization': 'key=%s' % serverKey}
  200. req = requests.post(url, data, headers=headers)
  201. return response.json(0)
  202. def do_apns(self, request_dict, response):
  203. device_token = request_dict.get('device_token')
  204. try:
  205. daytime = time.strftime("%Y%m%d%H%M", time.localtime(1547256103))
  206. print(daytime)
  207. pem_path = os.path.join(BASE_DIR, 'Ansjer/file/apns-dev.pem')
  208. cli = apns2.APNSClient(mode="dev", client_cert=pem_path, password='111111')
  209. alert = apns2.PayloadAlert(body="body!", title="title!")
  210. payload = apns2.Payload(alert=alert)
  211. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  212. res = cli.push(n=n, device_token=device_token, topic='com.ansjer.zsavcloud')
  213. # assert res.status_code == 200, res.reason
  214. # assert res.apns_id
  215. if res.status_code == 200:
  216. return response.json(0)
  217. else:
  218. return response.json(404, res.reason)
  219. except Exception as e:
  220. return response.json(10, repr(e))