Skip to content

Commit

Permalink
Google API (#510)
Browse files Browse the repository at this point in the history
### Description

Please explain the changes you made here.

### Checklist

- [ ] Created tests which fail without the change (if possible)
- [ ] All tests passing
- [ ] Extended the documentation, if necessary
  • Loading branch information
armanddidierjean authored Aug 23, 2024
1 parent 39aa9b3 commit c0ac46e
Show file tree
Hide file tree
Showing 11 changed files with 393 additions and 2 deletions.
6 changes: 6 additions & 0 deletions .env.template
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ CORS_ORIGINS=["http://localhost"]
#MATRIX_LOG_ERROR_ROOM_ID = ""
#MATRIX_LOG_AMAP_ROOM_ID = ""

# Google API configuration #
# Google API is used to upload files to Google Drive and generate PDF using App Script
# See ./app/utils/google_api/README.md for more information
#GOOGLE_API_CLIENT_ID = ""
#GOOGLE_API_CLIENT_SECRET = ""

# Token to use the TMDB API
#THE_MOVIE_DB_API = ""

Expand Down
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,15 @@ To enable the service:
2. Choose _Manage keys_ and create a new JSON key.
3. Rename the file `firebase.json` and add it at Hyperion root

## Use websocket

When using multiples workers, a Redis server must be configured to broadcast messages between workers.

## Google API usage

Hyperion can use Google API to run App Script and upload files to Google Drive.
See [app/utils/google_api/README.md](./app/utils/google_api/README.md) for more information.

---

## Running Hyperion with Gunicorn
Expand Down
7 changes: 7 additions & 0 deletions app/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ class Settings(BaseSettings):
REDIS_LIMIT: int
REDIS_WINDOW: int

##############
# Google API #
##############
# Google API is used to upload files to Google Drive and to use Google Apps Script to generate PDF from Google Sheets
GOOGLE_API_CLIENT_ID: str | None = None
GOOGLE_API_CLIENT_SECRET: str | None = None

##########################
# Firebase Configuration #
##########################
Expand Down
28 changes: 27 additions & 1 deletion app/core/endpoints_core.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import logging
from os import path
from pathlib import Path

from fastapi import APIRouter, Depends, HTTPException
from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import FileResponse
from sqlalchemy.ext.asyncio import AsyncSession

Expand All @@ -15,10 +16,13 @@
is_user_a_member_of,
)
from app.modules.module_list import module_list
from app.utils.google_api.google_api import GoogleAPI
from app.utils.tools import is_group_id_valid

router = APIRouter(tags=["Core"])

hyperion_error_logger = logging.getLogger("hyperion.error")


@router.get(
"/information",
Expand Down Expand Up @@ -247,3 +251,25 @@ async def delete_session(
allowed_group_id=group_id,
db=db,
)


@router.get("/google-api/oauth2callback", status_code=200)
async def google_api_callback(
request: Request,
db: AsyncSession = Depends(get_db),
settings: Settings = Depends(get_settings),
):
try:
await GoogleAPI().authentication_callback(
db=db,
settings=settings,
request=request,
)

except Exception:
hyperion_error_logger.exception(
"Google API authentication callback error",
)
return "An error occurred during the Google API authentication callback"
else:
return "Ok"
9 changes: 9 additions & 0 deletions app/types/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ class CoreDataNotFoundError(Exception):
pass


class GoogleAPIInvalidCredentialsError(Exception):
pass


class GoogleAPIMissingConfigInDotenvError(Exception):
def __init__(self):
super().__init__("Google API is not configured in dotenv")


class ContentHTTPException(HTTPException):
"""
A custom HTTPException allowing to return custom content.
Expand Down
25 changes: 25 additions & 0 deletions app/utils/google_api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Google API usage in Hyperion

Hyperion can use Google API to run App Script and upload files to Google Drive.

## Configuration

You need to configure a client id and secret in the dotenv:

```yml
GOOGLE_API_CLIENT_ID
GOOGLE_API_CLIENT_SECRET
```

1. Go to https://console.cloud.google.com/projectcreate and create a new project
2. Select the project and open [API and Services](https://console.cloud.google.com/apis/dashboard)
3. Select "Library" and add the following libraries:
a. Google Drive API
b. Google Sheets API
c. Apps Script API
4. Go to [Credentials](https://console.cloud.google.com/apis/credentials). Select "Configure Consent Screen"
a. User Type : Internal
5. Go to [Credentials](https://console.cloud.google.com/apis/credentials). Select "Create credentials" then:
a. OAuth client id
b. Web Application
c. TODO: redirect uri?
Empty file.
17 changes: 17 additions & 0 deletions app/utils/google_api/coredata_google_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from datetime import datetime

from app.types.core_data import BaseCoreData


class GoogleAPICredentials(BaseCoreData):
token: str
refresh_token: str
token_uri: str
client_id: str
client_secret: str
scopes: list[str]
expiry: datetime


class GoogleAPIOAuthFlow(BaseCoreData):
state: str | None = None
Loading

0 comments on commit c0ac46e

Please sign in to comment.