Skip to content

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

feat: import private Pinterest boards through the signed-in browser

[._.]/ Adam Eivybdbf160f56f8
diff --git a/client/src/pages/MoodBoardDetail.jsx b/client/src/pages/MoodBoardDetail.jsx
index 73f120170c..d1ab1164d6 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, AtSign } from 'lucide-react';
+import { ArrowLeft, ImageIcon, FileText, Trash2, Plus, Save, Link2, Unlink, RefreshCw, Images, Film, Play, ScanEye, Copy, AtSign, Download } 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,
+ importMoodBoardPinterest,
importMoodBoardXPost,
} from '../services/api';
import { moodBoardItemSrc, moodBoardItemVideoSrc, moodBoardItemAnalysisSource } from '../lib/moodBoardItemSrc';
@@ -73,6 +74,7 @@ function MoodBoardEditor({ id }) {
const [pinUrl, setPinUrl] = useState('');
const [linking, setLinking] = useState(false);
const [syncing, setSyncing] = useState(false);
+ const [importingPinterest, setImportingPinterest] = useState(false);
const [confirmingUnlink, setConfirmingUnlink] = useState(false);
// X.com (Twitter) post import — one-shot, no persisted link.
@@ -280,6 +282,23 @@ function MoodBoardEditor({ id }) {
: 'Up to date — no new pins');
};
+ const handleImportPinterest = async () => {
+ if (!mountedRef.current) return;
+ if (!pinUrl.trim()) { toast.error('Enter a Pinterest board URL'); return; }
+ setImportingPinterest(true);
+ const result = await importMoodBoardPinterest(id, pinUrl.trim(), { silent: true }).catch(() => null);
+ if (!mountedRef.current) return;
+ setImportingPinterest(false);
+ if (!result?.board) {
+ toast.error('Could not import that board — check that Pinterest is signed in to the PortOS browser');
+ return;
+ }
+ setBoard(result.board);
+ toast.success(result.added > 0
+ ? `Added ${result.added} of ${result.found} Pinterest pins`
+ : result.found > 0 ? 'No new Pinterest pins were added' : 'The Pinterest board has no pins');
+ };
+
const handleImportXPost = async () => {
if (!mountedRef.current) return;
if (!xPostUrl.trim()) { toast.error('Enter an x.com/twitter.com post URL'); return; }
@@ -344,11 +363,20 @@ function MoodBoardEditor({ id }) {
<button
type="button"
onClick={handleLinkPinterest}
- disabled={linking || !pinUrl.trim() || (isLinked && !pinDirty)}
+ disabled={linking || importingPinterest || !pinUrl.trim() || (isLinked && !pinDirty)}
className="px-3 py-1.5 text-sm rounded bg-port-success text-white hover:bg-port-success/80 disabled:opacity-50 transition-colors"
>
{linking ? 'Linking…' : buttonText}
</button>
+ <button
+ type="button"
+ onClick={handleImportPinterest}
+ disabled={importingPinterest || linking || syncing || !pinUrl.trim()}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50 transition-colors"
+ >
+ <Download className={`w-4 h-4 ${importingPinterest ? 'animate-pulse' : ''}`} aria-hidden="true" />
+ {importingPinterest ? 'Importing…' : 'Import pins'}
+ </button>
</div>
</div>
);
@@ -425,11 +453,14 @@ function MoodBoardEditor({ id }) {
<p className="text-[11px] text-gray-500">
Pinterest’s feed exposes only the most-recent ~25 pins, so a sync pulls those — not the entire board.
</p>
+ <p className="text-[11px] text-gray-500">
+ Use “Import pins” below to read the full board from your signed-in PortOS browser.
+ </p>
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
onClick={handleSyncPinterest}
- disabled={syncing || linking || pinDirty}
+ disabled={syncing || linking || importingPinterest || pinDirty}
title={pinDirty ? 'Link the new URL before syncing' : undefined}
className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50 transition-colors"
>
@@ -459,7 +490,7 @@ function MoodBoardEditor({ id }) {
<div>
{renderPinUrlForm('Board URL', 'Link')}
<p className="text-[11px] text-gray-500 mt-2">
- Paste a public Pinterest board URL. “Sync now” downloads its pins (newest ~25) into this board.
+ Link a public board to sync its newest ~25 pins. “Import pins” reads the full board from your signed-in PortOS browser and saves the images here.
</p>
</div>
)}
diff --git a/client/src/pages/MoodBoardDetail.test.jsx b/client/src/pages/MoodBoardDetail.test.jsx
index 0275b96a3e..c16bb68939 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 mockImportMoodBoardPinterest = vi.fn();
const mockImportMoodBoardXPost = vi.fn();
vi.mock('../services/api', () => ({
@@ -21,6 +22,7 @@ vi.mock('../services/api', () => ({
linkMoodBoardPinterest: vi.fn(),
unlinkMoodBoardPinterest: vi.fn(),
syncMoodBoardPinterest: (...args) => mockSyncMoodBoardPinterest(...args),
+ importMoodBoardPinterest: (...args) => mockImportMoodBoardPinterest(...args),
importMoodBoardXPost: (...args) => mockImportMoodBoardXPost(...args),
}));
@@ -231,6 +233,34 @@ describe('MoodBoardDetail stale-response guards', () => {
});
});
+describe('MoodBoardDetail private Pinterest import', () => {
+ it('imports a board directly through the signed-in PortOS browser action', async () => {
+ const boardUrl = 'https://www.pinterest.com/example-user/example-board/';
+ const importedBoard = {
+ id: 'a',
+ name: 'Board A',
+ items: [{
+ id: 'mbi-1',
+ type: 'image',
+ imageUrl: '/data/images/pinterest-example.jpg',
+ caption: 'Example pin',
+ source: 'https://www.pinterest.com/pin/9999999999999999999/',
+ }],
+ };
+ mockGetMoodBoard.mockResolvedValueOnce({ id: 'a', name: 'Board A', items: [] });
+ mockImportMoodBoardPinterest.mockResolvedValueOnce({ board: importedBoard, added: 1, found: 1, skipped: 0 });
+ renderPage();
+ await waitFor(() => expect(boardNameValue()).toBe('Board A'));
+
+ fireEvent.change(screen.getByLabelText('Board URL'), { target: { value: boardUrl } });
+ fireEvent.click(screen.getByRole('button', { name: 'Import pins' }));
+
+ await waitFor(() => expect(mockToastSuccess).toHaveBeenCalledWith('Added 1 of 1 Pinterest pins'));
+ expect(mockImportMoodBoardPinterest).toHaveBeenCalledWith('a', boardUrl, { silent: true });
+ expect(screen.getByAltText('Example pin')).toHaveAttribute('src', '/data/images/pinterest-example.jpg');
+ });
+});
+
describe('MoodBoardDetail X post import', () => {
it('imports a post URL and merges the returned board', async () => {
mockGetMoodBoard.mockResolvedValueOnce({ id: 'a', name: 'Board A', items: [] });
diff --git a/client/src/services/apiMoodBoard.js b/client/src/services/apiMoodBoard.js
index 7313d03196..9b2c66c9c2 100644
--- a/client/src/services/apiMoodBoard.js
+++ b/client/src/services/apiMoodBoard.js
@@ -83,6 +83,15 @@ export const syncMoodBoardPinterest = (id, options) =>
...options,
});
+// One-shot import through the signed-in PortOS CDP browser. Resolves
+// `{ board, added, found, skipped }`; no credentials or recurring link stored.
+export const importMoodBoardPinterest = (id, url, options) =>
+ request(`/mood-boards/${encodeURIComponent(id)}/pinterest/import`, {
+ method: 'POST',
+ body: JSON.stringify({ url }),
+ ...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) =>
diff --git a/server/routes/moodBoard.js b/server/routes/moodBoard.js
index 5f2cdda520..950c6142e6 100644
--- a/server/routes/moodBoard.js
+++ b/server/routes/moodBoard.js
@@ -37,6 +37,7 @@ import {
linkPinterestBoard,
unlinkPinterestBoard,
syncPinterestBoard,
+ importPrivatePinterestBoard,
importXPost,
} from '../services/moodBoard/index.js';
@@ -136,6 +137,14 @@ router.post('/:id/pinterest/sync', asyncHandler(async (req, res) => {
res.json(result);
}));
+// One-shot import through the signed-in PortOS CDP browser. No Pinterest
+// credentials are stored and this does not create a background sync.
+router.post('/:id/pinterest/import', asyncHandler(async (req, res) => {
+ const data = validateRequest(moodBoardPinterestLinkSchema, req.body);
+ const result = await importPrivatePinterestBoard(req.params.id, data);
+ 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) => {
diff --git a/server/services/moodBoard/index.js b/server/services/moodBoard/index.js
index 63b24c1956..945260201c 100644
--- a/server/services/moodBoard/index.js
+++ b/server/services/moodBoard/index.js
@@ -36,6 +36,7 @@ export { imageUrlToAppAsset } from './logic.js';
// (network I/O + image download) but is surfaced here so routes import a single
// moodBoard entry. It fires its own federation emits after each store mutation.
export { linkPinterestBoard, unlinkPinterestBoard, syncPinterestBoard } from './pinterest.js';
+export { importPrivatePinterestBoard } from './privatePinterest.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
diff --git a/server/services/moodBoard/pinterest.js b/server/services/moodBoard/pinterest.js
index 9a2ec4c856..40fb2f8549 100644
--- a/server/services/moodBoard/pinterest.js
+++ b/server/services/moodBoard/pinterest.js
@@ -47,7 +47,7 @@ const DOWNLOAD_CONCURRENCY = 3;
* also rejects a non-image body (an error/HTML page served with 200) — more
* trustworthy than Pinterest's Content-Type header.
*/
-async function downloadPinImage({ pinUrl, imageUrl, imageUrlOriginal }) {
+export async function downloadPinImage({ pinUrl, imageUrl, imageUrlOriginal }) {
let res = await fetchPublicBinary(imageUrl, { timeoutMs: IMAGE_TIMEOUT_MS, headers: IMAGE_HEADERS, maxBytes: MAX_IMAGE_BYTES });
if (!res?.buffer?.length && imageUrlOriginal && imageUrlOriginal !== imageUrl) {
res = await fetchPublicBinary(imageUrlOriginal, { timeoutMs: IMAGE_TIMEOUT_MS, headers: IMAGE_HEADERS, maxBytes: MAX_IMAGE_BYTES });
diff --git a/server/services/moodBoard/privatePinterest.js b/server/services/moodBoard/privatePinterest.js
new file mode 100644
index 0000000000..6cf196a9cd
--- /dev/null
+++ b/server/services/moodBoard/privatePinterest.js
@@ -0,0 +1,237 @@
+/**
+ * One-shot import for Pinterest boards that are visible only to the signed-in
+ * PortOS browser profile. The page read is pinned through the browser service's
+ * CDP SSRF guard; only Pinterest pin permalinks and i.pinimg.com image URLs
+ * leave the page, and the images are re-hosted into the normal mood-board asset
+ * store. No cookies, credentials, or recurring sync state are persisted.
+ */
+
+import { ServerError } from '../../lib/errorHandler.js';
+import { PATHS, ensureDir } from '../../lib/fileUtils.js';
+import { isBlockedIngestHost } from '../../lib/catalogValidation.js';
+import { normalizePinterestFeedUrl } from '../../lib/pinterestFeed.js';
+import { getHealthStatus, navigateToUrlPinned } from '../browserService.js';
+import { emitRecordUpdated } from '../sharing/recordEvents.js';
+import { MAX_ITEMS_PER_BOARD } from './logic.js';
+import * as store from './db.js';
+import { downloadPinImage } from './pinterest.js';
+
+const PINTEREST_PAGE_SETTLE_MS = 2500;
+// The pinned DOM scan can take up to roughly 58 seconds: a 32 × 250 ms
+// board-title wait, one 300 ms reset, then 140 × 350 ms scroll/load steps.
+const PINTEREST_PAGE_READ_TIMEOUT_MS = 70000;
+const DOWNLOAD_CONCURRENCY = 3;
+
+// Runs only on the user-triggered import path. The page is opened in a fresh
+// tab in the PortOS browser's existing profile, and the bounded scroll loop
+// collects only the board's pin grid (never recommendation carousels).
+const PINTEREST_BOARD_SNAPSHOT_EXPRESSION = `(() => new Promise(async (resolve) => {
+ const maxPins = __MAX_PINS__;
+ const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
+ const boardTitle = () => (document.querySelector('#board-name')?.innerText || '').trim();
+ const isLoginPage = () => /^\\/(?:login|session\\/login)(?:\\/|$)/i.test(location.pathname)
+ || Boolean(document.querySelector('input[type="password"]'))
+ || (!boardTitle() && /log in to pinterest|sign in to pinterest/i.test(document.body?.innerText || ''));
+ const expectedPinCount = () => {
+ const text = (document.body?.innerText || '').slice(0, 5000);
+ const match = text.match(/\\b([\\d,]+)\\s+Pins?\\b/i);
+ return match ? Number(match[1].replace(/,/g, '')) : null;
+ };
+ const pins = new Map();
+ const safeImageUrl = (raw) => {
+ try {
+ const url = new URL(raw, location.href);
+ return url.protocol === 'https:' && url.hostname === 'i.pinimg.com' ? url.href : '';
+ } catch {
+ return '';
+ }
+ };
+ const collect = () => {
+ const grid = document.querySelector('[data-test-id="masonry-container"]');
+ if (!grid) return;
+ for (const anchor of grid.querySelectorAll('a[href*="/pin/"]')) {
+ let pin;
+ try { pin = new URL(anchor.href); } catch { continue; }
+ if (!['www.pinterest.com', 'pinterest.com'].includes(pin.hostname)) continue;
+ const pinId = pin.pathname.match(/^\\/pin\\/(\\d+)\\/?$/)?.[1];
+ if (!pinId) continue;
+ const source = 'https://www.pinterest.com/pin/' + pinId + '/';
+ if (anchor.closest('[data-test-id="carousel-pin"]')) continue;
+ const card = anchor.closest('[data-test-id="pin"]') || anchor;
+ const img = card.querySelector('img');
+ const srcset = (img?.getAttribute('srcset') || img?.getAttribute('data-srcset') || '')
+ .split(',').map((entry) => entry.trim().split(/\\s+/)[0]).filter(Boolean);
+ const imageCandidates = [...new Set([
+ ...srcset,
+ img?.currentSrc,
+ img?.getAttribute('data-src'),
+ img?.src,
+ ].map(safeImageUrl).filter(Boolean))];
+ const original = imageCandidates.find((url) => url.includes('/originals/')) || '';
+ const imageUrl = imageCandidates.find((url) => url.includes('/736x/'))
+ || imageCandidates.find((url) => url.includes('/474x/'))
+ || imageCandidates[0]
+ || '';
+ const rawCaption = (img?.alt
+ || card.querySelector('h1,h2,h3,[data-test-id*="title"]')?.textContent
+ || '').replace(/^This may contain:\\s*/i, '').trim();
+ const prior = pins.get(source) || {};
+ pins.set(source, {
+ source,
+ imageUrl: imageUrl || prior.imageUrl || '',
+ imageUrlOriginal: original || prior.imageUrlOriginal || '',
+ caption: rawCaption || prior.caption || null,
+ });
+ }
+ };
+
+ for (let i = 0; i < 32 && !boardTitle() && !isLoginPage(); i++) await sleep(250);
+ const loginRequired = isLoginPage();
+ const expectedCount = expectedPinCount();
+ if (loginRequired || !boardTitle()) {
+ resolve({ loginRequired, boardTitle: boardTitle(), expectedCount, pins: [] });
+ return;
+ }
+
+ window.scrollTo(0, 0);
+ await sleep(300);
+ const targetCount = Math.min(expectedCount ?? maxPins, maxPins);
+ const hasEnoughPinsAndImages = () => pins.size >= targetCount
+ && [...pins.values()].filter((pin) => pin.imageUrl).length >= targetCount;
+ let stableAtBottom = 0;
+ let lastProgress = '';
+ let lastY = -1;
+ for (let i = 0; i < 140; i++) {
+ collect();
+ const progress = () => [pins.size, [...pins.values()].filter((pin) => pin.imageUrl).length].join(':');
+ if (hasEnoughPinsAndImages()) break;
+
+ const beforeY = window.scrollY;
+ const beforeProgress = progress();
+ window.scrollBy(0, Math.max(500, Math.round(window.innerHeight * 0.8)));
+ await sleep(350);
+ collect();
+
+ const pageHeight = Math.max(document.documentElement.scrollHeight, document.body?.scrollHeight || 0);
+ const atBottom = window.scrollY + window.innerHeight >= pageHeight - 8;
+ const currentProgress = progress();
+ const noProgress = window.scrollY <= beforeY + 1 && currentProgress === beforeProgress;
+ stableAtBottom = atBottom && (noProgress || (currentProgress === lastProgress && window.scrollY === lastY))
+ ? stableAtBottom + 1
+ : 0;
+ lastProgress = currentProgress;
+ lastY = window.scrollY;
+ if (stableAtBottom >= 8) break;
+ }
+ collect();
+ resolve({ boardTitle: boardTitle(), loginRequired: false, expectedCount, pins: [...pins.values()].slice(0, maxPins) });
+}))()` .replace('__MAX_PINS__', String(MAX_ITEMS_PER_BOARD));
+
+function sameBoardPath(left, right) {
+ const leftPath = new URL(left).pathname.replace(/\/+$/, '');
+ const rightPath = new URL(right).pathname.replace(/\/+$/, '');
+ return leftPath === rightPath;
+}
+
+/**
+ * Import the visible pins from a private Pinterest board using the signed-in
+ * PortOS CDP browser. Images download outside the mood-board row lock, then the
+ * store performs a locked, source-deduplicated append.
+ *
+ * @returns {Promise<{ board: object, added: number, found: number, skipped: number }>}
+ */
+export async function importPrivatePinterestBoard(boardId, { url }) {
+ const { boardUrl } = normalizePinterestFeedUrl(url);
+ const board = await store.getBoard(boardId);
+ if (!board) throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });
+
+ const browser = await getHealthStatus();
+ if (!browser.connected) {
+ throw new ServerError('The PortOS browser is not running', { status: 503, code: 'BROWSER_UNAVAILABLE' });
+ }
+
+ const page = await navigateToUrlPinned(boardUrl, {
+ verifyRemoteIp: (ip) => !isBlockedIngestHost(ip),
+ settleMs: PINTEREST_PAGE_SETTLE_MS,
+ evaluateExpression: PINTEREST_BOARD_SNAPSHOT_EXPRESSION,
+ evaluateTimeoutMs: PINTEREST_PAGE_READ_TIMEOUT_MS,
+ }).catch(() => {
+ throw new ServerError('Could not read the Pinterest board in the PortOS browser', {
+ status: 502,
+ code: 'PINTEREST_BROWSER_READ_FAILED',
+ });
+ });
+
+ const snapshot = page.evalResult;
+ if (!snapshot || typeof snapshot !== 'object') {
+ throw new ServerError('Pinterest did not return a readable board page', { status: 502, code: 'PINTEREST_BOARD_UNREADABLE' });
+ }
+ if (snapshot.loginRequired) {
+ throw new ServerError('Sign in to Pinterest in the PortOS browser, then retry the import', {
+ status: 401,
+ code: 'PINTEREST_LOGIN_REQUIRED',
+ });
+ }
+ if (!snapshot.boardTitle) {
+ throw new ServerError('Pinterest did not show this board in the PortOS browser', {
+ status: 403,
+ code: 'PINTEREST_BOARD_UNAVAILABLE',
+ });
+ }
+
+ const landedBoardUrl = normalizePinterestFeedUrl(page.url).boardUrl;
+ if (!sameBoardPath(landedBoardUrl, boardUrl)) {
+ throw new ServerError('Pinterest opened a different board than the one requested', {
+ status: 502,
+ code: 'PINTEREST_BOARD_REDIRECTED',
+ });
+ }
+
+ const pins = Array.isArray(snapshot.pins) ? snapshot.pins : [];
+ const expectedCount = Number.isInteger(snapshot.expectedCount) && snapshot.expectedCount >= 0
+ ? snapshot.expectedCount
+ : null;
+ const found = expectedCount ?? pins.length;
+ if (expectedCount !== null && expectedCount <= MAX_ITEMS_PER_BOARD && pins.length < expectedCount) {
+ throw new ServerError('Pinterest did not load every pin; retry the import when the board is available', {
+ status: 502,
+ code: 'PINTEREST_BOARD_INCOMPLETE',
+ });
+ }
+ if (found === 0) return { board, added: 0, found: 0, skipped: 0 };
+ if (!pins.length) {
+ throw new ServerError('No Pinterest pins could be read from this board', {
+ status: 502,
+ code: 'PINTEREST_NO_PINS_READ',
+ });
+ }
+
+ const items = Array.isArray(board.items) ? board.items : [];
+ const seen = new Set(items.map((item) => item?.source).filter(Boolean));
+ const capacity = Math.max(0, MAX_ITEMS_PER_BOARD - items.length);
+ const candidates = pins.filter((pin) => pin?.source && pin?.imageUrl && !seen.has(pin.source)).slice(0, capacity);
+ if (!candidates.length) return { board, added: 0, found, skipped: found };
+
+ await ensureDir(PATHS.images);
+ const imported = [];
+ for (let i = 0; i < candidates.length; i += DOWNLOAD_CONCURRENCY) {
+ const batch = candidates.slice(i, i + DOWNLOAD_CONCURRENCY);
+ const results = await Promise.all(batch.map(async (pin) => {
+ const imageUrl = await downloadPinImage({ ...pin, pinUrl: pin.source }).catch(() => null);
+ return imageUrl
+ ? { imageUrl, caption: pin.caption || null, source: pin.source }
+ : null;
+ }));
+ for (const result of results) if (result) imported.push(result);
+ }
+ if (!imported.length) {
+ throw new ServerError('Pinterest pin images could not be downloaded', {
+ status: 502,
+ code: 'PINTEREST_IMAGE_DOWNLOAD_FAILED',
+ });
+ }
+
+ const { board: nextBoard, added } = await store.appendImportedItems(boardId, imported);
+ if (added > 0) emitRecordUpdated('moodBoard', boardId);
+ return { board: nextBoard, added, found, skipped: Math.max(0, found - added) };
+}
diff --git a/server/services/moodBoard/privatePinterest.test.js b/server/services/moodBoard/privatePinterest.test.js
new file mode 100644
index 0000000000..1b6aab40b4
--- /dev/null
+++ b/server/services/moodBoard/privatePinterest.test.js
@@ -0,0 +1,124 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const store = vi.hoisted(() => ({
+ getBoard: vi.fn(),
+ appendImportedItems: vi.fn(),
+}));
+vi.mock('./db.js', () => store);
+
+const browser = vi.hoisted(() => ({
+ getHealthStatus: vi.fn(),
+ navigateToUrlPinned: vi.fn(),
+}));
+vi.mock('../browserService.js', () => browser);
+
+const fileUtils = vi.hoisted(() => ({
+ ensureDir: vi.fn(),
+ PATHS: { images: '/tmp/portos-mood-board-tests/images' },
+}));
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const original = await importOriginal();
+ return {
+ ...original,
+ PATHS: { ...original.PATHS, ...fileUtils.PATHS },
+ ensureDir: (...args) => fileUtils.ensureDir(...args),
+ };
+});
+
+const downloadPinImage = vi.hoisted(() => vi.fn());
+vi.mock('./pinterest.js', () => ({ downloadPinImage }));
+
+const emitRecordUpdated = vi.hoisted(() => vi.fn());
+vi.mock('../sharing/recordEvents.js', () => ({ emitRecordUpdated }));
+
+import { importPrivatePinterestBoard } from './privatePinterest.js';
+
+const BOARD_URL = 'https://www.pinterest.com/example-user/example-board/';
+const firstPin = {
+ source: 'https://www.pinterest.com/pin/9999999999999999999/',
+ imageUrl: 'https://i.pinimg.com/736x/example/first.jpg',
+ imageUrlOriginal: 'https://i.pinimg.com/originals/example/first.jpg',
+ caption: 'Example pin one',
+};
+const secondPin = {
+ source: 'https://www.pinterest.com/pin/9999999999999999998/',
+ imageUrl: 'https://i.pinimg.com/736x/example/second.jpg',
+ imageUrlOriginal: '',
+ caption: 'Example pin two',
+};
+
+function mockReadableBoard(snapshot) {
+ browser.getHealthStatus.mockResolvedValue({ connected: true });
+ browser.navigateToUrlPinned.mockResolvedValue({ url: BOARD_URL, evalResult: snapshot });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ store.getBoard.mockResolvedValue({ id: 'mb-example', items: [] });
+ store.appendImportedItems.mockImplementation(async (_id, items) => ({
+ board: { id: 'mb-example', items },
+ added: items.length,
+ }));
+ downloadPinImage.mockResolvedValue('/data/images/pinterest-example.jpg');
+});
+
+describe('importPrivatePinterestBoard', () => {
+ it('reads the requested board through pinned CDP and appends re-hosted, source-deduped images', async () => {
+ store.getBoard.mockResolvedValue({
+ id: 'mb-example',
+ items: [{ source: firstPin.source }],
+ });
+ mockReadableBoard({ boardTitle: 'Example Board', loginRequired: false, expectedCount: 2, pins: [firstPin, secondPin] });
+
+ const result = await importPrivatePinterestBoard('mb-example', { url: BOARD_URL });
+
+ expect(browser.navigateToUrlPinned).toHaveBeenCalledWith(BOARD_URL, expect.objectContaining({
+ settleMs: expect.any(Number),
+ evaluateTimeoutMs: 70000,
+ evaluateExpression: expect.any(String),
+ verifyRemoteIp: expect.any(Function),
+ }));
+ const verifyRemoteIp = browser.navigateToUrlPinned.mock.calls[0][1].verifyRemoteIp;
+ expect(verifyRemoteIp('93.184.216.34')).toBe(true);
+ expect(verifyRemoteIp('127.0.0.1')).toBe(false);
+ expect(fileUtils.ensureDir).toHaveBeenCalledWith(fileUtils.PATHS.images);
+ expect(downloadPinImage).toHaveBeenCalledTimes(1);
+ expect(downloadPinImage).toHaveBeenCalledWith(expect.objectContaining({ ...secondPin, pinUrl: secondPin.source }));
+ expect(store.appendImportedItems).toHaveBeenCalledWith('mb-example', [{
+ imageUrl: '/data/images/pinterest-example.jpg',
+ caption: secondPin.caption,
+ source: secondPin.source,
+ }]);
+ expect(result).toMatchObject({ added: 1, found: 2, skipped: 1 });
+ expect(emitRecordUpdated).toHaveBeenCalledWith('moodBoard', 'mb-example');
+ });
+
+ it('reports the signed-in-browser login requirement without writing board items', async () => {
+ mockReadableBoard({ boardTitle: '', loginRequired: true, expectedCount: null, pins: [] });
+
+ await expect(importPrivatePinterestBoard('mb-example', { url: BOARD_URL }))
+ .rejects.toMatchObject({ status: 401, code: 'PINTEREST_LOGIN_REQUIRED' });
+
+ expect(downloadPinImage).not.toHaveBeenCalled();
+ expect(store.appendImportedItems).not.toHaveBeenCalled();
+ });
+
+ it('fails closed when Pinterest reports more pins than the snapshot loaded', async () => {
+ mockReadableBoard({ boardTitle: 'Example Board', loginRequired: false, expectedCount: 2, pins: [firstPin] });
+
+ await expect(importPrivatePinterestBoard('mb-example', { url: BOARD_URL }))
+ .rejects.toMatchObject({ status: 502, code: 'PINTEREST_BOARD_INCOMPLETE' });
+
+ expect(downloadPinImage).not.toHaveBeenCalled();
+ expect(store.appendImportedItems).not.toHaveBeenCalled();
+ });
+
+ it('does not navigate when the PortOS browser is unavailable', async () => {
+ browser.getHealthStatus.mockResolvedValue({ connected: false });
+
+ await expect(importPrivatePinterestBoard('mb-example', { url: BOARD_URL }))
+ .rejects.toMatchObject({ status: 503, code: 'BROWSER_UNAVAILABLE' });
+
+ expect(browser.navigateToUrlPinned).not.toHaveBeenCalled();
+ });
+});