DetectController.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. import json
  15. import os
  16. import time
  17. import apns2
  18. import jpush as jpush
  19. import oss2
  20. import requests
  21. from django.utils.decorators import method_decorator
  22. from django.views.decorators.csrf import csrf_exempt
  23. from django.views.generic.base import View
  24. from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET
  25. from Ansjer.config import BASE_DIR
  26. from Ansjer.config import SERVER_DOMAIN
  27. from Model.models import Device_Info, App_Info, UID_App
  28. from Model.models import Equipment_Info
  29. from Object.ResponseObject import ResponseObject
  30. from Object.TokenObject import TokenObject
  31. from Object.UidTokenObject import UidTokenObject
  32. from django.http import JsonResponse
  33. from Service.CommonService import CommonService
  34. # 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
  35. class DetectControllerView(View):
  36. @method_decorator(csrf_exempt)
  37. def dispatch(self, *args, **kwargs):
  38. return super(DetectControllerView, self).dispatch(*args, **kwargs)
  39. def get(self, request, *args, **kwargs):
  40. request.encoding = 'utf-8'
  41. operation = kwargs.get('operation')
  42. return self.validation(request.GET, operation)
  43. def post(self, request, *args, **kwargs):
  44. request.encoding = 'utf-8'
  45. operation = kwargs.get('operation')
  46. return self.validation(request.POST, operation)
  47. def validation(self, request_dict, operation):
  48. response = ResponseObject()
  49. if operation is None:
  50. return response.json(444, 'error path')
  51. token = request_dict.get('token', None)
  52. tko = TokenObject(token)
  53. if tko.code == 0:
  54. userID = tko.userID
  55. if operation == 'changeStatus':
  56. return self.do_change_status(userID, request_dict, response)
  57. if operation == 'queryInfo':
  58. return self.do_query(request_dict, response, userID)
  59. else:
  60. return response.json(414)
  61. else:
  62. return response.json(tko.code)
  63. def do_query(self, request_dict, response, userID):
  64. page = int(request_dict.get('page', None))
  65. line = int(request_dict.get('line', None))
  66. if not page or not line:
  67. return response.json(444, 'page,line')
  68. qs = Equipment_Info.objects.filter(userID_id=userID)
  69. uid = request_dict.get('uid', None)
  70. if uid:
  71. qs.filter(devUid=uid)
  72. if not qs.exists():
  73. return response.json(0, {'datas': [], 'count': 0})
  74. qs = qs.values('id', 'devUid', 'devNickName', 'Channel', 'eventType', 'status', 'alarm', 'eventTime',
  75. 'receiveTime')
  76. count = qs.count()
  77. qr = qs[(page - 1) * line:page * line]
  78. # send_json = CommonService.qs_to_dict(res)
  79. res = []
  80. import oss2
  81. auth = oss2.Auth('LTAIyMkGfEdogyL9', '71uIjpsqVOmF7DAITRyRuc259jHOjO')
  82. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  83. for p in qr:
  84. p['img'] = bucket.sign_url('GET',
  85. '{uid}/{channel}/{time}.jpeg'.format(uid=p['devUid'], channel=p['Channel'],
  86. time=p['time']), 300)
  87. res.append(p)
  88. return response.json(0, {'datas': res, 'count': count})
  89. def do_change_status(self, userID, request_dict, response):
  90. uid = request_dict.get('uid', None)
  91. token_val = request_dict.get('token_val', None)
  92. appBundleId = request_dict.get('appBundleId', None)
  93. push_type = request_dict.get('push_type', None)
  94. status = request_dict.get('status', None)
  95. print('status')
  96. print(status)
  97. if status == '0':
  98. uid_app_qs = UID_App.objects.filter(appBundleId=appBundleId, userID_id=userID, token_val=token_val,
  99. uid=uid)
  100. if uid_app_qs.exists():
  101. uid_app_qs.update(status=0)
  102. return response.json(0)
  103. else:
  104. return response.json(173)
  105. elif status == '1':
  106. # return response.json(10)
  107. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  108. aiqs = App_Info.objects.filter(appBundleId=appBundleId).values('app_type')
  109. print(dvqs)
  110. print(aiqs)
  111. if dvqs.exists() and aiqs.exists():
  112. now_time = int(time.time())
  113. try:
  114. uid_app_qs = UID_App.objects.filter(appBundleId=appBundleId, userID_id=userID, token_val=token_val,
  115. uid=uid)
  116. print(uid_app_qs)
  117. if uid_app_qs.exists():
  118. uid_app_qs.update(status=1)
  119. else:
  120. UID_App.objects.create(
  121. uid=uid,
  122. userID_id=userID,
  123. appBundleId=appBundleId,
  124. app_type=aiqs[0]['app_type'],
  125. push_type=push_type,
  126. token_val=token_val,
  127. status=1,
  128. addTime=now_time,
  129. updTime=now_time)
  130. except Exception as e:
  131. print(repr(e))
  132. return response.json(10, repr(e))
  133. else:
  134. utko = UidTokenObject()
  135. utko.generate(data={'uid': uid})
  136. detectUrl = "{SERVER_DOMAIN}notify/push?uidToken={uidToken}". \
  137. format(uidToken=utko.token, SERVER_DOMAIN=SERVER_DOMAIN)
  138. return response.json(0, {'detectUrl': detectUrl})
  139. else:
  140. return response.json(173)
  141. # http://192.168.136.40:8077/notify/push?uidToken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJUTjdNUEUzMjExVUU3NkFQMTExQSJ9.k501567VdnhFpn_ygzGRDat3Kqlz5CsEA9jAC2dDk_g&obj=12341234&n_time=1234561234
  142. # 移动侦测接口
  143. class NotificationView(View):
  144. def get(self, request, *args, **kwargs):
  145. request.encoding = 'utf-8'
  146. # operation = kwargs.get('operation')
  147. return self.validation(request.GET)
  148. def post(self, request, *args, **kwargs):
  149. request.encoding = 'utf-8'
  150. # operation = kwargs.get('operation')
  151. return self.validation(request.POST)
  152. def validation(self, request_dict):
  153. response = ResponseObject()
  154. uidToken = request_dict.get('uidToken', None)
  155. channel = request_dict.get('channel', None)
  156. n_time = request_dict.get('n_time')
  157. if not all([uidToken, channel, n_time]):
  158. return JsonResponse(status=404)
  159. # return response.json(444)
  160. utko = UidTokenObject(uidToken)
  161. uid = utko.UID
  162. uaqs = UID_App.objects.filter(uid=uid). \
  163. values('token_val', 'app_type', 'appBundleId', 'push_type', 'uid', 'userID_id', 'userID__NickName')
  164. if uaqs.exists():
  165. for ua in uaqs:
  166. push_type = ua['push_type']
  167. # ios apns
  168. if push_type == 0:
  169. self.do_apns(request_dict, ua, response)
  170. # android gcm
  171. elif push_type == 1:
  172. self.do_gmc(request_dict, ua, response)
  173. # android jpush
  174. elif push_type == 2:
  175. self.do_jpush(request_dict, ua, response)
  176. self.do_save_equipment_info(ua, n_time, channel)
  177. #############
  178. # 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
  179. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  180. # Endpoint以杭州为例,其它Region请按实际情况填写。
  181. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  182. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  183. # 设置此签名URL在60秒内有效。
  184. url = bucket.sign_url('PUT', obj, 7200)
  185. res_data = {
  186. 'code': 0,
  187. 'img_push': url,
  188. 'msg': 'success'
  189. }
  190. return JsonResponse(status=200, data=res_data)
  191. ############
  192. else:
  193. return JsonResponse(status=200, data={
  194. 'code': 173,
  195. 'msg': 'data is not exist'})
  196. def do_jpush(self, request_dict, uaql, response):
  197. jpush_config = {
  198. 'com.ansjer.accloud_ab': {
  199. 'Key': 'f0dc047e5e53fd14199de5b0',
  200. 'Secret': 'aa7f7db33e9f0a7f3871aa1c'},
  201. 'com.ansjer.adcloud_ab': {
  202. 'Key': '76d97b535185114985608234',
  203. 'Secret': 'c9a92b301043cc9c52778692'},
  204. 'com.ansjer.zccloud_ab': {
  205. 'Key': 'd9924f56d3cc7c6017965130',
  206. 'Secret': '869d832d126a232f158b5987'},
  207. 'com.ansjer.loocamccloud_ab': {
  208. 'Key': 'd1cc44797b4642b0e05304fe',
  209. 'Secret': 'c3e8b4ca8c576de61401e56a'},
  210. 'com.ansjer.loocamdcloud_ab': {
  211. 'Key': '76d97b535185114985608234',
  212. 'Secret': 'c9a92b301043cc9c52778692'},
  213. 'com.ansjer.zccloud_a': {
  214. 'Key': '57de2a80d68bf270fd6bdf5a',
  215. 'Secret': '3d354eb6a0b49c2610decf42'},
  216. 'com.ansjer.accloud_a': {
  217. 'Key': 'ff95ee685f49c0dc4013347b',
  218. 'Secret': 'de2c20959f5516fdeeafe78e'},
  219. 'com.ansjer.adcloud_a': {
  220. 'Key': '2e47eb1aee9b164460df3668',
  221. 'Secret': 'b9137d8d684bc248f1809b6d'},
  222. 'com.ansjer.loocamccloud_a': {
  223. 'Key': '23c9213215c7ca0ec945629b',
  224. 'Secret': '81e4b1e859cc8387e2e6c431'},
  225. 'com.ansjer.loocamdcloud_a': {
  226. 'Key': '1dbdd60a16e9892d6f68a073',
  227. 'Secret': '80a97690e7e043109059b403'},
  228. 'com.ansjer.customizedb_a': {
  229. 'Key': '9d79630aa49adfa291fe2568',
  230. 'Secret': '4d8ff52f88136561875a0212'},
  231. }
  232. n_time = request_dict.get('n_time', None)
  233. appBundleId = uaql['appBundleId']
  234. token_val = uaql['token_val']
  235. uid = uaql['uid']
  236. response = ResponseObject()
  237. app_key = jpush_config[appBundleId]['Key']
  238. master_secret = jpush_config[appBundleId]['Secret']
  239. # 此处换成各自的app_key和master_secret
  240. _jpush = jpush.JPush(app_key, master_secret)
  241. push = _jpush.create_push()
  242. # if you set the logging level to "DEBUG",it will show the debug logging.
  243. _jpush.set_logging("DEBUG")
  244. # push.audience = jpush.all_
  245. push.audience = jpush.registration_id(token_val)
  246. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": "51", "msg": "",
  247. "received_at": n_time, "sound": "sound.aif", "uid": uid}
  248. push_msg = json.dumps(push_data)
  249. # push.notification = jpush.notification(alert="hello jpush api")
  250. # push.notification = jpush.notification(alert=push_msg)
  251. # android = jpush.android(alert="Hello, Android msg",extras=push_data)
  252. # push.notification = jpush.notification(alert="Hello, JPush!", android=android)
  253. # push.notification = jpush.message(msg_content=push_data, extras=push_data)
  254. push.message = jpush.message('Motion', extras=push_data, title='KPNS', content_type='text')
  255. push.platform = jpush.all_
  256. try:
  257. res = push.send()
  258. print(res)
  259. except Exception as e:
  260. print("Exception")
  261. print(repr(e))
  262. return response.json(10, repr(e))
  263. else:
  264. return response.json(0)
  265. def do_gmc(self, request_dict, uaql, response):
  266. n_time = request_dict.get('n_time')
  267. appBundleId = uaql['appBundleId']
  268. token_val = uaql['token_val']
  269. uid = uaql['uid']
  270. gcm_config = {
  271. 'com.ansjer.zccloud_a': 'AAAAb9YP3rk:APA91bHu8u-CTpcd0g6lKPo0WNVqCi8jZub1cPPbSAY9AucT1HxlF65ZDUko9iG8q2ch17bwu9YWHpK1xI1gHSRXCslLvZlXEmHZC0AG3JKg15XuUvlFKACIajUFV-pOeGRT8tM6-31I',
  272. 'com.ansjer.loocamccloud_a': 'AAAAb9YP3rk:APA91bFCgd-kbVmpK4EVpfdHH_PJZQCYTkOGnTZdIuBWEz2r7aMRsJYHOH3sB-rwcbaRWgnufTyjX9nGQxb6KxQbWVk4ah_H-M3IqGh6Mb60WQQAuR33V6g_Jes5pGL6ViuIxGHqVMaR',
  273. 'com.ansjer.loocamdcloud_a': 'AAAAb9YP3rk:APA91bGw2I2KMD4i-5T7nZO_wB8kuAOuqgyqe5rxmY-W5qkpYEx9IL2IfmC_qf6B_xOyjIDDSjckvMo-RauN__SEoxvAkis7042GRkoKpw7cjZ_H8lC-d50PC0GclPzccrOGFusyKbFY',
  274. 'com.ansjer.customizedb_a': 'AAAAb9YP3rk:APA91bE7kI4vcm-9h_CJNFlOZfc-xwP4Btn6AnjOrwoKV6fgYN7fdarkO76sYxVZiAbDnxsFfOJyP7vQfwyan6mdjuyD5iHdt_XgO22VqniC0vA1V4GJiCS8Tp7LxIX8JVKZl9I_Powt',
  275. 'com.ansjer.customizeda_a': 'AAAAb9YP3rk:APA91bF0HzizVWDc6dKzobY9fsaKDK4veqkOZehDXshVXs8pEEvNWjR_YWbhP60wsRYCHCal8fWN5cECVOWNMMzDsfU88Ty2AUl8S5FtZsmeDTkoGntQOswBr8Ln7Fm_LAp1VqTf9CpM',
  276. }
  277. serverKey = gcm_config[appBundleId]
  278. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": "51", "msg": "",
  279. "received_at": n_time, "sound": "sound.aif", "uid": uid}
  280. json_data = {
  281. "collapse_key": "WhatYouWant",
  282. "data": push_data,
  283. "delay_while_idle": False,
  284. "time_to_live": 3600,
  285. "registration_ids": [token_val]
  286. }
  287. url = 'https://android.googleapis.com/gcm/send'
  288. # serverKey = "AAAAb9YP3rk:APA91bHu8u-CTpcd0g6lKPo0WNVqCi8jZub1cPPbSAY9AucT1HxlF65ZDUko9iG8q2ch17bwu9YWHpK1xI1gHSRXCslLvZlXEmHZC0AG3JKg15XuUvlFKACIajUFV-pOeGRT8tM6-31I"
  289. data = json.dumps(json_data).encode('utf-8')
  290. headers = {'Content-Type': 'application/json', 'Authorization': 'key=%s' % serverKey}
  291. req = requests.post(url, data, headers=headers)
  292. return response.json(0)
  293. def do_apns(self, request_dict, uaql, response):
  294. token_val = uaql['token_val']
  295. n_time = request_dict.get('n_time')
  296. appBundleId = uaql['appBundleId']
  297. uid = uaql['uid']
  298. apns_config = {
  299. 'appbundleId': {'pem_path': 'xxxx', 'topic': 'topic', 'password': 'password'}
  300. }
  301. try:
  302. # daytime = time.strftime("%Y%m%d%H%M", time.localtime(1547256103))
  303. # print(daytime)
  304. pem_path = os.path.join(BASE_DIR, apns_config[appBundleId]['topic'])
  305. # pem_path = os.path.join(BASE_DIR, 'Ansjer/file/apns-dev.pem')
  306. cli = apns2.APNSClient(mode="dev", client_cert=pem_path, password='111111')
  307. body = json.dumps({'uid': uid, 'n_time': n_time})
  308. alert = apns2.PayloadAlert(body="body!", title="title!")
  309. payload = apns2.Payload(alert=alert)
  310. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  311. res = cli.push(n=n, device_token=token_val, topic=apns_config[appBundleId]['pem_path'])
  312. # assert res.status_code == 200, res.reason
  313. # assert res.apns_id
  314. if res.status_code == 200:
  315. return response.json(0)
  316. else:
  317. return response.json(404, res.reason)
  318. except Exception as e:
  319. return response.json(10, repr(e))
  320. def do_save_equipment_info(self, uaql, n_time, channel):
  321. Equipment_Info.objects.create(
  322. userID_id=uaql['userID_id'],
  323. eventTime=n_time,
  324. eventType=1,
  325. devUid=uaql['uid'],
  326. devNickName=uaql['userID__NickName'],
  327. Channel=channel,
  328. alarm='0',
  329. receiveTime=n_time)