mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
feat: open graph embed image generation
This commit is contained in:
@@ -0,0 +1,114 @@
|
||||
<script lang="ts">
|
||||
import CalendarDays from '@lucide/svelte/icons/calendar-days';
|
||||
import CalendarOff from '@lucide/svelte/icons/calendar-off';
|
||||
import Code from '@lucide/svelte/icons/code';
|
||||
import Eye from '@lucide/svelte/icons/eye';
|
||||
import EyeOff from '@lucide/svelte/icons/eye-off';
|
||||
import FileBox from '@lucide/svelte/icons/file-box';
|
||||
import Globe from '@lucide/svelte/icons/globe';
|
||||
import Lock from '@lucide/svelte/icons/lock';
|
||||
import User from '@lucide/svelte/icons/user';
|
||||
import type { PasteEmbedProps } from './pasteEmbed';
|
||||
|
||||
export let title: PasteEmbedProps['title'];
|
||||
export let uploader: PasteEmbedProps['uploader'];
|
||||
export let metadata: PasteEmbedProps['metadata'];
|
||||
export let previewLines: PasteEmbedProps['previewLines'];
|
||||
export let isEncrypted: PasteEmbedProps['isEncrypted'];
|
||||
|
||||
const metadataIcons = {
|
||||
size: FileBox,
|
||||
views: Eye,
|
||||
created: CalendarDays,
|
||||
expires: CalendarOff,
|
||||
syntax: Code,
|
||||
'visibility-0': Globe,
|
||||
'visibility-1': EyeOff,
|
||||
'visibility-2': Lock
|
||||
} as const;
|
||||
</script>
|
||||
|
||||
<!--
|
||||
the following tailwindcss styles fail to parse, so they are applied inline:
|
||||
neutral-950
|
||||
gap-1.5
|
||||
truncate
|
||||
whitespace-nowrap
|
||||
gap-2
|
||||
gap-x-6.5
|
||||
gap-y-3
|
||||
gap-0.75
|
||||
gap-3
|
||||
whitespace-pre
|
||||
-->
|
||||
<!-- 630px by 1200px -->
|
||||
<div class="flex h-157.5 w-300 p-6" style="font-family:'Inter'; background-color: #0a0a0a;">
|
||||
<div
|
||||
class="flex h-full w-full flex-col rounded-lg border-2 border-neutral-800 bg-neutral-900 p-4"
|
||||
>
|
||||
<div class="mb-3.5 flex flex-col items-center justify-center" style="gap: 6px;">
|
||||
<div
|
||||
class="max-w-250 text-[54px] leading-[1.1] font-bold text-white"
|
||||
style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"
|
||||
>
|
||||
{title}
|
||||
</div>
|
||||
<div class="flex items-center text-[20px] text-neutral-400" style="gap: 8px;">
|
||||
<User class="h-4.5 w-4.5 text-neutral-400" />
|
||||
<div>{uploader}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-3 flex flex-wrap items-center justify-center" style="gap: 12px;">
|
||||
{#each metadata as item (item.value)}
|
||||
{@const Icon = metadataIcons[item.icon]}
|
||||
<div class="flex items-center text-[24px] leading-none text-neutral-400">
|
||||
<Icon class="mr-2 h-5.5 w-5.5 text-neutral-400" />
|
||||
<div class="text-[24px] text-neutral-400">{item.value}</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{#if isEncrypted}
|
||||
<div
|
||||
class="flex flex-1 items-center justify-center overflow-hidden rounded-lg bg-neutral-800"
|
||||
>
|
||||
<div class="flex flex-col items-center justify-center gap-3.5 p-6">
|
||||
<Lock class="h-16 w-16 text-neutral-400" />
|
||||
<div class="text-[36px] leading-[1.1] font-bold text-neutral-100">Encrypted Paste</div>
|
||||
<div class="max-w-195 text-center text-[20px] leading-[1.3] text-neutral-400">
|
||||
Preview is hidden for private encrypted pastes. Open the paste page and decrypt with the
|
||||
password to view content.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="relative flex flex-1 overflow-hidden rounded-lg bg-neutral-800">
|
||||
<div class="flex w-full flex-col pt-3" style="gap: 3px;">
|
||||
{#each previewLines as line, index (index)}
|
||||
<!-- emulates whitespace for indentation since satori doesnt seem to render it properly -->
|
||||
{@const leadingSpaceCount = line.length - line.trimStart().length}
|
||||
{@const contentWithoutIndent = line.trimStart()}
|
||||
<div class="flex items-center px-3.5" style="gap: 12px;">
|
||||
<div
|
||||
class="w-7.5 text-right text-[20px] text-neutral-500"
|
||||
style="font-family:'JetBrains Mono'; white-space: pre;"
|
||||
>
|
||||
{String(index + 1).padStart(3, ' ')}
|
||||
</div>
|
||||
<div
|
||||
class="flex items-center text-[20px] text-neutral-100"
|
||||
style="font-family:'JetBrains Mono'; white-space: pre;"
|
||||
>
|
||||
<div style={`width: ${leadingSpaceCount * 12}px;`}></div>
|
||||
<div>{contentWithoutIndent}</div>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<div
|
||||
class="absolute right-0 bottom-0 left-0"
|
||||
style="height: 58px; background: linear-gradient(to bottom, rgba(38, 38, 38, 0), rgba(38, 38, 38, 1));"
|
||||
></div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,202 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
|
||||
const CACHE_DIR = '.cache/og-images';
|
||||
const CACHE_DB_PATH = join(CACHE_DIR, 'index.db');
|
||||
const CACHE_EXPIRY_MS = 24 * 60 * 60 * 1000;
|
||||
const CACHE_CLEAN_INTERVAL_MS = 60 * 60 * 1000;
|
||||
const CACHE_STALE_WHILE_REVALIDATE_SECONDS = 300;
|
||||
const PURGE_BATCH_SIZE = 200;
|
||||
|
||||
type CacheRow = {
|
||||
relativePath: string;
|
||||
pasteExpiresAt: number | null;
|
||||
cacheExpiresAt: number;
|
||||
};
|
||||
|
||||
type ExpiredCacheRow = {
|
||||
pasteId: string;
|
||||
relativePath: string;
|
||||
};
|
||||
|
||||
export type CachedOgImage = {
|
||||
jpg: Buffer;
|
||||
ttlSeconds: number;
|
||||
};
|
||||
|
||||
export type StoreCachedOgImageInput = {
|
||||
id: string;
|
||||
jpg: Buffer;
|
||||
pasteExpiresAt?: number | null;
|
||||
};
|
||||
|
||||
let database: DatabaseSync | null = null;
|
||||
let lastPurgeAt = 0;
|
||||
let purgeInFlight: Promise<void> | null = null;
|
||||
|
||||
function getDatabase(): DatabaseSync {
|
||||
if (database) return database;
|
||||
|
||||
mkdirSync(CACHE_DIR, { recursive: true });
|
||||
const nextDatabase = new DatabaseSync(CACHE_DB_PATH);
|
||||
nextDatabase.exec('PRAGMA journal_mode = WAL');
|
||||
nextDatabase.exec('PRAGMA synchronous = NORMAL');
|
||||
nextDatabase.exec(`
|
||||
CREATE TABLE IF NOT EXISTS og_image_cache (
|
||||
paste_id TEXT PRIMARY KEY,
|
||||
relative_path TEXT NOT NULL,
|
||||
paste_expires_at INTEGER,
|
||||
cache_expires_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_og_image_cache_cache_expires_at
|
||||
ON og_image_cache (cache_expires_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_og_image_cache_paste_expires_at
|
||||
ON og_image_cache (paste_expires_at);
|
||||
`);
|
||||
database = nextDatabase;
|
||||
return nextDatabase;
|
||||
}
|
||||
|
||||
function getCacheTtlExpiry(pasteExpiresAt?: number | null): number {
|
||||
const cacheExpiresAt = Date.now() + CACHE_EXPIRY_MS;
|
||||
if (!pasteExpiresAt) return cacheExpiresAt;
|
||||
return Math.min(cacheExpiresAt, pasteExpiresAt);
|
||||
}
|
||||
|
||||
export function getCacheTtlSeconds(expiresAt?: number | null): number {
|
||||
if (!expiresAt) return CACHE_EXPIRY_MS / 1000;
|
||||
const secondsUntilExpiry = Math.floor((expiresAt - Date.now()) / 1000);
|
||||
if (secondsUntilExpiry <= 0) return 0;
|
||||
return Math.min(secondsUntilExpiry, CACHE_EXPIRY_MS / 1000);
|
||||
}
|
||||
|
||||
export function getCacheControlHeader(ttlSeconds: number): string {
|
||||
return ttlSeconds > 0
|
||||
? `private, max-age=${ttlSeconds}, stale-while-revalidate=${CACHE_STALE_WHILE_REVALIDATE_SECONDS}`
|
||||
: 'no-store, max-age=0';
|
||||
}
|
||||
|
||||
function getShardRelativePath(id: string): string {
|
||||
const hash = createHash('sha256').update(id).digest('hex');
|
||||
return join(hash.slice(0, 2), hash.slice(2, 4), `${id}.jpg`);
|
||||
}
|
||||
|
||||
function getAbsolutePath(relativePath: string): string {
|
||||
return join(CACHE_DIR, relativePath);
|
||||
}
|
||||
|
||||
async function deleteCacheFile(relativePath: string): Promise<void> {
|
||||
await unlink(getAbsolutePath(relativePath)).catch(() => undefined);
|
||||
}
|
||||
|
||||
async function deleteCacheEntry(id: string, relativePath?: string): Promise<void> {
|
||||
const db = getDatabase();
|
||||
const resolvedPath =
|
||||
relativePath ??
|
||||
((db
|
||||
.prepare('SELECT relative_path AS relativePath FROM og_image_cache WHERE paste_id = ?')
|
||||
.get(id) as { relativePath: string } | undefined)?.relativePath ?? null);
|
||||
|
||||
db.prepare('DELETE FROM og_image_cache WHERE paste_id = ?').run(id);
|
||||
if (resolvedPath) {
|
||||
await deleteCacheFile(resolvedPath);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getCachedOgImage(id: string): Promise<CachedOgImage | null> {
|
||||
const db = getDatabase();
|
||||
const row = db
|
||||
.prepare(
|
||||
'SELECT relative_path AS relativePath, paste_expires_at AS pasteExpiresAt, cache_expires_at AS cacheExpiresAt FROM og_image_cache WHERE paste_id = ?'
|
||||
)
|
||||
.get(id) as CacheRow | undefined;
|
||||
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const ttlSeconds = getCacheTtlSeconds(row.cacheExpiresAt);
|
||||
if (ttlSeconds <= 0) {
|
||||
await deleteCacheEntry(id, row.relativePath);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (typeof row.pasteExpiresAt === 'number' && row.pasteExpiresAt <= Date.now()) {
|
||||
await deleteCacheEntry(id, row.relativePath);
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const jpg = await readFile(getAbsolutePath(row.relativePath));
|
||||
return { jpg, ttlSeconds };
|
||||
} catch {
|
||||
await deleteCacheEntry(id, row.relativePath);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function storeCachedOgImage({
|
||||
id,
|
||||
jpg,
|
||||
pasteExpiresAt
|
||||
}: StoreCachedOgImageInput): Promise<void> {
|
||||
const db = getDatabase();
|
||||
const relativePath = getShardRelativePath(id);
|
||||
const absolutePath = getAbsolutePath(relativePath);
|
||||
const tempPath = `${absolutePath}.tmp-${process.pid}-${Date.now()}`;
|
||||
await mkdir(dirname(absolutePath), { recursive: true });
|
||||
await writeFile(tempPath, jpg);
|
||||
await rename(tempPath, absolutePath);
|
||||
|
||||
try {
|
||||
db.prepare(
|
||||
`INSERT INTO og_image_cache (paste_id, relative_path, paste_expires_at, cache_expires_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(paste_id) DO UPDATE SET
|
||||
relative_path = excluded.relative_path,
|
||||
paste_expires_at = excluded.paste_expires_at,
|
||||
cache_expires_at = excluded.cache_expires_at`
|
||||
).run(id, relativePath, pasteExpiresAt ?? null, getCacheTtlExpiry(pasteExpiresAt));
|
||||
} catch (error) {
|
||||
await unlink(absolutePath).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function purgeExpiredCache(limit: number = PURGE_BATCH_SIZE): Promise<void> {
|
||||
const db = getDatabase();
|
||||
const now = Date.now();
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT paste_id AS pasteId, relative_path AS relativePath
|
||||
FROM og_image_cache
|
||||
WHERE cache_expires_at <= ?
|
||||
OR (paste_expires_at IS NOT NULL AND paste_expires_at <= ?)
|
||||
LIMIT ?`
|
||||
)
|
||||
.all(now, now, limit) as ExpiredCacheRow[];
|
||||
|
||||
if (rows.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const row of rows) {
|
||||
await deleteCacheFile(row.relativePath);
|
||||
db.prepare('DELETE FROM og_image_cache WHERE paste_id = ?').run(row.pasteId);
|
||||
}
|
||||
}
|
||||
|
||||
export function scheduleOgImageCachePurge(): void {
|
||||
const now = Date.now();
|
||||
if (purgeInFlight || now - lastPurgeAt < CACHE_CLEAN_INTERVAL_MS) {
|
||||
return;
|
||||
}
|
||||
|
||||
purgeInFlight = purgeExpiredCache().finally(() => {
|
||||
lastPurgeAt = Date.now();
|
||||
purgeInFlight = null;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
export type PasteEmbedMetadataItem = {
|
||||
icon:
|
||||
| 'size'
|
||||
| 'views'
|
||||
| 'created'
|
||||
| 'expires'
|
||||
| 'syntax'
|
||||
| 'visibility-0'
|
||||
| 'visibility-1'
|
||||
| 'visibility-2';
|
||||
value: string;
|
||||
};
|
||||
|
||||
export type PasteEmbedProps = {
|
||||
title: string;
|
||||
uploader: string;
|
||||
metadata: PasteEmbedMetadataItem[];
|
||||
previewLines: string[];
|
||||
isEncrypted: boolean;
|
||||
};
|
||||
Reference in New Issue
Block a user