Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: import photos/video from an x.com post into a mood board
[._.]/ Adam Eivy17c7fa7430e3
diff --git a/client/src/pages/MoodBoardDetail.jsx b/client/src/pages/MoodBoardDetail.jsxindex 2dd315dfef..73f120170c 100644--- a/client/src/pages/MoodBoardDetail.jsx+++ b/client/src/pages/MoodBoardDetail.jsx@@ -11,7 +11,7 @@import { useEffect, useState, useCallback, useMemo, useRef } from 'react';import { useParams, useNavigate, Link } from 'react-router';-import { ArrowLeft, ImageIcon, FileText, Trash2, Plus, Save, Link2, Unlink, RefreshCw, Images, Film, Play, ScanEye, Copy } from 'lucide-react';+import { ArrowLeft, ImageIcon, FileText, Trash2, Plus, Save, Link2, Unlink, RefreshCw, Images, Film, Play, ScanEye, Copy, AtSign } from 'lucide-react';import PageSkeleton from '../components/ui/PageSkeleton';import toast from '../components/ui/Toast';import TabPills from '../components/ui/TabPills';@@ -29,6 +29,7 @@ import {linkMoodBoardPinterest,unlinkMoodBoardPinterest,syncMoodBoardPinterest,+ importMoodBoardXPost,} from '../services/api';import { moodBoardItemSrc, moodBoardItemVideoSrc, moodBoardItemAnalysisSource } from '../lib/moodBoardItemSrc';import { timeAgo } from '../utils/formatters';@@ -74,6 +75,10 @@ function MoodBoardEditor({ id }) {const [syncing, setSyncing] = useState(false);const [confirmingUnlink, setConfirmingUnlink] = useState(false);+ // X.com (Twitter) post import — one-shot, no persisted link.+ const [xPostUrl, setXPostUrl] = useState('');+ const [importingXPost, setImportingXPost] = useState(false);+// The keyed editor isolates board state. Also guard async continuations and// delayed child callbacks so the old editor cannot toast or start a mutation// after navigation. The load sequence drops StrictMode's duplicate GET.@@ -275,6 +280,19 @@ function MoodBoardEditor({ id }) {: 'Up to date — no new pins');};+ const handleImportXPost = async () => {+ if (!mountedRef.current) return;+ if (!xPostUrl.trim()) { toast.error('Enter an x.com/twitter.com post URL'); return; }+ setImportingXPost(true);+ const result = await importMoodBoardXPost(id, xPostUrl.trim(), { silent: true }).catch(() => null);+ if (!mountedRef.current) return;+ setImportingXPost(false);+ if (!result?.board) { toast.error('Could not import that post — check the URL or try again'); return; }+ setBoard(result.board);+ setXPostUrl('');+ toast.success(`Added ${result.added} item${result.added === 1 ? '' : 's'} from the post`);+ };+if (loading) {return (<div className="max-w-5xl mx-auto">@@ -447,6 +465,39 @@ function MoodBoardEditor({ id }) {)}</div>+ {/* X.com (Twitter) post import */}+ <div className="bg-port-card border border-port-border rounded-md p-4 mb-6">+ <div className="flex items-center gap-2 mb-3">+ <AtSign className="w-4 h-4 text-port-accent" aria-hidden="true" />+ <h2 className="text-sm font-medium text-white">Import from an X post</h2>+ </div>+ <div>+ <label htmlFor="x-post-url" className="block text-xs text-gray-400 mb-1">Post URL</label>+ <div className="flex gap-2">+ <input+ id="x-post-url"+ type="text"+ value={xPostUrl}+ maxLength={2048}+ placeholder="https://x.com/user/status/1234567890"+ onChange={(e) => setXPostUrl(e.target.value)}+ className="flex-1 min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:border-port-accent outline-none"+ />+ <button+ type="button"+ onClick={handleImportXPost}+ disabled={importingXPost || !xPostUrl.trim()}+ className="px-3 py-1.5 text-sm rounded bg-port-success text-white hover:bg-port-success/80 disabled:opacity-50 transition-colors"+ >+ {importingXPost ? 'Importing…' : 'Import'}+ </button>+ </div>+ </div>+ <p className="text-[11px] text-gray-500 mt-2">+ Paste a public x.com/twitter.com post URL. Pulls every attached photo (or its video) into this board.+ </p>+ </div>+{/* Add item */}<div className="bg-port-card border border-port-border rounded-md p-4 mb-6"><div className="flex flex-wrap items-center gap-2 mb-3">diff --git a/client/src/pages/MoodBoardDetail.test.jsx b/client/src/pages/MoodBoardDetail.test.jsxindex 7b7fbb8b6e..0275b96a3e 100644--- a/client/src/pages/MoodBoardDetail.test.jsx+++ b/client/src/pages/MoodBoardDetail.test.jsx@@ -10,6 +10,7 @@ const mockUpdateMoodBoard = vi.fn();const mockAddMoodBoardItem = vi.fn();const mockUpdateMoodBoardItem = vi.fn();const mockSyncMoodBoardPinterest = vi.fn();+const mockImportMoodBoardXPost = vi.fn();vi.mock('../services/api', () => ({getMoodBoard: (...args) => mockGetMoodBoard(...args),@@ -20,6 +21,7 @@ vi.mock('../services/api', () => ({linkMoodBoardPinterest: vi.fn(),unlinkMoodBoardPinterest: vi.fn(),syncMoodBoardPinterest: (...args) => mockSyncMoodBoardPinterest(...args),+ importMoodBoardXPost: (...args) => mockImportMoodBoardXPost(...args),}));const mockToastError = vi.fn();@@ -229,6 +231,38 @@ describe('MoodBoardDetail stale-response guards', () => {});});+describe('MoodBoardDetail X post import', () => {+ it('imports a post URL and merges the returned board', async () => {+ mockGetMoodBoard.mockResolvedValueOnce({ id: 'a', name: 'Board A', items: [] });+ mockImportMoodBoardXPost.mockResolvedValueOnce({+ board: { id: 'a', name: 'Board A', items: [{ id: 'mbi-1', type: 'image', imageUrl: '/data/images/x.jpg' }] },+ added: 1,+ });+ renderPage();+ await waitFor(() => expect(boardNameValue()).toBe('Board A'));++ fireEvent.change(screen.getByLabelText('Post URL'), { target: { value: 'https://x.com/user/status/1' } });+ fireEvent.click(screen.getByRole('button', { name: 'Import' }));++ await waitFor(() => expect(mockToastSuccess).toHaveBeenCalledWith('Added 1 item from the post'));+ expect(mockImportMoodBoardXPost).toHaveBeenCalledWith('a', 'https://x.com/user/status/1', { silent: true });+ expect(screen.getByLabelText('Post URL')).toHaveValue('');+ });++ it('toasts an error and keeps the typed URL on failure', async () => {+ mockGetMoodBoard.mockResolvedValueOnce({ id: 'a', name: 'Board A', items: [] });+ mockImportMoodBoardXPost.mockRejectedValueOnce(new Error('boom'));+ renderPage();+ await waitFor(() => expect(boardNameValue()).toBe('Board A'));++ fireEvent.change(screen.getByLabelText('Post URL'), { target: { value: 'https://x.com/user/status/1' } });+ fireEvent.click(screen.getByRole('button', { name: 'Import' }));++ await waitFor(() => expect(mockToastError).toHaveBeenCalledWith('Could not import that post — check the URL or try again'));+ expect(screen.getByLabelText('Post URL')).toHaveValue('https://x.com/user/status/1');+ });+});+describe('MoodBoardDetail item-type tabs (#7244)', () => {it('keeps one tab stop on the bar and switches the add form with arrow keys', async () => {mockGetMoodBoard.mockResolvedValueOnce({ id: 'a', name: 'Board A', items: [] });diff --git a/client/src/services/apiMoodBoard.js b/client/src/services/apiMoodBoard.jsindex 1a6ce093cf..7313d03196 100644--- a/client/src/services/apiMoodBoard.js+++ b/client/src/services/apiMoodBoard.js@@ -82,3 +82,12 @@ export const syncMoodBoardPinterest = (id, options) =>method: 'POST',...options,});++// One-shot import: paste a public x.com/twitter.com post URL, server pulls its+// attached photos/video into the board. Resolves `{ board, added }`.+export const importMoodBoardXPost = (id, url, options) =>+ request(`/mood-boards/${encodeURIComponent(id)}/x-post`, {+ method: 'POST',+ body: JSON.stringify({ url }),+ ...options,+ });diff --git a/server/lib/README.md b/server/lib/README.mdindex 8980227290..f0e054e6d0 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -334,7 +334,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `homePath.js` | `scrubHomePath(value)` — replace the running user's home-directory prefix with `~` anywhere in a string, so `/Users/<name>/…` never embeds the OS username in anything a user pastes into a bug report. Non-strings pass through; a root-user container reporting `/` as home is left alone (substituting on it would rewrite every separator in every path). Zero-dependency by design: `agentRunEvents.js` re-exports it for the CoS ledger, and `scripts/doctor.js` imports it statically because it must load from a bare checkout with no `node_modules` (`scripts/pre-install-entrypoints.test.js` enforces that). || `jsonIo.js` | JSON/JSONL parsing and file IO, strict read sentinels, append/read/write helpers, and `createCachedStore` — a TTL-cached mutable JSON document with serialized `save`/`mutate`; its `load()` is strict (#4115) so a corrupt file rejects instead of being overwritten by the next `mutate`. || `settingsStore.js` | `createSettingsStore(filePath | () => filePath, defaults, { normalize? })` → `{ get, update, path }` — the one owner of a flat per-feature settings document with shipped defaults (`journal-settings.json`, `activity-digest-settings.json`, `goal-scorecard-settings.json`, …). `get()` reads strict (#4115: a corrupt file rejects rather than reading as the defaults, because `update` writes it back), merges the file over `defaults`, then runs `normalize`; `update(patch)` is a serialized `get → apply → atomicWrite` that skips `undefined` values and writes `null` as an explicit clear. Filter client-settable keys BEFORE calling `update`. Reach for `createCachedStore` for an in-place-edited document and `createCollectionStore` for per-record collections. |-| `mimeTypes.js` | MIME tables and extension allowlists (incl. `UPLOAD_AUDIO_EXTENSIONS`, the playable-audio subset of `/api/uploads`), image format detection, and filename sanitization. |+| `mimeTypes.js` | MIME tables and extension allowlists (incl. `UPLOAD_AUDIO_EXTENSIONS`, the playable-audio subset of `/api/uploads`), image/video format detection (`detectImageFormat`, `detectVideoFormat`), and filename sanitization. || `paths.js` | Canonical source/install `PATHS`, `dataPath`, and home-directory expansion. || `pathContainment.js` | Dependency-free leaf holding `isPathAtOrInsideDir(dir, path)` (containment where the root itself counts as inside — what a guard policing a whole tree wants, as opposed to `pathSafety.js`'s strict `isPathInsideDir`; case-folded on Windows/macOS) and `canonicalizePath(path)` (realpath of the deepest EXISTING ancestor plus the not-yet-created tail, so a target that does not exist yet still resolves through symlinked ancestors). Split out so `fileCore.js`'s #6176 guard can reach them without dragging `errorHandler.js`/`paths.js` into the closure of every server suite — see the budget in `importScoping.test.js`. Keep it free of non-builtin imports. || `pathSafety.js` | Filename/traversal validation, path containment, and approved image-asset resolvers. |@@ -429,6 +429,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `connectivity.js` | `isMachineOnline({timeoutMs?, hosts?})` — internet-reachability probe: bare TCP `connect` to public anycast resolvers on :443 (no DNS, no HTTP), resolves `true` on the first connect and `false` only after all fail; never rejects. Reuse when a caller needs a best-effort local reachability signal. Also `isPortReachable({host?, port, timeoutMs?})` — the same connect primitive aimed at ONE address, for "is anything listening there yet?"; use it rather than a bind probe whenever another process is expected to own the port, since a bind probe can win the race and kill that process with `EADDRINUSE`. || `safeUrlFetch.js` | SSRF-guarded public-URL fetch: `isPublicHttpUrlSafe`/`assertPublicHttpUrl` (scheme + blocked-host-literal via `catalogValidation.isBlockedIngestHost` + DNS-resolve), exported strict `isPrivateAddress`, plus `fetchPublicText`/`fetchPublicBinary` (timeout, redirect revalidation, size cap) and `buildPinnedLookup`/`buildPinnedDispatcher` (the connect-time IP pin that closes the DNS-rebinding TOCTOU). Reuse instead of copying the SSRF guard for any "fetch this remote thing the user pointed us at" flow. Also `readBodyCapped(response, maxBytes)` bounds streamed bodies without choosing a network policy. || `pinterestFeed.js` | Pure Pinterest board RSS helpers: `normalizePinterestFeedUrl(input)` (board URL or `.rss` → `{ feedUrl, boardUrl }`, host-gated) + `parsePinterestRss(xml)` (per-pin `pinUrl`/`imageUrl`/title/description, 736x size upgrade). Feeds the mood-board Pinterest importer. |+| `xPostMedia.js` | Pure x.com/twitter.com post helpers: `parseXPostUrl(input)` (post URL → `{ statusId, canonicalUrl }`, host-gated) + `buildSyndicationUrl`/`syndicationToken` (Twitter's public unauthenticated tweet-syndication endpoint) + `extractXPostMedia(json)` (→ `{ images, video }`). Feeds the mood-board X post importer. || `requestAbort.js` | `abortSignalFromResponse(res)` — AbortSignal that fires only when an Express client disconnects *before the response finishes* (keyed off `res` close + `writableEnded`). Plus `anyAbortSignal(signals)` — combine several signals into one (native `AbortSignal.any` with a Node-18 fallback). || `readResponseJson.js` | Read a `Response` body as JSON, tolerating a non-JSON/HTML error page (no `Unexpected token <` crash). Object callers need no opts; pass `{ fallback, emptyValue }` for arrays or to surface the raw error text. || `peerHttpClient.js` | Federation HTTP/Socket.IO client (TLS validation off — Tailnet is the trust boundary). |diff --git a/server/lib/index.js b/server/lib/index.jsindex dcaad16141..7c86e19671 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -420,6 +420,7 @@ export * from './syncWire.js';export * from './tailscale.js';export * from './tailcatAddress.js';export * from './tailcatVersion.js';+export * from './xPostMedia.js';// === Search & indexing ===export * from './bm25.js';diff --git a/server/lib/mimeTypes.js b/server/lib/mimeTypes.jsindex b90939e26f..64cf9256dc 100644--- a/server/lib/mimeTypes.js+++ b/server/lib/mimeTypes.js@@ -165,6 +165,24 @@ export function detectImageFormat(buf) {return null;}+/**+ * Magic-byte sniff of a video buffer. Mirrors `detectImageFormat`'s reasoning —+ * a remote CDN's Content-Type isn't trustworthy, so downloaded video bytes+ * (e.g. the mood-board X post importer) are verified from the leading bytes.+ * Recognises an ISO-BMFF/MP4 container, which carries an `ftyp` box within its+ * first few dozen bytes (X serves a looping GIF as an mp4 too).+ *+ * @param {Buffer} buf - Raw decoded video bytes+ * @returns {{ format: 'mp4', ext: string, mime: string } | null}+ */+export function detectVideoFormat(buf) {+ if (!Buffer.isBuffer(buf) || buf.length <= 16) return null;+ if (buf.subarray(0, 64).includes('ftyp')) {+ return { format: 'mp4', ext: '.mp4', mime: 'video/mp4' };+ }+ return null;+}+/*** Get a file's extension, normalised to lowercase with a leading dot.* Returns null when the filename has no extension.diff --git a/server/lib/moodBoardValidation.js b/server/lib/moodBoardValidation.jsindex f25200f938..b50f2f62e6 100644--- a/server/lib/moodBoardValidation.js+++ b/server/lib/moodBoardValidation.js@@ -113,6 +113,17 @@ export const moodBoardPinterestLinkSchema = z.object({),}).strict();+// X.com (Twitter) post import body. The URL shape is validated lightly here+// (present, http(s), bounded); the x.com/twitter.com host check + post-URL+// normalization happens in `parseXPostUrl` (server/lib/xPostMedia.js), which+// throws a specific 400 so a non-X URL gets a clear reason.+export const moodBoardXPostImportSchema = z.object({+ url: z.string().trim().min(1).max(2048).refine(+ (v) => /^https?:\/\//.test(v),+ 'url must be an http(s) x.com/twitter.com post URL',+ ),+}).strict();+// Per-item prompt-from-media analysis (#4188 Phase 3) — written by the item// PATCH after a user-triggered vision run on the item's media. Additive on the// wire: the board federates whole-record LWW (sanitizeBoardForSync's `...raw`diff --git a/server/lib/moodBoardValidation.test.js b/server/lib/moodBoardValidation.test.jsindex 081f8eb785..dbc13ede0a 100644--- a/server/lib/moodBoardValidation.test.js+++ b/server/lib/moodBoardValidation.test.js@@ -10,6 +10,7 @@ import {moodBoardUpdateSchema,moodBoardItemCreateSchema,moodBoardItemUpdateSchema,+ moodBoardXPostImportSchema,isVideoItemMediaKey,} from './moodBoardValidation.js';@@ -32,6 +33,21 @@ describe('moodBoardUpdateSchema', () => {});});+describe('moodBoardXPostImportSchema', () => {+ it('accepts an http(s) URL', () => {+ expect(moodBoardXPostImportSchema.parse({ url: 'https://x.com/user/status/1' }).url).toBe('https://x.com/user/status/1');+ });+ it('rejects a non-http(s) value', () => {+ expect(moodBoardXPostImportSchema.safeParse({ url: 'not a url' }).success).toBe(false);+ });+ it('rejects an empty url', () => {+ expect(moodBoardXPostImportSchema.safeParse({ url: '' }).success).toBe(false);+ });+ it('rejects unknown keys (strict)', () => {+ expect(moodBoardXPostImportSchema.safeParse({ url: 'https://x.com/user/status/1', extra: true }).success).toBe(false);+ });+});+describe('moodBoardItemCreateSchema', () => {it('accepts an image item with imageUrl', () => {expect(moodBoardItemCreateSchema.safeParse({ type: 'image', imageUrl: 'https://x/y.png' }).success).toBe(true);diff --git a/server/lib/xPostMedia.js b/server/lib/xPostMedia.jsnew file mode 100644index 0000000000..6956638968--- /dev/null+++ b/server/lib/xPostMedia.js@@ -0,0 +1,100 @@+/**+ * X.com (Twitter) post URL + media — pure helpers (no I/O).+ *+ * `parseXPostUrl` validates a pasted post URL and reduces it to a status id+ * plus a username-independent canonical URL (the mood-board importer's+ * per-item dedupe key). `buildSyndicationUrl`/`syndicationToken` build the+ * request for Twitter's public, unauthenticated tweet-syndication endpoint —+ * the same one oEmbed-style embeds use, so a post's attached photos/video+ * resolve to direct CDN URLs without an API key or a headless browser.+ * `extractXPostMedia` reads that endpoint's JSON into `{ images, video }`.+ *+ * Kept pure (string/JSON in → data out) so the URL and extraction rules are+ * unit-tested without a network. The fetching/download orchestration lives in+ * `services/moodBoard/xPost.js`.+ */++import { ServerError } from './errorHandler.js';++// Explicit allow-list (mirrors pinterestFeed.js's registrable-domain check) so+// a lookalike host (x.com.evil.com, evil-x.com) can't slip past a loose+// "ends with x.com" test.+const X_DOMAINS = Object.freeze(['x.com', 'twitter.com']);++function isXHost(host) {+ const h = host.toLowerCase();+ return X_DOMAINS.some((d) => h === d || h.endsWith(`.${d}`));+}++const badUrl = (msg) => new ServerError(msg, { status: 400, code: 'INVALID_X_POST_URL' });++/**+ * Validate + normalize a pasted x.com/twitter.com post URL into+ * `{ statusId, canonicalUrl }`. `canonicalUrl` drops the username segment+ * (`https://x.com/i/status/<id>`, which X itself resolves) so the same post+ * shared under a different handle still dedupes to one board item. Throws a+ * 400 ServerError for a non-URL, non-http(s) scheme, non-X host, or a path+ * that isn't `/<user>/status/<id>`.+ */+export function parseXPostUrl(input) {+ if (typeof input !== 'string' || !input.trim()) {+ throw badUrl('An x.com post URL is required');+ }+ let u;+ try { u = new URL(input.trim()); } catch { throw badUrl('Not a valid URL'); }+ if (u.protocol !== 'http:' && u.protocol !== 'https:') {+ throw badUrl('URL must be http(s)');+ }+ if (!isXHost(u.hostname)) {+ throw badUrl('That doesn’t look like an x.com/twitter.com post URL');+ }+ const match = u.pathname.match(/^\/[^/]+\/status\/(\d+)/);+ if (!match) {+ throw badUrl('Include the full post URL, e.g. x.com/user/status/1234567890');+ }+ const statusId = match[1];+ return { statusId, canonicalUrl: `https://x.com/i/status/${statusId}` };+}++/**+ * The syndication endpoint's access token is derived from the status id by a+ * fixed public formula (used by oEmbed-style embed widgets) — not a secret,+ * just an anti-abuse checksum. `Number(statusId)` loses precision for the+ * largest snowflake ids (>2^53), matching the same known limitation every+ * public consumer of this formula has; a resulting fetch failure surfaces as+ * the normal "could not fetch that post" error rather than a crash.+ */+export function syndicationToken(statusId) {+ return ((Number(statusId) / 1e15) * Math.PI).toString(36).replace(/(0+|\.)/g, '');+}++export function buildSyndicationUrl(statusId) {+ return `https://cdn.syndication.twimg.com/tweet-result?id=${encodeURIComponent(statusId)}&token=${syndicationToken(statusId)}&lang=en`;+}++/**+ * Read the syndication endpoint's JSON into `{ images: string[], video:+ * {url, poster}|null }`. A post carries EITHER photos OR a video/GIF, never+ * both (X's own constraint), but this reads whichever is present without+ * assuming which. `video.variants` may list multiple encodings (mp4 ++ * HLS/`application/x-mpegURL`); only mp4 is downloadable via a plain fetch, so+ * the highest-bitrate mp4 variant is picked. Returns `{ images: [], video:+ * null }` for a malformed/empty payload rather than throwing — the caller+ * decides that's "no media" (400), not a parse crash.+ */+export function extractXPostMedia(json) {+ if (!json || typeof json !== 'object') return { images: [], video: null };+ const images = Array.isArray(json.photos)+ ? json.photos.map((p) => p?.url).filter((u) => typeof u === 'string' && u)+ : [];+ let video = null;+ const variants = json.video?.variants;+ if (Array.isArray(variants)) {+ const mp4Variants = variants.filter((v) => v?.type === 'video/mp4' && typeof v.src === 'string' && v.src);+ if (mp4Variants.length) {+ const best = mp4Variants.reduce((a, b) => ((b.bitrate || 0) > (a.bitrate || 0) ? b : a));+ video = { url: best.src, poster: typeof json.video.poster === 'string' ? json.video.poster : null };+ }+ }+ return { images, video };+}diff --git a/server/lib/xPostMedia.test.js b/server/lib/xPostMedia.test.jsnew file mode 100644index 0000000000..721d96b56e--- /dev/null+++ b/server/lib/xPostMedia.test.js@@ -0,0 +1,115 @@+import { describe, it, expect } from 'vitest';+import { parseXPostUrl, buildSyndicationUrl, syndicationToken, extractXPostMedia } from './xPostMedia.js';++describe('parseXPostUrl', () => {+ it('extracts the status id and canonicalizes to /i/status/<id>', () => {+ expect(parseXPostUrl('https://x.com/someuser/status/1234567890123456789')).toEqual({+ statusId: '1234567890123456789',+ canonicalUrl: 'https://x.com/i/status/1234567890123456789',+ });+ });++ it('accepts twitter.com and www subdomains', () => {+ expect(parseXPostUrl('https://www.twitter.com/someuser/status/42').statusId).toBe('42');+ expect(parseXPostUrl('https://twitter.com/someuser/status/42').statusId).toBe('42');+ });++ it('ignores trailing path segments and query strings', () => {+ expect(parseXPostUrl('https://x.com/someuser/status/42/photo/1?s=20').statusId).toBe('42');+ });++ it('rejects a non-string/empty input', () => {+ expect(() => parseXPostUrl('')).toThrow(/required/i);+ expect(() => parseXPostUrl(null)).toThrow(/required/i);+ });++ it('rejects an unparseable URL', () => {+ expect(() => parseXPostUrl('not a url')).toThrow(/valid url/i);+ });++ it('rejects a non-http(s) scheme', () => {+ expect(() => parseXPostUrl('ftp://x.com/user/status/1')).toThrow(/http/i);+ });++ it('rejects a lookalike host', () => {+ expect(() => parseXPostUrl('https://x.com.evil.com/user/status/1')).toThrow(/doesn.t look like/i);+ expect(() => parseXPostUrl('https://evil-x.com/user/status/1')).toThrow(/doesn.t look like/i);+ expect(() => parseXPostUrl('https://example.com/user/status/1')).toThrow(/doesn.t look like/i);+ });++ it('rejects an X URL that is not a status post', () => {+ expect(() => parseXPostUrl('https://x.com/someuser')).toThrow(/full post url/i);+ expect(() => parseXPostUrl('https://x.com/i/lists/1')).toThrow(/full post url/i);+ });++ it('every ServerError carries the same error code', () => {+ for (const bad of ['', 'ftp://x.com/user/status/1', 'https://example.com/user/status/1', 'https://x.com/user']) {+ try {+ parseXPostUrl(bad);+ throw new Error('expected parseXPostUrl to throw');+ } catch (err) {+ expect(err.status).toBe(400);+ expect(err.code).toBe('INVALID_X_POST_URL');+ }+ }+ });+});++describe('syndicationToken / buildSyndicationUrl', () => {+ it('produces a deterministic non-empty token for a given status id', () => {+ const token = syndicationToken('1234567890123456789');+ expect(typeof token).toBe('string');+ expect(token.length).toBeGreaterThan(0);+ expect(syndicationToken('1234567890123456789')).toBe(token);+ });++ it('builds a syndication URL carrying the id and a token', () => {+ const url = buildSyndicationUrl('42');+ expect(url).toContain('cdn.syndication.twimg.com/tweet-result');+ expect(url).toContain('id=42');+ expect(url).toMatch(/token=[a-z0-9]+/);+ });+});++describe('extractXPostMedia', () => {+ it('returns empty media for malformed input', () => {+ expect(extractXPostMedia(null)).toEqual({ images: [], video: null });+ expect(extractXPostMedia('not json')).toEqual({ images: [], video: null });+ expect(extractXPostMedia({})).toEqual({ images: [], video: null });+ });++ it('extracts photo URLs', () => {+ const { images, video } = extractXPostMedia({+ photos: [{ url: 'https://pbs.twimg.com/media/a.jpg' }, { url: 'https://pbs.twimg.com/media/b.jpg' }],+ });+ expect(images).toEqual(['https://pbs.twimg.com/media/a.jpg', 'https://pbs.twimg.com/media/b.jpg']);+ expect(video).toBeNull();+ });++ it('drops malformed photo entries', () => {+ const { images } = extractXPostMedia({ photos: [{ url: 'ok.jpg' }, {}, { url: 42 }, null] });+ expect(images).toEqual(['ok.jpg']);+ });++ it('picks the highest-bitrate mp4 variant and the poster', () => {+ const { images, video } = extractXPostMedia({+ video: {+ poster: 'https://pbs.twimg.com/poster.jpg',+ variants: [+ { type: 'application/x-mpegURL', src: 'https://video.twimg.com/x.m3u8' },+ { type: 'video/mp4', src: 'https://video.twimg.com/low.mp4', bitrate: 256000 },+ { type: 'video/mp4', src: 'https://video.twimg.com/high.mp4', bitrate: 2176000 },+ ],+ },+ });+ expect(images).toEqual([]);+ expect(video).toEqual({ url: 'https://video.twimg.com/high.mp4', poster: 'https://pbs.twimg.com/poster.jpg' });+ });++ it('returns a null video when only a non-mp4 variant is present', () => {+ const { video } = extractXPostMedia({+ video: { variants: [{ type: 'application/x-mpegURL', src: 'https://video.twimg.com/x.m3u8' }] },+ });+ expect(video).toBeNull();+ });+});diff --git a/server/routes/moodBoard.js b/server/routes/moodBoard.jsindex d4254a0c41..5f2cdda520 100644--- a/server/routes/moodBoard.js+++ b/server/routes/moodBoard.js@@ -17,6 +17,7 @@ import {moodBoardItemCreateSchema,moodBoardItemUpdateSchema,moodBoardPinterestLinkSchema,+ moodBoardXPostImportSchema,isPaginationRequested,paginateArray,} from '../lib/validation.js';@@ -36,6 +37,7 @@ import {linkPinterestBoard,unlinkPinterestBoard,syncPinterestBoard,+ importXPost,} from '../services/moodBoard/index.js';const router = Router();@@ -134,4 +136,12 @@ router.post('/:id/pinterest/sync', asyncHandler(async (req, res) => {res.json(result);}));+// One-shot import: paste a public x.com/twitter.com post URL, pull its+// attached photos/video into the board.+router.post('/:id/x-post', asyncHandler(async (req, res) => {+ const data = validateRequest(moodBoardXPostImportSchema, req.body);+ const result = await importXPost(req.params.id, data);+ res.json(result);+}));+export default router;diff --git a/server/routes/moodBoard.test.js b/server/routes/moodBoard.test.jsindex 325149c46c..8f6e3841aa 100644--- a/server/routes/moodBoard.test.js+++ b/server/routes/moodBoard.test.js@@ -18,6 +18,7 @@ vi.mock('../services/moodBoard/index.js', () => ({linkPinterestBoard: vi.fn(),unlinkPinterestBoard: vi.fn(),syncPinterestBoard: vi.fn(),+ importXPost: vi.fn(),}));// The synthesis service pulls the aiProvider/promptRunner stack — stub it so@@ -125,4 +126,20 @@ describe('mood-board routes', () => {expect(synthesizeBoardStyle).not.toHaveBeenCalled();});});++ describe('POST /:id/x-post', () => {+ it('validates the body and passes it to the service', async () => {+ svc.importXPost.mockResolvedValueOnce({ board: { id: 'mb-1' }, added: 2 });+ const res = await request(makeApp()).post('/api/mood-boards/mb-1/x-post').send({ url: 'https://x.com/user/status/1' });+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ board: { id: 'mb-1' }, added: 2 });+ expect(svc.importXPost).toHaveBeenCalledWith('mb-1', { url: 'https://x.com/user/status/1' });+ });++ it('400s on a non-http(s) url (schema gate)', async () => {+ const res = await request(makeApp()).post('/api/mood-boards/mb-1/x-post').send({ url: 'not a url' });+ expect(res.status).toBe(400);+ expect(svc.importXPost).not.toHaveBeenCalled();+ });+ });});diff --git a/server/services/moodBoard/db.js b/server/services/moodBoard/db.jsindex dd8ff79afc..4f3a8e11fa 100644--- a/server/services/moodBoard/db.js+++ b/server/services/moodBoard/db.js@@ -36,6 +36,7 @@ import {healPinterestFeedRecord,clearPinterestLinkRecord,appendPinterestPins,+ appendImportedItems as appendImportedItemsRecord,} from './logic.js';import {maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,@@ -289,6 +290,17 @@ export async function appendPinterestItems(id, imported, opts = {}) {return { board, ...result };}+// Append already-downloaded one-shot import items (X post importer) in ONE+// locked write. Unlike appendPinterestItems, there's no persisted link to+// stamp or race against — skips the write entirely when nothing new landed.+export async function appendImportedItems(id, imported) {+ const { board, result } = await withLockedBoard(id, (b) => {+ const { board: next, added } = appendImportedItemsRecord(b, imported);+ return { board: next, result: { added }, skipPersist: added === 0 };+ });+ return { board, ...result };+}+export async function removeBoardItem(id, itemId) {// Unknown itemId → skip the write entirely (no-op, no updated_at bump). The// route still 200s — removing an already-gone item is idempotent.diff --git a/server/services/moodBoard/index.js b/server/services/moodBoard/index.jsindex f88d69763f..63b24c1956 100644--- a/server/services/moodBoard/index.js+++ b/server/services/moodBoard/index.js@@ -37,6 +37,12 @@ export { imageUrlToAppAsset } from './logic.js';// moodBoard entry. It fires its own federation emits after each store mutation.export { linkPinterestBoard, unlinkPinterestBoard, syncPinterestBoard } from './pinterest.js';+// X.com (Twitter) post importer — one-shot "paste a post URL, pull its+// photos/video in". Lives in its own module (network I/O + downloads) but+// surfaced here so routes import a single moodBoard entry; fires its own+// federation emit after the store mutation.+export { importXPost } from './xPost.js';+// Announce a newly-created board to the per-record peer-sync pipeline: emit the// 'updated' event so any existing subscription pushes it, AND auto-subscribe// every moodBoards-enabled peer so brand-new boards (and their later tombstones)diff --git a/server/services/moodBoard/logic.js b/server/services/moodBoard/logic.jsindex b99b7279e1..92563b3ae2 100644--- a/server/services/moodBoard/logic.js+++ b/server/services/moodBoard/logic.js@@ -338,15 +338,33 @@ export function clearPinterestLinkRecord(board) {return { board: next, changed: true };}+/**+ * Shared dedupe-by-`source` + MAX_ITEMS_PER_BOARD-capacity core for every+ * "append already-downloaded media as board items" flow (the persisted+ * Pinterest sync below and the one-shot X post importer) — one place owning+ * the truncate-rather-than-throw contract so it can't drift between the two+ * callers. `buildItem(imp)` turns one `imported` entry into a normalized item;+ * the caller decides the rest (what to stamp on the board afterward).+ */+function buildFreshItems(existingItems, imported, buildItem) {+ const seen = new Set(existingItems.map((it) => it && it.source).filter(Boolean));+ const capacity = Math.max(0, MAX_ITEMS_PER_BOARD - existingItems.length);+ const fresh = [];+ for (const imp of Array.isArray(imported) ? imported : []) {+ if (fresh.length >= capacity) break;+ if (imp.source && seen.has(imp.source)) continue;+ if (imp.source) seen.add(imp.source);+ fresh.push(buildItem(imp));+ }+ return fresh;+}+/*** Append already-downloaded Pinterest pins as image items, then stamp the sync* timestamp. Each `imported` entry is `{ imageUrl, caption, source }` where- * `source` is the pin permalink — the dedupe key. Skips pins whose `source`- * already exists on the board (in-lock safety net; the service pre-dedupes- * before downloading) and respects MAX_ITEMS_PER_BOARD by truncating to the- * remaining capacity rather than throwing — a partial import beats a hard- * mid-sync failure. Always re-stamps `pinterest.lastSyncedAt` (even on zero new)- * so the UI reflects the check. Returns `{ board, added, aborted }`.+ * `source` is the pin permalink — the dedupe key (see buildFreshItems). Always+ * re-stamps `pinterest.lastSyncedAt` (even on zero new) so the UI reflects the+ * check. Returns `{ board, added, aborted }`.** `expectedFeedUrl` guards a single-user re-entrancy race: the feed fetch +* image downloads run OUTSIDE the row lock, so the user can unlink or re-link@@ -359,18 +377,10 @@ export function appendPinterestPins(board, imported, { syncedAt = nowIso(), expereturn { board, added: 0, aborted: true };}const items = Array.isArray(board.items) ? board.items : [];- const seen = new Set(items.map((it) => it && it.source).filter(Boolean));- const capacity = Math.max(0, MAX_ITEMS_PER_BOARD - items.length);- const fresh = [];- for (const imp of Array.isArray(imported) ? imported : []) {- if (fresh.length >= capacity) break;- if (imp.source && seen.has(imp.source)) continue;- if (imp.source) seen.add(imp.source);- fresh.push(normalizeItem(- { type: 'image', imageUrl: imp.imageUrl, caption: imp.caption ?? null, source: imp.source ?? null },- { id: `mbi-${randomUUID()}`, now: syncedAt },- ));- }+ const fresh = buildFreshItems(items, imported, (imp) => normalizeItem(+ { type: 'image', imageUrl: imp.imageUrl, caption: imp.caption ?? null, source: imp.source ?? null },+ { id: `mbi-${randomUUID()}`, now: syncedAt },+ ));const next = {...board,items: [...items, ...fresh],@@ -379,3 +389,25 @@ export function appendPinterestPins(board, imported, { syncedAt = nowIso(), expe};return { board: next, added: fresh.length, aborted: false };}++// ─── One-shot media imports (X post importer) ────────────────────────────────++/**+ * Append already-downloaded media items in ONE locked write — same+ * dedupe/capacity core as appendPinterestPins (buildFreshItems), generalized+ * for a one-shot import (X post) that has no persisted link/lastSyncedAt to+ * stamp. Each `imported` entry is `{ type, imageUrl, mediaKey, caption,+ * source }`; `source` is the dedupe key, re-checked here as an in-lock safety+ * net (the service pre-dedupes before downloading, but two concurrent imports+ * of the same post could race between that check and this write). Returns+ * `{ board, added }`.+ */+export function appendImportedItems(board, imported) {+ const items = Array.isArray(board.items) ? board.items : [];+ const fresh = buildFreshItems(items, imported, (imp) => normalizeItem(+ { type: imp.type, imageUrl: imp.imageUrl ?? null, mediaKey: imp.mediaKey ?? null, caption: imp.caption ?? null, source: imp.source ?? null },+ { id: `mbi-${randomUUID()}` },+ ));+ const next = { ...board, items: [...items, ...fresh], updatedAt: nowIso() };+ return { board: next, added: fresh.length };+}diff --git a/server/services/moodBoard/logic.test.js b/server/services/moodBoard/logic.test.jsindex cfd5c66bb7..b2994cdf14 100644--- a/server/services/moodBoard/logic.test.js+++ b/server/services/moodBoard/logic.test.js@@ -20,6 +20,7 @@ import {healPinterestFeedRecord,clearPinterestLinkRecord,appendPinterestPins,+ appendImportedItems,} from './logic.js';describe('buildBoardRecord', () => {@@ -413,3 +414,42 @@ describe('appendPinterestPins', () => {expect(added).toBe(1);});});++describe('appendImportedItems', () => {+ const board = () => buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' });++ it('appends image and video items', () => {+ const { board: next, added } = appendImportedItems(board(), [+ { type: 'image', imageUrl: '/data/images/a.jpg', source: 'https://x.com/i/status/1#0' },+ { type: 'video', mediaKey: 'video:x-abc.mp4', imageUrl: '/data/images/poster.jpg', source: 'https://x.com/i/status/1#video' },+ ]);+ expect(added).toBe(2);+ expect(next.items[0]).toMatchObject({ type: 'image', imageUrl: '/data/images/a.jpg' });+ expect(next.items[1]).toMatchObject({ type: 'video', mediaKey: 'video:x-abc.mp4', imageUrl: '/data/images/poster.jpg' });+ });++ it('dedupes against existing item sources', () => {+ const existing = { ...board(), items: [{ id: 'mbi-x', type: 'image', source: 'https://x.com/i/status/1#0' }] };+ const { added, board: next } = appendImportedItems(existing, [+ { type: 'image', imageUrl: '/data/images/a.jpg', source: 'https://x.com/i/status/1#0' },+ { type: 'image', imageUrl: '/data/images/b.jpg', source: 'https://x.com/i/status/1#1' },+ ]);+ expect(added).toBe(1);+ expect(next.items).toHaveLength(2);+ });++ it('truncates to MAX_ITEMS_PER_BOARD capacity', () => {+ const full = { ...board(), items: Array.from({ length: MAX_ITEMS_PER_BOARD - 1 }, (_, i) => ({ id: `e${i}`, type: 'image', source: `e${i}` })) };+ const { added } = appendImportedItems(full, [+ { type: 'image', imageUrl: '/data/images/a.jpg', source: 's1' },+ { type: 'image', imageUrl: '/data/images/b.jpg', source: 's2' },+ ]);+ expect(added).toBe(1);+ });++ it('handles an empty/non-array imported list', () => {+ const { added, board: next } = appendImportedItems(board(), []);+ expect(added).toBe(0);+ expect(next.items).toEqual([]);+ });+});diff --git a/server/services/moodBoard/xPost.js b/server/services/moodBoard/xPost.jsnew file mode 100644index 0000000000..1a0260b0b5--- /dev/null+++ b/server/services/moodBoard/xPost.js@@ -0,0 +1,151 @@+/**+ * Mood Board — X.com (Twitter) post importer.+ *+ * Paste a public x.com/twitter.com post URL and pull its attached photos/video+ * into the board as re-hosted local assets — mirrors the Pinterest importer's+ * "fetch → download → dedupe → append in one locked write" shape (pinterest.js),+ * but this is a ONE-SHOT import, not a persisted link+sync: there's no ongoing+ * feed to track, so nothing is stored on the board beyond the resulting items.+ *+ * Uses Twitter's public, unauthenticated tweet-syndication endpoint (the same+ * one oEmbed-style embeds use) to read a post's attached media without an API+ * key, a scraper, or a headless browser (xPostMedia.js owns that parsing, pure+ * and unit-tested). Both a post's photos and its video/GIF resolve to direct+ * CDN URLs, downloaded through the same SSRF-guarded fetch Pinterest uses and+ * re-hosted under data/images / data/videos so the board survives link rot.+ */++import { createHash } from 'crypto';+import { unlink } from 'fs/promises';+import { join, basename } from 'path';+import { ServerError } from '../../lib/errorHandler.js';+import { PATHS, ensureDir, detectImageFormat, detectVideoFormat, writeFileGuarded } from '../../lib/fileUtils.js';+import { parseXPostUrl, buildSyndicationUrl, extractXPostMedia } from '../../lib/xPostMedia.js';+import { fetchPublicText, fetchPublicBinary } from '../../lib/safeUrlFetch.js';+import { emitRecordUpdated } from '../sharing/recordEvents.js';+import { MAX_ITEMS_PER_BOARD } from './logic.js';+import * as store from './db.js';++const FETCH_TIMEOUT_MS = 20000;+const VIDEO_TIMEOUT_MS = 60000;+const MAX_IMAGE_BYTES = 12 * 1024 * 1024;+const MAX_VIDEO_BYTES = 200 * 1024 * 1024;+// X's CDN (like Pinterest's) 403s obviously-bot user-agents; present a browsery one.+const X_UA = 'Mozilla/5.0 (compatible; PortOS Mood Board/1.0; +https://github.com/atomantic/PortOS)';+const JSON_HEADERS = { 'User-Agent': X_UA, Accept: 'application/json' };+const MEDIA_HEADERS = { 'User-Agent': X_UA, Accept: '*/*' };++function fingerprint(canonicalUrl, tag) {+ return createHash('sha1').update(`${canonicalUrl}#${tag}`).digest('hex').slice(0, 16);+}++// Download an image (photo or video poster) into data/images/, sniffing the+// format from bytes (never trusting Content-Type) — same posture as Pinterest's+// downloadPinImage. Returns the served path, or null on any failure.+async function downloadImage(url, canonicalUrl, tag) {+ const res = await fetchPublicBinary(url, { timeoutMs: FETCH_TIMEOUT_MS, headers: MEDIA_HEADERS, maxBytes: MAX_IMAGE_BYTES });+ if (!res?.buffer?.length) return null;+ const fmt = detectImageFormat(res.buffer);+ if (!fmt) return null;+ const filename = `x-${fingerprint(canonicalUrl, tag)}${fmt.ext}`;+ await writeFileGuarded(join(PATHS.images, filename), res.buffer);+ return `/data/images/${filename}`;+}++// Download the post's video/GIF (X serves a looping GIF as an mp4) into+// data/videos/, sniffing the container from bytes (X's video CDN doesn't+// reliably set Content-Type). Returns the on-disk FILENAME (not a served path+// — video items' mediaKey carries the filename, matching+// handlePickGalleryVideo's shape), or null on any failure.+async function downloadVideo(url, canonicalUrl) {+ const res = await fetchPublicBinary(url, { timeoutMs: VIDEO_TIMEOUT_MS, headers: MEDIA_HEADERS, maxBytes: MAX_VIDEO_BYTES });+ if (!res?.buffer?.length || !detectVideoFormat(res.buffer)) return null;+ const filename = `x-${fingerprint(canonicalUrl, 'video')}.mp4`;+ await writeFileGuarded(join(PATHS.videos, filename), res.buffer);+ return filename;+}++/**+ * Import a public x.com/twitter.com post's photos/video into a board. Fetches+ * the post's attached media via Twitter's public syndication endpoint (no API+ * key), downloads each into the local gallery, and appends the new items in+ * one locked write — deduping by a per-item `source` (`<canonical post+ * url>#0`, `#video`, …) so re-importing the same post is a no-op. Downloads run+ * OUTSIDE the board row lock, same as the Pinterest sync.+ *+ * Throws 404 (no board), 400 (not an x.com/twitter.com post URL, or the post+ * has no photos/video attached), or 502 (the post or its media couldn't be+ * fetched).+ *+ * @returns {Promise<{ board: object, added: number }>}+ */+export async function importXPost(boardId, { url }) {+ const { statusId, canonicalUrl } = parseXPostUrl(url);++ // Independent lookups (board row vs. the post's media) — run concurrently.+ const [board, raw] = await Promise.all([+ store.getBoard(boardId),+ fetchPublicText(buildSyndicationUrl(statusId), { timeoutMs: FETCH_TIMEOUT_MS, headers: JSON_HEADERS }),+ ]);+ if (!board) throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });+ if (!raw) {+ throw new ServerError('Could not fetch that post (it may be private, deleted, or rate-limited)', {+ status: 502, code: 'X_POST_FETCH_FAILED',+ });+ }+ let json;+ try {+ json = JSON.parse(raw);+ } catch {+ throw new ServerError('Could not read that post’s media', { status: 502, code: 'X_POST_FETCH_FAILED' });+ }++ const { images, video } = extractXPostMedia(json);+ if (!images.length && !video) {+ throw new ServerError('That post has no photos or video attached', { status: 400, code: 'NO_MEDIA_FOUND' });+ }++ const items = Array.isArray(board.items) ? board.items : [];+ const seen = new Set(items.map((it) => it?.source).filter(Boolean));+ const capacity = Math.max(0, MAX_ITEMS_PER_BOARD - items.length);++ await ensureDir(PATHS.images);+ const imported = [];+ for (let i = 0; i < images.length && imported.length < capacity; i++) {+ const source = `${canonicalUrl}#${i}`;+ if (seen.has(source)) continue;+ const imageUrl = await downloadImage(images[i], canonicalUrl, String(i));+ if (imageUrl) imported.push({ type: 'image', imageUrl, source, caption: null });+ }+ if (video && imported.length < capacity) {+ const source = `${canonicalUrl}#video`;+ if (!seen.has(source)) {+ await ensureDir(PATHS.videos);+ // The video body and its poster are independent CDN downloads — run+ // them concurrently rather than one after the other.+ const [filename, poster] = await Promise.all([+ downloadVideo(video.url, canonicalUrl),+ video.poster ? downloadImage(video.poster, canonicalUrl, 'poster') : Promise.resolve(null),+ ]);+ if (filename) {+ imported.push({ type: 'video', mediaKey: `video:${filename}`, imageUrl: poster, source, caption: null });+ } else if (poster) {+ // The video failed but its poster downloaded first (they ran in+ // parallel) — nothing will ever reference it, so remove it rather+ // than leaving an orphaned file in data/images.+ await unlink(join(PATHS.images, basename(poster))).catch(() => {});+ }+ }+ }++ if (!imported.length) {+ throw new ServerError('Could not download that post’s media (the CDN links may have expired or be geo-restricted)', {+ status: 502, code: 'X_POST_DOWNLOAD_FAILED',+ });+ }++ const { board: nextBoard, added } = await store.appendImportedItems(boardId, imported);+ emitRecordUpdated('moodBoard', boardId);+ console.log(`🐦 X post import: board ${boardId} +${added} item(s) from ${canonicalUrl}`);+ return { board: nextBoard, added };+}diff --git a/server/services/moodBoard/xPost.test.js b/server/services/moodBoard/xPost.test.jsnew file mode 100644index 0000000000..4769b5a550--- /dev/null+++ b/server/services/moodBoard/xPost.test.js@@ -0,0 +1,163 @@+/**+ * X post importer orchestration tests. The network (safeUrlFetch), the board+ * store (db.js), disk (fs/promises + fileUtils), and the federation emit are+ * mocked; the real pure parser (xPostMedia) runs so the URL→fetch→media→item+ * pipeline is exercised end to end without a DB or network.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const store = {+ getBoard: vi.fn(),+ appendImportedItems: vi.fn(),+};+vi.mock('./db.js', () => store);++const net = { fetchPublicText: vi.fn(), fetchPublicBinary: vi.fn() };+vi.mock('../../lib/safeUrlFetch.js', () => net);++const emitRecordUpdated = vi.fn();+vi.mock('../sharing/recordEvents.js', () => ({ emitRecordUpdated: (...a) => emitRecordUpdated(...a) }));++const writeFile = vi.fn();+const unlink = vi.fn(async () => {});+vi.mock('fs/promises', () => ({ writeFile: (...a) => writeFile(...a), unlink: (...a) => unlink(...a) }));+// Keep the real detectImageFormat (byte-sniffing) — only override PATHS/ensureDir.+vi.mock('../../lib/fileUtils.js', async (importOriginal) => ({+ ...(await importOriginal()),+ PATHS: { images: '/tmp/imgs', videos: '/tmp/vids' },+ ensureDir: vi.fn(),+}));++const { importXPost } = await import('./xPost.js');++const JPEG_BYTES = Buffer.from([0xff, 0xd8, 0xff, 0x00]);+const mp4Bytes = () => Buffer.concat([Buffer.alloc(4), Buffer.from('ftyp'), Buffer.alloc(20)]);++const POST_URL = 'https://x.com/someuser/status/42';+const CANONICAL = 'https://x.com/i/status/42';++beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(console, 'log').mockImplementation(() => {});+});++describe('importXPost', () => {+ it('rejects a non-X URL before touching the store', async () => {+ await expect(importXPost('mb-1', { url: 'https://example.com/x' })).rejects.toMatchObject({ status: 400 });+ expect(store.getBoard).not.toHaveBeenCalled();+ });++ it('404s when the board is missing', async () => {+ store.getBoard.mockResolvedValue(null);+ await expect(importXPost('mb-x', { url: POST_URL })).rejects.toMatchObject({ status: 404 });+ });++ it('502s when the post cannot be fetched', async () => {+ store.getBoard.mockResolvedValue({ id: 'mb-1', items: [] });+ net.fetchPublicText.mockResolvedValue(null);+ await expect(importXPost('mb-1', { url: POST_URL })).rejects.toMatchObject({ status: 502, code: 'X_POST_FETCH_FAILED' });+ });++ it('502s on unparseable JSON', async () => {+ store.getBoard.mockResolvedValue({ id: 'mb-1', items: [] });+ net.fetchPublicText.mockResolvedValue('not json');+ await expect(importXPost('mb-1', { url: POST_URL })).rejects.toMatchObject({ status: 502, code: 'X_POST_FETCH_FAILED' });+ });++ it('400s when the post has no photos or video', async () => {+ store.getBoard.mockResolvedValue({ id: 'mb-1', items: [] });+ net.fetchPublicText.mockResolvedValue(JSON.stringify({}));+ await expect(importXPost('mb-1', { url: POST_URL })).rejects.toMatchObject({ status: 400, code: 'NO_MEDIA_FOUND' });+ });++ it('downloads photos and appends them, deduping by source', async () => {+ store.getBoard.mockResolvedValue({+ id: 'mb-1',+ // photo #0 already on the board → should be deduped out+ items: [{ id: 'mbi-old', type: 'image', source: `${CANONICAL}#0` }],+ });+ net.fetchPublicText.mockResolvedValue(JSON.stringify({+ photos: [{ url: 'https://pbs.twimg.com/a.jpg' }, { url: 'https://pbs.twimg.com/b.jpg' }],+ }));+ net.fetchPublicBinary.mockResolvedValue({ buffer: JPEG_BYTES, contentType: 'image/jpeg' });+ store.appendImportedItems.mockImplementation(async (_id, imported) => ({ board: { id: 'mb-1' }, added: imported.length }));++ const result = await importXPost('mb-1', { url: POST_URL });++ // only photo #1 was downloaded (photo #0 deduped before fetching)+ expect(net.fetchPublicBinary).toHaveBeenCalledTimes(1);+ expect(net.fetchPublicBinary.mock.calls[0][0]).toBe('https://pbs.twimg.com/b.jpg');+ expect(writeFile).toHaveBeenCalledTimes(1);++ const [, imported] = store.appendImportedItems.mock.calls[0];+ expect(imported).toHaveLength(1);+ expect(imported[0]).toMatchObject({ type: 'image', source: `${CANONICAL}#1` });+ expect(imported[0].imageUrl).toMatch(/^\/data\/images\/x-[0-9a-f]{16}\.jpg$/);+ expect(result).toMatchObject({ added: 1 });+ expect(emitRecordUpdated).toHaveBeenCalledWith('moodBoard', 'mb-1');+ });++ it('downloads a video + poster and appends a video item', async () => {+ store.getBoard.mockResolvedValue({ id: 'mb-1', items: [] });+ net.fetchPublicText.mockResolvedValue(JSON.stringify({+ video: {+ poster: 'https://pbs.twimg.com/poster.jpg',+ variants: [{ type: 'video/mp4', src: 'https://video.twimg.com/v.mp4', bitrate: 1000 }],+ },+ }));+ net.fetchPublicBinary.mockImplementation(async (url) => (+ url === 'https://video.twimg.com/v.mp4'+ ? { buffer: mp4Bytes(), contentType: 'video/mp4' }+ : { buffer: JPEG_BYTES, contentType: 'image/jpeg' }+ ));+ store.appendImportedItems.mockImplementation(async (_id, imported) => ({ board: { id: 'mb-1' }, added: imported.length }));++ await importXPost('mb-1', { url: POST_URL });++ const [, imported] = store.appendImportedItems.mock.calls[0];+ expect(imported).toHaveLength(1);+ expect(imported[0]).toMatchObject({ type: 'video', source: `${CANONICAL}#video` });+ expect(imported[0].mediaKey).toMatch(/^video:x-[0-9a-f]{16}\.mp4$/);+ expect(imported[0].imageUrl).toMatch(/^\/data\/images\/x-[0-9a-f]{16}\.jpg$/);+ });++ it('502s when media exists but every download fails', async () => {+ store.getBoard.mockResolvedValue({ id: 'mb-1', items: [] });+ net.fetchPublicText.mockResolvedValue(JSON.stringify({ photos: [{ url: 'https://pbs.twimg.com/a.jpg' }] }));+ net.fetchPublicBinary.mockResolvedValue({ buffer: Buffer.from('<html>'), contentType: 'text/html' });++ await expect(importXPost('mb-1', { url: POST_URL })).rejects.toMatchObject({ status: 502, code: 'X_POST_DOWNLOAD_FAILED' });+ expect(store.appendImportedItems).not.toHaveBeenCalled();+ });++ it('rejects a video download whose bytes are not an mp4 container', async () => {+ store.getBoard.mockResolvedValue({ id: 'mb-1', items: [] });+ net.fetchPublicText.mockResolvedValue(JSON.stringify({+ video: { variants: [{ type: 'video/mp4', src: 'https://video.twimg.com/v.mp4', bitrate: 1000 }] },+ }));+ net.fetchPublicBinary.mockResolvedValue({ buffer: Buffer.from('<html>not a video</html>'), contentType: 'video/mp4' });++ await expect(importXPost('mb-1', { url: POST_URL })).rejects.toMatchObject({ status: 502, code: 'X_POST_DOWNLOAD_FAILED' });+ });++ it('deletes an orphaned poster when the video body fails but the poster downloaded (they run in parallel)', async () => {+ store.getBoard.mockResolvedValue({ id: 'mb-1', items: [] });+ net.fetchPublicText.mockResolvedValue(JSON.stringify({+ video: {+ poster: 'https://pbs.twimg.com/poster.jpg',+ variants: [{ type: 'video/mp4', src: 'https://video.twimg.com/v.mp4', bitrate: 1000 }],+ },+ }));+ net.fetchPublicBinary.mockImplementation(async (url) => (+ url === 'https://video.twimg.com/v.mp4'+ ? { buffer: Buffer.from('<html>not a video</html>'), contentType: 'video/mp4' } // video body fails+ : { buffer: JPEG_BYTES, contentType: 'image/jpeg' } // poster succeeds+ ));++ await expect(importXPost('mb-1', { url: POST_URL })).rejects.toMatchObject({ status: 502, code: 'X_POST_DOWNLOAD_FAILED' });+ expect(unlink).toHaveBeenCalledTimes(1);+ expect(unlink.mock.calls[0][0]).toMatch(/^\/tmp\/imgs\/x-[0-9a-f]{16}\.jpg$/);+ expect(store.appendImportedItems).not.toHaveBeenCalled();+ });+});