1414import io , base64 , zipfile
1515from typing import List , Dict , Optional
1616
17-
18- from google .oauth2 .service_account import Credentials
19- from googleapiclient .discovery import build
20- from googleapiclient .http import MediaIoBaseUpload
21-
22-
2317# ========== SETTINGS ==========
2418
2519UPLOAD_FOLDER = 'uploads'
@@ -57,9 +51,11 @@ def get_drive_service():
5751 - GDRIVE_SA_JSON_BASE64: base64-encoded JSON content
5852 Requires env: GDRIVE_ROOT_FOLDER_ID (top folder shared with SA).
5953 """
54+ # Lazy imports so the app can boot even if libs aren't installed
6055 try :
6156 from google .oauth2 import service_account
6257 from googleapiclient .discovery import build
58+ import json , base64
6359 except Exception as ie :
6460 raise RuntimeError (
6561 "Google API libraries not installed. "
@@ -68,22 +64,28 @@ def get_drive_service():
6864
6965 scopes = ["https://www.googleapis.com/auth/drive" ]
7066 json_path = os .environ .get ("GDRIVE_SA_JSON" )
71- json_b64 = os .environ .get ("GDRIVE_SA_JSON_BASE64" )
67+ json_b64 = os .environ .get ("GDRIVE_SA_JSON_BASE64" )
7268
7369 if json_path and os .path .isfile (json_path ):
7470 creds = service_account .Credentials .from_service_account_file (json_path , scopes = scopes )
7571 elif json_b64 :
76- info = json .loads (base64 .b64decode (json_b64 ).decode ("utf-8" ))
72+ try :
73+ info = json .loads (base64 .b64decode (json_b64 ).decode ("utf-8" ))
74+ except Exception as e :
75+ raise RuntimeError ("GDRIVE_SA_JSON_BASE64 is not valid base64 JSON." ) from e
7776 creds = service_account .Credentials .from_service_account_info (info , scopes = scopes )
7877 else :
7978 raise RuntimeError ("Missing service account: set GDRIVE_SA_JSON or GDRIVE_SA_JSON_BASE64." )
8079
80+ # Build the Drive client (handle older client versions without cache_discovery kw)
8181 try :
82- service = build ("drive" , "v3" , credentials = creds , cache_discovery = False )
83- return service
82+ return build ("drive" , "v3" , credentials = creds , cache_discovery = False )
83+ except TypeError :
84+ return build ("drive" , "v3" , credentials = creds )
8485 except Exception as e :
8586 raise RuntimeError (f"Failed to build Drive service: { e } " )
8687
88+
8789def _drive_extract_id (link_or_id : str ) -> Optional [str ]:
8890 """
8991 Accepts a full Drive URL (file or folder) or a raw ID and returns the ID.
0 commit comments