Transforme XIP en réseau social satirique complet : monnaie fictive, marketplace, cosmétiques visibles de tous, messages riches sandboxés, pubs pilotées par les données, et tous les compteurs mock rendus réels. Backend (Bun + Hono + Prisma + Redis) - Économie par IP : modèles Wallet/Purchase/Entitlement, lib/wallet.ts avec spend() atomique (point unique du paywall) + recharge gratuite. - isLocalhost() → mode gratuit (README « si localhost: pas de paywall »). - Marketplace : lib/catalog.ts (achat transactionnel, stock limité, limites par IP) + routes/shop.ts ; 10 produits seedés (idempotent). - Perks : lib/perks.ts (cache Redis busté à l'achat) ; authorPerks injecté dans les payloads messages + endpoint batch /api/perks ; frame WS « perks » global pour MAJ live des messages déjà affichés. - Messages riches : Message.richMode/richContent, gating par entitlement. - Pubs réelles : modèle Ad seedé avec les 4 pubs (ex-hardcodées), rotation par API, comptage d'impressions réel + réconciliation. - WebSocket : IP capturée par connexion → broadcastToIp / broadcast ; frames wallet/perks/ads/alert. - Pièces jointes : lib/storage.ts (UUID, jamais exécuté) + routes/uploads.ts (limite 1 Mo sauf déblocage/localhost, Content-Disposition: attachment). - Alerte audio : routes/alert.ts (cooldown serveur Redis NX, clamp durée). - Compteur « argent extorqué » réel : impressions×CPM + crédits dépensés. Frontend (Vue 3 + Vite) - /shop : ShopPage + ProductCard fidèles aux maquettes ; composables useWallet/useShop/usePerks/useAds/useAttachments/useAlert. - UI de réponse (bannière + sous-threads), solde + lien Shop dans le header. - Perks rendus : Style Doré (or), Pets autour de l'IP, NoAds masque les pubs. - RichContent.vue : iframe sandbox verrouillée (htmlcss sans script ; js allow-scripts seul, jamais allow-same-origin) + CSP. - AdBand/InlineCasinoAd pilotés par l'API ; barre de saisie avec 📎, compteur de caractères, composer riche et bouton alerte. Infra - Migration economy_ads_attachments_rich ; seed idempotent (produits+pubs). - vite.config : usePolling (HMR fiable sur /mnt/c via WSL). - backend/.gitignore : uploads/. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
200 lines
6.2 KiB
TypeScript
200 lines
6.2 KiB
TypeScript
import { ref, onMounted } from 'vue';
|
|
import { useRealtime } from './useRealtime';
|
|
import { useWallet, applyWalletFrame } from './useWallet';
|
|
import { setPerks, applyPerksFrame, type Perks } from './usePerks';
|
|
import { bumpAdsRevision } from './useAds';
|
|
import { handleAlertFrame } from './useAlert';
|
|
|
|
export interface Reply {
|
|
id: string;
|
|
content: string;
|
|
authorIp: string;
|
|
createdAt: string;
|
|
parentId?: string | null;
|
|
authorPerks?: Perks;
|
|
richMode?: 'none' | 'htmlcss' | 'js';
|
|
richContent?: string | null;
|
|
attachments?: Attachment[];
|
|
}
|
|
|
|
export interface Attachment {
|
|
id: string;
|
|
filename: string;
|
|
mimeType: string;
|
|
size: number;
|
|
}
|
|
|
|
export interface Message extends Reply {
|
|
parentId: string | null;
|
|
replies: Reply[];
|
|
}
|
|
|
|
const API_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:3000';
|
|
|
|
export function useMessages() {
|
|
const messages = ref<Message[]>([]);
|
|
const loading = ref(false);
|
|
const sending = ref(false);
|
|
|
|
/** Seed the perks store from a message + its replies. */
|
|
function harvestPerks(m: Message): void {
|
|
setPerks(m.authorIp, m.authorPerks);
|
|
for (const r of m.replies ?? []) setPerks(r.authorIp, r.authorPerks);
|
|
}
|
|
|
|
async function fetchMessages(): Promise<void> {
|
|
loading.value = true;
|
|
try {
|
|
const res = await fetch(`${API_URL}/api/messages`);
|
|
if (res.ok) {
|
|
// API returns newest→oldest; reverse for chronological display.
|
|
const list = ((await res.json()) as Message[]).reverse();
|
|
list.forEach(harvestPerks);
|
|
messages.value = list;
|
|
}
|
|
} finally {
|
|
loading.value = false;
|
|
}
|
|
}
|
|
|
|
/** Add a message pushed over the WebSocket (new thread or reply), with dedup. */
|
|
function addIncoming(raw: Message & { parentId: string | null }): void {
|
|
if (!raw || !raw.id) return;
|
|
|
|
// Always record the author's perks, even for replies.
|
|
setPerks(raw.authorIp, raw.authorPerks);
|
|
|
|
if (raw.parentId == null) {
|
|
// New top-level thread.
|
|
if (messages.value.some((m) => m.id === raw.id)) return;
|
|
messages.value.push({ ...raw, replies: raw.replies ?? [] });
|
|
return;
|
|
}
|
|
|
|
// Reply: attach to its parent thread if we have it.
|
|
const parent = messages.value.find((m) => m.id === raw.parentId);
|
|
if (!parent) return; // thread not loaded; reconnect-resync will reconcile
|
|
if (parent.replies.some((r) => r.id === raw.id)) return;
|
|
parent.replies.push({
|
|
id: raw.id,
|
|
content: raw.content,
|
|
authorIp: raw.authorIp,
|
|
createdAt: raw.createdAt,
|
|
parentId: raw.parentId,
|
|
authorPerks: raw.authorPerks,
|
|
richMode: raw.richMode,
|
|
richContent: raw.richContent,
|
|
attachments: raw.attachments,
|
|
});
|
|
}
|
|
|
|
const { fetchWallet, ip: myIp } = useWallet();
|
|
|
|
// The viewer's own perks (drives NoAds gating, rich-composer unlocks, etc.).
|
|
const myPerks = ref<Perks>({});
|
|
|
|
async function fetchMyPerks(): Promise<void> {
|
|
try {
|
|
const res = await fetch(`${API_URL}/api/shop/me`);
|
|
if (!res.ok) return;
|
|
const { entitlements } = (await res.json()) as {
|
|
entitlements: { kind: string; metaJson?: string | null }[];
|
|
};
|
|
const p: Perks = {};
|
|
const pets: { char: string; position: 'left' | 'right' | 'both' }[] = [];
|
|
for (const e of entitlements) {
|
|
let meta: any = {};
|
|
try { meta = e.metaJson ? JSON.parse(e.metaJson) : {}; } catch { /* */ }
|
|
if (e.kind === 'noads') { p.noads = true; if (meta.plan === 'annual') p.badge = true; }
|
|
if (e.kind === 'style-dore') p.skin = 'gold';
|
|
if (e.kind === 'pet' && meta.char) pets.push({ char: meta.char, position: meta.position ?? 'left' });
|
|
if (e.kind === 'element-skin') p.elementSkin = true;
|
|
if (e.kind === 'rich-htmlcss') p.richHtmlcss = true;
|
|
if (e.kind === 'rich-js') p.richJs = true;
|
|
if (e.kind === 'no-file-limit') p.noFileLimit = true;
|
|
if (e.kind === 'audio-alert') p.audioAlert = true;
|
|
}
|
|
if (pets.length) p.pets = pets.slice(0, 3);
|
|
myPerks.value = p;
|
|
if (myIp.value) setPerks(myIp.value, p);
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
}
|
|
|
|
const { stats, connected, sendTyping } = useRealtime({
|
|
onMessage: addIncoming,
|
|
onReconnect: () => {
|
|
fetchMessages();
|
|
fetchWallet();
|
|
fetchMyPerks();
|
|
},
|
|
onWallet: applyWalletFrame,
|
|
onPerks: (data: { ip: string; perks: Perks }) => {
|
|
applyPerksFrame(data);
|
|
// If it's about us, update myPerks too (viewer-scoped perks like NoAds).
|
|
if (myIp.value && data.ip === myIp.value) myPerks.value = data.perks ?? {};
|
|
},
|
|
onAds: () => bumpAdsRevision(), // a user ad entered rotation → refetch
|
|
onAlert: (data) => handleAlertFrame(data), // paid global audio alert
|
|
});
|
|
|
|
interface PostExtras {
|
|
parentId?: string;
|
|
richMode?: 'htmlcss' | 'js';
|
|
richContent?: string;
|
|
attachmentIds?: string[];
|
|
}
|
|
|
|
async function postMessage(content: string, extras: PostExtras = {}): Promise<boolean> {
|
|
const hasRich = !!extras.richContent && !!extras.richMode;
|
|
const hasFiles = !!extras.attachmentIds?.length;
|
|
// Allow empty text only when there's rich content or an attachment.
|
|
if (!content.trim() && !hasRich && !hasFiles) return false;
|
|
sending.value = true;
|
|
try {
|
|
const res = await fetch(`${API_URL}/api/messages`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
content: content.trim() || ' ',
|
|
parentId: extras.parentId,
|
|
richMode: extras.richMode,
|
|
richContent: extras.richContent,
|
|
attachmentIds: extras.attachmentIds,
|
|
}),
|
|
});
|
|
if (!res.ok) return false;
|
|
// The created message comes back via the WebSocket broadcast, so no
|
|
// re-fetch here. Fallback: if the socket is down, add it locally.
|
|
if (!connected.value) {
|
|
const created = (await res.json()) as Message;
|
|
addIncoming(
|
|
created.parentId == null ? { ...created, replies: [] } : created
|
|
);
|
|
}
|
|
return true;
|
|
} finally {
|
|
sending.value = false;
|
|
}
|
|
}
|
|
|
|
onMounted(() => {
|
|
fetchMessages();
|
|
fetchWallet();
|
|
fetchMyPerks();
|
|
});
|
|
|
|
return {
|
|
messages,
|
|
loading,
|
|
sending,
|
|
postMessage,
|
|
stats,
|
|
connected,
|
|
sendTyping,
|
|
myPerks,
|
|
fetchMyPerks,
|
|
};
|
|
}
|