lang пре 4 година
родитељ
комит
b12aefbe94
4 измењених фајлова са 277 додато и 116 уклоњено
  1. 101 86
      controller/deviceStatus.py
  2. 0 30
      controller/index.py
  3. 18 0
      model/models.py
  4. 158 0
      object/ResponseObject.py

+ 101 - 86
controller/deviceStatus.py

@@ -16,6 +16,7 @@ from object.ResObject import ResObject
 import subprocess
 # from gevent.pool import Pool
 from model.models import UserModel,UidRtspModel
+from object.ResponseObject import ResponseObject
 from object.tkObject import tkObject
 from service.CommonService import CommonService
 from object.RedisObject import RedisObject
@@ -23,6 +24,7 @@ from django.utils.decorators import method_decorator
 from django.views.decorators.csrf import csrf_exempt
 
 
+
 rtspServer = "rtsp.zositech.org,3.16.66.144"
 
 class deviceStatus(TemplateView):
@@ -30,101 +32,114 @@ class deviceStatus(TemplateView):
     def dispatch(self, *args, **kwargs):
         return super(deviceStatus, self).dispatch(*args, **kwargs)
 
-    def post(self, request, *args, **kwargs):
+    def get(self, request, *args, **kwargs):
         request.encoding = 'utf-8'
         operation = kwargs.get('operation')
-        if operation == 'test':
-            return JsonResponse({'res': '11'})
+        return self.validation(request.GET, request, operation)
 
-
-    def get(self, request, *args, **kwargs):
-            request.encoding = 'utf-8'
-            request_dict = request.GET
-            operation = kwargs.get('operation')
-            if operation == 'test':
-                api_uri = 'https://api.amazonalexa.com/v3/events'
-                messageId = str(uuid.uuid4())
-                access_token = 'xvc48ylgwzZ7yThu3s113oKTr5LSTuFm'
-                bearer_access_token = 'Bearer {access_token}'.format(access_token=access_token)
-                headers =  {'content-type': "application/json", 'Authorization': bearer_access_token}
-                payload = {
-                    "event": {
-                        "header": {
-                            "namespace": "Alexa.Discovery",
-                            "name": "AddOrUpdateReport",
-                            "payloadVersion": "3",
-                            "messageId": messageId
-                        },
-                        "payload": {
-                            "endpoints": [
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation')
+        return self.validation(request.POST, request, operation)
+
+    def validation(self, request_dict, request, operation):
+        response = ResponseObject()
+        if operation is None:
+            return JsonResponse({'code':404,'msg':'not found'})
+        if operation == 'getAccessToken':
+            return self.accessToken(request_dict, response)
+        # 付款完成
+        elif operation == 'test':
+            return JsonResponse({'code':404,'msg':'not found'})
+            return self.test(request_dict, response)
+
+
+
+
+    def getAccessToken(self,request_dict, response):
+        # lwa_params = {
+        #     "grant_type" : "authorization_code",
+        #     "code": 'NHxKR2mgPmNgCp9yxNCJvJ7fgPbCayNa',
+        #     "client_id": 'amzn1.application-oa2-client.efb07b51dd444f848b6f0598635da3cc',
+        #     "client_secret": 'showmeyousecret.zosi'
+        # }
+        # header = {"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"}
+        # response = requests.post('https://api.amazon.com/auth/o2/token', data=lwa_params, headers= header, allow_redirects=True)
+        #
+        #
+        # request_json = response.json()
+        # return JsonResponse({'res': request_json})
+        user_qs = UserModel.objects.filter(userID='158943604783713800138000').values('userID','refresh_token')
+        refresh_token = user_qs[0]['refresh_token']
+
+        payload = {
+            'grant_type': 'refresh_token',
+            'refresh_token': refresh_token,
+            'client_id': 'amzn1.application-oa2-client.efb07b51dd444f848b6f0598635da3cc',
+            'client_secret': '8a49390ebe362bfee153be87587f5673d0c1d8aeb6bc1ef736fda6c9d5d81c8f',
+            'redirect_uri': 'http://www.baidu.com'
+        }
+        return self.post_to_api(payload)
+
+    def test(self,request_dict, response):
+        api_uri = 'https://api.amazonalexa.com/v3/events'
+        messageId = str(uuid.uuid4())
+        access_token = 'Atza|IwEBIGZVV6GPFAXf1_ySVAZkOfGc2j0rNhAnGW8dQ71KVnBY9XmKoi5xd1742t-64FLiM27ErgW_D9sqfAd2A69F1o63_HyPeTfP1_CpgYj6ohGGoMTAN9id58PBOyXtqoJr698luykXb8cT30LBxTqU8zYcmxwJfMzyr2Mxz6KkNtusSB4mHBEkfmQ-xkZ_87G0sUscbVokLnkd676kQAuPzmuYzY_nLLbkR28x8ohh0F9lGZYyEJjyg8-VXdoqWBMfEYxgCnQo76FOXXDFyVEPg6ZC'
+        bearer_access_token = 'Bearer {access_token}'.format(access_token=access_token)
+        headers =  {'content-type': "application/json", 'Authorization': bearer_access_token}
+        payload = {
+            "event": {
+                "header": {
+                    "namespace": "Alexa.Discovery",
+                    "name": "AddOrUpdateReport",
+                    "payloadVersion": "3",
+                    "messageId": messageId
+                },
+                "payload": {
+                    "endpoints": [
+                        {
+                            "endpointId": "HVTLKFJM6KDTAF9J111A",
+                            "manufacturerName": "Sample Manufacturer",
+                            "description": "Smart Light by Sample Manufacturer",
+                            "friendlyName": "Kitchen Light",
+                            "displayCategories": [
+                                "CAMERA"
+                            ],
+                            "capabilities": [
                                 {
-                                    "endpointId": "HVTLKFJM6KDTAF9J111A",
-                                    "manufacturerName": "Sample Manufacturer",
-                                    "description": "Smart Light by Sample Manufacturer",
-                                    "friendlyName": "Kitchen Light",
-                                    "displayCategories": [
-                                        "CAMERA"
-                                    ],
-                                    "capabilities": [
-                                        {
-                                            "type": "AlexaInterface",
-                                            "interface": "Alexa.CameraStreamController",
-                                            "version": "3",
-                                            "cameraStreamConfigurations": [
-                                                {
-                                                    "protocols": ["RTSP"],
-                                                    "resolutions":  [{"width": 1280, "height": 720}],
-                                                    "authorizationTypes": ["NONE"],
-                                                    "videoCodecs": ["H264"],
-                                                    "audioCodecs": ["ACC"]
-                                                }]
-                                        },
+                                    "type": "AlexaInterface",
+                                    "interface": "Alexa.CameraStreamController",
+                                    "version": "3",
+                                    "cameraStreamConfigurations": [
                                         {
-                                            "type": "AlexaInterface",
-                                            "interface": "Alexa.MediaMetadata",
-                                            "version": "3",
-                                            "proactivelyReported": True,
-                                            # "retrievable": True
-
-                                        }
-                                    ]
+                                            "protocols": ["RTSP"],
+                                            "resolutions":  [{"width": 1280, "height": 720}],
+                                            "authorizationTypes": ["NONE"],
+                                            "videoCodecs": ["H264"],
+                                            "audioCodecs": ["ACC"]
+                                        }]
+                                },
+                                {
+                                    "type": "AlexaInterface",
+                                    "interface": "Alexa.MediaMetadata",
+                                    "version": "3",
+                                    "proactivelyReported": True,
+                                    # "retrievable": True
+
                                 }
-                            ],
-                            "scope": {
-                                "type": "BearerToken",
-                                "token": access_token
-                            }
+                            ]
                         }
+                    ],
+                    "scope": {
+                        "type": "BearerToken",
+                        "token": access_token
                     }
                 }
-                response = requests.post(api_uri, data = payload, headers = headers)
-                request_json = response.json()
-                return JsonResponse({'res': request_json})
-
-            elif operation == 'getAccessToken':
-                # lwa_params = {
-                #     "grant_type" : "authorization_code",
-                #     "code": 'NHxKR2mgPmNgCp9yxNCJvJ7fgPbCayNa',
-                #     "client_id": 'amzn1.application-oa2-client.efb07b51dd444f848b6f0598635da3cc',
-                #     "client_secret": 'showmeyousecret.zosi'
-                # }
-                # header = {"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"}
-                # response = requests.post('https://api.amazon.com/auth/o2/token', data=lwa_params, headers= header, allow_redirects=True)
-                #
-                #
-                # request_json = response.json()
-                # return JsonResponse({'res': request_json})
-                user_qs = UserModel.objects.filter(userID='158943604783713800138000').values('userID','refresh_token')
-                refresh_token = user_qs[0]['refresh_token']
-
-                payload = {
-                    'grant_type': 'refresh_token',
-                    'refresh_token': refresh_token,
-                    'client_id': 'amzn1.application-oa2-client.efb07b51dd444f848b6f0598635da3cc',
-                    'client_secret': '8a49390ebe362bfee153be87587f5673d0c1d8aeb6bc1ef736fda6c9d5d81c8f',
-                    'redirect_uri': 'http://www.baidu.com'
-                }
-                return self.post_to_api(payload)
+            }
+        }
+        response = requests.post(api_uri, data = payload, headers = headers)
+        request_json = response.json()
+        return JsonResponse({'res': request_json})
 
 
     def post_to_api(self, payload):

+ 0 - 30
controller/index.py

@@ -133,7 +133,6 @@ class oa2TokenView(TemplateView):
         code = request_dict.get("code", None)
         client_id = request_dict.get("client_id", None)
         refresh_token = request_dict.get("refresh_token", None)
-        redirect_uri = request_dict.get("redirect_uri", None)
         from var_dump import var_dump
         logger = logging.getLogger('django')
         logger.info('token-------------begin')
@@ -151,22 +150,6 @@ class oa2TokenView(TemplateView):
         print('client_id:')
         print(client_id)
         user_qs = UserModel.objects.filter(code=code)
-
-
-
-
-
-
-        payload = {
-            'grant_type': 'authorization_code',
-            'code': code,
-            'client_id': 'amzn1.application-oa2-client.efb07b51dd444f848b6f0598635da3cc',
-            'client_secret': '8a49390ebe362bfee153be87587f5673d0c1d8aeb6bc1ef736fda6c9d5d81c8f',
-            'redirect_uri': redirect_uri
-        }
-        self.post_to_api(payload)
-
-
         if not user_qs.exists():
             user_qs = UserModel.objects.filter(refresh_token=refresh_token)
         if user_qs.exists():
@@ -192,19 +175,6 @@ class oa2TokenView(TemplateView):
             print(res_json)
             return JsonResponse(res_json)
 
-    def post_to_api(self, payload):
-        # connection = http.client.HTTPSConnection("api.amazon.com")
-        headers = {
-            'content-type': "application/x-www-form-urlencoded",
-            'cache-control': "no-cache"
-        }
-
-        response = requests.post('https://api.amazon.com/auth/o2/token', urlencode(payload), headers= headers, allow_redirects=True)
-        request_json = response.json()
-        logger = logging.getLogger('django')
-        logger.info('------------this is get_access_token')
-        logger.info(request_json)
-
 
 import threading
 

+ 18 - 0
model/models.py

@@ -40,3 +40,21 @@ class UidRtspModel(models.Model):
 
     def __str__(self):
         return self.id
+
+
+class AlexaAuthModel(models.Model):
+    id = models.AutoField(primary_key=True)
+    userID = models.CharField(blank=True, max_length=32,verbose_name=u'用户ID', unique=True)
+    access_token = models.CharField(max_length=150, unique=True, default='', verbose_name='访问令牌')
+    refresh_token = models.CharField(max_length=150, unique=False, default='', verbose_name='刷新令牌')
+    token = models.CharField(max_length=150, unique=False, default='', verbose_name='区分用户token')
+    addTime = models.IntegerField(verbose_name='添加时间', default=0)
+    updTime = models.IntegerField(verbose_name='更新时间', default=0)
+
+    class Meta:
+        ordering = ('-addTime',)
+        verbose_name = 'alexa授权表'
+        db_table = 'alexa_auth'
+
+    def __str__(self):
+        return self.id

+ 158 - 0
object/ResponseObject.py

@@ -0,0 +1,158 @@
+from django.shortcuts import HttpResponse
+import simplejson as json
+
+
+class ResponseObject(object):
+    def __init__(self, lang='en'):
+        self.lang = lang
+
+    def data(self, code, res={}):
+        data_en = {
+            0: 'Success',
+            5: 'Please try again one minute later!',
+            10: res,
+            12: 'You are not the primary user of the device!',
+            14: 'Device is not belong to you',
+            15: 'Device has been bound',
+            16: 'WeChat has been bound, please log in and unbind using WeChat',
+            17: 'No email or mobile phone login',
+            44: 'System error! Can not send email',
+            48: 'System object error!',
+            89: 'Already send the code, please check it or get it again after 10m',
+            90: 'please check code or get it again after 1m',
+            99: 'Mail doesn\'t exist!',
+            100: 'Phone format error!',
+            101: 'Phone already existed!',
+            102: 'Phone doesn\'t exist!',
+            103: 'Mail already existed!',
+            104: 'Account doesn\'t exist!',
+            105: 'Email format error!',
+            107: 'The username not conform to the rules!',
+            109: 'The password not conform to the rules!',
+            110: 'user doesn\'t activated',
+            111: 'Error password',
+            112: 'Fingerprint login is not turned on',
+            119: 'The qr code has expired',
+            120: 'The code has expired',
+            121: 'The verification code is wrong!',
+            173: 'Data does not exists!',
+            174: 'Data already exists!',
+            176: 'Delete error',
+            177: 'Update error',
+            178: 'ADD error',
+            179: 'Nickname repeated',
+            306: 'The link has expired!',
+            309: 'Please ReLogin! errmsg token',
+            404: 'You don not have permission to access this!',
+            414: 'Please confirm the request url!',
+            424: 'Database Error !',
+            444: 'Wrong parameters!',
+            474: 'System Maintaining!',
+            475: 'App Version too low, please upgrade!',
+            500: 'Query Database Error:',
+            700: 'Upload file error',
+            701: 'The file does not exist!',
+            711: 'Do not downgrade',
+            712: 'Area needs to be consistent',
+            713: 'Storage rules cannot be changed during the validity period',
+            717: 'Authorization expires',
+            900: 'There is no information about this version!',
+            901: 'Getting URL failure!',
+            902: 'No update!',
+            903: 'Error filename',
+            904: 'Version does not support this feature!',
+            906: 'Cause of file operation error',
+            907: 'The download file does not exist!',
+            10001: 'Customer number, customer confidentiality error',
+            10002: 'Check your configuration: no customer number, customer confidentiality',
+            10003: 'The authorization code does not exist. Please reauthorize',
+            10004: 'The request method is incorrect. Please contact the developer',
+            10005: 'Wrong configuration, wrong customer number',
+            10006: 'Configuration error. The path value is incorrect',
+        }
+        data_cn = {
+            0: '成功',
+            5: '请一分钟后再尝试',
+            10: res,
+            12: '非设备主用户',
+            14: '设备不属于您',
+            15: '设备已被绑定',
+            16: '微信已被绑定,请使用微信登录并解绑',
+            17: '未绑定邮箱或者手机登录方式',
+            44: '系统错误!无法发送电子邮件',
+            48: '系统对象错误',
+            89: '已发验证码,请检测或10分钟后重新获取。',
+            90: '请检测或1分钟后重新获取。',
+            99: '邮箱不存在!',
+            100: '手机格式错误!',
+            101: '手机已存在!',
+            102: '手机不存在!',
+            103: '邮箱已存在!',
+            104: '账户不存在!',
+            105: '邮箱格式错误!',
+            107: '用户名格式不符合!',
+            109: '密码格式不符合!',
+            110: '用户未激活!',
+            111: '密码不正确!',
+            112: '未开通指纹登录',
+            119: '二维码过期',
+            120: '验证码过期',
+            121: '验证码错了!',
+            173: '数据不存在!',
+            174: '数据已存在!',
+            176: '删除错误',
+            177: '更新错误',
+            178: '增加错误',
+            179: '名称不能重复',
+            306: '链接已超过有效期!',
+            309: '请重新登录!',
+            404: '您没有访问的权限!',
+            414: '请确认请求url!',
+            424: '数据库错误!',
+            444: '参数错误!',
+            474: '系统维护中!',
+            475: '版本过低,请升级程序!',
+            500: '查询数据库错误!',
+            700: '上传文件错误',
+            701: '文件不存在',
+            711: '不可降级',
+            712: '区域不一致',
+            713: '有效期内不可更改存储规则',
+            717: '授权过期',
+            900: '版本信息不存在',
+            901: '获取链接失败',
+            902: '无更新!',
+            903: '文件名不符合!',
+            904: '版本不支持本功能!',
+            906: '文件操作错误',
+            907: '文件不存在!',
+            10001: '客户编号,客户机密错误',
+            10002: '检查您的配置:没有客户编号,客户机密',
+            10003: '授权码不存在,请重新授权',
+            10004: '请求方法不正确。请联系开发者',
+            10005: '配置错误,客户编号这个值是错误的',
+            10006: '配置错误,路径这个值是错误的',
+        }
+        if self.lang == 'cn':
+            msg = data_cn
+        elif self.lang == 'zh-Hans':
+            msg = data_cn
+        elif self.lang == 'zh-Hant':
+            msg = data_cn
+        else:
+            msg = data_en
+        try:
+            message = msg[code]
+        except Exception as e:
+            message = '系统错误,code不存在'
+        print(self.lang == 'cn')
+        print(msg)
+        return {'result_code': code, 'reason': message, 'result': res, 'error_code': code}
+
+    def formal(self, code, res={}):
+        formal_data = self.data(code, res)
+        return json.dumps(formal_data, ensure_ascii=False)
+
+    def json(self, code, res={}):
+        result = self.formal(code, res)
+        return HttpResponse(result)