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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
# D03 - 架构设计

## 技术栈

| 层 | 技术 | 说明 |
|---|---|---|
| 框架 | Nuxt 3 | SSR + auto-import + Nitro server |
| UI组件 | Naive UI | 按需引入、暗色模式、轻量 |
| 样式 | Tailwind CSS 4 | 布局/响应式/动效 |
| 播放器 | ArtPlayer 5 + HLS插件 | M3U8播放 + iframe嵌入 |
| 语言 | TypeScript | 严格类型 |
| HTTP | ofetch (Nuxt内置) | useFetch / useAsyncData |
| 状态 | Pinia (nuxt-pinia) | 用户/播放状态 |
| 图标 | @iconify/vue | Lucide 图标集 |
| 部署 | Docker + Node.js | 自有服务器 |

## 目录结构

```
web/
├── nuxt.config.ts              # Nuxt 配置
├── app.vue                     # 根组件
├── tailwind.config.ts          # Tailwind 配置
├── tsconfig.json
├── package.json
├── Dockerfile                  # 生产部署
├── docker-compose.yml          # 编排
├── .env                        # 环境变量
│
├── pages/                      # 页面(文件路由)
│   ├── index.vue               # 首页
│   ├── category/
│   │   └── [id].vue            # 分类列表 (SSR)
│   ├── search.vue              # 搜索结果
│   ├── vod/
│   │   └── [id].vue            # 影片详情+播放 (SSR)
│   ├── login.vue               # 登录
│   ├── register.vue            # 注册
│   ├── favorite.vue            # 收藏
│   └── history.vue             # 播放历史
│
├── components/                 # 组件
│   ├── VodCard.vue             # 海报卡片
│   ├── VodGrid.vue             # 卡片网格
│   ├── VodPlayer.vue           # 播放器封装
│   ├── SourceSelector.vue      # 多源切换
│   ├── EpisodeList.vue         # 选集列表
│   ├── CategoryNav.vue         # 分类导航
│   ├── SearchBar.vue           # 搜索栏
│   ├── AppHeader.vue           # 顶栏
│   ├── AppFooter.vue           # 底栏
│   └── UserAvatar.vue          # 用户头像/登录入口
│
├── composables/                # 组合式函数
│   ├── useAuth.ts              # 用户鉴权 (login/logout/profile)
│   ├── usePlayer.ts            # 播放器状态管理
│   ├── useApi.ts               # API 请求封装
│   └── useInfiniteScroll.ts    # 无限滚动
│
├── server/                     # Nuxt Server
│   ├── api/
│   │   └── [...].ts           # 代理到后端API
│   └── middleware/
│       └── auth.ts             # 服务端鉴权
│
├── middleware/                  # 客户端路由守卫
│   └── auth.ts                 # 需登录页面守卫
│
├── layouts/                    # 布局
│   ├── default.vue             # 带顶栏+底栏
│   └── blank.vue               # 全屏(播放页可选)
│
├── stores/                     # Pinia
│   ├── user.ts                 # 用户状态 (token/info)
│   └── player.ts               # 播放状态 (当前源/集/进度)
│
├── assets/
│   └── css/
│       └── main.css            # Tailwind 入口
│
├── public/
│   ├── favicon.ico
│   └── logo.svg
│
└── types/                      # 全局类型
    ├── vod.ts
    ├── category.ts
    ├── user.ts
    └── api.ts
```

## 分层架构

```
用户操作
    │
    ▼
Nuxt Pages (pages/)              ← 文件路由、SSR/CSR 自动选择
    │
    ▼
Composables (composables/)       ← 业务逻辑、状态组合
    │
    ▼
Nuxt Server Proxy (server/api/)  ← 代理到后端,避免跨域
    │
    ▼
useFetch / useAsyncData           ← 自动缓存、去重、SSR 数据获取
    │
    ▼
BinV API (FastAPI :9999)          ← 后端服务
```

## 数据获取策略

### SSR 页面

使用 `useAsyncData` + `useFetch`,服务端渲染时直接请求数据:

```typescript
// pages/vod/[id].vue
const route = useRoute();
const { data: vod } = await useAsyncData(
  `vod-${route.params.id}`,
  () => $fetch(`/api/user/vod/${route.params.id}`),
);

useHead({
  title: () => `${vod.value?.name} - 在线播放 - BinV`,
  meta: [
    { name: 'description', content: () => vod.value?.blurb?.slice(0, 100) || '' },
    { property: 'og:title', content: () => vod.value?.name || '' },
    { property: 'og:image', content: () => vod.value?.cover || '' },
  ],
});
```

### CSR 页面(收藏/历史/搜索)

使用 `useFetch` + 客户端加载:

```typescript
// pages/favorite.vue
const { data, pending } = await useFetch('/api/user/favorite', {
  lazy: true,
  headers: { Authorization: `Bearer ${token}` },
});
```

### Nuxt Server Proxy

```typescript
// server/api/[...].ts
export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig();
  const path = event.path.replace('/api/', '/user/');
  return proxyRequest(event, `${config.apiBaseUrl}${path}`);
});
```

所有前端请求 `/api/user/*` → Nuxt server 代理 → `API_BASE_URL/user/*`

优势:
- 无跨域问题
- 隐藏后端真实地址
- 可在 server 端注入公共 header

## 请求层设计

### useApi composable

```typescript
// composables/useApi.ts
export function useApi() {
  const userStore = useUserStore();
  const config = useRuntimeConfig();

  function getHeaders() {
    const headers: Record<string, string> = {};
    if (userStore.token) {
      headers.Authorization = `Bearer ${userStore.token}`;
    }
    return headers;
  }

  async function get<T>(path: string, params?: Record<string, any>) {
    return $fetch<T>(`${config.public.apiBase}${path}`, {
      method: 'GET',
      params,
      headers: getHeaders(),
    });
  }

  async function post<T>(path: string, body?: Record<string, any>) {
    return $fetch<T>(`${config.public.apiBase}${path}`, {
      method: 'POST',
      body,
      headers: getHeaders(),
    });
  }

  async function del<T>(path: string) {
    return $fetch<T>(`${config.public.apiBase}${path}`, {
      method: 'DELETE',
      headers: getHeaders(),
    });
  }

  return { get, post, del };
}
```

### 错误处理

```typescript
// 全局错误拦截 (Nuxt plugin)
export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.hook('vue:error', (error) => {
    const code = error?.statusCode;
    if (code === 401) {
      const userStore = useUserStore();
      userStore.logout();
      navigateTo('/login');
    }
  });
});
```

## 播放器架构

### VodPlayer 组件

```typescript
// components/VodPlayer.vue
// 播放类型判断
function getPlayType(url: string, parseUrl?: string): 'hls' | 'iframe' {
  if (parseUrl) return 'iframe';
  if (url.includes('.m3u8')) return 'hls';
  if (url.startsWith('http')) return 'iframe';
  return 'hls';
}
```

### HLS 模式

```typescript
import ArtPlayer from 'artplayer';
import artplayerPluginHls from 'artplayer-plugin-hls';
import Hls from 'hls.js';

const art = new ArtPlayer({
  container: '.artplayer-app',
  url: m3u8Url,
  plugins: [artplayerPluginHls({ hls: Hls })],
  // 预留扩展位
  // plugins: [hlsPlugin, danmukuPlugin, subtitlePlugin],
});
```

### iframe 模式

```html
<iframe
  :src="iframeSrc"
  allowfullscreen
  class="w-full aspect-video"
  sandbox="allow-scripts allow-same-origin allow-popups"
/>
```

### 播放状态管理

```typescript
// stores/player.ts
export const usePlayerStore = defineStore('player', () => {
  const currentSourceIndex = ref(0);
  const currentEpisodeIndex = ref(0);
  const progress = ref(0);
  const duration = ref(0);

  function switchSource(index: number) {
    currentSourceIndex.value = index;
    currentEpisodeIndex.value = 0;
    progress.value = 0;
  }

  function switchEpisode(index: number) {
    currentEpisodeIndex.value = index;
    progress.value = 0;
  }

  function onTimeUpdate(p: number, d: number) {
    progress.value = p;
    duration.value = d;
  }

  return {
    currentSourceIndex, currentEpisodeIndex,
    progress, duration,
    switchSource, switchEpisode, onTimeUpdate,
  };
});
```

### 播放历史上报

```typescript
// composables/usePlayer.ts
// 进度上报: 每30秒或暂停/退出时上报
const REPORT_INTERVAL = 30_000;

function startProgressReport(vodId: number, sourceId: number, episode: string, playUrl: string) {
  const playerStore = usePlayerStore();
  const { post } = useApi();
  let timer: ReturnType<typeof setInterval>;

  function report() {
    post('/user/history', {
      vod_id: vodId,
      source_id: sourceId,
      episode,
      play_url: playUrl,
      progress: Math.floor(playerStore.progress),
      duration: Math.floor(playerStore.duration),
    });
  }

  onMounted(() => {
    timer = setInterval(report, REPORT_INTERVAL);
  });

  onUnmounted(() => {
    clearInterval(timer);
    report();
  });
}
```

## 用户鉴权

### Token 管理

```typescript
// stores/user.ts
export const useUserStore = defineStore('user', () => {
  const token = useCookie('binv_token', { maxAge: 60 * 60 * 24 * 7 });
  const userInfo = ref<UserInfo | null>(null);
  const isLoggedIn = computed(() => !!token.value);

  async function login(username: string, password: string) {
    const { post } = useApi();
    const res = await post<{ token: string; expires_in: number }>('/user/auth/login', {
      username, password,
    });
    token.value = res.token;
    await fetchProfile();
  }

  async function fetchProfile() {
    if (!token.value) return;
    const { get } = useApi();
    userInfo.value = await get<UserInfo>('/user/auth/profile');
  }

  function logout() {
    token.value = null;
    userInfo.value = null;
  }

  return { token, userInfo, isLoggedIn, login, fetchProfile, logout };
});
```

### 路由守卫

```typescript
// middleware/auth.ts
export default defineNuxtRouteMiddleware((to) => {
  const userStore = useUserStore();
  if (!userStore.isLoggedIn) {
    return navigateTo(`/login?redirect=${to.fullPath}`);
  }
});
```

```typescript
// pages/favorite.vue
definePageMeta({
  middleware: 'auth',
});
```

## Naive UI 集成

### 按需引入

```typescript
// nuxt.config.ts
export default defineNuxtConfig({
  modules: ['nuxtjs-naive-ui'],
  naiveui: {
    themeConfig: true,
  },
});
```

### 暗色模式

```typescript
// Naive UI 主题由 Nuxt app 提供
// 通过 nuxtjs-naive-ui 模块自动处理 SSR 兼容
```

### 常用组件映射

| 场景 | Naive UI 组件 |
|---|---|
| 海报卡片 | NCard + NImage |
| 分类Tab | NTabs / NTabPane |
| 按钮组 | NButton / NButtonGroup |
| 选集按钮 | NTag / NButton |
| 分页 | NPagination |
| 搜索输入 | NInput |
| 弹窗提示 | NMessage / NDialog |
| 骨架屏 | NSkeleton |
| 下拉菜单 | NDropdown (用户菜单) |

## 部署

### Docker

```dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN npm i -g corepack && pnpm install --frozen-lockfile
COPY . .
RUN pnpm build

FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/.output ./.output
ENV HOST=0.0.0.0 PORT=3000
EXPOSE 3000
CMD ["node", ".output/server/index.mjs"]
```

### docker-compose.yml

```yaml
version: '3.8'
services:
  web:
    build: .
    ports:
      - "3000:3000"
    environment:
      - NUXT_PUBLIC_API_BASE=http://api:9999
      - NUXT_API_BASE_URL=http://api:9999
    depends_on:
      - api
    restart: unless-stopped

  api:
    build: ../api
    ports:
      - "9999:9999"
    restart: unless-stopped
```

### Nginx 反代(可选)

```nginx
server {
    listen 80;
    server_name binv.example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}
```

### 环境变量

```bash
# .env
NUXT_PUBLIC_API_BASE=/api            # 前端请求前缀
NUXT_API_BASE_URL=http://api:9999    # Server proxy 目标
```

## 性能优化策略

| 策略 | 实现 | 说明 |
|---|---|---|
| SSR 首屏 | Nuxt 默认 | 首页/详情/分类 SSR |
| ISR 缓存 | `routeRules` 配置 | 热门页缓存 60s |
| 图片懒加载 | NImage + nuxt/image | 懒加载 + WebP |
| 骨架屏 | NSkeleton | 列表加载态 |
| 播放器懒加载 | defineAsyncComponent | 进入详情页才加载 |
| 路由预取 | NuxtLink prefetch | 默认开启 |
| Bundle 优化 | Naive UI tree-shake | 按需引入 |
| Gzip/Brotli | Nginx/Node | 传输压缩 |

### ISR 配置

```typescript
// nuxt.config.ts
export default defineNuxtConfig({
  routeRules: {
    '/': { isr: 60 },
    '/category/**': { isr: 60 },
    '/vod/**': { isr: 300 },
    '/search': { swr: false },
  },
});
```