-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapi.php
More file actions
564 lines (462 loc) · 17.9 KB
/
api.php
File metadata and controls
564 lines (462 loc) · 17.9 KB
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
<?php
/*********************************************************************
* AnFire API *
* ----------------------------------------------------------------- *
* COMO UTILIZAR: *
* Github do projeto: https://github.com/MestreTM/AnFireAPI/ *
*********************************************************************/
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');
// Configurações do Banco de Dados e Cache
define('DB_HOST', '');
define('DB_NAME', '');
define('DB_USER', '');
define('DB_PASS', '');
define('USE_CACHE', false); // Habilita ou desabilita o uso de cache (BANCO DE DADOS)
// Configuração da API Key
define('API_KEY', 'SUA_API_KEY');
// Estabelece a conexão com o banco de dados usando PDO.
function getDatabaseConnection(): PDO
{
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4';
try {
$pdo = new PDO($dsn, DB_USER, DB_PASS, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
return $pdo;
} catch (PDOException $e) {
http_response_code(500);
echo json_encode(['error' => 'Falha na conexão com o banco de dados: ' . $e->getMessage()]);
exit;
}
}
// Cria a tabela 'api_cache' se ela não existir.
function createCacheTableIfNotExists(PDO $pdo): void
{
$sql = "
CREATE TABLE IF NOT EXISTS `api_cache` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`anime_slug` VARCHAR(255) DEFAULT NULL,
`anime_link` VARCHAR(512) DEFAULT NULL,
`response` LONGTEXT NOT NULL,
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `idx_anime_slug` (`anime_slug`),
INDEX `idx_anime_link` (`anime_link`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
";
try {
$pdo->exec($sql);
} catch (PDOException $e) {
http_response_code(500);
echo json_encode(['error' => 'Falha ao criar a tabela api_cache: ' . $e->getMessage()]);
exit;
}
}
if (!isset($_GET['api_key']) || $_GET['api_key'] !== API_KEY) {
http_response_code(403);
echo json_encode(['error' => 'API Key inválida ou ausente.']);
exit;
}
if (!isset($_GET['anime_slug']) && !isset($_GET['anime_link'])) {
echo json_encode(['error' => 'Parâmetro anime_slug ou anime_link é obrigatório.']);
exit;
}
if (isset($_GET['anime_link'])) {
$animeLink = $_GET['anime_link'];
if (!preg_match('#^https://animefire\.plus/animes/.+#', $animeLink)) {
http_response_code(400);
echo json_encode(['error' => 'Formato inválido para anime_link. Deve ser "https://animefire.plus/animes/*"']);
exit;
}
}
// Obtém os parâmetros 'force' e 'update', padrão para false. 'force' força a atualização completa, 'update' faz atualização incremental.
$force = isset($_GET['force']) ? filter_var($_GET['force'], FILTER_VALIDATE_BOOLEAN) : false;
$update = isset($_GET['update']) ? filter_var($_GET['update'], FILTER_VALIDATE_BOOLEAN) : false;
$animeSlug = $_GET['anime_slug'] ?? null;
$animeTitle = null;
$animeTitle1 = null;
$animeImage = null;
$animeInfo = null;
$animeSynopsis = null;
$animeScore = null;
$animeVotes = null;
$youtubeTrailer = null;
function getApiResponse(array $params, bool $useCache, bool $force, bool $update): array
{
if ($useCache) {
$pdo = getDatabaseConnection();
createCacheTableIfNotExists($pdo);
$animeSlug = $params['anime_slug'] ?? null;
$animeLink = $params['anime_link'] ?? null;
$cachedResponse = getCachedResponse($pdo, $animeSlug, $animeLink);
if ($cachedResponse) {
$cachedData = json_decode($cachedResponse, true);
if ($update) {
// Se anime_slug não foi fornecido, mas está no cache, use-o
if (!$animeSlug && isset($cachedData['anime_slug'])) {
$animeSlug = $cachedData['anime_slug'];
}
if (!$animeSlug) {
return ['error' => 'anime_slug não fornecido e não encontrado no cache.'];
}
// Encontrar o último episódio existente
$lastEpisode = 0;
foreach ($cachedData['episodes'] as $ep) {
if ($ep['episode'] > $lastEpisode) {
$lastEpisode = $ep['episode'];
}
}
// Buscar novos episódios a partir do próximo episódio
$newEpisodes = testEpisodes($animeSlug, $lastEpisode + 1);
if (!empty($newEpisodes)) {
// Mesclar novos episódios com os existentes
$cachedData['episodes'] = array_merge($cachedData['episodes'], $newEpisodes);
// Coletar os números dos novos episódios
$new_episode_numbers = array_map(function($ep) {
return $ep['episode'];
}, $newEpisodes);
// Adicionar informações sobre os novos episódios
$cachedData['new_episodes'] = $new_episode_numbers;
// Atualizar o cache com os novos dados
storeCacheResponse($pdo, $animeSlug, $animeLink, json_encode($cachedData));
return $cachedData;
} else {
// Nenhum novo episódio encontrado
$cachedData['new_episodes'] = [];
return $cachedData;
}
}
if (!$force) {
// Retornar dados do cache
return $cachedData;
}
}
}
// Processa a solicitação diretamente
$response = processApiRequest($params);
if ($useCache && !isset($response['error'])) {
$pdo = getDatabaseConnection();
storeCacheResponse($pdo, $params['anime_slug'] ?? null, $params['anime_link'] ?? null, json_encode($response));
}
return $response;
}
function getCachedResponse(PDO $pdo, ?string $animeSlug, ?string $animeLink): ?string
{
try {
$sql = "SELECT response FROM api_cache WHERE anime_slug = :anime_slug OR anime_link = :anime_link LIMIT 1";
$stmt = $pdo->prepare($sql);
$stmt->execute([
':anime_slug' => $animeSlug,
':anime_link' => $animeLink,
]);
$result = $stmt->fetch();
return $result ? $result['response'] : null;
} catch (Exception $e) {
error_log('Erro ao obter resposta do cache: ' . $e->getMessage());
return null;
}
}
function storeCacheResponse(PDO $pdo, ?string $animeSlug, ?string $animeLink, string $response): void
{
try {
$sql = "SELECT id FROM api_cache WHERE anime_slug = :anime_slug OR anime_link = :anime_link LIMIT 1";
$stmt = $pdo->prepare($sql);
$stmt->execute([
':anime_slug' => $animeSlug,
':anime_link' => $animeLink,
]);
$existing = $stmt->fetch();
if ($existing) {
$updateSql = "UPDATE api_cache SET response = :response, updated_at = NOW() WHERE id = :id";
$updateStmt = $pdo->prepare($updateSql);
$updateStmt->execute([
':response' => $response,
':id' => $existing['id'],
]);
} else {
$insertSql = "INSERT INTO api_cache (anime_slug, anime_link, response, created_at, updated_at) VALUES (:anime_slug, :anime_link, :response, NOW(), NOW())";
$insertStmt = $pdo->prepare($insertSql);
$insertStmt->execute([
':anime_slug' => $animeSlug,
':anime_link' => $animeLink,
':response' => $response,
]);
}
} catch (Exception $e) {
error_log('Erro ao armazenar resposta no cache: ' . $e->getMessage());
}
}
function processApiRequest(array $params): array
{
$animeSlug = $params['anime_slug'] ?? null;
$animeLink = $params['anime_link'] ?? null;
global $animeTitle, $animeTitle1, $animeImage, $animeInfo, $animeSynopsis, $animeScore, $animeVotes, $youtubeTrailer;
if (!$animeSlug && isset($animeLink)) {
$animeSlug = fetchAnimeSlug($animeLink);
$animeTitle = cleanText(fetchAnimeTitle($animeLink));
$animeTitle1 = cleanText(fetchAnimeTitle1($animeLink));
$animeImage = fetchAnimeImage($animeLink);
$animeInfo = cleanText(fetchAnimeInfo($animeLink));
$animeSynopsis = cleanText(fetchAnimeSynopsis($animeLink));
$animeScore = fetchAnimeScore($animeLink);
$animeVotes = fetchAnimeVotes($animeLink);
$youtubeTrailer = fetchYoutubeTrailer($animeLink);
if (!$animeSlug) {
return ['error' => 'Não foi possível extrair anime_slug do anime_link.'];
}
}
$episodes = testEpisodes($animeSlug);
return [
'anime_slug' => $animeSlug,
'anime_title' => $animeTitle,
'anime_title1' => $animeTitle1,
'anime_image' => $animeImage,
'anime_info' => $animeInfo,
'anime_synopsis' => $animeSynopsis,
'anime_score' => $animeScore,
'anime_votes' => $animeVotes,
'youtube_trailer' => $youtubeTrailer,
'episodes' => $episodes,
'metadata' => [
'op_start' => null,
'op_end' => null
],
'response' => [
'status' => '200',
'text' => 'OK'
]
];
}
$response = getApiResponse($_GET, USE_CACHE, $force, $update);
// Define o código de resposta apropriado em caso de erro
if (isset($response['error'])) {
http_response_code(400);
}
echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
function fetchAnimeSlug(string $animeLink): ?string
{
$html = @file_get_contents($animeLink);
if ($html === false) return null;
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//div[contains(@class, 'div_video_list')]//a");
foreach ($nodes as $node) {
$href = $node->getAttribute('href');
if (preg_match('#/animes/([^/]+)/#', $href, $matches)) {
return $matches[1];
}
}
return null;
}
function fetchAnimeTitle(string $animeLink): ?string
{
$html = @file_get_contents($animeLink);
if ($html === false) return null;
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$titleNode = $xpath->query("//h1[contains(@class, 'quicksand400')]")->item(0);
return $titleNode ? trim($titleNode->nodeValue) : null;
}
function fetchAnimeTitle1(string $animeLink): ?string
{
$html = @file_get_contents($animeLink);
if ($html === false) return null;
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$titleNode = $xpath->query("//h6[contains(@class, 'text-gray')]")->item(0);
return $titleNode ? trim($titleNode->nodeValue) : null;
}
function fetchAnimeImage(string $animeLink): ?string
{
$html = @file_get_contents($animeLink);
if ($html === false) return null;
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$imageNode = $xpath->query("//div[contains(@class, 'sub_animepage_img')]//img")->item(0);
return $imageNode ? $imageNode->getAttribute('data-src') : null;
}
function fetchAnimeInfo(string $animeLink): ?string
{
$html = @file_get_contents($animeLink);
if ($html === false) return null;
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$infoNodes = $xpath->query("//div[contains(@class, 'animeInfo')]//a");
$infoTexts = [];
foreach ($infoNodes as $node) {
$infoTexts[] = trim($node->nodeValue);
}
return implode(", ", $infoTexts);
}
function fetchAnimeSynopsis(string $animeLink): ?string
{
$html = @file_get_contents($animeLink);
if ($html === false) return null;
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$synopsisNode = $xpath->query("//div[contains(@class, 'divSinopse')]//span[contains(@class, 'spanAnimeInfo')]")->item(0);
return $synopsisNode ? trim($synopsisNode->nodeValue) : null;
}
function fetchAnimeScore(string $animeLink): ?string
{
$html = @file_get_contents($animeLink);
if ($html === false) return null;
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$scoreNode = $xpath->query("//h4[@id='anime_score']")->item(0);
return $scoreNode ? trim($scoreNode->nodeValue) : null;
}
function fetchAnimeVotes(string $animeLink): ?string
{
$html = @file_get_contents($animeLink);
if ($html === false) return null;
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$votesNode = $xpath->query("//h6[@id='anime_votos']")->item(0);
return $votesNode ? trim($votesNode->nodeValue) : null;
}
function fetchYoutubeTrailer(string $animeLink): ?string
{
$html = @file_get_contents($animeLink);
if ($html === false) return null;
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$trailerNode = $xpath->query("//div[@id='iframe-trailer']//iframe")->item(0);
return $trailerNode ? $trailerNode->getAttribute('src') : null;
}
// Testa os episódios do anime a partir de um número específico até o máximo especificado. O padrão é 200.
function testEpisodes(string $animeSlug, int $startEpisode = 1, int $maxEpisodes = 200): array
{
$results = [];
for ($episode = $startEpisode; $episode <= $maxEpisodes; $episode++) {
$url = "https://animefire.plus/video/$animeSlug/$episode";
$response = @file_get_contents($url);
if ($response === false) {
break;
}
$json = json_decode($response, true);
if (isset($json['response']['status']) && $json['response']['status'] === "500") {
break;
}
if (!empty($json['data'])) {
$hasGoogleVideo = false;
foreach ($json['data'] as $item) {
if (strpos($item['src'], 'googlevideo.com') !== false) {
$hasGoogleVideo = true;
break;
}
}
if ($hasGoogleVideo) {
$episodePageUrl = "https://animefire.plus/animes/$animeSlug/$episode";
$bloggerUrl = fetchBloggerIframeUrl($episodePageUrl);
if ($bloggerUrl) {
$formattedData = array_map(function ($item) use ($bloggerUrl) {
if (strpos($item['src'], 'googlevideo.com') !== false) {
return [
'url' => $bloggerUrl,
'resolution' => $item['label'],
'status' => 'ONLINE'
];
} else {
return [
'url' => formatUrl($item['src']),
'resolution' => $item['label'],
'status' => 'ONLINE'
];
}
}, $json['data']);
} else {
$formattedData = array_map(function ($item) {
if (strpos($item['src'], 'googlevideo.com') !== false) {
return [
'url' => null,
'resolution' => $item['label'],
'status' => 'OFFLINE'
];
} else {
return [
'url' => formatUrl($item['src']),
'resolution' => $item['label'],
'status' => 'ONLINE'
];
}
}, $json['data']);
}
} else {
$formattedData = array_map(function ($item) {
return [
'url' => formatUrl($item['src']),
'resolution' => $item['label'],
'status' => 'ONLINE'
];
}, $json['data']);
}
$results[] = ['episode' => $episode, 'data' => $formattedData];
} else {
$results[] = ['episode' => $episode, 'data' => [], 'status' => 'OFFLINE'];
}
}
return $results;
}
function fetchBloggerIframeUrl(string $episodePageUrl): ?string
{
$html = @file_get_contents($episodePageUrl);
if ($html === false) return null;
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$iframeNode = $xpath->query("//iframe[contains(@src, 'blogger.com')]")->item(0);
return $iframeNode ? $iframeNode->getAttribute('src') : null;
}
/**
* Limpa o texto removendo caracteres indesejados.
*
* @param string $text
* @return string
*/
function cleanText(?string $text): string
{
if ($text === null) {
return '';
}
$unwanted = [
'ç' => 'c', 'Ç' => 'C',
'á' => 'a', 'Á' => 'A',
'à' => 'a', 'À' => 'A',
'ã' => 'a', 'Ã' => 'A',
'â' => 'a', 'Â' => 'A',
'é' => 'e', 'É' => 'E',
'ê' => 'e', 'Ê' => 'E',
'í' => 'i', 'Í' => 'I',
'ó' => 'o', 'Ó' => 'O',
'õ' => 'o', 'Õ' => 'O',
'ô' => 'o', 'Ô' => 'O',
'ú' => 'u', 'Ú' => 'U',
'ü' => 'u', 'Ü' => 'U'
];
return strtr($text, $unwanted);
}
/**
* Formata a URL removendo barras invertidas.
*
* @param string $url
* @return string
*/
function formatUrl(string $url): string
{
return str_replace(["\\/", "\\"], "/", $url);
}
?>