Spaces:
Sleeping
Sleeping
File size: 12,883 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 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 | import { getLocalMovies } from '../../../lib/localDb.js';
// Cấu hình timeout cho fetch
async function fetchWithTimeout(resource, options = {}) {
const { timeout = 8000 } = options;
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(resource, {
...options,
signal: controller.signal
});
return response;
} finally {
clearTimeout(id);
}
}
// Trích xuất slug từ URL hoặc chuỗi nhập vào
function extractSlug(input) {
if (!input) return null;
const trimmed = input.trim();
if (!trimmed) return null;
try {
if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
const url = new URL(trimmed);
const pathname = url.pathname;
const parts = pathname.split('/').filter(Boolean);
if (parts.length > 0) {
return parts[parts.length - 1];
}
}
} catch (e) {}
const parts = trimmed.split('/').filter(Boolean);
if (parts.length > 0) {
return parts[parts.length - 1];
}
return trimmed;
}
// Hàm gộp tập phim để nhẩm tính số tập mới
function checkEpisodesDiff(existingEpisodes, crawledEpisodes) {
let addedCount = 0;
const existingList = existingEpisodes || [];
for (const crawledServer of crawledEpisodes) {
let existingServer = existingList.find(s => s.server_name === crawledServer.server_name);
if (!existingServer) {
addedCount += crawledServer.server_data?.length || 0;
continue;
}
const existingNames = new Set((existingServer.server_data || []).map(e => e.name));
for (const crawledEp of crawledServer.server_data || []) {
if (!existingNames.has(crawledEp.name)) {
addedCount++;
}
}
}
return addedCount;
}
// Dọn dẹp máy chủ
function cleanAndFilterServers(episodes) {
if (!Array.isArray(episodes)) return [];
const tempMap = new Map();
for (const srv of episodes) {
if (!srv || !srv.server_name) continue;
let rawName = srv.server_name.trim();
let cleanName = '';
if (/vietsub/i.test(rawName)) {
cleanName = 'Vietsub';
} else if (/thuyết minh|thuyet minh/i.test(rawName)) {
cleanName = 'Thuyết Minh';
} else if (/lồng tiếng|long tieng/i.test(rawName)) {
cleanName = 'Lồng Tiếng';
} else {
cleanName = rawName.replace(/#\s*/g, '').replace(/\([^)]*\)/g, '').trim();
if (!cleanName) cleanName = 'Vietsub';
}
if (cleanName !== 'Vietsub' && cleanName !== 'Thuyết Minh' && cleanName !== 'Lồng Tiếng') {
continue;
}
if (!tempMap.has(cleanName)) {
srv.server_name = cleanName;
tempMap.set(cleanName, srv);
}
}
const result = [];
if (tempMap.has('Vietsub')) result.push(tempMap.get('Vietsub'));
if (tempMap.has('Thuyết Minh')) result.push(tempMap.get('Thuyết Minh'));
if (result.length < 2 && tempMap.has('Lồng Tiếng')) {
result.push(tempMap.get('Lồng Tiếng'));
}
if (result.length === 0 && episodes.length > 0) {
const fallbackSrv = episodes[0];
fallbackSrv.server_name = fallbackSrv.server_name.replace(/#\s*/g, '').replace(/\([^)]*\)/g, '').trim() || 'Vietsub';
result.push(fallbackSrv);
}
return result;
}
export async function POST({ request }) {
// Check quyền admin từ cookie auth_token
const cookies = request.headers.get('cookie') || '';
const hasToken = cookies.includes('auth_token=');
if (!hasToken) {
return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401, headers: { 'Content-Type': 'application/json' } });
}
try {
const { type, urls, pageStart, pageEnd, countrySlug, genreSlug } = await request.json();
const localMovies = await getLocalMovies();
const slugsToCrawl = [];
if (type === 'url') {
const urlList = Array.isArray(urls) ? urls : [urls];
for (const rawUrl of urlList) {
const slug = extractSlug(rawUrl);
if (slug) {
try {
const res = await fetchWithTimeout(`https://phimapi.com/phim/${slug}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
if (data.status && data.movie) {
const crawledMovie = data.movie;
const crawledEpisodes = cleanAndFilterServers(data.episodes || []);
let crawledEpCount = 0;
if (crawledEpisodes.length > 0) {
crawledEpCount = Math.max(...crawledEpisodes.map(s => s.server_data?.length || 0));
}
const existing = localMovies[slug];
let expectedNew = crawledEpCount;
let exists = false;
let skip = false;
let skipReason = '';
if (existing) {
exists = true;
const addedCount = checkEpisodesDiff(existing.episodes, crawledEpisodes);
expectedNew = addedCount;
if (addedCount === 0) {
skip = true;
skipReason = 'Đã đủ tập';
}
}
slugsToCrawl.push({
raw: crawledMovie.name,
slug,
totalEpisodes: crawledEpCount,
expectedNew,
exists,
skip,
skipReason
});
}
} catch (e) {
slugsToCrawl.push({
raw: slug,
slug,
totalEpisodes: 0,
expectedNew: 0,
exists: false,
skip: false,
skipReason: `Lỗi quét: ${e.message}`
});
}
}
}
} else if (type === 'country') {
const start = parseInt(pageStart || '1');
const end = parseInt(pageEnd || '1');
for (let p = start; p <= end; p++) {
try {
const res = await fetchWithTimeout(`https://phimapi.com/v1/api/quoc-gia/${countrySlug}?page=${p}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const resData = await res.json();
const items = resData.data?.items || [];
for (const item of items) {
if (item.slug && !slugsToCrawl.some(s => s.slug === item.slug)) {
const existing = localMovies[item.slug];
let skip = false;
let skipReason = '';
let expectedNew = 1;
let exists = false;
if (existing) {
exists = true;
const localStatus = (existing.movie?.episode_current || '').toLowerCase();
const remoteStatus = (item.episode_current || '').toLowerCase();
const isStatusEqual = localStatus === remoteStatus && remoteStatus !== '';
const isBothCompleted = (localStatus.includes('hoàn tất') || localStatus.includes('full') || localStatus.includes('complete') || localStatus.includes('12/12')) &&
(remoteStatus.includes('hoàn tất') || remoteStatus.includes('full') || remoteStatus.includes('complete') || remoteStatus.includes('12/12'));
if (isStatusEqual || isBothCompleted) {
skip = true;
skipReason = remoteStatus.includes('hoàn tất') ? 'Phim đã hoàn tất' : 'Số tập trùng khớp';
expectedNew = 0;
}
}
slugsToCrawl.push({
raw: item.name,
slug: item.slug,
totalEpisodes: item.episode_total || (item.episode_current ? item.episode_current : '?'),
expectedNew,
exists,
skip,
skipReason
});
}
}
} catch (e) {
console.error(`Error scanning page ${p}:`, e);
}
}
} else if (type === 'genre') {
const start = parseInt(pageStart || '1');
const end = parseInt(pageEnd || '1');
for (let p = start; p <= end; p++) {
try {
let apiUrl = `https://phimapi.com/v1/api/the-loai/${genreSlug}?page=${p}`;
const listSlugs = ['hoat-hinh', 'phim-chieu-rap', 'phim-le', 'phim-bo', 'tv-shows'];
if (listSlugs.includes(genreSlug)) {
apiUrl = `https://phimapi.com/v1/api/danh-sach/${genreSlug}?page=${p}`;
}
const res = await fetchWithTimeout(apiUrl);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const resData = await res.json();
const items = resData.data?.items || [];
for (const item of items) {
if (item.slug && !slugsToCrawl.some(s => s.slug === item.slug)) {
const existing = localMovies[item.slug];
let skip = false;
let skipReason = '';
let expectedNew = 1;
let exists = false;
if (existing) {
exists = true;
const localStatus = (existing.movie?.episode_current || '').toLowerCase();
const remoteStatus = (item.episode_current || '').toLowerCase();
const isStatusEqual = localStatus === remoteStatus && remoteStatus !== '';
const isBothCompleted = (localStatus.includes('hoàn tất') || localStatus.includes('full') || localStatus.includes('complete') || localStatus.includes('12/12')) &&
(remoteStatus.includes('hoàn tất') || remoteStatus.includes('full') || remoteStatus.includes('complete') || remoteStatus.includes('12/12'));
if (isStatusEqual || isBothCompleted) {
skip = true;
skipReason = remoteStatus.includes('hoàn tất') ? 'Phim đã hoàn tất' : 'Số tập trùng khớp';
expectedNew = 0;
}
}
slugsToCrawl.push({
raw: item.name,
slug: item.slug,
totalEpisodes: item.episode_total || (item.episode_current ? item.episode_current : '?'),
expectedNew,
exists,
skip,
skipReason
});
}
}
} catch (e) {
console.error(`Error scanning genre page ${p}:`, e);
}
}
} else if (type === 'batch') {
const start = parseInt(pageStart || '1');
const end = parseInt(pageEnd || '1');
for (let p = start; p <= end; p++) {
try {
const res = await fetchWithTimeout(`https://phimapi.com/danh-sach/phim-moi-cap-nhat?page=${p}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
const items = data.items || [];
for (const item of items) {
if (item.slug && !slugsToCrawl.some(s => s.slug === item.slug)) {
const existing = localMovies[item.slug];
let skip = false;
let skipReason = '';
let expectedNew = 1;
let exists = false;
if (existing) {
exists = true;
// Nhẩm tính thử
}
slugsToCrawl.push({
raw: item.name,
slug: item.slug,
totalEpisodes: item.episode_total || '?',
expectedNew,
exists,
skip,
skipReason
});
}
}
} catch (e) {
console.error(`Error scanning batch page ${p}:`, e);
}
}
} else if (type === 'all') {
// Vì scan all có thể mất thời gian nếu lấy hết nghìn slugs, ta chỉ quét trang 1-2 để đảm bảo không timeout
// Hoặc trả về nhanh 1 danh sách
const res = await fetchWithTimeout(`https://phimapi.com/danh-sach/phim-moi-cap-nhat?page=1`);
if (res.ok) {
const data = await res.json();
const items = data.items || [];
for (const item of items) {
slugsToCrawl.push({
raw: item.name,
slug: item.slug,
totalEpisodes: '?',
expectedNew: 1,
exists: !!localMovies[item.slug],
skip: false,
skipReason: ''
});
}
}
}
return new Response(JSON.stringify({ success: true, count: slugsToCrawl.length, slugs: slugsToCrawl }), {
headers: { 'Content-Type': 'application/json' }
});
} catch (err) {
return new Response(JSON.stringify({ error: err.message }), { status: 500, headers: { 'Content-Type': 'application/json' } });
}
}
|