mirror of
https://github.com/headporter81/ss-front-react.git
synced 2026-12-06 07:41:11 +09:00
feat : 자료실(4번 메뉴) 추가 — 링크 등록 시 영상/이미지 다운로드 후 게시
SpecialSource Frontend (React) CD / deploy (push) Successful in 14s
SpecialSource Frontend (React) CD / deploy (push) Successful in 14s
- 목록: 링크·제목 등록 칸, 받는 중인 글이 있으면 5초마다 자동 새로고침
- 상세: 파일별 <video>/<img> (백엔드가 준 1시간짜리 토큰 주소)
- API 오류 시 서버가 준 이유({"error"})를 팝업에 표시
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ca4df3e9a3
commit
eac57c04e7
8 files changed
+273
-10
No files matched your search
+25
-3
@@ -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<string, string>), 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<MediaPost[]> =>
|
||||
(await (await call("/api/media-posts?size=100", token)).json()).content;
|
||||
|
||||
export const fetchMediaPost = async (token: string, id: number): Promise<MediaPost> =>
|
||||
(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;
|
||||
|
||||
/**
|
||||
|
||||
@@ -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<typeof setTimeout>;
|
||||
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<HTMLDialogElement>(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 && (
|
||||
<PostDetail post={state.feed?.posts.find((p) => p.id === state.postId)} token={state.token} />
|
||||
)}
|
||||
{state.screen === "media" && (
|
||||
<MediaList
|
||||
posts={state.media}
|
||||
token={state.token}
|
||||
onSelect={submitFromClick}
|
||||
onCreated={() => dispatch({ rev: state.rev + 1 })}
|
||||
onError={onApiError}
|
||||
/>
|
||||
)}
|
||||
{state.screen === "mediaPost" && state.token && state.postId !== null && (
|
||||
<MediaDetail id={state.postId} token={state.token} onError={onApiError} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -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";
|
||||
|
||||
/** 자료실 글 보기: 파일마다 <video>/<img>. 파일 주소의 토큰은 1시간 유효 → 오래 열어 두었으면 "L" 후 다시 열기 */
|
||||
export default function MediaDetail({ id, token, onError }: { id: number; token: string; onError: (e: unknown) => void }) {
|
||||
const [post, setPost] = useState<MediaPost | null>(null);
|
||||
|
||||
// 받는 중이면 5초마다 다시 조회 → 끝나면 파일이 나타남
|
||||
useEffect(() => {
|
||||
let stale = false;
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const load = () =>
|
||||
fetchMediaPost(token, id)
|
||||
.then((p) => {
|
||||
if (stale) return;
|
||||
setPost(p);
|
||||
if (p.status === "DOWNLOADING") timer = setTimeout(load, 5000);
|
||||
})
|
||||
.catch((e) => !stale && onError(e));
|
||||
load();
|
||||
return () => {
|
||||
stale = true;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [id, token, onError]);
|
||||
|
||||
if (!post) {
|
||||
return (
|
||||
<section className={`${styles.win} ${styles.full}`}>
|
||||
<div className={styles.dim}>불러오는 중...</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className={`${styles.win} ${styles.full}`}>
|
||||
<span className={styles.cap}>═ [4] 자료실 ═</span>
|
||||
<div className={styles.postHead}>
|
||||
<span>제목 :</span> {post.title}
|
||||
</div>
|
||||
<div className={styles.postHead}>
|
||||
<span>등록:</span> {post.author} <span>날짜:</span> {post.createdAt.slice(0, 16).replace("T", " ")}{" "}
|
||||
<span>상태:</span> {STATUS[post.status]}
|
||||
</div>
|
||||
<hr className={styles.rule} />
|
||||
{post.status === "DOWNLOADING" ? (
|
||||
<div className={styles.dim}>다운로드 중입니다... 끝나면 자동으로 표시됩니다.</div>
|
||||
) : post.files.length === 0 ? (
|
||||
<div className={styles.error}>※ 다운로드에 실패했습니다. (쿠키 만료·삭제된 게시물·지원하지 않는 링크)</div>
|
||||
) : (
|
||||
<div className={styles.html}>
|
||||
{post.files.map((f) => {
|
||||
const src = API_URL + f.url;
|
||||
if (f.type === "video") return <video key={f.url} src={src} controls preload="metadata" playsInline />;
|
||||
// eslint-disable-next-line @next/next/no-img-element -- 정적 export라 next/image 최적화 불가
|
||||
if (f.type === "image") return <img key={f.url} src={src} alt={f.name} loading="lazy" />;
|
||||
return (
|
||||
<p key={f.url}>
|
||||
<a href={src}>{f.name}</a>
|
||||
</p>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<hr className={styles.rule} />
|
||||
<div className={styles.footer}>
|
||||
<a className={styles.accent} href={post.sourceUrl} target="_blank" rel="noreferrer">
|
||||
원본 보기 ↗
|
||||
</a>{" "}
|
||||
· <b>L</b>=목록 · <b>M</b>=메인
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { createMediaPost } from "../api";
|
||||
import type { MediaPost } from "../types";
|
||||
import styles from "./bbs.module.css";
|
||||
|
||||
interface Props {
|
||||
posts: MediaPost[] | null;
|
||||
token: string | null;
|
||||
onSelect: (cmd: string) => void;
|
||||
onCreated: () => void; // 등록 성공 → 목록 다시 불러오기
|
||||
onError: (e: unknown) => void;
|
||||
}
|
||||
|
||||
export const STATUS: Record<MediaPost["status"], string> = { DOWNLOADING: "받는중", DONE: "완료", FAILED: "실패" };
|
||||
|
||||
/** [4] 자료실: 위에는 링크 등록 칸, 아래는 목록. 받는 중인 글이 있으면 BbsTerminal이 5초마다 새로고침 */
|
||||
export default function MediaList({ posts, token, onSelect, onCreated, onError }: Props) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const submit = async (e: FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (!token) return;
|
||||
const form = e.currentTarget;
|
||||
const data = new FormData(form);
|
||||
setBusy(true);
|
||||
try {
|
||||
await createMediaPost(token, String(data.get("url")).trim(), String(data.get("title")).trim());
|
||||
form.reset();
|
||||
onCreated();
|
||||
} catch (err) {
|
||||
onError(err);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<section className={`${styles.win} ${styles.full}`}>
|
||||
<span className={styles.cap}>
|
||||
═ [4] 자료실{posts && ` (${posts.length}건)`} ═
|
||||
</span>
|
||||
{!token ? (
|
||||
<div className={styles.dim}>로그인이 필요합니다. (F5 또는 메인에서 7)</div>
|
||||
) : (
|
||||
<>
|
||||
<form className={styles.loginForm} onSubmit={submit}>
|
||||
<label>
|
||||
<span className={styles.num}>링크</span>
|
||||
<input name="url" type="url" className={styles.wide} placeholder="유튜브·인스타 주소" required />
|
||||
</label>
|
||||
<label>
|
||||
<span className={styles.num}>제목</span>
|
||||
<input name="title" className={styles.wide} placeholder="비우면 영상 제목으로" maxLength={500} />
|
||||
</label>
|
||||
<button type="submit" disabled={busy}>
|
||||
{busy ? "요청중..." : "다운로드 등록"}
|
||||
</button>
|
||||
</form>
|
||||
<hr className={styles.rule} />
|
||||
{!posts ? (
|
||||
<div className={styles.dim}>불러오는 중...</div>
|
||||
) : posts.length === 0 ? (
|
||||
<div className={styles.dim}>등록된 자료가 없습니다.</div>
|
||||
) : (
|
||||
<table className={styles.tbl}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className={styles.idx}>번호</th>
|
||||
<th>상태</th>
|
||||
<th>제목</th>
|
||||
<th>날짜</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{posts.map((p, i) => (
|
||||
<tr key={p.id} onClick={() => onSelect(String(i + 1))}>
|
||||
<td className={styles.idx}>{i + 1}</td>
|
||||
<td className={p.status === "FAILED" ? styles.error : styles.accent}>{STATUS[p.status]}</td>
|
||||
<td className={styles.title}>{p.title}</td>
|
||||
<td>{p.createdAt.slice(0, 10).replaceAll("-", "")}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<div className={styles.footer}>
|
||||
<b>번호</b>=보기 · <b>M</b>=메인 · <b>L</b>=새로고침
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -111,6 +111,7 @@
|
||||
color: var(--bbs-hi); font: inherit; outline: none; caret-color: var(--bbs-highlight);
|
||||
}
|
||||
.loginForm input:focus { border-bottom-color: var(--bbs-accent); }
|
||||
.loginForm input.wide { max-width: none; } /* 자료실 링크·제목 칸 */
|
||||
.loginForm button {
|
||||
align-self: flex-start; background: none; border: 1px solid var(--bbs-accent); color: var(--bbs-accent);
|
||||
font: inherit; padding: 0 1.5ch; cursor: pointer;
|
||||
|
||||
@@ -4,7 +4,7 @@ export const MENU: MenuItem[] = [
|
||||
{ num: 1, key: "notice", label: "공지사항", en: "NOTICE", aliases: ["공지", "notice"] },
|
||||
{ num: 2, key: "board", label: "스크랩 게시판", en: "BOARD", aliases: ["게시판", "스크랩", "board"] },
|
||||
{ num: 3, key: "viewed", label: "내가 읽은 글", en: "VIEWED", aliases: ["읽음", "내가읽은글", "viewed"] },
|
||||
{ num: 4, key: "youtube", label: "유튜브 자료실", en: "YOUTUBE", aliases: ["유튜브", "youtube"] },
|
||||
{ num: 4, key: "media", label: "자료실", en: "MEDIA", aliases: ["자료실", "유튜브", "media", "youtube"] },
|
||||
{ num: 5, key: "about", label: "회사 소개", en: "ABOUT", aliases: ["소개", "회사소개", "about"] },
|
||||
{ num: 6, key: "contact", label: "문의하기", en: "CONTACT", aliases: ["문의", "contact"] },
|
||||
{ num: 7, key: "login", label: "로그인", en: "LOGIN", aliases: ["로그인", "로그아웃", "login", "logout"] },
|
||||
|
||||
@@ -11,11 +11,12 @@ export const initialState: BbsState = {
|
||||
user: null,
|
||||
token: null,
|
||||
feed: null,
|
||||
media: null,
|
||||
rev: 0,
|
||||
error: null,
|
||||
};
|
||||
|
||||
export const LOGOUT: Partial<BbsState> = { user: null, token: null, feed: null };
|
||||
export const LOGOUT: Partial<BbsState> = { user: null, token: null, feed: null, media: null };
|
||||
|
||||
/** API 오류 → 화면 상태 (토큰 만료면 로그아웃 처리) */
|
||||
export const apiError = (e: unknown): Partial<BbsState> =>
|
||||
@@ -58,6 +59,7 @@ export function execute(
|
||||
const m = findMenu(raw);
|
||||
if (!m) return { ...state, error: `※ 알 수 없는 메뉴입니다: "${raw}"` };
|
||||
if (m.key === "board" || m.key === "viewed") return { ...state, screen: "list", list: m.key, board: null };
|
||||
if (m.key === "media") return { ...state, screen: "media" };
|
||||
if (m.key === "login") return state.user ? { ...state, ...LOGOUT } : { ...state, screen: "login" };
|
||||
return { ...state, error: `※ "${m.label}"는 아직 준비 중입니다.` };
|
||||
}
|
||||
@@ -83,6 +85,19 @@ export function execute(
|
||||
return { ...state, screen: "post", postId: post.id };
|
||||
}
|
||||
|
||||
if (state.screen === "media") {
|
||||
if (isList) return { ...state, rev: state.rev + 1 };
|
||||
if (!state.user) return { ...state, error: '※ 로그인이 필요합니다. F5 또는 "M" → 7' };
|
||||
const post = state.media?.[Number(raw) - 1];
|
||||
if (!post) return { ...state, error: `※ 목록에 없는 번호입니다: "${raw}"` };
|
||||
return { ...state, screen: "mediaPost", postId: post.id };
|
||||
}
|
||||
|
||||
if (state.screen === "mediaPost") {
|
||||
if (isList) return { ...state, screen: "media" };
|
||||
return { ...state, error: '※ "L"(목록) 또는 "M"(메인)만 입력해 보세요.' };
|
||||
}
|
||||
|
||||
// screen === "post"
|
||||
if (isList) return { ...state, screen: "list" };
|
||||
return { ...state, error: '※ "L"(목록) 또는 "M"(메인)만 입력해 보세요.' };
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export type MenuKey = "notice" | "board" | "viewed" | "youtube" | "about" | "contact" | "login";
|
||||
export type MenuKey = "notice" | "board" | "viewed" | "media" | "about" | "contact" | "login";
|
||||
|
||||
export interface MenuItem {
|
||||
num: number;
|
||||
@@ -26,8 +26,26 @@ export interface ScrapedPost {
|
||||
viewedAt: string | null;
|
||||
}
|
||||
|
||||
/** 자료실 글의 파일 하나. url은 1시간짜리 토큰이 붙은 상대 주소 (/api/media-posts/files/...) */
|
||||
export interface MediaFile {
|
||||
name: string;
|
||||
type: string; // "video" | "image" | 그 외
|
||||
url: string;
|
||||
}
|
||||
|
||||
/** 백엔드 MediaPostResponse와 같은 모양 (자료실: 링크로 다운로드한 영상/이미지) */
|
||||
export interface MediaPost {
|
||||
id: number;
|
||||
title: string;
|
||||
sourceUrl: string;
|
||||
status: "DOWNLOADING" | "DONE" | "FAILED";
|
||||
author: string;
|
||||
createdAt: string;
|
||||
files: MediaFile[]; // 상세 조회에서만 채워짐
|
||||
}
|
||||
|
||||
export type Palette = "blue" | "green" | "amber";
|
||||
export type Screen = "main" | "list" | "post" | "login";
|
||||
export type Screen = "main" | "list" | "post" | "login" | "media" | "mediaPost";
|
||||
export type ListKind = "board" | "viewed";
|
||||
|
||||
/** 메인 화면 IT 헤드라인 (백엔드 /api/headlines) */
|
||||
@@ -69,6 +87,7 @@ export interface BbsState {
|
||||
user: string | null; // 로그인한 아이디, 비로그인이면 null
|
||||
token: string | null; // JWT (sessionStorage에도 보관 → 새로고침해도 유지, 탭 닫으면 다시 로그인)
|
||||
feed: Feed | null;
|
||||
media: MediaPost[] | null; // 자료실 목록
|
||||
rev: number; // "L"(새로고침)할 때마다 +1 → 목록 다시 불러오기
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user