lang 4 tahun lalu
induk
melakukan
692bc949f1
1 mengubah file dengan 119 tambahan dan 51 penghapusan
  1. 119 51
      controller/deviceStatus.py

+ 119 - 51
controller/deviceStatus.py

@@ -114,14 +114,32 @@ class deviceStatus(TemplateView):
         uid_nick = request_dict.get("uid_nick", '')
 
         logger = logging.getLogger('django')
-        logger.info('in_my_api------------------')
+        logger.info('in_my_api_updateOrAdd------------------')
 
-        if UID != '' and userID != '' and uid_nick != '':
-            return JsonResponse({'code':200,'msg':'success'})
-        else:
-            return JsonResponse({'code':200,'msg':'fail'})
+        if UID == '' or userID == '' or uid_nick == '':
+            return JsonResponse({'code':101,'msg':'fail'})
+
+        alexAuth = AlexaAuthModel.objects.filter(userID=userID)
+        if not alexAuth.exists():
+            return JsonResponse({'code':102,'msg':'not found user'})
+        info = alexAuth.values()
+        expiresTime = info[0]['expiresTime']
+        now_time = int(time.time())
+        access_token = info[0]['access_token']
+        refresh_token = info[0]['refresh_token']
 
-        access_token = 'xx'
+        if now_time > expiresTime:
+            res = self.getRefreshToken(refresh_token)
+            if('error' not in res):
+                alexAuth.update(
+                    access_token = res['access_token'],
+                    refresh_token = res['refresh_token'],
+                    expiresTime = now_time + 3200,
+                    updTime = now_time,
+                )
+                access_token = res['access_token'],
+            else:
+                return JsonResponse({'code':102,'msg':'get refresh_token fail'})
         api_uri = 'https://api.amazonalexa.com/v3/events'
         messageId = str(uuid.uuid4())
         access_token = access_token
@@ -136,70 +154,120 @@ class deviceStatus(TemplateView):
                     "messageId": messageId
                 },
                 "payload": {
-                    "endpoints": [
-                        {
-                            "endpointId": UID,
-                            "manufacturerName": "zosi smart",
-                            "description": "Camera connected via zosi smart",
-                            "friendlyName": uid_nick,
-                            "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.MediaMetadata",
-                                    "version": "3",
-                                    "proactivelyReported": True,
-                                    # "retrievable": True
-                                }
-                            ]
-                        }
-                    ],
-                    "scope": {
-                        "type": "BearerToken",
-                        "token": access_token
+                    "endpoints": {
+                        "endpointId": UID,
+                        "manufacturerName": 'zosi smart',
+                        "modelName": 'P1425-LE',
+                        "friendlyName": uid_nick,
+                        "description": 'Camera connected via zosi smart',
+                        "displayCategories": ['CAMERA'],
+                        "cookie": {},
+                        "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.MediaMetadata',
+                            #     "version": '3',
+                            #     "proactivelyReported": True,
+                            #     # "retrievable": True
+                            #
+                            # }
+                        ]
+                    },
+                    'scope': {
+                        'type': 'BearerToken',
+                        'token': access_token
                     }
                 }
             }
         }
+
         response = requests.post(api_uri, data = payload, headers = headers)
         request_json = response.json()
         return JsonResponse({'res': request_json})
 
     def delete(self,request_dict, response):
         UID = request_dict.get("UID", '')
-        if UID != '':
-            return JsonResponse({'code':200,'msg':'success'})
-        else:
-            return JsonResponse({'code':200,'msg':'fail'})
+        if UID == '':
+            return JsonResponse({'code':111,'msg':'fail'})
+
+        userID = 158943604783713800138000
+        alexAuth = AlexaAuthModel.objects.filter(userID=userID)
+        if not alexAuth.exists():
+            return JsonResponse({'code':102,'msg':'not found user'})
 
+        info = alexAuth.values()
+        expiresTime = info[0]['expiresTime']
+        refresh_token = info[0]['refresh_token']
+        now_time = int(time.time())
+        access_token = info[0]['access_token']
 
-    def post_to_api(self, payload):
-        connection = http.client.HTTPSConnection("api.amazon.com")
+        if now_time > expiresTime:
+            res = self.getRefreshToken(refresh_token)
+            if('error' not in res):
+                alexAuth.update(
+                    access_token = res['access_token'],
+                    refresh_token = res['refresh_token'],
+                    expiresTime = now_time + 3200,
+                    updTime = now_time,
+                )
+                access_token = res['access_token'],
+            else:
+                return JsonResponse({'code':102,'msg':'get refresh_token fail'})
+        messageId = str(uuid.uuid4())
         headers = {
-            'content-type': "application/x-www-form-urlencoded",
-            'cache-control': "no-cache"
+            'Authorization': "Bearer " + access_token,
+            'Content-Type': "application/json;charset=UTF-8",
+            'Cache-Control': "no-cache"
+        }
+        payload = {
+            'endpoints': [
+                {
+                    'endpointId': UID
+                }
+            ],
+            "scope": {
+                "type": "BearerToken",
+                "token": access_token
+            }
         }
+        # return JsonResponse({'res': headers})
 
-        response = requests.post('https://api.amazon.com/auth/o2/token', urlencode(payload), headers= headers, allow_redirects=True)
+        api_uri = 'https://api.amazonalexa.com/v3/events'
+        response = requests.post(api_uri, payload, headers)
         request_json = response.json()
         return JsonResponse({'res': request_json})
 
 
+    def getRefreshToken(self,refresh_token):
+        payload = {
+            'grant_type': 'refresh_token',
+            'refresh_token': refresh_token,
+            'client_id': 'amzn1.application-oa2-client.efb07b51dd444f848b6f0598635da3cc',
+            'client_secret': '8a49390ebe362bfee153be87587f5673d0c1d8aeb6bc1ef736fda6c9d5d81c8f',
+        }
+        auth_request_url = 'https://api.amazon.com/auth/o2/token'
+        headers = {
+            'content-type': "application/x-www-form-urlencoded",
+            'cache-control': "no-cache"
+        }
+        res = requests.post(auth_request_url, payload,headers)
+        request_json = res.json()
+        return request_json
+
+