123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- """
- import json
- import time
- import requests
- import uuid
- import logging
- from django.views.generic import TemplateView
- from django.shortcuts import render_to_response
- from django.http import JsonResponse
- import http.client
- from urllib.parse import urlencode
- 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 model.models import AlexaAuthModel
- from object.RedisObject import RedisObject
- 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):
- @method_decorator(csrf_exempt)
- def dispatch(self, *args, **kwargs):
- return super(deviceStatus, self).dispatch(*args, **kwargs)
- def get(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- operation = kwargs.get('operation')
- return self.validation(request.GET, request, operation)
- 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 == 'saveAccessToken':
- return self.saveAccessToken(request_dict, response)
- if operation == 'addOrUpdate':
- return self.addOrUpdate(request_dict, response)
- if operation == 'delete':
- return self.delete(request_dict, response)
- elif operation == 'test':
- return self.discover(request_dict, response)
- def saveAccessToken(self,request_dict, response):
- access_token = request_dict.get("access_token", '')
- refresh_token = request_dict.get("refresh_token", '')
- token = request_dict.get("token", '')
- logger = logging.getLogger('django')
- logger.info('login-------------begin---token')
- logger.info(access_token)
- logger.info(refresh_token)
- alexAuth = AlexaAuthModel.objects.filter(token=token)
- nowTime = int(time.time())
- if not alexAuth.exists():
- AlexaAuthModel.objects.create(
- access_token = access_token,
- refresh_token = refresh_token,
- token = token,
- expiresTime = nowTime + 3200,
- addTime=nowTime,
- updTime=nowTime)
- else:
- alexAuth.update(
- access_token = access_token,
- refresh_token = refresh_token,
- expiresTime = nowTime + 3200,
- token = token,
- updTime=nowTime
- )
- return JsonResponse({'code':200,'msg':'success'})
- def discover(self,request_dict, response):
- userID = 158943604783713800138000
- # token = 'cGSOD01pi2BICtGd1SVdjegwrVKV1Kmn'
- token = 'cGSOD01pi2BICtGd1SVdjegwrVKV1Kmn'
- alexAuth = AlexaAuthModel.objects.filter(token=token)
- if alexAuth.exists():
- res = alexAuth.values()
- access_token = res[0]['access_token']
- refresh_token = res[0]['refresh_token']
- token = res[0]['token']
- expiresTime = res[0]['expiresTime']
- AlexaAuthModel.objects.filter(userID = userID).delete()
- alexAuth.delete()
- AlexaAuthModel.objects.create(
- userID = userID,
- access_token = access_token,
- refresh_token = refresh_token,
- token = token,
- expiresTime = expiresTime,
- )
- return JsonResponse({'code':200,'msg':'xxx'})
- def addOrUpdate(self,request_dict, response):
- UID = request_dict.get("UID", '')
- userID = request_dict.get("userID", '')
- uid_nick = request_dict.get("uid_nick", '')
- logger = logging.getLogger('django')
- logger.info('in_my_api_updateOrAdd------------------')
- logger.info(UID)
- logger.info(userID)
- logger.info(uid_nick)
- 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']
- 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
- 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": 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, payload, headers)
- request_json = response.json()
- return JsonResponse({'res': request_json})
- def delete(self,request_dict, response):
- UID = request_dict.get("UID", '')
- userID = request_dict.get("userID", '')
- logger = logging.getLogger('django')
- logger.info('in_my_api_delete------------------')
- logger.info(UID)
- logger.info(userID)
- if UID == '':
- return JsonResponse({'code':111,'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']
- refresh_token = info[0]['refresh_token']
- now_time = int(time.time())
- access_token = info[0]['access_token']
- 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 = {
- '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})
- 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
|