Add fotos.carloselugo.com photo-upload service

Event photo upload app with OAuth2 (Google Drive), Caddy route, and
env-var-driven compose config. Refresh token persists to token.json
so re-auth isn't needed after container restarts.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-22 23:24:00 +00:00
co-authored by Claude Sonnet 5
parent 0b6dcb037e
commit 6ee4022d21
13 changed files with 1364 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
DRIVE_FOLDER_ID=1AbCdEfGhIjKlMnOpQrStUvWxYz
GOOGLE_OAUTH_CLIENT_ID=xxxxx.apps.googleusercontent.com
GOOGLE_OAUTH_CLIENT_SECRET=xxxxx
GOOGLE_OAUTH_REFRESH_TOKEN=xxxxx
PORT=3000
ADMIN_PASSWORD=cambia-esta-clave
+15
View File
@@ -0,0 +1,15 @@
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install --omit=dev
COPY . .
# tmp_uploads se crea en runtime, pero lo dejamos listo por si acaso
RUN mkdir -p tmp_uploads
EXPOSE 3000
CMD ["node", "server.js"]
+59
View File
@@ -0,0 +1,59 @@
/**
* Utilidad de un solo uso para obtener un refresh token de OAuth2 para la
* cuenta personal de Google dueña de la carpeta de Drive (necesario porque
* las Service Accounts no tienen cuota de almacenamiento en Drive personal).
*
* Uso:
* node get-refresh-token.js <CLIENT_ID> <CLIENT_SECRET>
*
* 1. Imprime una URL de autorización.
* 2. Ábrela en un navegador (donde sea, no tiene que ser este servidor),
* inicia sesión con la cuenta de Google dueña de la carpeta y autoriza.
* 3. El navegador redirige a una URL rota tipo http://localhost/?code=XXXX
* (dará error de conexión, es normal). Copia el valor de "code" de la
* barra de direcciones.
* 4. Pega el código aquí cuando el script lo pida.
* 5. El script imprime el refresh_token — guárdalo en GOOGLE_OAUTH_REFRESH_TOKEN.
*/
'use strict';
const readline = require('readline');
const { google } = require('googleapis');
const [, , CLIENT_ID, CLIENT_SECRET] = process.argv;
if (!CLIENT_ID || !CLIENT_SECRET) {
console.error('Uso: node get-refresh-token.js <CLIENT_ID> <CLIENT_SECRET>');
process.exit(1);
}
const REDIRECT_URI = 'http://localhost';
const oauth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);
const authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
prompt: 'consent',
scope: ['https://www.googleapis.com/auth/drive']
});
console.log('\n1. Abre esta URL en un navegador (con la cuenta de Google dueña de la carpeta):\n');
console.log(authUrl);
console.log('\n2. Autoriza. Te redirigirá a una URL rota (http://localhost/?code=...) — está bien.');
console.log('3. Copia el valor de "code" de esa URL y pégalo abajo.\n');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.question('Código: ', async (code) => {
rl.close();
try {
const { tokens } = await oauth2Client.getToken(code.trim());
console.log('\n✅ Refresh token obtenido:\n');
console.log(tokens.refresh_token);
console.log('\nGuárdalo como GOOGLE_OAUTH_REFRESH_TOKEN.\n');
} catch (err) {
console.error('\n❌ Error al intercambiar el código:', err.message);
process.exit(1);
}
});
+20
View File
@@ -0,0 +1,20 @@
{
"name": "evento-fotos-upload",
"version": "1.0.0",
"description": "Landing page de cero fricción para subir fotos de un evento directo a Google Drive, sin login ni registro.",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "node --watch server.js"
},
"engines": {
"node": ">=18.0.0"
},
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"googleapis": "^140.0.1",
"multer": "^1.4.5-lts.1"
}
}
+345
View File
@@ -0,0 +1,345 @@
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin · Fotos del Evento</title>
<!--
============================================================
VISTA DE ADMINISTRACIÓN
Permite activar/desactivar la subida de fotos sin tocar el
servidor. Protegida por password (ADMIN_PASSWORD en .env).
No hay sesión persistente: la contraseña se envía en cada
toggle, igual de simple que el host password de NI Quiz.
============================================================
-->
<style>
:root {
--accent: #ec3013;
--bg: #faf9f5;
--text: #1a1a1a;
--muted: #6b6b6b;
--success: #1e8e3e;
--error: #d93025;
--radius: 16px;
}
* { box-sizing: border-box; }
body {
margin: 0;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
padding: 24px;
}
.card {
width: 100%;
max-width: 380px;
background: #fff;
border-radius: var(--radius);
padding: 28px 24px;
box-shadow: 0 4px 24px rgba(0,0,0,0.08);
display: flex;
flex-direction: column;
gap: 16px;
}
h1 {
font-size: 1.2rem;
margin: 0 0 4px 0;
}
input[type="password"] {
width: 100%;
padding: 14px;
border: 1.5px solid #e0e0e0;
border-radius: 10px;
font-size: 1rem;
}
button {
width: 100%;
padding: 14px;
border: none;
border-radius: 10px;
font-size: 1rem;
font-weight: 700;
cursor: pointer;
}
#loginBtn {
background: var(--text);
color: #fff;
}
.toggle-row {
display: none;
flex-direction: column;
gap: 14px;
align-items: center;
text-align: center;
}
.toggle-row.active { display: flex; }
.switch {
position: relative;
width: 72px;
height: 40px;
}
.switch input { display: none; }
.slider {
position: absolute;
inset: 0;
background: #d93025;
border-radius: 999px;
cursor: pointer;
transition: background 0.25s ease;
}
.slider::before {
content: '';
position: absolute;
width: 32px;
height: 32px;
left: 4px;
top: 4px;
background: #fff;
border-radius: 50%;
transition: transform 0.25s ease;
}
input:checked + .slider {
background: var(--success);
}
input:checked + .slider::before {
transform: translateX(32px);
}
.state-label {
font-weight: 700;
font-size: 1rem;
}
.state-label.on { color: var(--success); }
.state-label.off { color: var(--error); }
#msg {
font-size: 0.85rem;
min-height: 18px;
text-align: center;
}
#msg.error { color: var(--error); }
#msg.success { color: var(--success); }
.hint {
font-size: 0.8rem;
color: var(--muted);
text-align: center;
}
.divider {
border: none;
border-top: 1px solid #eee;
margin: 4px 0;
}
.token-section {
display: none;
flex-direction: column;
gap: 10px;
align-items: center;
text-align: center;
}
.token-section.active { display: flex; }
#tokenBtn {
background: #fff;
color: var(--text);
border: 1.5px solid var(--text);
}
#tokenInfo {
font-size: 0.78rem;
color: var(--muted);
}
</style>
</head>
<body>
<div class="card">
<h1>🔐 Panel de administración</h1>
<div id="loginView">
<input type="password" id="passwordInput" placeholder="Contraseña" autocomplete="off">
<button id="loginBtn" style="margin-top:10px;">Entrar</button>
</div>
<div class="toggle-row" id="toggleRow">
<p class="hint">Controla si los asistentes pueden subir fotos ahora mismo.</p>
<label class="switch">
<input type="checkbox" id="toggleInput">
<span class="slider"></span>
</label>
<div class="state-label" id="stateLabel"></div>
<hr class="divider">
<div class="token-section active" id="tokenSection">
<p class="hint">Si las subidas empiezan a fallar por autenticación con Google, genera un token nuevo.</p>
<button id="tokenBtn">🔄 Generar nuevo token de Google</button>
<div id="tokenInfo">Verificando estado del token...</div>
</div>
</div>
<div id="msg"></div>
</div>
<script>
(function () {
'use strict';
const loginView = document.getElementById('loginView');
const passwordInput = document.getElementById('passwordInput');
const loginBtn = document.getElementById('loginBtn');
const toggleRow = document.getElementById('toggleRow');
const toggleInput = document.getElementById('toggleInput');
const stateLabel = document.getElementById('stateLabel');
const msgEl = document.getElementById('msg');
const tokenBtn = document.getElementById('tokenBtn');
const tokenInfo = document.getElementById('tokenInfo');
let currentPassword = '';
function setMsg(type, text) {
msgEl.className = type;
msgEl.textContent = text;
}
function renderState(enabled) {
toggleInput.checked = enabled;
stateLabel.textContent = enabled ? '✅ Subidas ACTIVADAS' : '⛔ Subidas DESACTIVADAS';
stateLabel.className = 'state-label ' + (enabled ? 'on' : 'off');
}
function formatDate(iso) {
if (!iso) return null;
try {
return new Date(iso).toLocaleString('es-PR', { dateStyle: 'medium', timeStyle: 'short' });
} catch (e) {
return iso;
}
}
async function loadTokenInfo() {
try {
const res = await fetch('/admin/oauth/token-info', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password: currentPassword })
});
const data = await res.json();
if (!res.ok || !data.success) {
tokenInfo.textContent = 'No se pudo verificar el estado del token.';
return;
}
if (!data.hasToken) {
tokenInfo.textContent = '⚠️ No hay ningún token configurado todavía.';
} else if (data.updatedAt) {
tokenInfo.textContent = 'Último generado desde este panel: ' + formatDate(data.updatedAt);
} else {
tokenInfo.textContent = 'Usando el token inicial configurado en el servidor (.env).';
}
} catch (err) {
tokenInfo.textContent = 'No se pudo verificar el estado del token.';
}
}
loginBtn.addEventListener('click', async () => {
const password = passwordInput.value.trim();
if (!password) return;
setMsg('', '');
loginBtn.disabled = true;
loginBtn.textContent = 'Verificando...';
try {
const res = await fetch('/admin/status-check', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password })
});
const data = await res.json();
if (!res.ok || !data.success) {
setMsg('error', '❌ ' + (data.error || 'Contraseña incorrecta.'));
loginBtn.disabled = false;
loginBtn.textContent = 'Entrar';
return;
}
currentPassword = password;
loginView.style.display = 'none';
toggleRow.classList.add('active');
renderState(data.enabled);
loadTokenInfo();
} catch (err) {
setMsg('error', '❌ Error de conexión.');
loginBtn.disabled = false;
loginBtn.textContent = 'Entrar';
}
});
passwordInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') loginBtn.click();
});
toggleInput.addEventListener('change', async () => {
const desired = toggleInput.checked;
toggleInput.disabled = true;
setMsg('', '');
try {
const res = await fetch('/admin/toggle', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password: currentPassword, enabled: desired })
});
const data = await res.json();
if (!res.ok || !data.success) {
setMsg('error', '❌ ' + (data.error || 'No se pudo actualizar.'));
toggleInput.checked = !desired; // revertir visualmente
} else {
renderState(data.enabled);
setMsg('success', '✅ Estado actualizado.');
}
} catch (err) {
setMsg('error', '❌ Error de conexión.');
toggleInput.checked = !desired;
} finally {
toggleInput.disabled = false;
}
});
// Redirige a Google para reautorizar. El servidor valida la contraseña
// antes de generar la URL de consentimiento (ver /admin/oauth/start).
tokenBtn.addEventListener('click', () => {
window.location.href = '/admin/oauth/start?password=' + encodeURIComponent(currentPassword);
});
})();
</script>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

+392
View File
@@ -0,0 +1,392 @@
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Fotos del Evento</title>
<!--
============================================================
LANDING PAGE "CERO FRICCIÓN" - SUBIDA DE FOTOS DEL EVENTO
============================================================
- Sin login, sin registro, sin email.
- Un solo botón grande: "Añadir fotos".
- Subida automática en segundo plano vía fetch() + FormData.
- Feedback visual claro en cada estado.
============================================================
-->
<style>
:root {
/* Paleta tomada del escudo "War Hawks": azul marino + dorado */
--navy: #0d1b3e;
--navy-dark: #081127;
--gold: #d4af5f;
--gold-light: #e8cd8f;
--bg: #f5f2e9;
--text: #0d1b3e;
--muted: #5c6172;
--success: #1e8e3e;
--error: #d93025;
--radius: 18px;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
padding: 0;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
-webkit-tap-highlight-color: transparent;
}
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
text-align: center;
padding: 24px;
background:
radial-gradient(circle at 50% 0%, rgba(212, 175, 95, 0.10), transparent 55%),
var(--bg);
}
.container {
width: 100%;
max-width: 420px;
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
.card {
width: 100%;
background: #fff;
border-radius: 22px;
padding: 36px 22px 44px;
box-shadow: 0 10px 30px rgba(13, 27, 62, 0.15);
display: flex;
flex-direction: column;
align-items: center;
gap: 22px;
}
.card img.logo {
width: 260px;
height: auto;
margin-top: -4px;
}
p.subtitle {
margin: 0;
color: var(--muted);
font-size: 0.95rem;
line-height: 1.4;
}
/* Input real de archivo, oculto. Usamos un <label> como botón visual
para poder estilizarlo libremente en iOS/Android. */
#fileInput {
display: none;
}
.upload-btn {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
width: 100%;
padding: 20px 18px;
background: linear-gradient(135deg, var(--gold-light) 0%, var(--gold) 100%);
color: var(--navy-dark);
font-size: 1.1rem;
font-weight: 800;
border: none;
border-radius: var(--radius);
cursor: pointer;
user-select: none;
transition: transform 0.12s ease, filter 0.2s ease, opacity 0.2s ease;
box-shadow: 0 8px 22px rgba(212, 175, 95, 0.35);
}
.upload-btn:active {
transform: scale(0.97);
filter: brightness(0.95);
}
.upload-btn.disabled {
opacity: 0.6;
pointer-events: none;
}
/* ---- Estado / feedback ---- */
#status {
min-height: 28px;
font-size: 0.95rem;
font-weight: 600;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
}
#status.uploading { color: var(--muted); }
#status.success { color: var(--success); }
#status.error { color: var(--error); }
.spinner {
width: 16px;
height: 16px;
border: 2.5px solid rgba(13, 27, 62, 0.15);
border-top-color: var(--navy);
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
/* Barra de progreso simple (número de archivos subidos / total) */
.progress-wrap {
width: 100%;
height: 8px;
background: rgba(13, 27, 62, 0.08);
border-radius: 999px;
overflow: hidden;
display: none;
}
.progress-wrap.active { display: block; }
.progress-bar {
height: 100%;
width: 0%;
background: linear-gradient(90deg, var(--navy), var(--gold));
transition: width 0.25s ease;
}
footer {
margin-top: 8px;
margin-bottom: 24px;
font-size: 0.75rem;
color: var(--muted);
letter-spacing: 0.04em;
text-transform: uppercase;
}
/* Preview miniaturas opcional (pequeñas, solo confirmación visual) */
.thumbs {
display: flex;
flex-wrap: wrap;
gap: 6px;
justify-content: center;
max-width: 100%;
}
.thumbs img {
width: 52px;
height: 52px;
object-fit: cover;
border-radius: 8px;
opacity: 0.9;
border: 2px solid var(--gold-light);
}
.disabled-msg {
background: rgba(217, 48, 37, 0.08);
color: var(--error);
padding: 16px;
border-radius: var(--radius);
font-size: 0.95rem;
font-weight: 600;
line-height: 1.4;
width: 100%;
}
/* Ajustes finos para pantallas muy pequeñas (iPhone SE y similares) */
@media (max-width: 360px) {
.card { padding: 28px 16px 34px; border-radius: 18px; }
.card img.logo { width: 220px; }
}
/* Pantallas grandes: un poco más de aire */
@media (min-width: 600px) {
.container { max-width: 460px; }
.card img.logo { width: 290px; }
}
</style>
</head>
<body>
<div class="container">
<div class="card">
<img class="logo" src="/assets/logo.png" alt="War Hawks - Reencuentro de Clase Graduada - Sube tus fotos">
<p class="subtitle">Selecciona las fotos o videos de tu galería.<br>Se suben automáticamente, sin necesidad de registrarte.</p>
<!-- Label estilizado como botón, dispara el input real -->
<label for="fileInput" id="uploadBtn" class="upload-btn">
➕ Añadir fotos
</label>
<input
type="file"
id="fileInput"
accept="image/*,video/*"
multiple
>
<!-- Mensaje mostrado cuando el admin desactiva las subidas -->
<div id="disabledMsg" class="disabled-msg" style="display:none;">
🚫 La subida de fotos está desactivada por el momento.<br>Vuelve a intentarlo más tarde.
</div>
<div class="progress-wrap" id="progressWrap">
<div class="progress-bar" id="progressBar"></div>
</div>
<div id="status"></div>
<div class="thumbs" id="thumbs"></div>
</div>
</div>
<footer>War Hawks · Reencuentro de Clase Graduada</footer>
<script>
(function () {
'use strict';
// ------------------------------------------------------------------
// CONFIGURACIÓN
// ------------------------------------------------------------------
// URL del backend. Si el frontend y backend se sirven desde el mismo
// origen (ej. Express sirviendo /public), puede dejarse como ruta
// relativa '/upload'. Si se despliega por separado, poner la URL
// completa, ej: 'https://mi-api.onrender.com/upload'
const UPLOAD_ENDPOINT = '/upload';
const fileInput = document.getElementById('fileInput');
const uploadBtn = document.getElementById('uploadBtn');
const statusEl = document.getElementById('status');
const progressWrap = document.getElementById('progressWrap');
const progressBar = document.getElementById('progressBar');
const thumbsEl = document.getElementById('thumbs');
const disabledMsg = document.getElementById('disabledMsg');
// ------------------------------------------------------------------
// Verifica al cargar si las subidas están activadas (panel /admin).
// Si el admin las desactivó, ocultamos el botón y mostramos el aviso.
// ------------------------------------------------------------------
async function checkUploadStatus() {
try {
const res = await fetch('/status');
const data = await res.json();
if (!data.enabled) {
uploadBtn.style.display = 'none';
disabledMsg.style.display = 'block';
}
} catch (err) {
// Si /status falla, dejamos el botón visible por defecto
// para no bloquear al usuario por un error de red transitorio.
console.warn('No se pudo verificar el estado de subidas:', err);
}
}
checkUploadStatus();
function setStatus(type, html) {
statusEl.className = type;
statusEl.innerHTML = html;
}
function resetStatusAfterDelay(ms) {
setTimeout(() => {
setStatus('', '');
progressWrap.classList.remove('active');
progressBar.style.width = '0%';
thumbsEl.innerHTML = '';
}, ms);
}
function showThumbs(files) {
thumbsEl.innerHTML = '';
Array.from(files).slice(0, 8).forEach((file) => {
if (!file.type.startsWith('image/')) return;
const img = document.createElement('img');
img.src = URL.createObjectURL(file);
img.onload = () => URL.revokeObjectURL(img.src);
thumbsEl.appendChild(img);
});
}
fileInput.addEventListener('change', async () => {
const files = fileInput.files;
if (!files || files.length === 0) return;
showThumbs(files);
uploadBtn.classList.add('disabled');
progressWrap.classList.add('active');
progressBar.style.width = '5%';
setStatus('uploading', '<span class="spinner"></span> Subiendo ' + files.length + ' archivo(s)...');
const formData = new FormData();
// El backend espera el campo 'photos' (array, múltiples archivos)
Array.from(files).forEach((file) => {
formData.append('photos', file);
});
try {
// Usamos XMLHttpRequest en vez de fetch puro para poder mostrar
// progreso real de subida (fetch no expone upload progress nativo).
await uploadWithProgress(formData);
progressBar.style.width = '100%';
setStatus('success', '✅ ¡Fotos subidas con éxito!');
resetStatusAfterDelay(4000);
} catch (err) {
console.error('Error subiendo archivos:', err);
setStatus('error', '❌ Error al subir. Intenta de nuevo.');
progressWrap.classList.remove('active');
} finally {
uploadBtn.classList.remove('disabled');
fileInput.value = ''; // permite volver a seleccionar los mismos archivos
}
});
function uploadWithProgress(formData) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', UPLOAD_ENDPOINT, true);
xhr.upload.onprogress = (event) => {
if (event.lengthComputable) {
const pct = Math.max(10, Math.round((event.loaded / event.total) * 100));
progressBar.style.width = pct + '%';
}
};
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.responseText);
} else if (xhr.status === 403) {
// Las subidas fueron desactivadas por el admin justo ahora
uploadBtn.style.display = 'none';
disabledMsg.style.display = 'block';
reject(new Error('Subidas desactivadas'));
} else {
reject(new Error('HTTP ' + xhr.status + ': ' + xhr.responseText));
}
};
xhr.onerror = () => reject(new Error('Error de red'));
xhr.send(formData);
});
}
})();
</script>
</body>
</html>
+485
View File
@@ -0,0 +1,485 @@
/**
* ============================================================
* SERVER.JS
* Backend "cero fricción" para subida de fotos de evento.
*
* Flujo:
* 1. El cliente envía fotos/videos vía multipart/form-data (campo "photos").
* 2. Multer las guarda temporalmente en disco (./tmp_uploads).
* 3. El servidor se autentica en Google Drive vía OAuth2 (cuenta personal).
* 4. Cada archivo se sube a una carpeta específica de Drive (FOLDER_ID).
* 5. El archivo temporal local se borra (limpieza automática).
* 6. Se responde al cliente con el resultado.
*
* Requisitos de entorno (.env):
* GOOGLE_CLIENT_ID = Client ID del OAuth client (Web application)
* GOOGLE_CLIENT_SECRET = Client Secret del mismo OAuth client
* GOOGLE_OAUTH_REFRESH_TOKEN = refresh token inicial (opcional si ya existe token.json)
* (también se acepta GOOGLE_REFRESH_TOKEN como alias)
* OAUTH_REDIRECT_URI = https://tu-dominio/admin/oauth/callback
* DRIVE_FOLDER_ID = ID de la carpeta compartida de Drive
* PORT = 3000 (opcional)
* ADMIN_PASSWORD = contraseña para el panel /admin
*
* Panel de administración:
* GET /admin -> vista con toggle ON/OFF + botón de token
* GET /status -> { enabled } (pública, la consulta el frontend)
* POST /admin/toggle -> { password, enabled } activa/desactiva subidas
* GET /admin/oauth/start -> ?password=... inicia el flujo de reautorización
* GET /admin/oauth/callback -> recibe el "code" de Google, guarda refresh token nuevo
* POST /admin/oauth/token-info -> { password } devuelve cuándo se generó el token actual
*
* El estado de subidas se persiste en upload_status.json.
* El refresh token vigente se persiste en token.json (sobrescribe el de .env).
* ============================================================
*/
'use strict';
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const multer = require('multer');
const fs = require('fs');
const path = require('path');
const { google } = require('googleapis');
// ------------------------------------------------------------------
// CONFIGURACIÓN GENERAL
// ------------------------------------------------------------------
const PORT = process.env.PORT || 3000;
const FOLDER_ID = process.env.DRIVE_FOLDER_ID;
const TMP_DIR = path.join(__dirname, 'tmp_uploads');
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'cambia-esta-clave';
const STATUS_FILE = path.join(__dirname, 'upload_status.json');
const TOKEN_FILE = path.join(__dirname, 'token.json');
const CLIENT_ID = process.env.GOOGLE_CLIENT_ID;
const CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET;
const OAUTH_REDIRECT_URI = process.env.OAUTH_REDIRECT_URI || `http://localhost:${PORT}/admin/oauth/callback`;
const OAUTH_SCOPES = ['https://www.googleapis.com/auth/drive'];
if (!process.env.ADMIN_PASSWORD) {
console.warn('⚠️ ADVERTENCIA: ADMIN_PASSWORD no está definida, usando valor por defecto inseguro. Configúrala en producción.');
}
if (!FOLDER_ID) {
console.warn('⚠️ ADVERTENCIA: la variable de entorno DRIVE_FOLDER_ID no está definida.');
}
if (!CLIENT_ID || !CLIENT_SECRET) {
console.warn('⚠️ ADVERTENCIA: GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET no están definidas.');
}
// Aseguramos que exista el directorio temporal
if (!fs.existsSync(TMP_DIR)) {
fs.mkdirSync(TMP_DIR, { recursive: true });
}
// ------------------------------------------------------------------
// TOKEN DE GOOGLE (refresh token) - persistido en disco
// ------------------------------------------------------------------
// Prioridad: token.json (generado por el botón /admin) > .env (bootstrap inicial)
function readRefreshToken() {
try {
const raw = fs.readFileSync(TOKEN_FILE, 'utf-8');
const data = JSON.parse(raw);
if (data.refresh_token) return data.refresh_token;
} catch (err) {
// token.json no existe aún, caemos al valor de .env
}
return process.env.GOOGLE_OAUTH_REFRESH_TOKEN || process.env.GOOGLE_REFRESH_TOKEN || null;
}
function writeRefreshToken(refreshToken) {
fs.writeFileSync(TOKEN_FILE, JSON.stringify({
refresh_token: refreshToken,
updatedAt: new Date().toISOString()
}, null, 2));
}
function readTokenUpdatedAt() {
try {
const raw = fs.readFileSync(TOKEN_FILE, 'utf-8');
const data = JSON.parse(raw);
return data.updatedAt || null;
} catch (err) {
return null; // viene de .env, sin fecha registrada
}
}
// ------------------------------------------------------------------
// ESTADO DE SUBIDAS (activado / desactivado) - persistido en disco
// ------------------------------------------------------------------
function readUploadEnabled() {
try {
const raw = fs.readFileSync(STATUS_FILE, 'utf-8');
const data = JSON.parse(raw);
return data.enabled !== false; // por defecto true si el campo falta
} catch (err) {
// Si el archivo no existe aún, asumimos habilitado por defecto
return true;
}
}
function writeUploadEnabled(enabled) {
fs.writeFileSync(STATUS_FILE, JSON.stringify({ enabled, updatedAt: new Date().toISOString() }, null, 2));
}
// Inicializa el archivo de estado si no existe
if (!fs.existsSync(STATUS_FILE)) {
writeUploadEnabled(true);
}
// ------------------------------------------------------------------
// EXPRESS APP
// ------------------------------------------------------------------
const app = express();
app.use(cors()); // Ajustar origin en producción si se sirve desde otro dominio
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public'))); // sirve index.html
// ------------------------------------------------------------------
// MULTER (procesamiento de multipart/form-data)
// ------------------------------------------------------------------
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, TMP_DIR),
filename: (req, file, cb) => {
// Prefijo con timestamp + random para evitar colisiones de nombres
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
const ext = path.extname(file.originalname);
const safeBase = path.basename(file.originalname, ext).replace(/[^a-zA-Z0-9-_]/g, '_');
cb(null, `${safeBase}-${uniqueSuffix}${ext}`);
}
});
const MAX_FILE_SIZE_MB = 100; // límite razonable para fotos/videos de celular
const upload = multer({
storage,
limits: {
fileSize: MAX_FILE_SIZE_MB * 1024 * 1024,
files: 30 // máximo de archivos por request
},
fileFilter: (req, file, cb) => {
const allowed = /^image\/|^video\//;
if (allowed.test(file.mimetype)) {
cb(null, true);
} else {
cb(new Error('Tipo de archivo no permitido: ' + file.mimetype));
}
}
});
// ------------------------------------------------------------------
// GOOGLE DRIVE - AUTENTICACIÓN VÍA OAuth2 (cuenta personal)
// ------------------------------------------------------------------
function getOAuth2Client() {
const oauth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, OAUTH_REDIRECT_URI);
const refreshToken = readRefreshToken();
if (refreshToken) {
oauth2Client.setCredentials({ refresh_token: refreshToken });
}
return oauth2Client;
}
function getDriveClient() {
const auth = getOAuth2Client();
if (!auth.credentials || !auth.credentials.refresh_token) {
throw new Error('No hay refresh token configurado. Genera uno desde /admin.');
}
return google.drive({ version: 'v3', auth });
}
/**
* Sube un único archivo local a la carpeta de Drive configurada.
* Devuelve el objeto de respuesta de la API de Drive (id, name, webViewLink).
*/
async function uploadFileToDrive(drive, localFilePath, originalName, mimeType) {
const fileMetadata = {
name: originalName,
parents: FOLDER_ID ? [FOLDER_ID] : undefined
};
const media = {
mimeType,
body: fs.createReadStream(localFilePath)
};
const response = await drive.files.create({
resource: fileMetadata,
media,
fields: 'id, name, webViewLink'
});
return response.data;
}
/**
* Borra un archivo temporal local. No lanza si ya no existe.
*/
function cleanupLocalFile(filePath) {
fs.unlink(filePath, (err) => {
if (err && err.code !== 'ENOENT') {
console.error('No se pudo borrar el archivo temporal:', filePath, err.message);
}
});
}
// ------------------------------------------------------------------
// RUTA: POST /upload
// ------------------------------------------------------------------
app.post('/upload', (req, res) => {
// Puerta de entrada: si el admin desactivó las subidas, rechazamos antes
// de tocar disco. Devolvemos 403 con mensaje claro para el frontend.
if (!readUploadEnabled()) {
return res.status(403).json({ success: false, error: 'La subida de fotos está desactivada por el momento.' });
}
upload.array('photos', 30)(req, res, async (multerErr) => {
if (multerErr) {
console.error('Error de Multer:', multerErr.message);
return res.status(400).json({
success: false,
error: multerErr.message
});
}
const files = req.files;
if (!files || files.length === 0) {
return res.status(400).json({ success: false, error: 'No se recibieron archivos.' });
}
let drive;
try {
drive = getDriveClient();
} catch (err) {
console.error('Error autenticando con Google Drive:', err.message);
// Limpieza aunque falle la autenticación, para no dejar basura en disco
files.forEach((f) => cleanupLocalFile(f.path));
return res.status(500).json({ success: false, error: 'Error de autenticación con Google Drive.' });
}
const results = [];
const errors = [];
// Subimos archivo por archivo. Si uno falla, seguimos con los demás
// y reportamos el detalle al final (más resiliente para el usuario).
for (const file of files) {
try {
const uploaded = await uploadFileToDrive(
drive,
file.path,
file.originalname,
file.mimetype
);
results.push({ originalName: file.originalname, driveId: uploaded.id, link: uploaded.webViewLink });
} catch (err) {
console.error('Error subiendo a Drive:', file.originalname, err.message);
errors.push({ originalName: file.originalname, error: err.message });
} finally {
// Limpieza automática del archivo temporal, suba o no exitosamente
cleanupLocalFile(file.path);
}
}
if (errors.length > 0 && results.length === 0) {
// Todos fallaron
return res.status(502).json({ success: false, error: 'No se pudo subir ningún archivo a Drive.', details: errors });
}
return res.status(200).json({
success: true,
uploaded: results.length,
failed: errors.length,
results,
errors: errors.length > 0 ? errors : undefined
});
});
});
// ------------------------------------------------------------------
// RUTA DE SALUD (útil para Render/Railway/health checks)
// ------------------------------------------------------------------
app.get('/health', (req, res) => {
res.json({ status: 'ok', timestamp: new Date().toISOString() });
});
// ------------------------------------------------------------------
// RUTA PÚBLICA: GET /status
// El frontend la consulta antes de mostrar el botón de subida.
// ------------------------------------------------------------------
app.get('/status', (req, res) => {
res.json({ enabled: readUploadEnabled() });
});
// ------------------------------------------------------------------
// RUTA: GET /admin
// Sirve la vista de administración (protegida con password en el propio
// formulario/JS del frontend, ver public/admin.html).
// ------------------------------------------------------------------
app.get('/admin', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'admin.html'));
});
// ------------------------------------------------------------------
// RUTA: POST /admin/toggle
// Body: { password: string, enabled: boolean }
// ------------------------------------------------------------------
app.post('/admin/toggle', (req, res) => {
const { password, enabled } = req.body || {};
if (password !== ADMIN_PASSWORD) {
return res.status(401).json({ success: false, error: 'Contraseña incorrecta.' });
}
if (typeof enabled !== 'boolean') {
return res.status(400).json({ success: false, error: 'El campo "enabled" debe ser true o false.' });
}
writeUploadEnabled(enabled);
return res.json({ success: true, enabled });
});
// ------------------------------------------------------------------
// RUTA: POST /admin/status-check
// Permite validar la contraseña y obtener el estado actual en un solo
// paso, para pintar el toggle correctamente al cargar /admin.
// ------------------------------------------------------------------
app.post('/admin/status-check', (req, res) => {
const { password } = req.body || {};
if (password !== ADMIN_PASSWORD) {
return res.status(401).json({ success: false, error: 'Contraseña incorrecta.' });
}
return res.json({ success: true, enabled: readUploadEnabled() });
});
// ------------------------------------------------------------------
// RUTA: POST /admin/oauth/token-info
// Devuelve cuándo se generó el refresh token vigente (o null si viene
// del .env inicial y nunca se ha regenerado desde el panel).
// ------------------------------------------------------------------
app.post('/admin/oauth/token-info', (req, res) => {
const { password } = req.body || {};
if (password !== ADMIN_PASSWORD) {
return res.status(401).json({ success: false, error: 'Contraseña incorrecta.' });
}
return res.json({
success: true,
hasToken: !!readRefreshToken(),
updatedAt: readTokenUpdatedAt() // null si nunca se regeneró desde /admin
});
});
// ------------------------------------------------------------------
// RUTA: GET /admin/oauth/start
// Punto de entrada del botón "Generar nuevo token" del panel /admin.
// Valida la contraseña por query string y redirige a la pantalla de
// consentimiento de Google.
//
// Nota: la contraseña viaja en la URL (necesario porque es un redirect
// de navegador, no un fetch). Va sobre HTTPS, pero por eso este link
// no debe compartirse ni guardarse en marcadores.
// ------------------------------------------------------------------
app.get('/admin/oauth/start', (req, res) => {
const { password } = req.query;
if (password !== ADMIN_PASSWORD) {
return res.status(401).send('Contraseña incorrecta.');
}
if (!CLIENT_ID || !CLIENT_SECRET) {
return res.status(500).send('GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET no están configurados en el servidor.');
}
const oauth2Client = getOAuth2Client();
const authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline', // necesario para recibir refresh_token
prompt: 'consent', // fuerza a Google a reemitir refresh_token siempre
scope: OAUTH_SCOPES
});
return res.redirect(authUrl);
});
// ------------------------------------------------------------------
// RUTA: GET /admin/oauth/callback
// Google redirige aquí después de que el usuario autoriza. Intercambia
// el "code" por tokens y persiste el refresh_token nuevo en token.json.
// ------------------------------------------------------------------
app.get('/admin/oauth/callback', async (req, res) => {
const { code, error } = req.query;
if (error) {
return res.status(400).send(`
<body style="font-family:sans-serif;text-align:center;padding:60px 20px;">
<h2>❌ Autorización cancelada</h2>
<p>${error}</p>
<a href="/admin">Volver al panel</a>
</body>
`);
}
if (!code) {
return res.status(400).send('Falta el parámetro "code" en la respuesta de Google.');
}
try {
const oauth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, OAUTH_REDIRECT_URI);
const { tokens } = await oauth2Client.getToken(code);
if (!tokens.refresh_token) {
// Esto puede pasar si Google decide no reemitirlo pese a prompt=consent
// (raro, pero posible si la cuenta ya tenía uno activo muy reciente).
return res.status(200).send(`
<body style="font-family:sans-serif;text-align:center;padding:60px 20px;">
<h2>⚠️ Autorización correcta, pero sin refresh token nuevo</h2>
<p>Google no devolvió un refresh_token esta vez. Intenta de nuevo, o revoca el acceso previo en
<a href="https://myaccount.google.com/permissions" target="_blank">myaccount.google.com/permissions</a> y reintenta.</p>
<a href="/admin">Volver al panel</a>
</body>
`);
}
writeRefreshToken(tokens.refresh_token);
return res.status(200).send(`
<body style="font-family:sans-serif;text-align:center;padding:60px 20px;">
<h2>✅ Token de Google actualizado</h2>
<p>El servidor ya está usando el nuevo refresh token. No hace falta reiniciar nada.</p>
<a href="/admin">Volver al panel</a>
</body>
`);
} catch (err) {
console.error('Error intercambiando el code por tokens:', err.message);
return res.status(500).send(`
<body style="font-family:sans-serif;text-align:center;padding:60px 20px;">
<h2>❌ Error al generar el token</h2>
<p>${err.message}</p>
<a href="/admin">Volver al panel</a>
</body>
`);
}
});
// ------------------------------------------------------------------
// MANEJO DE ERRORES GLOBAL (fallback)
// ------------------------------------------------------------------
app.use((err, req, res, next) => {
console.error('Error no controlado:', err);
res.status(500).json({ success: false, error: 'Error interno del servidor.' });
});
// ------------------------------------------------------------------
// INICIO DEL SERVIDOR
// ------------------------------------------------------------------
app.listen(PORT, () => {
console.log(`🚀 Servidor escuchando en http://localhost:${PORT}`);
console.log(`📁 Carpeta de Drive destino: ${FOLDER_ID || '(no configurada)'}`);
});
View File