diff --git a/duplicar_plantilla_contrato.py b/duplicar_plantilla_contrato.py index 1fd950d..b0a458f 100644 --- a/duplicar_plantilla_contrato.py +++ b/duplicar_plantilla_contrato.py @@ -1,6 +1,3 @@ -from google.auth.transport.requests import Request -from google_auth_oauthlib.flow import InstalledAppFlow -from google.oauth2.credentials import Credentials from google.oauth2 import service_account from googleapiclient.discovery import build import os @@ -18,11 +15,27 @@ libs_dir = os.path.join(base_dir, 'librerias', 'py_libs', 'py310') if os.path.isdir(libs_dir) and libs_dir not in sys.path: sys.path.insert(0, libs_dir) + +def rb_get_var(name, required=True, default=''): + try: + value = GetVar(name) + except NameError: + value = os.environ.get(name, default) + + if value is None: + value = '' + + value = str(value).strip() + + if required and (not value or value == f'{{{name}}}'): + raise RuntimeError(f'La variable Rocketbot "{name}" está vacía o no fue leída correctamente.') + + return value SCOPES = {scopes_api_google} -CREDENTIALS_PATH = '{gdoc_sa_json}' -TOKEN_PATH = '{gmail_token_json}' +CREDENTIALS_PATH = rb_get_var('gdoc_sa_json2') +IMPERSONATED_USER = rb_get_var('gdoc_impersonated_user') def _load_json(path): @@ -30,37 +43,17 @@ def _load_json(path): return json.load(f) -def get_drive_service(credentials_json_path=CREDENTIALS_PATH, token_json_path=TOKEN_PATH): +def get_drive_service(credentials_json_path=CREDENTIALS_PATH, impersonated_user=IMPERSONATED_USER): info = _load_json(credentials_json_path) + if not isinstance(info, dict) or info.get('type') != 'service_account': + raise RuntimeError('gdoc_sa_json2 debe apuntar a un JSON de cuenta de servicio.') - # Service account - if isinstance(info, dict) and info.get('type') == 'service_account': - creds = service_account.Credentials.from_service_account_file( - credentials_json_path, scopes=SCOPES) - drive_service = build( - 'drive', 'v3', credentials=creds, cache_discovery=False) - return drive_service - - # OAuth flow - creds = None - if os.path.exists(token_json_path): - creds = Credentials.from_authorized_user_file(token_json_path, SCOPES) - - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - credentials_json_path, SCOPES) - try: - creds = flow.run_local_server(port=0) - except Exception: - creds = flow.run_console() - - os.makedirs(os.path.dirname(token_json_path), exist_ok=True) - with open(token_json_path, 'w', encoding='utf-8') as f: - f.write(creds.to_json()) + impersonated_user = (impersonated_user or '').strip() + if not impersonated_user: + raise RuntimeError('Falta la variable gdoc_impersonated_user.') + creds = service_account.Credentials.from_service_account_file( + credentials_json_path, scopes=SCOPES, subject=impersonated_user) drive_service = build( 'drive', 'v3', credentials=creds, cache_discovery=False) return drive_service @@ -119,11 +112,14 @@ def get_doc_url(doc_id): return f"https://docs.google.com/document/d/{doc_id}/edit" -# IDs y URLs -TEMPLATE_DOC_ID = '{template_contrato_id}' -FOLDER_URL = '{drive_contratos_carpeta}' -# Opcional -NEW_DOC_NAME = '{proyecto} - {numeracion_dpto} - {nombre_comprador}' # Nombre del contrato +TEMPLATE_DOC_ID = rb_get_var('template_contrato_id') +FOLDER_URL = rb_get_var('drive_contratos_carpeta') + +proyecto = rb_get_var('proyecto') +numeracion_dpto = rb_get_var('numeracion_dpto') +nombre_comprador = rb_get_var('nombre_comprador') + +NEW_DOC_NAME = f'{proyecto} - {numeracion_dpto} - {nombre_comprador}' try: @@ -132,7 +128,7 @@ try: f'No existe el archivo de credenciales: {CREDENTIALS_PATH}') # Inicializar servicio - drive_service = get_drive_service(CREDENTIALS_PATH, TOKEN_PATH) + drive_service = get_drive_service(CREDENTIALS_PATH, IMPERSONATED_USER) # Extraer ID de carpeta desde URL folder_id = extract_folder_id_from_url(FOLDER_URL)