Script duplicar_plantilla_contrato.py con los ajustes necesarios para usar la cuenta de servicio.
This commit is contained in:
@@ -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 google.oauth2 import service_account
|
||||||
from googleapiclient.discovery import build
|
from googleapiclient.discovery import build
|
||||||
import os
|
import os
|
||||||
@@ -19,10 +16,26 @@ if os.path.isdir(libs_dir) and libs_dir not in sys.path:
|
|||||||
sys.path.insert(0, libs_dir)
|
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}
|
SCOPES = {scopes_api_google}
|
||||||
|
|
||||||
CREDENTIALS_PATH = '{gdoc_sa_json}'
|
CREDENTIALS_PATH = rb_get_var('gdoc_sa_json2')
|
||||||
TOKEN_PATH = '{gmail_token_json}'
|
IMPERSONATED_USER = rb_get_var('gdoc_impersonated_user')
|
||||||
|
|
||||||
|
|
||||||
def _load_json(path):
|
def _load_json(path):
|
||||||
@@ -30,37 +43,17 @@ def _load_json(path):
|
|||||||
return json.load(f)
|
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)
|
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.')
|
||||||
|
|
||||||
|
impersonated_user = (impersonated_user or '').strip()
|
||||||
|
if not impersonated_user:
|
||||||
|
raise RuntimeError('Falta la variable gdoc_impersonated_user.')
|
||||||
|
|
||||||
# Service account
|
|
||||||
if isinstance(info, dict) and info.get('type') == 'service_account':
|
|
||||||
creds = service_account.Credentials.from_service_account_file(
|
creds = service_account.Credentials.from_service_account_file(
|
||||||
credentials_json_path, scopes=SCOPES)
|
credentials_json_path, scopes=SCOPES, subject=impersonated_user)
|
||||||
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())
|
|
||||||
|
|
||||||
drive_service = build(
|
drive_service = build(
|
||||||
'drive', 'v3', credentials=creds, cache_discovery=False)
|
'drive', 'v3', credentials=creds, cache_discovery=False)
|
||||||
return drive_service
|
return drive_service
|
||||||
@@ -119,11 +112,14 @@ def get_doc_url(doc_id):
|
|||||||
return f"https://docs.google.com/document/d/{doc_id}/edit"
|
return f"https://docs.google.com/document/d/{doc_id}/edit"
|
||||||
|
|
||||||
|
|
||||||
# IDs y URLs
|
TEMPLATE_DOC_ID = rb_get_var('template_contrato_id')
|
||||||
TEMPLATE_DOC_ID = '{template_contrato_id}'
|
FOLDER_URL = rb_get_var('drive_contratos_carpeta')
|
||||||
FOLDER_URL = '{drive_contratos_carpeta}'
|
|
||||||
# Opcional
|
proyecto = rb_get_var('proyecto')
|
||||||
NEW_DOC_NAME = '{proyecto} - {numeracion_dpto} - {nombre_comprador}' # Nombre del contrato
|
numeracion_dpto = rb_get_var('numeracion_dpto')
|
||||||
|
nombre_comprador = rb_get_var('nombre_comprador')
|
||||||
|
|
||||||
|
NEW_DOC_NAME = f'{proyecto} - {numeracion_dpto} - {nombre_comprador}'
|
||||||
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -132,7 +128,7 @@ try:
|
|||||||
f'No existe el archivo de credenciales: {CREDENTIALS_PATH}')
|
f'No existe el archivo de credenciales: {CREDENTIALS_PATH}')
|
||||||
|
|
||||||
# Inicializar servicio
|
# 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
|
# Extraer ID de carpeta desde URL
|
||||||
folder_id = extract_folder_id_from_url(FOLDER_URL)
|
folder_id = extract_folder_id_from_url(FOLDER_URL)
|
||||||
|
|||||||
Reference in New Issue
Block a user