Files
Solus/src/index.js
T

278 lines
14 KiB
JavaScript

import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { init, uid, getChars, safeJson, getState, setState } from './store.js';
import { SEED_CHARACTERS, personaSystemPrompt, pickDailyChar, seedCharacters } from './personas.js';
import { chatText, genImage, hasKey } from './ai.js';
import { reactToUserPost, charactersEngageEachOther, charsReplyToUserComment, genCharPost, sendProactiveDM } from './engagement.js';
const app = new Hono();
// Enable CORS so external web clients, Capacitor or native APKs can access the API
app.use('*', cors());
app.use('*', async (c, next) => {
await init(c.env);
await next();
});
const USER = { id: 'user', name: 'Du', handle: 'du' };
function charBrief(c) {
return { id: c.id, name: c.name, handle: c.handle, avatarKey: c.avatar_key };
}
async function authorOf(env, post) {
if (post.author_type === 'user') return { ...USER, avatarKey: null };
const c = await env.DB.prepare('SELECT * FROM characters WHERE id = ?').bind(post.author_id).first();
return c ? charBrief(c) : { id: 'unknown', name: '?', handle: '?', avatarKey: null };
}
// ---------- FEED ----------
app.get('/api/feed', async (c) => {
const env = c.env;
const posts = await env.DB.prepare('SELECT * FROM posts ORDER BY created_at DESC LIMIT 100').all();
const out = [];
for (const p of posts.results) {
const author = await authorOf(env, p);
const comments = await env.DB.prepare('SELECT * FROM comments WHERE post_id = ? ORDER BY created_at ASC').bind(p.id).all();
const commentAuthors = {};
const commentList = [];
for (const cm of comments.results) {
if (!commentAuthors[cm.author_id]) commentAuthors[cm.author_id] = await authorOf(env, cm);
commentList.push({ id: cm.id, text: cm.text, createdAt: cm.created_at, author: commentAuthors[cm.author_id] });
}
const likes = await env.DB.prepare('SELECT COUNT(*) AS n FROM likes WHERE post_id = ?').bind(p.id).first();
const myLike = await env.DB.prepare("SELECT 1 AS x FROM likes WHERE post_id = ? AND liker_type = 'user'").bind(p.id).first();
out.push({
id: p.id, text: p.text, imageKey: p.image_key, createdAt: p.created_at, author,
comments: commentList, likes: likes?.n || 0, likedByMe: Boolean(myLike),
});
}
return c.json({ posts: out, aiEnabled: hasKey(env) });
});
// ---------- NEW POST ----------
app.post('/api/posts', async (c) => {
const { text, generateImage } = await c.req.json();
if (!text || typeof text !== 'string' || !text.trim()) return c.json({ error: 'Leerer Post' }, 400);
let imageKey = null;
if (generateImage && hasKey(c.env)) {
try { imageKey = await genImage(c.env, text, '1:1'); } catch (e) { console.error(e); }
}
const post = { id: uid(), author_type: 'user', author_id: 'user', text: text.trim().slice(0, 2000), image_key: imageKey, created_at: Date.now() };
await c.env.DB.prepare('INSERT INTO posts (id, author_type, author_id, text, image_key, created_at) VALUES (?, ?, ?, ?, ?, ?)')
.bind(post.id, post.author_type, post.author_id, post.text, post.image_key, post.created_at).run();
// background engagement
const chars = await getChars(c.env);
c.executionCtx.waitUntil(reactToUserPost(c.env, post, chars));
return c.json({ ok: true, id: post.id, imageKey });
});
// ---------- DELETE POST ----------
app.delete('/api/posts/:id', async (c) => {
const id = c.req.param('id');
const post = await c.env.DB.prepare("SELECT * FROM posts WHERE id = ? AND author_type = 'user'").bind(id).first();
if (!post) return c.json({ error: 'Post nicht gefunden oder keine Berechtigung' }, 404);
await c.env.DB.prepare('DELETE FROM posts WHERE id = ?').bind(id).run();
await c.env.DB.prepare('DELETE FROM comments WHERE post_id = ?').bind(id).run();
await c.env.DB.prepare('DELETE FROM likes WHERE post_id = ?').bind(id).run();
return c.json({ ok: true });
});
// ---------- LIKE ----------
app.post('/api/posts/:id/like', async (c) => {
const id = c.req.param('id');
const ex = await c.env.DB.prepare("SELECT 1 FROM likes WHERE post_id = ? AND liker_type = 'user'").bind(id).first();
if (ex) {
await c.env.DB.prepare("DELETE FROM likes WHERE post_id = ? AND liker_type = 'user'").bind(id).run();
} else {
await c.env.DB.prepare("INSERT OR IGNORE INTO likes (post_id, liker_type, liker_id, created_at) VALUES (?, 'user', 'user', ?)").bind(id, Date.now()).run();
}
return c.json({ ok: true, liked: !ex });
});
// ---------- COMMENT ----------
app.post('/api/posts/:id/comments', async (c) => {
const id = c.req.param('id');
const { text } = await c.req.json();
if (!text || !text.trim()) return c.json({ error: 'Leerer Kommentar' }, 400);
const post = await c.env.DB.prepare('SELECT * FROM posts WHERE id = ?').bind(id).first();
if (!post) return c.json({ error: 'Post nicht gefunden' }, 404);
const comment = { id: uid(), post_id: id, author_type: 'user', author_id: 'user', text: text.trim().slice(0, 1000), created_at: Date.now() };
await c.env.DB.prepare('INSERT INTO comments (id, post_id, author_type, author_id, text, created_at) VALUES (?, ?, ?, ?, ?, ?)')
.bind(comment.id, comment.post_id, comment.author_type, comment.author_id, comment.text, comment.created_at).run();
const chars = await getChars(c.env);
c.executionCtx.waitUntil(charsReplyToUserComment(c.env, comment, post, chars));
return c.json({ ok: true });
});
// ---------- CHARACTERS ----------
app.get('/api/characters', async (c) => {
const chars = await getChars(c.env);
const out = [];
for (const ch of chars) {
const n = await c.env.DB.prepare('SELECT COUNT(*) AS n FROM posts WHERE author_id = ?').bind(ch.id).first();
out.push({ ...charBrief(ch), bio: ch.bio, hobbies: ch.hobbies, language: ch.language, isCustom: ch.is_custom === 1, postCount: n?.n || 0 });
}
return c.json({ characters: out });
});
app.post('/api/characters', async (c) => {
const { name, bio, hobbies, personality, language } = await c.req.json();
if (!name || !name.trim()) return c.json({ error: 'Name fehlt' }, 400);
const handle = name.toLowerCase().replace(/[^a-z0-9]/g, '').slice(0, 12) + '.' + Math.floor(Math.random() * 90 + 10);
let avatarKey = null;
if (hasKey(c.env)) {
try { avatarKey = await genImage(c.env, `friendly social media profile avatar portrait of a person, ${name}. ${bio || ''}`, '1:1'); } catch (e) { console.error(e); }
}
const id = uid();
await c.env.DB.prepare('INSERT INTO characters (id, name, handle, bio, hobbies, personality, language, avatar_key, created_at, is_custom) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)')
.bind(id, name.trim().slice(0, 40), handle, (bio || '').slice(0, 500), JSON.stringify(Array.isArray(hobbies) ? hobbies : []), (personality || '').slice(0, 500), language === 'en' ? 'en' : 'de', avatarKey, Date.now()).run();
return c.json({ ok: true, id });
});
app.get('/api/characters/:id', async (c) => {
const ch = await c.env.DB.prepare('SELECT * FROM characters WHERE id = ?').bind(c.req.param('id')).first();
if (!ch) return c.json({ error: 'Nicht gefunden' }, 404);
const posts = await c.env.DB.prepare('SELECT * FROM posts WHERE author_id = ? ORDER BY created_at DESC LIMIT 50').bind(ch.id).all();
return c.json({
character: { ...charBrief(ch), bio: ch.bio, hobbies: safeJson(ch.hobbies, []), personality: ch.personality, language: ch.language, isCustom: ch.is_custom === 1 },
posts: posts.results.map((p) => ({ id: p.id, text: p.text, imageKey: p.image_key, createdAt: p.created_at })),
});
});
// ---------- DAILY CHARACTER ----------
app.post('/api/daily-character', async (c) => {
const today = new Date().toISOString().slice(0, 10);
const last = await getState(c.env, 'last_daily_char');
if (last === today) return c.json({ created: false });
const spec = pickDailyChar();
const id = uid();
let avatarKey = spec.avatar;
if (hasKey(c.env)) {
try {
const generated = await genImage(c.env, `social media profile avatar of: ${spec.name}, ${spec.bio}, cartoon style`, '1:1');
if (generated) avatarKey = generated;
} catch (e) { console.error(e); }
}
await c.env.DB.prepare('INSERT INTO characters (id, name, handle, bio, hobbies, personality, language, avatar_key, created_at, is_custom) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0)')
.bind(id, spec.name, spec.handle, spec.bio, JSON.stringify(spec.hobbies), spec.personality, spec.language, avatarKey, Date.now()).run();
await setState(c.env, 'last_daily_char', today);
// give them an initial post + comment somewhere
c.executionCtx.waitUntil((async () => {
try {
const char = await c.env.DB.prepare('SELECT * FROM characters WHERE id = ?').bind(id).first();
const post = await genCharPost(c.env, { ...char, hobbies: safeJson(char.hobbies, []) });
const chars = await getChars(c.env);
await charactersEngageEachOther(c.env, post, char, chars);
} catch (e) { console.error(e); }
})());
return c.json({ created: true, name: spec.name });
});
// ---------- FEED REFRESH: generate occasional character posts ----------
app.post('/api/feed-tick', async (c) => {
const env = c.env;
const lastTick = Number(await getState(env, 'last_feed_tick', '0'));
const now = Date.now();
if (now - lastTick < 1000 * 60 * 20) return c.json({ generated: false }); // max ~3 posts/hour
await setState(env, 'last_feed_tick', String(now));
const chars = await getChars(env);
if (!chars.length) return c.json({ generated: false });
const n = 1 + Math.floor(Math.random() * 2);
c.executionCtx.waitUntil((async () => {
for (let i = 0; i < n; i++) {
try {
const char = chars[Math.floor(Math.random() * chars.length)];
const post = await genCharPost(env, char);
await charactersEngageEachOther(env, post, char, chars);
} catch (e) { console.error(e); }
}
// ~30% chance for an active character to slide into user's DMs during a tick
if (Math.random() < 0.35) {
const activeChar = chars[Math.floor(Math.random() * chars.length)];
await sendProactiveDM(env, activeChar, 'Du bist gerade online und siehst, dass der Nutzer auch da ist. Schreib ihm eine kurze lockere Nachricht (1-2 Sätze), wie es ihm geht oder was er treibt.');
}
})());
return c.json({ generated: true });
});
// ---------- DM CHAT ----------
app.get('/api/chats', async (c) => {
const chars = await getChars(c.env);
const chats = [];
for (const ch of chars) {
const last = await c.env.DB.prepare('SELECT * FROM messages WHERE char_id = ? ORDER BY created_at DESC LIMIT 1').bind(ch.id).first();
const count = await c.env.DB.prepare('SELECT COUNT(*) AS n FROM messages WHERE char_id = ?').bind(ch.id).first();
const isUnread = last && last.sender === 'char';
chats.push({
char: charBrief(ch),
lastMessage: last ? { text: last.text, sender: last.sender, createdAt: last.created_at } : null,
count: count?.n || 0,
isUnread: Boolean(isUnread),
});
}
chats.sort((a, b) => (b.lastMessage?.createdAt || 0) - (a.lastMessage?.createdAt || 0));
const totalUnread = chats.filter((ch) => ch.isUnread).length;
return c.json({ chats, unreadCount: totalUnread });
});
app.get('/api/chats/:id', async (c) => {
const ch = await c.env.DB.prepare('SELECT * FROM characters WHERE id = ?').bind(c.req.param('id')).first();
if (!ch) return c.json({ error: 'Nicht gefunden' }, 404);
const msgs = await c.env.DB.prepare('SELECT * FROM messages WHERE char_id = ? ORDER BY created_at ASC LIMIT 200').bind(ch.id).all();
const posts = await c.env.DB.prepare('SELECT text, created_at FROM posts WHERE author_id = ? ORDER BY created_at DESC LIMIT 3').bind(ch.id).all();
return c.json({
character: { ...charBrief(ch), bio: ch.bio, hobbies: safeJson(ch.hobbies, []), language: ch.language },
messages: msgs.results.map((m) => ({ id: m.id, sender: m.sender, text: m.text, createdAt: m.created_at })),
recentActivity: posts.results,
});
});
app.post('/api/chats/:id/messages', async (c) => {
const raw = await c.env.DB.prepare('SELECT * FROM characters WHERE id = ?').bind(c.req.param('id')).first();
if (!raw) return c.json({ error: 'Nicht gefunden' }, 404);
const ch = { ...raw, hobbies: safeJson(raw.hobbies, []) };
const { text } = await c.req.json();
if (!text || !text.trim()) return c.json({ error: 'Leere Nachricht' }, 400);
const clean = text.trim().slice(0, 2000);
await c.env.DB.prepare('INSERT INTO messages (id, char_id, sender, text, created_at) VALUES (?, ?, ?, ?, ?)')
.bind(uid(), ch.id, 'user', clean, Date.now()).run();
// build context: persona + own recent activity + last 20 messages
const history = await c.env.DB.prepare('SELECT * FROM messages WHERE char_id = ? ORDER BY created_at DESC LIMIT 20').bind(ch.id).all();
const conv = history.results.reverse().map((m) => ({ role: m.sender === 'user' ? 'user' : 'assistant', content: m.text }));
const activity = await c.env.DB.prepare('SELECT text FROM posts WHERE author_id = ? ORDER BY created_at DESC LIMIT 3').bind(ch.id).all();
const actTxt = activity.results.length ? `\nDeine letzten Posts (Kontext fürs Gespräch): ${activity.results.map((p) => `"${p.text.slice(0, 80)}"`).join('; ')}` : '';
let reply;
try {
reply = await chatText(c.env, [
{ role: 'system', content: personaSystemPrompt(ch, 'Ihr schreibt gerade DMs.' + actTxt) },
...conv,
], { maxTokens: 250 });
} catch (e) {
console.error(e);
return c.json({ error: 'KI-Fehler' }, 502);
}
await c.env.DB.prepare('INSERT INTO messages (id, char_id, sender, text, created_at) VALUES (?, ?, ?, ?, ?)')
.bind(uid(), ch.id, 'char', reply, Date.now() + 1).run();
return c.json({ ok: true, reply });
});
// ---------- IMAGES (from R2) ----------
app.get('/img/:key', async (c) => {
const key = c.req.param('key');
const obj = await c.env.IMAGES.get(key.includes('/') ? key : `img/${key}`);
if (!obj) return c.notFound();
return new Response(obj.body, { headers: { 'Content-Type': obj.httpMetadata?.contentType || 'image/jpeg', 'Cache-Control': 'public, max-age=31536000, immutable' } });
});
// ---------- STATUS ----------
app.get('/api/status', (c) => c.json({ aiEnabled: hasKey(c.env), seed: SEED_CHARACTERS.length }));
app.notFound((c) => {
if (c.req.path.startsWith('/api/')) return c.json({ error: 'Not found' }, 404);
return c.env.ASSETS.fetch(c.req.raw);
});
export default { fetch: app.fetch, scheduled: async () => {} };