File size: 5,303 Bytes
4bea261
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { getLocalMovies, saveLocalMovie } from '../../../../lib/localDb.js';

export async function POST({ request }) {
  // Check quyền admin từ cookie
  const cookies = request.headers.get('cookie') || '';
  const hasToken = cookies.includes('auth_token=');
  if (!hasToken) {
    return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });
  }

  const { slug, type } = await request.json();
  if (!slug) {
    return new Response(JSON.stringify({ error: 'Thiếu slug phim' }), { status: 400 });
  }

  try {
    const localMovies = await getLocalMovies();
    const movieData = localMovies[slug];
    if (!movieData) {
      return new Response(JSON.stringify({ error: 'Không tìm thấy phim trong database cục bộ' }), { status: 404 });
    }

    // Gọi API KKPhim gốc
    const res = await fetch(`https://phimapi.com/phim/${slug}`);
    if (!res.ok) {
      return new Response(JSON.stringify({ error: `Không thể gọi API KKPhim (HTTP ${res.status})` }), { status: 500 });
    }

    const apiData = await res.json();
    if (!apiData.status || !apiData.episodes) {
      return new Response(JSON.stringify({ error: 'Dữ liệu API KKPhim rỗng' }), { status: 500 });
    }

    const apiEpisodes = apiData.episodes || [];
    const localEpisodes = movieData.episodes || [];
    let updatedCount = 0;
    let addedCount = 0;

    if (type === 'sync_new') {
      // Chỉ quét và thêm tập phim mới
      const updatedEpisodes = [];

      for (const apiServer of apiEpisodes) {
        const localServer = localEpisodes.find(s => s.server_name === apiServer.server_name);
        if (!localServer) {
          updatedEpisodes.push(apiServer);
          addedCount += apiServer.server_data.length;
          continue;
        }

        const mergedData = [...localServer.server_data];
        const localNames = new Set(localServer.server_data.map(e => e.name));

        for (const apiEp of apiServer.server_data) {
          if (!localNames.has(apiEp.name)) {
            mergedData.push(apiEp);
            addedCount++;
          }
        }

        updatedEpisodes.push({
          server_name: apiServer.server_name,
          server_data: mergedData
        });
      }

      movieData.episodes = updatedEpisodes;
      movieData.movie.episode_current = apiData.movie.episode_current || movieData.movie.episode_current;
      movieData.movie.episode_total = apiData.movie.episode_total || movieData.movie.episode_total || null;
      movieData.movie.modified = { time: new Date().toISOString() };

      await saveLocalMovie(slug, movieData);
      return new Response(JSON.stringify({ 
        message: `Đồng bộ thành công! Đã thêm ${addedCount} tập phim mới.`, 
        episodes: updatedEpisodes,
        episode_current: movieData.movie.episode_current
      }));

    } else if (type === 'sync_all') {
      // Cập nhật lại toàn bộ link stream của tất cả các tập, giữ nguyên Intro/Outro
      const updatedEpisodes = [];

      for (const apiServer of apiEpisodes) {
        const localServer = localEpisodes.find(s => s.server_name === apiServer.server_name);
        if (!localServer) {
          updatedEpisodes.push(apiServer);
          updatedCount += apiServer.server_data.length;
          continue;
        }

        const mergedData = [];
        const localMap = new Map(localServer.server_data.map(e => [e.name, e]));

        for (const apiEp of apiServer.server_data) {
          const localEp = localMap.get(apiEp.name);
          if (localEp) {
            // Giữ lại cấu hình Intro/Outro cũ
            mergedData.push({
              ...apiEp,
              introStart: localEp.introStart,
              introEnd: localEp.introEnd,
              outroStart: localEp.outroStart,
              outroEnd: localEp.outroEnd,
              // Tương thích với các trường cũ nếu có
              time_intro_start: localEp.time_intro_start || 0,
              time_intro_end: localEp.time_intro_end || 0,
              time_outro_start: localEp.time_outro_start || 0,
              time_outro_end: localEp.time_outro_end || 0
            });
            updatedCount++;
          } else {
            mergedData.push(apiEp);
            addedCount++;
          }
        }

        updatedEpisodes.push({
          server_name: apiServer.server_name,
          server_data: mergedData
        });
      }

      movieData.episodes = updatedEpisodes;
      movieData.movie.episode_current = apiData.movie.episode_current || movieData.movie.episode_current;
      movieData.movie.episode_total = apiData.movie.episode_total || movieData.movie.episode_total || null;
      movieData.movie.modified = { time: new Date().toISOString() };

      await saveLocalMovie(slug, movieData);
      return new Response(JSON.stringify({ 
        message: `Đồng bộ thành công! Làm mới ${updatedCount} link tập và thêm ${addedCount} tập mới.`, 
        episodes: updatedEpisodes,
        episode_current: movieData.movie.episode_current
      }));
    }

    return new Response(JSON.stringify({ error: 'Loại đồng bộ không hợp lệ' }), { status: 400 });

  } catch (e) {
    return new Response(JSON.stringify({ error: e.message }), { status: 500 });
  }
}