craw_web / google_drive.py
euler314's picture
Rename app/google_drive.py to google_drive.py
b7c015d verified
raw
history blame
3.06 kB
import os
import logging
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.http
logger = logging.getLogger(__name__)
# Load Google OAuth config from environment variables
GOOGLE_OAUTH_CONFIG = {
"web": {
"client_id": os.environ.get("GOOGLE_CLIENT_ID"),
"project_id": os.environ.get("GOOGLE_PROJECT_ID"),
"auth_uri": os.environ.get("GOOGLE_AUTH_URI", "https://accounts.google.com/o/oauth2/auth"),
"token_uri": os.environ.get("GOOGLE_TOKEN_URI", "https://oauth2.googleapis.com/token"),
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": os.environ.get("GOOGLE_CLIENT_SECRET"),
"redirect_uris": [os.environ.get("GOOGLE_REDIRECT_URI")]
}
}
def get_google_auth_url():
"""Generate URL for Google Auth"""
client_config = GOOGLE_OAUTH_CONFIG["web"]
flow = google_auth_oauthlib.flow.Flow.from_client_config(
{"web": client_config},
scopes=["https://www.googleapis.com/auth/drive.file"]
)
flow.redirect_uri = client_config["redirect_uris"][0]
authorization_url, _ = flow.authorization_url(
access_type="offline",
include_granted_scopes="true",
prompt="consent"
)
return authorization_url
def exchange_code_for_credentials(auth_code):
"""Exchange authorization code for credentials"""
if not auth_code.strip():
return None, "No code provided."
try:
client_config = GOOGLE_OAUTH_CONFIG["web"]
flow = google_auth_oauthlib.flow.Flow.from_client_config(
{"web": client_config},
scopes=["https://www.googleapis.com/auth/drive.file"]
)
flow.redirect_uri = client_config["redirect_uris"][0]
flow.fetch_token(code=auth_code.strip())
creds = flow.credentials
if not creds or not creds.valid:
return None, "Could not validate credentials. Check code and try again."
return creds, "Google Sign-In successful!"
except Exception as e:
return None, f"Error during token exchange: {e}"
def google_drive_upload(file_path, credentials, folder_id=None):
"""Upload a file to Google Drive"""
try:
drive_service = googleapiclient.discovery.build("drive", "v3", credentials=credentials)
file_metadata = {'name': os.path.basename(file_path)}
if folder_id:
file_metadata['parents'] = [folder_id]
media = googleapiclient.http.MediaFileUpload(file_path, resumable=True)
created = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()
return created.get("id", "")
except Exception as e:
return f"Error uploading to Drive: {str(e)}"
def create_drive_folder(drive_service, name):
"""Create a folder in Google Drive"""
folder_metadata = {'name': name, 'mimeType': 'application/vnd.google-apps.folder'}
folder = drive_service.files().create(body=folder_metadata, fields='id').execute()
return folder.get('id')