feat: naver list import

Added Naver List Import in a similar style like the Google List Import. To keep the frontend clean I combined both list options.
This commit is contained in:
Marco Sadowski
2026-04-07 14:04:27 +02:00
parent 96080e8a03
commit d9d389d090
19 changed files with 336 additions and 33 deletions
+30
View File
@@ -14,6 +14,7 @@ import {
deletePlace,
importGpx,
importGoogleList,
importNaverList,
searchPlaceImage,
} from '../services/placeService';
@@ -99,6 +100,35 @@ router.post('/import/google-list', authenticate, requireTripAccess, async (req:
}
});
// Import places from a shared Naver Maps list URL
router.post('/import/naver-list', authenticate, requireTripAccess, async (req: Request, res: Response) => {
const authReq = req as AuthRequest;
if (!checkPermission('place_edit', authReq.user.role, authReq.trip!.user_id, authReq.user.id, authReq.trip!.user_id !== authReq.user.id))
return res.status(403).json({ error: 'No permission' });
const { tripId } = req.params;
const { url } = req.body;
if (!url || typeof url !== 'string') return res.status(400).json({ error: 'URL is required' });
try {
const result = await importNaverList(tripId, url);
if ('error' in result) {
return res.status(result.status).json({ error: result.error });
}
const successResult = result as { places: any[]; listName: string };
res.status(201).json({ places: successResult.places, count: successResult.places.length, listName: successResult.listName });
for (const place of successResult.places) {
broadcast(tripId, 'place:created', { place }, req.headers['x-socket-id'] as string);
}
} catch (err: unknown) {
console.error('[Places] Naver list import error:', err instanceof Error ? err.message : err);
res.status(400).json({ error: 'Failed to import Naver Maps list. Make sure the list is shared publicly.' });
}
});
router.get('/:id', authenticate, requireTripAccess, (req: Request, res: Response) => {
const { tripId, id } = req.params;
+109
View File
@@ -382,6 +382,115 @@ export async function importGoogleList(tripId: string, url: string) {
return { places: created, listName };
}
// ---------------------------------------------------------------------------
// Import Naver Maps list
// ---------------------------------------------------------------------------
export async function importNaverList(
tripId: string,
url: string,
): Promise<{ places: any[]; listName: string } | { error: string; status: number }> {
let resolvedUrl = url;
const limit = 20;
// Resolve naver.me short links to the canonical map.naver.com folder URL.
if (url.includes('naver.me')) {
const redirectRes = await fetch(url, { redirect: 'follow', signal: AbortSignal.timeout(10000) });
resolvedUrl = redirectRes.url;
}
const folderMatch = resolvedUrl.match(/favorite\/myPlace\/folder\/([A-Za-z0-9_-]+)/i);
const folderId = folderMatch?.[1] || null;
if (!folderId) {
return { error: 'Could not extract folder ID from URL. Please use a shared Naver Maps list link.', status: 400 };
}
const fetchPage = async (start: number) => {
const apiUrl = `https://pages.map.naver.com/save-pages/api/maps-bookmark/v3/shares/${encodeURIComponent(folderId)}/bookmarks?placeInfo=true&start=${start}&limit=${limit}&sort=lastUseTime&mcids=ALL&createIdNo=true`;
const apiRes = await fetch(apiUrl, {
headers: {
Accept: 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
},
signal: AbortSignal.timeout(15000),
});
if (!apiRes.ok) {
return { error: 'Failed to fetch list from Naver Maps', status: 502 } as const;
}
try {
const data = await apiRes.json() as {
folder?: { bookmarkCount?: number; name?: string };
bookmarkList?: any[];
};
return { data } as const;
} catch {
return { error: 'Invalid list data received from Naver Maps', status: 400 } as const;
}
};
const firstPage = await fetchPage(0);
if ('error' in firstPage) {
return { error: firstPage.error, status: firstPage.status };
}
const listName = firstPage.data.folder?.name || 'Naver Maps List';
const totalCount = typeof firstPage.data.folder?.bookmarkCount === 'number'
? firstPage.data.folder.bookmarkCount
: (firstPage.data.bookmarkList?.length || 0);
const allItems: any[] = [...(firstPage.data.bookmarkList || [])];
for (let start = limit; start < totalCount; start += limit) {
const page = await fetchPage(start);
if ('error' in page) {
return { error: page.error, status: page.status };
}
const pageItems = page.data.bookmarkList || [];
if (!Array.isArray(pageItems) || pageItems.length === 0) break;
allItems.push(...pageItems);
}
if (allItems.length === 0) {
return { error: 'List is empty or could not be read', status: 400 };
}
const places: { name: string; lat: number; lng: number; notes: string | null; address: string | null }[] = [];
for (const item of allItems) {
const lat = Number(item?.py);
const lng = Number(item?.px);
const name = typeof item?.name === 'string' && item.name.trim()
? item.name.trim()
: (typeof item?.displayName === 'string' ? item.displayName.trim() : '');
const note = typeof item?.memo === 'string' && item.memo.trim() ? item.memo.trim() : null;
const address = typeof item?.address === 'string' && item.address.trim() ? item.address.trim() : null;
if (name && Number.isFinite(lat) && Number.isFinite(lng)) {
places.push({ name, lat, lng, notes: note, address });
}
}
if (places.length === 0) {
return { error: 'No places with coordinates found in list', status: 400 };
}
const insertStmt = db.prepare(`
INSERT INTO places (trip_id, name, lat, lng, address, notes, transport_mode)
VALUES (?, ?, ?, ?, ?, ?, 'walking')
`);
const created: any[] = [];
const insertAll = db.transaction(() => {
for (const p of places) {
const result = insertStmt.run(tripId, p.name, p.lat, p.lng, p.address, p.notes);
const place = getPlaceWithTags(Number(result.lastInsertRowid));
created.push(place);
}
});
insertAll();
return { places: created, listName };
}
// ---------------------------------------------------------------------------
// Search place image (Unsplash)
// ---------------------------------------------------------------------------
+76 -1
View File
@@ -7,7 +7,7 @@
* - PLACE-014: reordering within a day is tested in assignments.test.ts
* - PLACE-019: GPX bulk import tested here using the test fixture
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach, afterAll } from 'vitest';
import request from 'supertest';
import type { Application } from 'express';
import path from 'path';
@@ -500,6 +500,81 @@ describe('Categories', () => {
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Naver list import
// ─────────────────────────────────────────────────────────────────────────────
describe('Naver list import', () => {
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
it('POST /import/naver-list resolves shortlink, paginates, and creates places', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const folderId = 'a04c3f7a8dd24d42a8eb52d710a700cc';
const fetchMock = vi.fn()
.mockResolvedValueOnce({
ok: true,
url: `https://map.naver.com/v5/favorite/myPlace/folder/${folderId}`,
})
.mockResolvedValueOnce({
ok: true,
json: async () => ({
folder: { name: 'Seoul Food', bookmarkCount: 22 },
bookmarkList: [
{ name: 'SINSAJEON', px: 127.0226195, py: 37.5186363, memo: null, address: 'Sinsa-dong Seoul' },
{ name: 'Ilpyeondeungsim', px: 126.9852986, py: 37.5629334, memo: 'Try lunch set', address: 'Myeong-dong Seoul' },
],
}),
})
.mockResolvedValueOnce({
ok: true,
json: async () => ({
folder: { name: 'Seoul Food', bookmarkCount: 22 },
bookmarkList: [
{ name: 'WAIKIKI MARKET', px: 126.8886523, py: 37.5589079, memo: null, address: 'Mapo-gu Seoul' },
],
}),
});
vi.stubGlobal('fetch', fetchMock);
const res = await request(app)
.post(`/api/trips/${trip.id}/places/import/naver-list`)
.set('Cookie', authCookie(user.id))
.send({ url: 'https://naver.me/GYDpx3Wv' });
expect(res.status).toBe(201);
expect(res.body.count).toBe(3);
expect(res.body.listName).toBe('Seoul Food');
expect(res.body.places[0].name).toBe('SINSAJEON');
expect(res.body.places[1].notes).toBe('Try lunch set');
expect(res.body.places[2].address).toBe('Mapo-gu Seoul');
expect(fetchMock).toHaveBeenCalledTimes(3);
expect(fetchMock.mock.calls[1][0]).toContain(`shares/${folderId}/bookmarks?`);
expect(fetchMock.mock.calls[1][0]).toContain('start=0');
expect(fetchMock.mock.calls[1][0]).toContain('limit=20');
expect(fetchMock.mock.calls[2][0]).toContain('start=20');
});
it('POST /import/naver-list returns 400 for invalid URL', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const res = await request(app)
.post(`/api/trips/${trip.id}/places/import/naver-list`)
.set('Cookie', authCookie(user.id))
.send({ url: 'https://example.com/not-a-naver-list' });
expect(res.status).toBe(400);
expect(res.body.error).toContain('Could not extract folder ID');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// GPX Import
// ─────────────────────────────────────────────────────────────────────────────