diff --git a/src/features/bbs/api.ts b/src/features/bbs/api.ts index 8ec4d6c..1088aec 100644 --- a/src/features/bbs/api.ts +++ b/src/features/bbs/api.ts @@ -1,4 +1,4 @@ -import type { Board, Feed, Headline, ListKind, Weather } from "./types"; +import type { Board, Feed, Headline, ListKind, MediaPost, Weather } from "./types"; // 개발은 로컬 백엔드 직접 호출, 운영(nginx)은 같은 도메인의 /api 프록시. NEXT_PUBLIC_API_URL로 덮어쓰기 가능 export const API_URL = @@ -8,12 +8,34 @@ export const API_URL = export class AuthError extends Error {} async function call(path: string, token: string, init?: RequestInit) { - const res = await fetch(`${API_URL}${path}`, { ...init, headers: { Authorization: `Bearer ${token}` } }); + const res = await fetch(`${API_URL}${path}`, { + ...init, + headers: { ...(init?.headers as Record), Authorization: `Bearer ${token}` }, + }); if (res.status === 401 || res.status === 403) throw new AuthError("※ 로그인이 만료되었습니다. 다시 로그인하세요."); - if (!res.ok) throw new Error(`※ 서버 오류 (${res.status})`); + if (!res.ok) { + // 서버가 {"error": "..."}로 이유를 알려주면 그대로 보여줌 (예: 지원하지 않는 링크) + const reason = (await res.json().catch(() => null))?.error; + throw new Error(reason ? `※ ${reason}` : `※ 서버 오류 (${res.status})`); + } return res; } +// ponytail: 자료실은 직접 등록하는 글이라 적음 → 최근 100건만. 넘치면 fetchFeed처럼 before 커서로 무한 스크롤 +export const fetchMediaPosts = async (token: string): Promise => + (await (await call("/api/media-posts?size=100", token)).json()).content; + +export const fetchMediaPost = async (token: string, id: number): Promise => + (await call(`/api/media-posts/${id}`, token)).json(); + +/** 링크 등록 → 서버가 다운로드 봇에 요청. 다운로드는 뒤에서 진행 (status: DOWNLOADING → DONE/FAILED) */ +export const createMediaPost = (token: string, url: string, title: string) => + call("/api/media-posts", token, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ url, title }), + }); + const PAGE_SIZE = 30; /** diff --git a/src/features/bbs/components/BbsTerminal.tsx b/src/features/bbs/components/BbsTerminal.tsx index cab1538..2fc1757 100644 --- a/src/features/bbs/components/BbsTerminal.tsx +++ b/src/features/bbs/components/BbsTerminal.tsx @@ -1,12 +1,14 @@ "use client"; -import { useEffect, useLayoutEffect, useReducer, useRef, useState, useSyncExternalStore } from "react"; +import { useCallback, useEffect, useLayoutEffect, useReducer, useRef, useState, useSyncExternalStore } from "react"; import { AUTH_KEY, PALETTE_KEY, PALETTES } from "../constants"; -import { fetchBoards, fetchFeed } from "../api"; +import { fetchBoards, fetchFeed, fetchMediaPosts } from "../api"; import { apiError, execute, initialState, LOGOUT } from "../lib/command"; import type { ListKind, Nav, Palette } from "../types"; import LoginForm from "./LoginForm"; import MainMenu from "./MainMenu"; +import MediaDetail from "./MediaDetail"; +import MediaList from "./MediaList"; import PostDetail from "./PostDetail"; import PostList from "./PostList"; import styles from "./bbs.module.css"; @@ -97,6 +99,28 @@ export default function BbsTerminal() { }; }, [feedKind, feedBoard, state.token, state.rev]); + // 자료실 목록: 들어오거나 "L"을 누르면 다시 불러옴. 받는 중인 글이 있으면 5초마다 다시 불러와 상태 갱신 + const onApiError = useCallback((e: unknown) => dispatch(apiError(e)), []); + useEffect(() => { + if (state.screen !== "media" || !state.token) return; + const token = state.token; + let stale = false; + let timer: ReturnType; + const load = () => + fetchMediaPosts(token) + .then((media) => { + if (stale) return; + dispatch({ media }); + if (media.some((p) => p.status === "DOWNLOADING")) timer = setTimeout(load, 5000); + }) + .catch((e) => !stale && onApiError(e)); + load(); + return () => { + stale = true; + clearTimeout(timer); + }; + }, [state.screen, state.token, state.rev, onApiError]); + // 오류·안내 메시지가 생기면 팝업으로 띄우고, 다른 경로로 지워지면 닫음 const dialogRef = useRef(null); useEffect(() => { @@ -201,7 +225,7 @@ export default function BbsTerminal() { ref={screenRef} className={styles.screen} onScroll={(e) => { - if (state.screen !== "post") scrollPos.current[scrollKey] = e.currentTarget.scrollTop; + if (state.screen !== "post" && state.screen !== "mediaPost") scrollPos.current[scrollKey] = e.currentTarget.scrollTop; }} onTouchStart={(e) => { const t = e.touches[0]; @@ -252,6 +276,18 @@ export default function BbsTerminal() { {state.screen === "post" && state.token && ( p.id === state.postId)} token={state.token} /> )} + {state.screen === "media" && ( + dispatch({ rev: state.rev + 1 })} + onError={onApiError} + /> + )} + {state.screen === "mediaPost" && state.token && state.postId !== null && ( + + )} diff --git a/src/features/bbs/components/MediaDetail.tsx b/src/features/bbs/components/MediaDetail.tsx new file mode 100644 index 0000000..9f23d58 --- /dev/null +++ b/src/features/bbs/components/MediaDetail.tsx @@ -0,0 +1,77 @@ +import { useEffect, useState } from "react"; +import { API_URL, fetchMediaPost } from "../api"; +import type { MediaPost } from "../types"; +import { STATUS } from "./MediaList"; +import styles from "./bbs.module.css"; + +/** 자료실 글 보기: 파일마다