-
Notifications
You must be signed in to change notification settings - Fork 0
Add Links list mode with URL previews and tweet embeds #26
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
bclinkinbeard
wants to merge
2
commits into
main
Choose a base branch
from
codex/add-new-links-list-type-with-fetching
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| import { jsonResponse, serverError } from '../server/json.js'; | ||
|
|
||
| const MAX_HTML_LENGTH = 180000; | ||
| const REQUEST_TIMEOUT_MS = 6000; | ||
| const PREVIEW_CACHE_TTL_MS = 1000 * 60 * 60 * 12; | ||
| const previewCache = new Map(); | ||
|
|
||
| function extractMetaTag(html, attribute, value) { | ||
| const pattern = new RegExp(`<meta[^>]*${attribute}=["']${value}["'][^>]*content=["']([^"']+)["'][^>]*>`, 'i'); | ||
| const match = html.match(pattern); | ||
| return match ? decodeHtml(match[1].trim()) : ''; | ||
| } | ||
|
|
||
| function extractTitle(html) { | ||
| const match = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i); | ||
| return match ? decodeHtml(match[1].replace(/\s+/g, ' ').trim()) : ''; | ||
| } | ||
|
|
||
| function decodeHtml(value) { | ||
| return String(value || '') | ||
| .replace(/&/g, '&') | ||
| .replace(/</g, '<') | ||
| .replace(/>/g, '>') | ||
| .replace(/"/g, '"') | ||
| .replace(/'/g, '\''); | ||
| } | ||
|
|
||
| function truncate(value, maxLength = 280) { | ||
| if (!value) return ''; | ||
| return value.length <= maxLength ? value : `${value.slice(0, maxLength - 1).trim()}…`; | ||
| } | ||
|
|
||
| function stripTags(value) { | ||
| return String(value || '') | ||
| .replace(/<script[\s\S]*?<\/script>/gi, ' ') | ||
| .replace(/<style[\s\S]*?<\/style>/gi, ' ') | ||
| .replace(/<[^>]+>/g, ' ') | ||
| .replace(/\s+/g, ' ') | ||
| .trim(); | ||
| } | ||
|
|
||
| function extractFirstParagraph(html) { | ||
| const match = html.match(/<p[^>]*>([\s\S]*?)<\/p>/i); | ||
| if (!match) return ''; | ||
| return decodeHtml(stripTags(match[1])); | ||
| } | ||
|
|
||
| async function fetchHtml(url) { | ||
| const controller = new AbortController(); | ||
| const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS); | ||
| try { | ||
| const response = await fetch(url, { | ||
| redirect: 'follow', | ||
| signal: controller.signal, | ||
| headers: { | ||
| 'User-Agent': 'voice-notes-link-preview/1.0', | ||
| Accept: 'text/html,application/xhtml+xml', | ||
| }, | ||
| }); | ||
| if (!response.ok) { | ||
| throw new Error(`Upstream request failed with ${response.status}`); | ||
| } | ||
| const text = await response.text(); | ||
| return text.slice(0, MAX_HTML_LENGTH); | ||
| } finally { | ||
| clearTimeout(timeout); | ||
| } | ||
| } | ||
|
|
||
| function buildPreview(html, url) { | ||
| const ogTitle = extractMetaTag(html, 'property', 'og:title'); | ||
| const twitterTitle = extractMetaTag(html, 'name', 'twitter:title'); | ||
| const title = truncate(ogTitle || twitterTitle || extractTitle(html) || url, 180); | ||
|
|
||
| const ogDescription = extractMetaTag(html, 'property', 'og:description'); | ||
| const metaDescription = extractMetaTag(html, 'name', 'description'); | ||
| const twitterDescription = extractMetaTag(html, 'name', 'twitter:description'); | ||
| const firstParagraph = extractFirstParagraph(html); | ||
| const description = truncate(ogDescription || twitterDescription || metaDescription || firstParagraph, 320); | ||
|
|
||
| const siteName = truncate(extractMetaTag(html, 'property', 'og:site_name'), 100); | ||
|
|
||
| return { | ||
| title, | ||
| description, | ||
| summary: description, | ||
| siteName, | ||
| url, | ||
| }; | ||
| } | ||
|
|
||
| export async function GET(request) { | ||
| try { | ||
| const requestUrl = new URL(request.url); | ||
| const target = requestUrl.searchParams.get('url') || ''; | ||
| if (!target) { | ||
| return jsonResponse({ ok: false, error: 'Missing url query parameter.' }, { status: 400 }); | ||
| } | ||
|
|
||
| let parsed; | ||
| try { | ||
| parsed = new URL(target); | ||
| } catch { | ||
| return jsonResponse({ ok: false, error: 'Invalid URL.' }, { status: 400 }); | ||
| } | ||
|
|
||
| if (!/^https?:$/i.test(parsed.protocol)) { | ||
| return jsonResponse({ ok: false, error: 'Only HTTP(S) URLs are supported.' }, { status: 400 }); | ||
| } | ||
|
|
||
| const normalizedUrl = parsed.toString(); | ||
| const cached = previewCache.get(normalizedUrl); | ||
| if (cached && Date.now() - cached.cachedAt < PREVIEW_CACHE_TTL_MS) { | ||
| return jsonResponse({ ok: true, preview: cached.preview, cached: true }); | ||
| } | ||
|
|
||
| const html = await fetchHtml(normalizedUrl); | ||
| const preview = buildPreview(html, normalizedUrl); | ||
| previewCache.set(normalizedUrl, { | ||
| cachedAt: Date.now(), | ||
| preview, | ||
| }); | ||
|
|
||
| return jsonResponse({ ok: true, preview }); | ||
| } catch (error) { | ||
| return serverError(error.message || 'Failed to fetch link preview.'); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fetchHtmlcallsresponse.text()and only then truncates toMAX_HTML_LENGTH, so the configured cap does not prevent large upstream payloads from being fully downloaded and buffered. A large response can still cause avoidable memory/CPU pressure before truncation is applied.Useful? React with 👍 / 👎.