mirror of
https://github.com/Dasemu/si-no-o-indiferente.git
synced 2026-11-26 23:36:25 +00:00
Add Historias Incompletas: web+APK story game with Gemini-powered daily deck
Node/Express backend generates 5 lateral-thinking mystery stories a day via Gemini and serves the latest batch; React/Vite frontend (Capacitor-wrapped for Android) plays them pass-and-play style, falling back to a bundled set of 16 original stories when the backend has nothing new or is unreachable. Includes systemd/nginx deploy config for a Docker-less Debian LXC. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
de0dfec6af
commit
7f3e6cc839
97 files changed
+6803
-1
No files matched your search
@@ -0,0 +1,18 @@
|
||||
import "dotenv/config";
|
||||
import path from "node:path";
|
||||
|
||||
function required(name: string, value: string | undefined, fallback?: string): string {
|
||||
if (value && value.length > 0) return value;
|
||||
if (fallback !== undefined) return fallback;
|
||||
throw new Error(`Falta la variable de entorno ${name}`);
|
||||
}
|
||||
|
||||
export const config = {
|
||||
port: Number(process.env.PORT ?? 8787),
|
||||
corsOrigin: process.env.CORS_ORIGIN ?? "*",
|
||||
geminiApiKey: process.env.GEMINI_API_KEY ?? "",
|
||||
geminiModel: process.env.GEMINI_MODEL ?? "gemini-2.5-flash",
|
||||
storiesPerDay: Number(process.env.STORIES_PER_DAY ?? 5),
|
||||
dataDir: path.resolve(process.cwd(), process.env.DATA_DIR ?? "./data"),
|
||||
adminToken: required("ADMIN_TOKEN", process.env.ADMIN_TOKEN, "cambia-este-token"),
|
||||
};
|
||||
@@ -0,0 +1,105 @@
|
||||
import { config } from "./config.js";
|
||||
import { GeminiStoryBatchSchema, type Story } from "./storySchema.js";
|
||||
|
||||
const GEMINI_ENDPOINT = (model: string) =>
|
||||
`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent`;
|
||||
|
||||
// Subconjunto de OpenAPI que acepta el "structured output" de Gemini.
|
||||
const RESPONSE_SCHEMA = {
|
||||
type: "OBJECT",
|
||||
properties: {
|
||||
stories: {
|
||||
type: "ARRAY",
|
||||
items: {
|
||||
type: "OBJECT",
|
||||
properties: {
|
||||
id: { type: "STRING" },
|
||||
title: { type: "STRING" },
|
||||
difficulty: { type: "STRING", enum: ["easy", "medium", "hard"] },
|
||||
tags: { type: "ARRAY", items: { type: "STRING" } },
|
||||
teaser: { type: "STRING" },
|
||||
hints: { type: "ARRAY", items: { type: "STRING" } },
|
||||
solution: { type: "STRING" },
|
||||
},
|
||||
required: ["id", "title", "difficulty", "tags", "teaser", "hints", "solution"],
|
||||
},
|
||||
},
|
||||
},
|
||||
required: ["stories"],
|
||||
};
|
||||
|
||||
function buildPrompt(count: number, avoidTitles: string[]): string {
|
||||
const avoidList = avoidTitles.length
|
||||
? `Evita repetir o parafrasear estos titulos ya usados: ${avoidTitles.join(", ")}.`
|
||||
: "";
|
||||
|
||||
return `Sos un escritor experto en acertijos narrativos de pensamiento lateral, en el estilo del juego de mesa "historias negras"/"black stories": se cuenta un enigma breve y desconcertante (el "teaser"), y los jugadores deben adivinar la explicacion completa (la "solution") haciendo preguntas de si/no.
|
||||
|
||||
Genera exactamente ${count} historias completamente ORIGINALES en español (no copies acertijos clasicos ni de ningun juego comercial existente). Cada historia debe tener:
|
||||
- id: slug corto en minusculas separado por guiones, unico, derivado del titulo.
|
||||
- title: titulo corto y evocador.
|
||||
- difficulty: "easy", "medium" o "hard", variando entre las ${count} historias.
|
||||
- tags: 1 a 3 palabras clave en minusculas.
|
||||
- teaser: 2 a 4 frases. Presenta una situacion extraña o aparentemente inexplicable, resoluble con preguntas de si/no. No debe insinuar la solucion.
|
||||
- hints: entre 3 y 4 pistas progresivas (de mas vaga a mas reveladora) que el narrador puede leer si los jugadores estan trabados, sin regalar la solucion completa en las primeras.
|
||||
- solution: la explicacion completa y coherente que resuelve el enigma, respondiendo a todo lo planteado en el teaser. 4 a 8 frases.
|
||||
|
||||
Las historias deben ser aptas para todo publico (sin violencia grafica extrema, sin contenido sexual), pueden ser misteriosas, agridulces o con un giro emotivo, pero siempre con una explicacion logica y satisfactoria. ${avoidList}
|
||||
|
||||
Devolve unicamente el JSON que respeta el schema indicado.`;
|
||||
}
|
||||
|
||||
interface GeminiResponse {
|
||||
candidates?: Array<{
|
||||
content?: { parts?: Array<{ text?: string }> };
|
||||
}>;
|
||||
}
|
||||
|
||||
export async function generateStoriesWithGemini(
|
||||
count: number,
|
||||
avoidTitles: string[] = []
|
||||
): Promise<Story[]> {
|
||||
if (!config.geminiApiKey) {
|
||||
throw new Error("GEMINI_API_KEY no esta configurada");
|
||||
}
|
||||
|
||||
const body = {
|
||||
contents: [{ parts: [{ text: buildPrompt(count, avoidTitles) }] }],
|
||||
generationConfig: {
|
||||
responseMimeType: "application/json",
|
||||
responseSchema: RESPONSE_SCHEMA,
|
||||
temperature: 1,
|
||||
},
|
||||
};
|
||||
|
||||
const res = await fetch(`${GEMINI_ENDPOINT(config.geminiModel)}?key=${config.geminiApiKey}`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errText = await res.text().catch(() => "");
|
||||
throw new Error(`Gemini API error ${res.status}: ${errText}`);
|
||||
}
|
||||
|
||||
const data = (await res.json()) as GeminiResponse;
|
||||
const text = data.candidates?.[0]?.content?.parts?.[0]?.text;
|
||||
if (!text) {
|
||||
throw new Error("Respuesta de Gemini sin contenido de texto");
|
||||
}
|
||||
|
||||
const parsedJson = JSON.parse(text);
|
||||
const validated = GeminiStoryBatchSchema.parse(parsedJson);
|
||||
|
||||
// Aseguramos ids unicos por si el modelo repite alguno.
|
||||
const seen = new Set<string>();
|
||||
for (const story of validated.stories) {
|
||||
let id = story.id;
|
||||
while (seen.has(id)) id = `${id}-2`;
|
||||
seen.add(id);
|
||||
story.id = id;
|
||||
}
|
||||
|
||||
return validated.stories.slice(0, count);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import cors from "cors";
|
||||
import express from "express";
|
||||
import { config } from "./config.js";
|
||||
import { storiesRouter } from "./routes/stories.js";
|
||||
|
||||
const app = express();
|
||||
|
||||
app.use(cors({ origin: config.corsOrigin }));
|
||||
app.use(express.json());
|
||||
|
||||
app.get("/api/health", (_req, res) => {
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.use("/api", storiesRouter);
|
||||
|
||||
app.listen(config.port, () => {
|
||||
console.log(`API de historias escuchando en http://localhost:${config.port}`);
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Router } from "express";
|
||||
import { config } from "../config.js";
|
||||
import { generateStoriesWithGemini } from "../gemini.js";
|
||||
import { getLatestStories, saveDailyStories } from "../storyStore.js";
|
||||
|
||||
export const storiesRouter = Router();
|
||||
|
||||
/** GET /api/stories: devuelve el ultimo lote generado, o 204 si no hay ninguno todavia. */
|
||||
storiesRouter.get("/stories", async (_req, res) => {
|
||||
const latest = await getLatestStories();
|
||||
if (!latest) {
|
||||
res.status(204).end();
|
||||
return;
|
||||
}
|
||||
res.set("Cache-Control", "public, max-age=300");
|
||||
res.json(latest);
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/admin/generate: dispara manualmente una generacion con Gemini.
|
||||
* Requiere header "x-admin-token" que coincida con ADMIN_TOKEN.
|
||||
* Pensado para pruebas manuales; la generacion diaria real la dispara el
|
||||
* systemd timer llamando al script generateDaily.
|
||||
*/
|
||||
storiesRouter.post("/admin/generate", async (req, res) => {
|
||||
const token = req.header("x-admin-token");
|
||||
if (!token || token !== config.adminToken) {
|
||||
res.status(401).json({ error: "token invalido" });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const previous = await getLatestStories();
|
||||
const avoidTitles = previous?.stories.map((s) => s.title) ?? [];
|
||||
const stories = await generateStoriesWithGemini(config.storiesPerDay, avoidTitles);
|
||||
const saved = await saveDailyStories(stories);
|
||||
res.json(saved);
|
||||
} catch (err) {
|
||||
console.error("Error generando historias:", err);
|
||||
res.status(500).json({ error: "fallo la generacion", detail: String(err) });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Script pensado para correr una vez al dia via systemd timer / cron.
|
||||
* Genera STORIES_PER_DAY historias nuevas con Gemini y las guarda como el
|
||||
* nuevo "latest.json" que sirve la API.
|
||||
*
|
||||
* Uso: npm run generate (dev, con tsx)
|
||||
* npm run generate:built (prod, tras "npm run build")
|
||||
*/
|
||||
import { config } from "../config.js";
|
||||
import { generateStoriesWithGemini } from "../gemini.js";
|
||||
import { getLatestStories, saveDailyStories } from "../storyStore.js";
|
||||
|
||||
async function main() {
|
||||
console.log(`[${new Date().toISOString()}] Generando ${config.storiesPerDay} historias nuevas con ${config.geminiModel}...`);
|
||||
|
||||
const previous = await getLatestStories();
|
||||
const avoidTitles = previous?.stories.map((s) => s.title) ?? [];
|
||||
|
||||
const stories = await generateStoriesWithGemini(config.storiesPerDay, avoidTitles);
|
||||
const saved = await saveDailyStories(stories);
|
||||
|
||||
console.log(`[${new Date().toISOString()}] OK: ${saved.stories.length} historias guardadas.`);
|
||||
for (const s of saved.stories) console.log(` - (${s.difficulty}) ${s.title}`);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("Fallo la generacion diaria:", err);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const DifficultySchema = z.enum(["easy", "medium", "hard"]);
|
||||
|
||||
export const StorySchema = z.object({
|
||||
id: z.string().min(1),
|
||||
title: z.string().min(1),
|
||||
difficulty: DifficultySchema,
|
||||
tags: z.array(z.string()).default([]),
|
||||
teaser: z.string().min(1),
|
||||
hints: z.array(z.string()).min(1).max(5),
|
||||
solution: z.string().min(1),
|
||||
});
|
||||
export type Story = z.infer<typeof StorySchema>;
|
||||
|
||||
export const StoryListSchema = z.object({
|
||||
version: z.number().int().nonnegative(),
|
||||
generatedAt: z.string().nullable(),
|
||||
source: z.enum(["default", "gemini"]),
|
||||
stories: z.array(StorySchema),
|
||||
});
|
||||
export type StoryList = z.infer<typeof StoryListSchema>;
|
||||
|
||||
// Esquema que le pedimos a Gemini que respete (sin el wrapper de version/source).
|
||||
export const GeminiStoryBatchSchema = z.object({
|
||||
stories: z.array(StorySchema).min(1),
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { config } from "./config.js";
|
||||
import { StoryListSchema, type Story, type StoryList } from "./storySchema.js";
|
||||
|
||||
const LATEST_FILE = "latest.json";
|
||||
|
||||
async function ensureDataDir(): Promise<void> {
|
||||
await fs.mkdir(config.dataDir, { recursive: true });
|
||||
}
|
||||
|
||||
function dailyFileName(date: Date): string {
|
||||
const iso = date.toISOString().slice(0, 10); // YYYY-MM-DD
|
||||
return `${iso}.json`;
|
||||
}
|
||||
|
||||
/** Escritura atomica: escribe a un archivo temporal y luego renombra. */
|
||||
async function writeJsonAtomic(filePath: string, data: unknown): Promise<void> {
|
||||
const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
|
||||
await fs.writeFile(tmpPath, JSON.stringify(data, null, 2), "utf8");
|
||||
await fs.rename(tmpPath, filePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Guarda un nuevo lote de historias generado hoy, tanto en un archivo fechado
|
||||
* (historial) como en latest.json (lo que sirve la API).
|
||||
*/
|
||||
export async function saveDailyStories(stories: Story[]): Promise<StoryList> {
|
||||
await ensureDataDir();
|
||||
const list: StoryList = {
|
||||
version: Date.now(),
|
||||
generatedAt: new Date().toISOString(),
|
||||
source: "gemini",
|
||||
stories,
|
||||
};
|
||||
StoryListSchema.parse(list);
|
||||
|
||||
const dailyPath = path.join(config.dataDir, dailyFileName(new Date()));
|
||||
const latestPath = path.join(config.dataDir, LATEST_FILE);
|
||||
|
||||
await writeJsonAtomic(dailyPath, list);
|
||||
await writeJsonAtomic(latestPath, list);
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Devuelve el ultimo lote de historias generado (puede ser de un dia anterior
|
||||
* si la generacion de hoy todavia no corrio o fallo). Si nunca se genero
|
||||
* nada, devuelve null y el cliente debe usar su set default embebido.
|
||||
*/
|
||||
export async function getLatestStories(): Promise<StoryList | null> {
|
||||
const latestPath = path.join(config.dataDir, LATEST_FILE);
|
||||
try {
|
||||
const raw = await fs.readFile(latestPath, "utf8");
|
||||
const parsed = StoryListSchema.parse(JSON.parse(raw));
|
||||
return parsed;
|
||||
} catch (err: unknown) {
|
||||
if (isNodeError(err) && err.code === "ENOENT") return null;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function isNodeError(err: unknown): err is NodeJS.ErrnoException {
|
||||
return typeof err === "object" && err !== null && "code" in err;
|
||||
}
|
||||
Reference in new issue
Block a user