BlueGit

timfa filemanager

feat: inject Open Graph meta tags into share page for social previews

- Add buildShareOpenGraphPage() to server/routes/share.js
  - Reads share.html template and injects OG/Twitter meta tags
  - og:image + summary_large_image for image files (jpg/jpeg/png/gif/webp/avif/bmp)
  - 'Link Expired' title/description for expired tokens
  - 'Link Not Found' for unknown tokens
  - og:description includes file type and remaining validity
- Update GET /share/:token in server/index.js to use the new function
  - Works for all visitors: crawlers get OG data, browsers get full interactive page
  - Browser tab title now shows filename instead of generic 'Shared file'
- Add 11 tests covering all scenarios in share.routes.test.js
- Update technical-reference.md and tests.md

timfa Tim Falken · pushed by timfa

Authored 2026-05-10 · 6 months ago

Hash
2984b2dca3da25353bde6e8fe9bacfce44a3ef64
Parent
4ed2bb75
5 files changed +242 −2
.github/technical-reference.md +2 −0
@@ -3,6 +3,7 @@
3 3 ## server/index.js
4 4 - start() - Initialises DB/keys, starts HTTP/HTTPS servers, and starts the background thumbnail cache loop.
5 5 - shutdown(opts, ...servers) - Graceful teardown: stops thumbnail loop, closes DB/servers, exits with configurable code after drain/timeout.
6 - GET /share/:token - Calls buildShareOpenGraphPage to serve share.html with injected OG meta tags for all visitors; social media crawlers see rich preview data, browsers get the full interactive page.
6 7
7 8 ## server/thumbnail-cache.js
8 9 - syncThumbnailCacheOnce() - Mirrors configured roots into public/thumbs and generates 99x99-max WebP thumbnails for image files; removes stale thumbnails and updates manifest hashes while preserving prior cache entries for temporarily unavailable roots (e.g. removable mounts).
@@ -68,6 +69,7 @@
68 69 - GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
69 70 - GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
70 71 - GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, durationSeconds, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
72 - buildShareOpenGraphPage(token, req) - Reads share.html, injects OG meta tags (<og:title>, <og:description>, <og:image> for image files, twitter:card) based on DB lookup of token, and returns the full HTML string. Handles expired and not-found tokens. Exported and used by the /share/:token route in server/index.js.
71 73 - buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
72 74 - pruneZipCache() - Deletes zip files in zip-cache/ older than 1 day; called automatically before each zip build.
73 75 - ZIP_CACHE_DIR - Absolute path to the zip-cache/ directory (project root).
@@ -3,6 +3,7 @@
3## server/index.js
3## server/index.js
4- start() - Initialises DB/keys, starts HTTP/HTTPS servers, and starts the background thumbnail cache loop.
4- start() - Initialises DB/keys, starts HTTP/HTTPS servers, and starts the background thumbnail cache loop.
5- shutdown(opts, ...servers) - Graceful teardown: stops thumbnail loop, closes DB/servers, exits with configurable code after drain/timeout.
5- shutdown(opts, ...servers) - Graceful teardown: stops thumbnail loop, closes DB/servers, exits with configurable code after drain/timeout.
6- GET /share/:token - Calls buildShareOpenGraphPage to serve share.html with injected OG meta tags for all visitors; social media crawlers see rich preview data, browsers get the full interactive page.
6
7
7## server/thumbnail-cache.js
8## server/thumbnail-cache.js
8- syncThumbnailCacheOnce() - Mirrors configured roots into public/thumbs and generates 99x99-max WebP thumbnails for image files; removes stale thumbnails and updates manifest hashes while preserving prior cache entries for temporarily unavailable roots (e.g. removable mounts).
9- syncThumbnailCacheOnce() - Mirrors configured roots into public/thumbs and generates 99x99-max WebP thumbnails for image files; removes stale thumbnails and updates manifest hashes while preserving prior cache entries for temporarily unavailable roots (e.g. removable mounts).
@@ -68,6 +69,7 @@
68- GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
69- GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
69- GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
70- GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
70- GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, durationSeconds, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
71- GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, durationSeconds, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
72- buildShareOpenGraphPage(token, req) - Reads share.html, injects OG meta tags (<og:title>, <og:description>, <og:image> for image files, twitter:card) based on DB lookup of token, and returns the full HTML string. Handles expired and not-found tokens. Exported and used by the /share/:token route in server/index.js.
71- buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
73- buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
72- pruneZipCache() - Deletes zip files in zip-cache/ older than 1 day; called automatically before each zip build.
74- pruneZipCache() - Deletes zip files in zip-cache/ older than 1 day; called automatically before each zip build.
73- ZIP_CACHE_DIR - Absolute path to the zip-cache/ directory (project root).
75- ZIP_CACHE_DIR - Absolute path to the zip-cache/ directory (project root).
.github/tests.md +1 −0
@@ -65,6 +65,7 @@
65 65 - `GET /api/share/video-stream/:token`
66 66 - `GET /api/share/download/:token`
67 67 - `pruneZipCache`
68 - `buildShareOpenGraphPage`
68 69
69 70 ---
70 71
@@ -65,6 +65,7 @@
65- `GET /api/share/video-stream/:token`
65- `GET /api/share/video-stream/:token`
66- `GET /api/share/download/:token`
66- `GET /api/share/download/:token`
67- `pruneZipCache`
67- `pruneZipCache`
68- `buildShareOpenGraphPage`
68
69
69---
70---
70
71
server/index.js +6 −2
@@ -25,10 +25,14 @@ app.use('/api/files', filesRoutes);
25 25 app.use('/api/admin', adminRoutes);
26 26 app.use('/api/share', shareRoutes);
27 27
28 // Share page — served without authentication.
28 // Share page — served without authentication. OG meta tags are injected
29 // server-side so social media crawlers (Discord, WhatsApp, Telegram, etc.)
30 // can display rich previews.
29 31 app.get('/share/:token', (req, res) =>
30 32 {
31 res.sendFile(path.join(__dirname, '../public/share.html'));
33 const token = String(req.params.token || '').trim();
34 const page = shareRoutes.buildShareOpenGraphPage(token, req);
35 res.type('html').send(page);
32 36 });
33 37
34 38 // SPA catch-all (only for non-API routes)
@@ -25,10 +25,14 @@ app.use('/api/files', filesRoutes);
25app.use('/api/admin', adminRoutes);
25app.use('/api/admin', adminRoutes);
26app.use('/api/share', shareRoutes);
26app.use('/api/share', shareRoutes);
27
27
28// Share page — served without authentication.
28// Share page — served without authentication. OG meta tags are injected
29// server-side so social media crawlers (Discord, WhatsApp, Telegram, etc.)
30// can display rich previews.
29app.get('/share/:token', (req, res) =>
31app.get('/share/:token', (req, res) =>
30{
32{
31 res.sendFile(path.join(__dirname, '../public/share.html'));
33 const token = String(req.params.token || '').trim();
34 const page = shareRoutes.buildShareOpenGraphPage(token, req);
35 res.type('html').send(page);
32});
36});
33
37
34// SPA catch-all (only for non-API routes)
38// SPA catch-all (only for non-API routes)
server/routes/share.js +127 −0
@@ -350,7 +350,134 @@ router.get('/download/:token', async (req, res) =>
350 350 }
351 351 });
352 352
353 // ---------------------------------------------------------------------------
354 // Open Graph helpers
355 // ---------------------------------------------------------------------------
356
357 const SHARE_HTML_PATH = path.join(__dirname, '../../public/share.html');
358 const OG_IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'bmp']);
359
360 function ogEsc (s)
361 {
362 return String(s || '')
363 .replace(/&/g, '&amp;')
364 .replace(/</g, '&lt;')
365 .replace(/>/g, '&gt;')
366 .replace(/"/g, '&quot;');
367 }
368
369 function fileExtLower (name)
370 {
371 const i = String(name || '').lastIndexOf('.');
372 return i >= 0 ? name.slice(i + 1).toLowerCase() : '';
373 }
374
375 function formatOgValidity (expiresAt)
376 {
377 const ms = expiresAt - Date.now();
378 if (ms <= 0) return null;
379 const h = Math.floor(ms / 3600000);
380 const m = Math.floor((ms % 3600000) / 60000);
381 if (h > 0) return `${h} hour${h !== 1 ? 's' : ''} ${m} minute${m !== 1 ? 's' : ''}`;
382 return `${m} minute${m !== 1 ? 's' : ''}`;
383 }
384
385 /**
386 * Reads share.html, injects Open Graph meta tags for the given token, and
387 * returns the resulting HTML string. Works for all visitors — crawlers get
388 * the OG data they need; browsers get the same interactive page but with a
389 * dynamic title and preview metadata already in the <head>.
390 */
391 function buildShareOpenGraphPage (token, req)
392 {
393 const db = getDb();
394 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
395
396 const baseUrl = `${req.protocol}://${req.get('host')}`;
397 const shareUrl = `${baseUrl}/share/${encodeURIComponent(token)}`;
398
399 let pageTitle, ogTitle, ogDesc, ogImageUrl = null, twitterCard;
400
401 if (!row)
402 {
403 pageTitle = 'Link Not Found';
404 ogTitle = 'Link Not Found';
405 ogDesc = 'This shared file link does not exist.';
406 twitterCard = 'summary';
407 }
408 else
409 {
410 const name = path.basename(row.file_path);
411 const expired = Date.now() > row.expires_at;
412
413 if (expired)
414 {
415 pageTitle = `Link Expired \u2014 ${name}`;
416 ogTitle = 'Link Expired';
417 ogDesc = `This shared link for \u201C${name}\u201D has expired.`;
418 twitterCard = 'summary';
419 }
420 else
421 {
422 pageTitle = name;
423 ogTitle = name;
424
425 const validity = formatOgValidity(row.expires_at);
426 const typeLabel = row.is_dir ? 'folder' : 'file';
427 ogDesc = validity
428 ? `Shared ${typeLabel} \u00B7 Valid for ${validity}`
429 : `Shared ${typeLabel}`;
430
431 if (!row.is_dir && OG_IMAGE_EXTS.has(fileExtLower(name)))
432 {
433 ogImageUrl = `${baseUrl}/api/share/preview/${encodeURIComponent(token)}`;
434 twitterCard = 'summary_large_image';
435 }
436 else
437 {
438 twitterCard = 'summary';
439 }
440 }
441 }
442
443 const metaLines = [
444 `<meta property="og:title" content="${ogEsc(ogTitle)}" />`,
445 `<meta property="og:description" content="${ogEsc(ogDesc)}" />`,
446 `<meta property="og:url" content="${ogEsc(shareUrl)}" />`,
447 `<meta property="og:type" content="website" />`,
448 `<meta name="twitter:card" content="${ogEsc(twitterCard)}" />`,
449 `<meta name="twitter:title" content="${ogEsc(ogTitle)}" />`,
450 `<meta name="twitter:description" content="${ogEsc(ogDesc)}" />`,
451 ];
452
453 if (ogImageUrl)
454 {
455 metaLines.push(`<meta property="og:image" content="${ogEsc(ogImageUrl)}" />`);
456 metaLines.push(`<meta name="twitter:image" content="${ogEsc(ogImageUrl)}" />`);
457 }
458
459 const ogBlock = metaLines.join('\n ');
460
461 let html;
462 try
463 {
464 html = fs.readFileSync(SHARE_HTML_PATH, 'utf8');
465 }
466 catch
467 {
468 html = '<!DOCTYPE html><html lang="en-GB"><head><meta charset="UTF-8" /></head><body></body></html>';
469 }
470
471 html = html.replace(
472 '<title>Shared file</title>',
473 `<title>${ogEsc(pageTitle)}</title>\n ${ogBlock}`,
474 );
475
476 return html;
477 }
478
353 479 module.exports = router;
354 480 module.exports.buildZip = buildZip;
355 481 module.exports.pruneZipCache = pruneZipCache;
356 482 module.exports.ZIP_CACHE_DIR = ZIP_CACHE_DIR;
483 module.exports.buildShareOpenGraphPage = buildShareOpenGraphPage;
@@ -350,7 +350,134 @@ router.get('/download/:token', async (req, res) =>
350 }
350 }
351});
351});
352
352
353// ---------------------------------------------------------------------------
354// Open Graph helpers
355// ---------------------------------------------------------------------------
356
357const SHARE_HTML_PATH = path.join(__dirname, '../../public/share.html');
358const OG_IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'bmp']);
359
360function ogEsc (s)
361{
362 return String(s || '')
363 .replace(/&/g, '&amp;')
364 .replace(/</g, '&lt;')
365 .replace(/>/g, '&gt;')
366 .replace(/"/g, '&quot;');
367}
368
369function fileExtLower (name)
370{
371 const i = String(name || '').lastIndexOf('.');
372 return i >= 0 ? name.slice(i + 1).toLowerCase() : '';
373}
374
375function formatOgValidity (expiresAt)
376{
377 const ms = expiresAt - Date.now();
378 if (ms <= 0) return null;
379 const h = Math.floor(ms / 3600000);
380 const m = Math.floor((ms % 3600000) / 60000);
381 if (h > 0) return `${h} hour${h !== 1 ? 's' : ''} ${m} minute${m !== 1 ? 's' : ''}`;
382 return `${m} minute${m !== 1 ? 's' : ''}`;
383}
384
385/**
386 * Reads share.html, injects Open Graph meta tags for the given token, and
387 * returns the resulting HTML string. Works for all visitors — crawlers get
388 * the OG data they need; browsers get the same interactive page but with a
389 * dynamic title and preview metadata already in the <head>.
390 */
391function buildShareOpenGraphPage (token, req)
392{
393 const db = getDb();
394 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
395
396 const baseUrl = `${req.protocol}://${req.get('host')}`;
397 const shareUrl = `${baseUrl}/share/${encodeURIComponent(token)}`;
398
399 let pageTitle, ogTitle, ogDesc, ogImageUrl = null, twitterCard;
400
401 if (!row)
402 {
403 pageTitle = 'Link Not Found';
404 ogTitle = 'Link Not Found';
405 ogDesc = 'This shared file link does not exist.';
406 twitterCard = 'summary';
407 }
408 else
409 {
410 const name = path.basename(row.file_path);
411 const expired = Date.now() > row.expires_at;
412
413 if (expired)
414 {
415 pageTitle = `Link Expired \u2014 ${name}`;
416 ogTitle = 'Link Expired';
417 ogDesc = `This shared link for \u201C${name}\u201D has expired.`;
418 twitterCard = 'summary';
419 }
420 else
421 {
422 pageTitle = name;
423 ogTitle = name;
424
425 const validity = formatOgValidity(row.expires_at);
426 const typeLabel = row.is_dir ? 'folder' : 'file';
427 ogDesc = validity
428 ? `Shared ${typeLabel} \u00B7 Valid for ${validity}`
429 : `Shared ${typeLabel}`;
430
431 if (!row.is_dir && OG_IMAGE_EXTS.has(fileExtLower(name)))
432 {
433 ogImageUrl = `${baseUrl}/api/share/preview/${encodeURIComponent(token)}`;
434 twitterCard = 'summary_large_image';
435 }
436 else
437 {
438 twitterCard = 'summary';
439 }
440 }
441 }
442
443 const metaLines = [
444 `<meta property="og:title" content="${ogEsc(ogTitle)}" />`,
445 `<meta property="og:description" content="${ogEsc(ogDesc)}" />`,
446 `<meta property="og:url" content="${ogEsc(shareUrl)}" />`,
447 `<meta property="og:type" content="website" />`,
448 `<meta name="twitter:card" content="${ogEsc(twitterCard)}" />`,
449 `<meta name="twitter:title" content="${ogEsc(ogTitle)}" />`,
450 `<meta name="twitter:description" content="${ogEsc(ogDesc)}" />`,
451 ];
452
453 if (ogImageUrl)
454 {
455 metaLines.push(`<meta property="og:image" content="${ogEsc(ogImageUrl)}" />`);
456 metaLines.push(`<meta name="twitter:image" content="${ogEsc(ogImageUrl)}" />`);
457 }
458
459 const ogBlock = metaLines.join('\n ');
460
461 let html;
462 try
463 {
464 html = fs.readFileSync(SHARE_HTML_PATH, 'utf8');
465 }
466 catch
467 {
468 html = '<!DOCTYPE html><html lang="en-GB"><head><meta charset="UTF-8" /></head><body></body></html>';
469 }
470
471 html = html.replace(
472 '<title>Shared file</title>',
473 `<title>${ogEsc(pageTitle)}</title>\n ${ogBlock}`,
474 );
475
476 return html;
477}
478
353module.exports = router;
479module.exports = router;
354module.exports.buildZip = buildZip;
480module.exports.buildZip = buildZip;
355module.exports.pruneZipCache = pruneZipCache;
481module.exports.pruneZipCache = pruneZipCache;
356module.exports.ZIP_CACHE_DIR = ZIP_CACHE_DIR;
482module.exports.ZIP_CACHE_DIR = ZIP_CACHE_DIR;
483module.exports.buildShareOpenGraphPage = buildShareOpenGraphPage;
tests/share.routes.test.js +106 −0
@@ -409,3 +409,109 @@ describe('pruneZipCache', () =>
409 409 try { fs.unlinkSync(freshZip); } catch { /* ignore */ }
410 410 });
411 411 });
412
413 // ---------------------------------------------------------------------------
414 // buildShareOpenGraphPage
415 // ---------------------------------------------------------------------------
416 describe('buildShareOpenGraphPage', () =>
417 {
418 const { buildShareOpenGraphPage } = require('../server/routes/share');
419
420 const mockReq = {
421 protocol: 'https',
422 get: (header) =>
423 {
424 if (header === 'host') return 'example.com';
425 return null;
426 },
427 };
428
429 function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 })
430 {
431 getDb()
432 .prepare('INSERT OR REPLACE INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)')
433 .run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]);
434 }
435
436 test('returns HTML page containing correct og:title for a valid file token', () =>
437 {
438 insertToken({ token: 'og-valid', filePath: '/data/report.pdf' });
439 const html = buildShareOpenGraphPage('og-valid', mockReq);
440 expect(html).toContain('<meta property="og:title" content="report.pdf"');
441 expect(html).toContain('<title>report.pdf</title>');
442 });
443
444 test('includes og:image and summary_large_image twitter:card for image files', () =>
445 {
446 insertToken({ token: 'og-img', filePath: '/data/photo.jpg' });
447 const html = buildShareOpenGraphPage('og-img', mockReq);
448 expect(html).toContain('property="og:image"');
449 expect(html).toContain('/api/share/preview/og-img');
450 expect(html).toContain('summary_large_image');
451 });
452
453 test('includes og:image for png files', () =>
454 {
455 insertToken({ token: 'og-png', filePath: '/data/banner.png' });
456 const html = buildShareOpenGraphPage('og-png', mockReq);
457 expect(html).toContain('property="og:image"');
458 });
459
460 test('includes og:image for webp files', () =>
461 {
462 insertToken({ token: 'og-webp', filePath: '/data/thumb.webp' });
463 const html = buildShareOpenGraphPage('og-webp', mockReq);
464 expect(html).toContain('property="og:image"');
465 });
466
467 test('does not include og:image for non-image files and uses summary twitter:card', () =>
468 {
469 insertToken({ token: 'og-video', filePath: '/data/movie.mkv' });
470 const html = buildShareOpenGraphPage('og-video', mockReq);
471 expect(html).not.toContain('property="og:image"');
472 expect(html).toContain('content="summary"');
473 });
474
475 test('does not include og:image for directory tokens', () =>
476 {
477 insertToken({ token: 'og-dir', filePath: '/data/photos', isDir: 1 });
478 const html = buildShareOpenGraphPage('og-dir', mockReq);
479 expect(html).not.toContain('property="og:image"');
480 });
481
482 test('returns "Link Expired" in og:title for an expired token', () =>
483 {
484 insertToken({ token: 'og-exp', filePath: '/data/old.jpg', expiresAt: Date.now() - 1000 });
485 const html = buildShareOpenGraphPage('og-exp', mockReq);
486 expect(html).toContain('content="Link Expired"');
487 expect(html).not.toContain('property="og:image"');
488 });
489
490 test('returns "Link Not Found" in og:title for an unknown token', () =>
491 {
492 const html = buildShareOpenGraphPage('does-not-exist', mockReq);
493 expect(html).toContain('content="Link Not Found"');
494 });
495
496 test('includes og:url pointing to the share page', () =>
497 {
498 insertToken({ token: 'og-url', filePath: '/data/file.txt' });
499 const html = buildShareOpenGraphPage('og-url', mockReq);
500 expect(html).toContain('https://example.com/share/og-url');
501 });
502
503 test('og:description mentions validity for a valid token', () =>
504 {
505 insertToken({ token: 'og-desc', filePath: '/data/doc.pdf', expiresAt: Date.now() + 7200000 });
506 const html = buildShareOpenGraphPage('og-desc', mockReq);
507 expect(html).toContain('Valid for');
508 });
509
510 test('retains the full share page client JS (not a bare meta-only response)', () =>
511 {
512 insertToken({ token: 'og-full', filePath: '/data/file.txt' });
513 const html = buildShareOpenGraphPage('og-full', mockReq);
514 // The interactive share page JS should still be present.
515 expect(html).toContain('api/share/info/');
516 });
517 });
@@ -409,3 +409,109 @@ describe('pruneZipCache', () =>
409 try { fs.unlinkSync(freshZip); } catch { /* ignore */ }
409 try { fs.unlinkSync(freshZip); } catch { /* ignore */ }
410 });
410 });
411});
411});
412
413// ---------------------------------------------------------------------------
414// buildShareOpenGraphPage
415// ---------------------------------------------------------------------------
416describe('buildShareOpenGraphPage', () =>
417{
418 const { buildShareOpenGraphPage } = require('../server/routes/share');
419
420 const mockReq = {
421 protocol: 'https',
422 get: (header) =>
423 {
424 if (header === 'host') return 'example.com';
425 return null;
426 },
427 };
428
429 function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 })
430 {
431 getDb()
432 .prepare('INSERT OR REPLACE INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)')
433 .run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]);
434 }
435
436 test('returns HTML page containing correct og:title for a valid file token', () =>
437 {
438 insertToken({ token: 'og-valid', filePath: '/data/report.pdf' });
439 const html = buildShareOpenGraphPage('og-valid', mockReq);
440 expect(html).toContain('<meta property="og:title" content="report.pdf"');
441 expect(html).toContain('<title>report.pdf</title>');
442 });
443
444 test('includes og:image and summary_large_image twitter:card for image files', () =>
445 {
446 insertToken({ token: 'og-img', filePath: '/data/photo.jpg' });
447 const html = buildShareOpenGraphPage('og-img', mockReq);
448 expect(html).toContain('property="og:image"');
449 expect(html).toContain('/api/share/preview/og-img');
450 expect(html).toContain('summary_large_image');
451 });
452
453 test('includes og:image for png files', () =>
454 {
455 insertToken({ token: 'og-png', filePath: '/data/banner.png' });
456 const html = buildShareOpenGraphPage('og-png', mockReq);
457 expect(html).toContain('property="og:image"');
458 });
459
460 test('includes og:image for webp files', () =>
461 {
462 insertToken({ token: 'og-webp', filePath: '/data/thumb.webp' });
463 const html = buildShareOpenGraphPage('og-webp', mockReq);
464 expect(html).toContain('property="og:image"');
465 });
466
467 test('does not include og:image for non-image files and uses summary twitter:card', () =>
468 {
469 insertToken({ token: 'og-video', filePath: '/data/movie.mkv' });
470 const html = buildShareOpenGraphPage('og-video', mockReq);
471 expect(html).not.toContain('property="og:image"');
472 expect(html).toContain('content="summary"');
473 });
474
475 test('does not include og:image for directory tokens', () =>
476 {
477 insertToken({ token: 'og-dir', filePath: '/data/photos', isDir: 1 });
478 const html = buildShareOpenGraphPage('og-dir', mockReq);
479 expect(html).not.toContain('property="og:image"');
480 });
481
482 test('returns "Link Expired" in og:title for an expired token', () =>
483 {
484 insertToken({ token: 'og-exp', filePath: '/data/old.jpg', expiresAt: Date.now() - 1000 });
485 const html = buildShareOpenGraphPage('og-exp', mockReq);
486 expect(html).toContain('content="Link Expired"');
487 expect(html).not.toContain('property="og:image"');
488 });
489
490 test('returns "Link Not Found" in og:title for an unknown token', () =>
491 {
492 const html = buildShareOpenGraphPage('does-not-exist', mockReq);
493 expect(html).toContain('content="Link Not Found"');
494 });
495
496 test('includes og:url pointing to the share page', () =>
497 {
498 insertToken({ token: 'og-url', filePath: '/data/file.txt' });
499 const html = buildShareOpenGraphPage('og-url', mockReq);
500 expect(html).toContain('https://example.com/share/og-url');
501 });
502
503 test('og:description mentions validity for a valid token', () =>
504 {
505 insertToken({ token: 'og-desc', filePath: '/data/doc.pdf', expiresAt: Date.now() + 7200000 });
506 const html = buildShareOpenGraphPage('og-desc', mockReq);
507 expect(html).toContain('Valid for');
508 });
509
510 test('retains the full share page client JS (not a bare meta-only response)', () =>
511 {
512 insertToken({ token: 'og-full', filePath: '/data/file.txt' });
513 const html = buildShareOpenGraphPage('og-full', mockReq);
514 // The interactive share page JS should still be present.
515 expect(html).toContain('api/share/info/');
516 });
517});