feat(archive): add admin-only endpoint to list archived episodes and implement corresponding frontend page
This commit is contained in:
parent
204c71d7b5
commit
17f60c9ccb
@ -50,6 +50,7 @@ Compose uses the same image for `api` and the one-off `migrate` job.
|
||||
- `GET /api/v1/danime?part_id=...` — scrape dアニメ episode metadata (returns `{ ep_num, ep_title, season_name, playback_length }`)
|
||||
- `POST /api/v1/oauth/firebase` — verify a Firebase ID token and echo back UID/email
|
||||
- `POST /api/v1/oauth/firebase/claim-admin` — set the `admin` custom claim for a given Firebase UID
|
||||
- `GET /api/v1/archive` — list archived items (auth + admin required)
|
||||
- `DELETE /api/v1/shows?id=...` — delete a show (guarded by Firebase auth when `AUTH_ENABLED=true`)
|
||||
- `GET /healthz` — health check
|
||||
|
||||
@ -65,6 +66,10 @@ curl -X POST http://localhost:8082/api/v1/oauth/firebase/claim-admin \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"uid":"<firebase-uid>"}'
|
||||
|
||||
# List archive (admin only)
|
||||
curl -X GET http://localhost:8082/api/v1/archive \
|
||||
-H "Authorization: Bearer <firebase-id-token>"
|
||||
|
||||
# Delete a show with auth
|
||||
curl -X DELETE "http://localhost:8082/api/v1/shows?id=123" \
|
||||
-H "Authorization: Bearer <firebase-id-token>"
|
||||
|
||||
@ -26,6 +26,19 @@ type Episode struct {
|
||||
DateCreated time.Time `json:"date_created"`
|
||||
}
|
||||
|
||||
// ArchiveEpisode represents a row in the current_archive table.
|
||||
type ArchiveEpisode struct {
|
||||
Id int `json:"id"`
|
||||
EpNum int `json:"ep_num"`
|
||||
EpTitle string `json:"ep_title"`
|
||||
SeasonName string `json:"season_name"`
|
||||
StartTime string `json:"start_time"`
|
||||
PlaybackLength string `json:"playback_length"`
|
||||
CurrentEp bool `json:"current_ep"`
|
||||
DateCreated time.Time `json:"date_created"`
|
||||
DateArchived time.Time `json:"date_archived"`
|
||||
}
|
||||
|
||||
// NewShowInput is the payload needed to create a new show/episode.
|
||||
type NewShowInput struct {
|
||||
EpNum int `json:"ep_num"`
|
||||
@ -49,5 +62,6 @@ type Repository interface {
|
||||
Create(ctx context.Context, in NewShowInput) (Episode, error)
|
||||
MoveToArchive(ctx context.Context, ids []int64) (MoveResult, error)
|
||||
ListAll(ctx context.Context) ([]Episode, error)
|
||||
ListArchive(ctx context.Context) ([]ArchiveEpisode, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
@ -9,5 +9,6 @@ type UseCases interface {
|
||||
Create(ctx context.Context, in NewShowInput) (Episode, error)
|
||||
MoveToArchive(ctx context.Context, ids []int64) (MoveResult, error)
|
||||
ListAll(ctx context.Context) ([]Episode, error)
|
||||
ListArchive(ctx context.Context) ([]ArchiveEpisode, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
@ -38,6 +38,7 @@ func NewRouter(svc episode.UseCases, authClient auth.AuthClient, authEnabled boo
|
||||
protected.Use(AuthMiddleware(authClient))
|
||||
protected.DELETE("/shows", deleteShowsHandler(svc))
|
||||
protected.POST("/archive", moveToArchiveHandler(svc))
|
||||
protected.GET("/archive", AdminOnly(), listArchiveHandler(svc))
|
||||
} else {
|
||||
v1.DELETE("/shows", deleteShowsHandler(svc))
|
||||
v1.POST("/archive", moveToArchiveHandler(svc))
|
||||
@ -334,11 +335,16 @@ func oauthFirebaseHandler(verifier auth.TokenVerifier, authEnabled bool) gin.Han
|
||||
return
|
||||
}
|
||||
email, _ := token.Claims["email"].(string)
|
||||
admin, _ := token.Claims["admin"].(bool)
|
||||
c.JSON(http.StatusOK, FirebaseOAuthRes{
|
||||
UID: token.UID,
|
||||
Email: email,
|
||||
Issuer: token.Issuer,
|
||||
Expires: token.Expires,
|
||||
Admin: admin,
|
||||
CustomClaims: map[string]interface{}{
|
||||
"admin": admin,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -385,3 +391,37 @@ func claimFirebaseAdminHandler(client auth.AuthClient, authEnabled bool) gin.Han
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// listArchiveHandler godoc
|
||||
// @Summary List archive
|
||||
// @Description List all rows from `current_archive` (admin only).
|
||||
// @Tags archive
|
||||
// @Produce json
|
||||
// @Success 200 {array} ArchiveResponse
|
||||
// @Failure 403 {object} HTTPError "admin only"
|
||||
// @Failure 500 {object} HTTPError "list failed"
|
||||
// @Router /api/v1/archive [get]
|
||||
func listArchiveHandler(svc episode.UseCases) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
items, err := svc.ListArchive(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "list failed"})
|
||||
return
|
||||
}
|
||||
res := make([]ArchiveResponse, 0, len(items))
|
||||
for _, it := range items {
|
||||
res = append(res, ArchiveResponse{
|
||||
ID: it.Id,
|
||||
EpNum: it.EpNum,
|
||||
EpTitle: it.EpTitle,
|
||||
SeasonName: it.SeasonName,
|
||||
StartTime: it.StartTime,
|
||||
PlaybackLength: it.PlaybackLength,
|
||||
CurrentEp: it.CurrentEp,
|
||||
DateCreated: it.DateCreated,
|
||||
DateArchived: it.DateArchived,
|
||||
})
|
||||
}
|
||||
c.JSON(http.StatusOK, res)
|
||||
}
|
||||
}
|
||||
|
||||
@ -39,6 +39,8 @@ type fakeSvc struct {
|
||||
lastMove []int64
|
||||
lastDelID int64
|
||||
lastCreate episode.NewShowInput
|
||||
archiveRes []episode.ArchiveEpisode
|
||||
archiveErr error
|
||||
}
|
||||
|
||||
func (f *fakeSvc) GetCurrent(ctx context.Context) (episode.Episode, error) {
|
||||
@ -58,6 +60,9 @@ func (f *fakeSvc) ListAll(ctx context.Context) ([]episode.Episode, error) {
|
||||
}
|
||||
return f.listRes, f.listErr
|
||||
}
|
||||
func (f *fakeSvc) ListArchive(ctx context.Context) ([]episode.ArchiveEpisode, error) {
|
||||
return f.archiveRes, f.archiveErr
|
||||
}
|
||||
func (f *fakeSvc) Delete(ctx context.Context, id int64) error {
|
||||
f.lastDelID = id
|
||||
return f.deleteErr
|
||||
@ -490,6 +495,44 @@ func TestClaimFirebaseAdmin_OK(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestListArchive_AdminRequired(t *testing.T) {
|
||||
svc := &fakeSvc{}
|
||||
client := &fakeAuthClient{token: &fbauth.Token{UID: "uid-1", Claims: map[string]interface{}{"admin": false}}}
|
||||
r := newRouterWithOpts(svc, client, true)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/archive", nil)
|
||||
req.Header.Set("Authorization", "Bearer tok")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListArchive_OK(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
svc := &fakeSvc{
|
||||
archiveRes: []episode.ArchiveEpisode{
|
||||
{Id: 1, EpNum: 1, EpTitle: "Pilot", SeasonName: "S1", StartTime: "10:00:00", PlaybackLength: "00:24:00", DateCreated: now, DateArchived: now},
|
||||
},
|
||||
}
|
||||
client := &fakeAuthClient{token: &fbauth.Token{UID: "uid-1", Claims: map[string]interface{}{"admin": true}}}
|
||||
r := newRouterWithOpts(svc, client, true)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/archive", nil)
|
||||
req.Header.Set("Authorization", "Bearer tok")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var items []episode.ArchiveEpisode
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &items); err != nil {
|
||||
t.Fatalf("json: %v", err)
|
||||
}
|
||||
if len(items) != 1 || items[0].EpTitle != "Pilot" {
|
||||
t.Fatalf("unexpected items: %+v", items)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListShows_Error(t *testing.T) {
|
||||
svc := &fakeSvc{listErr: errors.New("query failed")}
|
||||
r := newRouterWithSvc(svc)
|
||||
|
||||
@ -6,6 +6,7 @@ import (
|
||||
|
||||
"watch-party-backend/internal/auth"
|
||||
|
||||
fbauth "firebase.google.com/go/v4/auth"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@ -31,3 +32,25 @@ func AuthMiddleware(verifier auth.TokenVerifier) gin.HandlerFunc {
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// AdminOnly ensures the firebaseToken context value has admin=true claim.
|
||||
func AdminOnly() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
val, ok := c.Get("firebaseToken")
|
||||
if !ok {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
|
||||
return
|
||||
}
|
||||
token, ok := val.(*fbauth.Token)
|
||||
if !ok || token == nil {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
|
||||
return
|
||||
}
|
||||
admin, _ := token.Claims["admin"].(bool)
|
||||
if !admin {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "admin only"})
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
@ -69,3 +69,54 @@ func TestAuthMiddleware_Success(t *testing.T) {
|
||||
t.Fatalf("expected status %d, got %d", http.StatusOK, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminOnly_MissingToken(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.Use(AdminOnly())
|
||||
r.GET("/", func(c *gin.Context) {})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("expected status %d, got %d", http.StatusUnauthorized, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminOnly_Forbidden(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) {
|
||||
c.Set("firebaseToken", &fbauth.Token{Claims: map[string]interface{}{"admin": false}})
|
||||
})
|
||||
r.Use(AdminOnly())
|
||||
r.GET("/", func(c *gin.Context) {})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected status %d, got %d", http.StatusForbidden, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminOnly_Success(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) {
|
||||
c.Set("firebaseToken", &fbauth.Token{Claims: map[string]interface{}{"admin": true}})
|
||||
})
|
||||
r.Use(AdminOnly())
|
||||
r.GET("/", func(c *gin.Context) { c.Status(http.StatusOK) })
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status %d, got %d", http.StatusOK, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
@ -69,6 +69,9 @@ type FirebaseOAuthRes struct {
|
||||
Email string `json:"email,omitempty" example:"user@example.com"`
|
||||
Issuer string `json:"issuer,omitempty" example:"https://securetoken.google.com/<project>"`
|
||||
Expires int64 `json:"expires,omitempty" example:"1700000000"`
|
||||
Admin bool `json:"admin,omitempty" example:"true"`
|
||||
// CustomClaims echoes back custom claims; only include non-sensitive claims.
|
||||
CustomClaims map[string]interface{} `json:"custom_claims,omitempty"`
|
||||
}
|
||||
|
||||
// FirebaseAdminClaimReq is the request body for POST /api/v1/oauth/firebase/claim-admin.
|
||||
@ -83,3 +86,16 @@ type FirebaseAdminClaimRes struct {
|
||||
Admin bool `json:"admin" example:"true"`
|
||||
CustomClaims map[string]interface{} `json:"custom_claims,omitempty"`
|
||||
}
|
||||
|
||||
// ArchiveResponse represents a row from current_archive.
|
||||
type ArchiveResponse struct {
|
||||
ID int `json:"id" example:"123"`
|
||||
EpNum int `json:"ep_num" example:"1"`
|
||||
EpTitle string `json:"ep_title" example:"Pilot"`
|
||||
SeasonName string `json:"season_name" example:"Season 1"`
|
||||
StartTime string `json:"start_time" example:"10:00:00"`
|
||||
PlaybackLength string `json:"playback_length" example:"00:24:00"`
|
||||
CurrentEp bool `json:"current_ep" example:"false"`
|
||||
DateCreated time.Time `json:"date_created" example:"2024-02-01T15:04:05Z"`
|
||||
DateArchived time.Time `json:"date_archived" example:"2024-03-01T15:04:05Z"`
|
||||
}
|
||||
|
||||
@ -112,6 +112,38 @@ RETURNING
|
||||
return e, nil
|
||||
}
|
||||
|
||||
func (r *pgxEpisodeRepo) ListArchive(ctx context.Context) ([]episode.ArchiveEpisode, error) {
|
||||
const q = `
|
||||
SELECT
|
||||
id,
|
||||
ep_num,
|
||||
ep_title,
|
||||
season_name,
|
||||
to_char(start_time, 'HH24:MI:SS') AS start_time,
|
||||
to_char(playback_length, 'HH24:MI:SS') AS playback_length,
|
||||
current_ep,
|
||||
date_created,
|
||||
date_archived
|
||||
FROM current_archive
|
||||
ORDER BY date_archived DESC, id DESC;
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []episode.ArchiveEpisode
|
||||
for rows.Next() {
|
||||
var e episode.ArchiveEpisode
|
||||
if err := rows.Scan(&e.Id, &e.EpNum, &e.EpTitle, &e.SeasonName, &e.StartTime, &e.PlaybackLength, &e.CurrentEp, &e.DateCreated, &e.DateArchived); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (r *pgxEpisodeRepo) SetCurrent(ctx context.Context, id int64, startHHMMSS string) error {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
|
||||
@ -24,6 +24,12 @@ func (s *Service) ListAll(ctx context.Context) ([]episode.Episode, error) {
|
||||
return s.repo.ListAll(c)
|
||||
}
|
||||
|
||||
func (s *Service) ListArchive(ctx context.Context) ([]episode.ArchiveEpisode, error) {
|
||||
c, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
return s.repo.ListArchive(c)
|
||||
}
|
||||
|
||||
func (s *Service) GetCurrent(ctx context.Context) (episode.Episode, error) {
|
||||
c, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
|
||||
@ -28,6 +28,8 @@ type fakeRepo struct {
|
||||
createRes episode.Episode
|
||||
createErr error
|
||||
createIn []episode.NewShowInput
|
||||
archiveRes []episode.ArchiveEpisode
|
||||
archiveErr error
|
||||
}
|
||||
|
||||
func (f *fakeRepo) GetCurrent(ctx context.Context) (episode.Episode, error) {
|
||||
@ -47,6 +49,9 @@ func (f *fakeRepo) MoveToArchive(ctx context.Context, ids []int64) (episode.Move
|
||||
func (f *fakeRepo) ListAll(ctx context.Context) ([]episode.Episode, error) {
|
||||
return f.listRes, f.listErr
|
||||
}
|
||||
func (f *fakeRepo) ListArchive(ctx context.Context) ([]episode.ArchiveEpisode, error) {
|
||||
return f.archiveRes, f.archiveErr
|
||||
}
|
||||
func (f *fakeRepo) Delete(ctx context.Context, id int64) error {
|
||||
return nil
|
||||
}
|
||||
@ -177,6 +182,28 @@ func TestEpisodeService_ListAll_Error(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEpisodeService_ListArchive(t *testing.T) {
|
||||
fr := &fakeRepo{
|
||||
archiveRes: []episode.ArchiveEpisode{{Id: 1}, {Id: 2}},
|
||||
}
|
||||
svc := service.NewEpisodeService(fr)
|
||||
got, err := svc.ListArchive(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected: %v", err)
|
||||
}
|
||||
if len(got) != 2 || got[0].Id != 1 {
|
||||
t.Fatalf("bad archive list: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEpisodeService_ListArchive_Error(t *testing.T) {
|
||||
fr := &fakeRepo{archiveErr: errors.New("down")}
|
||||
svc := service.NewEpisodeService(fr)
|
||||
if _, err := svc.ListArchive(context.Background()); err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEpisodeService_Create_Validation(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@ -2,10 +2,12 @@ import React from "react";
|
||||
import { Link, NavLink, Route, Routes, useLocation } from "react-router-dom";
|
||||
import Timer from "./components/Timer";
|
||||
import ShowsPage from "./pages/ShowsPage";
|
||||
import ArchivePage from "./pages/ArchivePage";
|
||||
import TimeSyncNotice from "./components/TimeSyncNotice";
|
||||
import { ToastViewport } from "./components/Toasts";
|
||||
import DebugOverlay from "./components/DebugOverlay";
|
||||
import AuthStatus from "./components/AuthStatus";
|
||||
import { useAuth } from "./auth/AuthProvider";
|
||||
import "./index.css";
|
||||
|
||||
const TIME_SYNC_OFF_THRESHOLD = 100;
|
||||
@ -13,6 +15,7 @@ const TIME_SYNC_OFF_THRESHOLD = 100;
|
||||
export default function App() {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const loc = useLocation();
|
||||
const { isAdmin } = useAuth();
|
||||
|
||||
// close sidebar on route change
|
||||
React.useEffect(() => setOpen(false), [loc.pathname]);
|
||||
@ -46,6 +49,7 @@ export default function App() {
|
||||
<nav className="sidebar-nav" onClick={() => setOpen(false)}>
|
||||
<NavLink end to="/" className="navlink">Timer</NavLink>
|
||||
<NavLink to="/shows" className="navlink">Shows</NavLink>
|
||||
{isAdmin && <NavLink to="/archive" className="navlink">Archive</NavLink>}
|
||||
</nav>
|
||||
<div className="sidebar-auth">
|
||||
<div className="sidebar-auth-title">管理用サインイン</div>
|
||||
@ -68,6 +72,7 @@ export default function App() {
|
||||
<Routes>
|
||||
<Route path="/" element={<Timer />} />
|
||||
<Route path="/shows" element={<ShowsPage />} />
|
||||
<Route path="/archive" element={<ArchivePage />} />
|
||||
</Routes>
|
||||
|
||||
<div className="footer">
|
||||
|
||||
@ -34,6 +34,8 @@ export type FirebaseAuthResponse = {
|
||||
email?: string;
|
||||
issuer?: string;
|
||||
expires?: number;
|
||||
admin?: boolean;
|
||||
custom_claims?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type ArchiveResult = {
|
||||
@ -44,3 +46,15 @@ export type ArchiveResult = {
|
||||
deleted: number;
|
||||
skipped: number;
|
||||
};
|
||||
|
||||
export type ArchiveItem = {
|
||||
id: number;
|
||||
ep_num: number;
|
||||
ep_title: string;
|
||||
season_name: string;
|
||||
start_time: string;
|
||||
playback_length: string;
|
||||
current_ep: boolean;
|
||||
date_created: string;
|
||||
date_archived: string;
|
||||
};
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import { API_ENDPOINT } from "./endpoint";
|
||||
import { ApiError, apiFetch } from "./client";
|
||||
import type { ArchiveResult, DanimeEpisode, ScheduleResponse, ShowItem, TimeResponse } from "./types";
|
||||
import type { ArchiveItem, ArchiveResult, DanimeEpisode, ScheduleResponse, ShowItem, TimeResponse } from "./types";
|
||||
|
||||
export type { DanimeEpisode, ScheduleResponse, ShowItem, TimeResponse } from "./types";
|
||||
export type { DanimeEpisode, ScheduleResponse, ShowItem, TimeResponse, ArchiveItem } from "./types";
|
||||
|
||||
function asNumber(v: unknown, fallback = 0) {
|
||||
const n = typeof v === "number" ? v : Number(v);
|
||||
@ -52,6 +52,33 @@ function normalizeShows(data: unknown): ShowItem[] {
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeArchive(data: unknown): ArchiveItem[] {
|
||||
if (!Array.isArray(data)) {
|
||||
throw new ApiError("Archive payload is not an array", { url: API_ENDPOINT.v1.ARCHIVE, data });
|
||||
}
|
||||
return data.map((item) => {
|
||||
if (!item || typeof item !== "object") {
|
||||
throw new ApiError("Bad archive item", { url: API_ENDPOINT.v1.ARCHIVE, data: item });
|
||||
}
|
||||
const obj = item as Record<string, unknown>;
|
||||
const id = asNumber(obj.id, NaN);
|
||||
if (!Number.isFinite(id)) {
|
||||
throw new ApiError("Archive item missing id", { url: API_ENDPOINT.v1.ARCHIVE, data: item });
|
||||
}
|
||||
return {
|
||||
id,
|
||||
ep_num: asNumber(obj.ep_num, 0),
|
||||
ep_title: asString(obj.ep_title, "不明"),
|
||||
season_name: asString(obj.season_name, "不明"),
|
||||
start_time: asString(obj.start_time, ""),
|
||||
playback_length: asString(obj.playback_length, ""),
|
||||
current_ep: Boolean(obj.current_ep),
|
||||
date_created: asString(obj.date_created, ""),
|
||||
date_archived: asString(obj.date_archived, ""),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeDanimeEpisode(data: unknown): DanimeEpisode {
|
||||
if (!data || typeof data !== "object") {
|
||||
throw new ApiError("Bad danime payload", { url: API_ENDPOINT.v1.DANIME, data });
|
||||
@ -153,3 +180,18 @@ export async function archiveShow(id: number, idToken: string) {
|
||||
logLabel: "archive show",
|
||||
});
|
||||
}
|
||||
|
||||
export async function fetchArchive(idToken: string) {
|
||||
if (!idToken) {
|
||||
throw new ApiError("Missing auth token for archive list");
|
||||
}
|
||||
const data = await apiFetch<ArchiveItem[]>(API_ENDPOINT.v1.ARCHIVE, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${idToken}`,
|
||||
},
|
||||
timeoutMs: 12_000,
|
||||
logLabel: "fetch archive",
|
||||
});
|
||||
return normalizeArchive(data);
|
||||
}
|
||||
|
||||
@ -13,6 +13,7 @@ type AuthContextShape = {
|
||||
user: User | null;
|
||||
idToken: string | null;
|
||||
backendClaims: FirebaseAuthResponse | null;
|
||||
isAdmin: boolean;
|
||||
verifying: boolean;
|
||||
signingIn: boolean;
|
||||
error: string | null;
|
||||
@ -29,6 +30,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [user, setUser] = React.useState<User | null>(null);
|
||||
const [idToken, setIdToken] = React.useState<string | null>(null);
|
||||
const [backendClaims, setBackendClaims] = React.useState<FirebaseAuthResponse | null>(null);
|
||||
const isAdmin = Boolean(backendClaims?.admin ?? backendClaims?.custom_claims?.admin);
|
||||
const [verifying, setVerifying] = React.useState(false);
|
||||
const [signingIn, setSigningIn] = React.useState(false);
|
||||
const [error, setError] = React.useState<string | null>(null);
|
||||
@ -132,13 +134,14 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
user,
|
||||
idToken,
|
||||
backendClaims,
|
||||
isAdmin,
|
||||
verifying,
|
||||
signingIn,
|
||||
error,
|
||||
signInWithGoogle,
|
||||
signOut,
|
||||
refreshToken,
|
||||
}), [enabled, status, user, idToken, backendClaims, verifying, signingIn, error, signInWithGoogle, signOut, refreshToken]);
|
||||
}), [enabled, status, user, idToken, backendClaims, isAdmin, verifying, signingIn, error, signInWithGoogle, signOut, refreshToken]);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={value}>
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import { useAuth } from "../auth/AuthProvider";
|
||||
|
||||
export default function AuthStatus() {
|
||||
const { enabled, status, user, verifying, signingIn, signInWithGoogle, signOut, error } = useAuth();
|
||||
const { enabled, status, user, verifying, signingIn, signInWithGoogle, signOut, error, isAdmin } = useAuth();
|
||||
|
||||
if (!enabled) {
|
||||
return <div className="auth-chip muted">Auth off</div>;
|
||||
@ -24,7 +24,10 @@ export default function AuthStatus() {
|
||||
<div className="auth-chip signed-in">
|
||||
{user.photoURL && <img src={user.photoURL} alt="" className="auth-avatar" referrerPolicy="no-referrer" />}
|
||||
<div className="auth-meta">
|
||||
<div className="auth-name">{user.displayName || user.email || user.uid}</div>
|
||||
<div className="auth-name">
|
||||
{user.displayName || user.email || user.uid}
|
||||
{isAdmin && <span style={{ marginLeft: 6, color: "#6de3a2", fontWeight: 700, fontSize: 11 }}>ADMIN</span>}
|
||||
</div>
|
||||
{verifying && (
|
||||
<div className="auth-subtle">
|
||||
確認中…
|
||||
|
||||
@ -503,6 +503,42 @@ kbd {
|
||||
background: var(--accent); color:#0b0f14; border:none;
|
||||
}
|
||||
.primary:disabled { opacity:0.5; cursor:not-allowed; }
|
||||
.archive-table {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
text-align: left;
|
||||
}
|
||||
.archive-header,
|
||||
.archive-row {
|
||||
display: grid;
|
||||
grid-template-columns: 70px 80px 1fr 90px 90px 150px 150px;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
padding: 10px 12px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
.archive-header {
|
||||
font-weight: 800;
|
||||
color: var(--subtle);
|
||||
background: rgba(255,255,255,0.04);
|
||||
border: 1px solid rgba(255,255,255,0.08);
|
||||
}
|
||||
.archive-row {
|
||||
background: rgba(255,255,255,0.03);
|
||||
border: 1px solid rgba(255,255,255,0.05);
|
||||
}
|
||||
.archive-row:hover { background: rgba(255,255,255,0.05); }
|
||||
.archive-row span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
@media (max-width: 820px) {
|
||||
.archive-header,
|
||||
.archive-row {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
row-gap: 6px;
|
||||
}
|
||||
.archive-header span:nth-child(3),
|
||||
.archive-row span:nth-child(3) { grid-column: span 2; }
|
||||
}
|
||||
|
||||
.scrape-card {
|
||||
padding: 14px;
|
||||
border-radius: 14px;
|
||||
|
||||
102
frontend/src/pages/ArchivePage.tsx
Normal file
102
frontend/src/pages/ArchivePage.tsx
Normal file
@ -0,0 +1,102 @@
|
||||
import React from "react";
|
||||
import { fetchArchive } from "../api/watchparty";
|
||||
import type { ArchiveItem } from "../api/types";
|
||||
import { useAuth } from "../auth/AuthProvider";
|
||||
import { toastError } from "../utils/toastBus";
|
||||
import { logApiError } from "../utils/logger";
|
||||
|
||||
function formatTimestamp(ts: string) {
|
||||
if (!ts) return "";
|
||||
const d = new Date(ts);
|
||||
if (Number.isNaN(d.getTime())) return ts;
|
||||
return d.toLocaleString("ja-JP", { timeZone: "Asia/Tokyo" });
|
||||
}
|
||||
|
||||
export default function ArchivePage() {
|
||||
const { enabled, idToken, isAdmin } = useAuth();
|
||||
const [items, setItems] = React.useState<ArchiveItem[]>([]);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [error, setError] = React.useState<string | null>(null);
|
||||
|
||||
const load = React.useCallback(async () => {
|
||||
if (!idToken) {
|
||||
setError("サインインが必要です");
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
try {
|
||||
setLoading(true);
|
||||
const data = await fetchArchive(idToken);
|
||||
setItems(data);
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : "アーカイブを取得できませんでした。";
|
||||
setError(msg);
|
||||
logApiError("fetch archive", e);
|
||||
toastError("アーカイブを取得できませんでした", msg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [idToken]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (enabled && isAdmin && idToken) {
|
||||
load().catch(() => { });
|
||||
} else {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [enabled, isAdmin, idToken, load]);
|
||||
|
||||
if (!enabled) {
|
||||
return <div className="subtle">認証が無効です。</div>;
|
||||
}
|
||||
if (!isAdmin) {
|
||||
return <div className="subtle">管理者のみアクセスできます。</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="shows-page">
|
||||
<h2 className="h1" style={{ marginBottom: 8 }}>アーカイブ一覧</h2>
|
||||
<div className="subtle" style={{ marginTop: 0, display: "flex", flexDirection: "column", gap: 4 }}>
|
||||
<span>削除済みのエピソードを表示します。最新のアーカイブが上に表示されます。</span>
|
||||
<button className="link-btn" disabled={loading} onClick={() => load().catch(() => { })}>
|
||||
再読み込み
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{loading && <div className="subtle">読み込み中…</div>}
|
||||
{error && (
|
||||
<div className="timer-status" style={{ color: "#f88" }}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
{!loading && !error && items.length === 0 && (
|
||||
<div className="subtle">アーカイブは空です。</div>
|
||||
)}
|
||||
|
||||
{items.length > 0 && (
|
||||
<div className="archive-table">
|
||||
<div className="archive-header">
|
||||
<span>ID</span>
|
||||
<span>話数</span>
|
||||
<span>タイトル</span>
|
||||
<span>開始時刻</span>
|
||||
<span>再生時間</span>
|
||||
<span>登録</span>
|
||||
<span>アーカイブ</span>
|
||||
</div>
|
||||
{items.map((it) => (
|
||||
<div key={it.id} className="archive-row">
|
||||
<span>#{it.id}</span>
|
||||
<span>第{it.ep_num}話</span>
|
||||
<span>{it.ep_title}</span>
|
||||
<span>{it.start_time.slice(0, 5)}</span>
|
||||
<span>{it.playback_length.slice(0, 5)}</span>
|
||||
<span className="subtle">{formatTimestamp(it.date_created)}</span>
|
||||
<span className="subtle">{formatTimestamp(it.date_archived)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user