-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.php
More file actions
278 lines (238 loc) · 8.77 KB
/
Copy pathapi.php
File metadata and controls
278 lines (238 loc) · 8.77 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
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
$action = $_GET['action'] ?? '';
switch ($action) {
case 'info':
getVideoInfo();
break;
case 'search':
searchYouTube();
break;
case 'spotify':
importSpotifyPlaylist();
break;
default:
echo json_encode(['error' => 'Unknown action']);
}
function getVideoInfo() {
$url = $_GET['url'] ?? '';
$id = extractYoutubeId($url);
if (!$id) {
echo json_encode(['error' => 'Invalid YouTube URL']);
return;
}
$oembed = "https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v={$id}&format=json";
$context = stream_context_create(['http' => ['timeout' => 10]]);
$data = @file_get_contents($oembed, false, $context);
if ($data) {
$info = json_decode($data, true);
echo json_encode([
'id' => $id,
'title' => $info['title'] ?? 'Unknown Title',
'author' => $info['author_name'] ?? 'Unknown Artist',
'thumbnail' => "https://img.youtube.com/vi/{$id}/maxresdefault.jpg",
'duration' => getDuration($id)
]);
} else {
echo json_encode([
'id' => $id,
'title' => 'Unknown Title',
'author' => 'Unknown Artist',
'thumbnail' => "https://img.youtube.com/vi/{$id}/maxresdefault.jpg",
'duration' => 0
]);
}
}
function getDuration($id) {
$url = "https://www.youtube.com/watch?v={$id}";
$context = stream_context_create(['http' => ['timeout' => 5]]);
$html = @file_get_contents($url, false, $context);
if ($html && preg_match('/"approxDurationMs":"(\d+)"/', $html, $m)) {
return intval($m[1]) / 1000;
}
return 0;
}
function searchYouTube() {
$q = $_GET['q'] ?? '';
if (!$q) {
echo json_encode(['error' => 'No search query']);
return;
}
$query = urlencode($q);
$url = "https://www.youtube.com/results?search_query={$query}";
$context = stream_context_create([
'http' => [
'timeout' => 6,
'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\r\n"
]
]);
$html = @file_get_contents($url, false, $context);
$results = [];
if ($html) {
preg_match_all('/\/watch\?v=([a-zA-Z0-9_-]{11})/', $html, $matches);
$ids = array_unique($matches[1]);
$titles = [];
$authors = [];
preg_match_all('/"title":{"runs":\[{"text":"([^"]+)"}\]}/', $html, $titleMatches);
if (!empty($titleMatches[1])) {
$titles = $titleMatches[1];
}
preg_match_all('/"author":{"name":"([^"]+)"/', $html, $authorMatches);
if (!empty($authorMatches[1])) {
$authors = $authorMatches[1];
}
foreach ($ids as $i => $id) {
if ($i >= 15) break;
$results[] = [
'id' => $id,
'title' => $titles[$i] ?? "Video {$id}",
'author' => $authors[$i] ?? '',
'thumbnail' => "https://img.youtube.com/vi/{$id}/default.jpg"
];
}
}
echo json_encode($results);
}
function extractYoutubeId($url) {
$patterns = [
'/youtube\.com\/watch\?v=([a-zA-Z0-9_-]{11})/',
'/youtu\.be\/([a-zA-Z0-9_-]{11})/',
'/youtube\.com\/embed\/([a-zA-Z0-9_-]{11})/',
'/youtube\.com\/shorts\/([a-zA-Z0-9_-]{11})/'
];
foreach ($patterns as $pattern) {
if (preg_match($pattern, $url, $matches)) {
return $matches[1];
}
}
if (preg_match('/^[a-zA-Z0-9_-]{11}$/', $url)) {
return $url;
}
return null;
}
/* ========== SPOTIFY PLAYLIST IMPORT (via embed) ========== */
function importSpotifyPlaylist() {
$input = $_GET['url'] ?? '';
$playlistId = extractSpotifyId($input);
if (!$playlistId) {
echo json_encode(['error' => 'Link/embed Spotify playlist tidak valid']);
return;
}
$tracks = fetchEmbedTracks($playlistId);
if ($tracks === null) {
echo json_encode(['error' => 'Gagal mengambil data dari Spotify']);
return;
}
if (empty($tracks)) {
echo json_encode(['error' => 'Tidak ada track ditemukan']);
return;
}
// Ambil max 20, kirim nama+artist doang
$tracks = array_slice($tracks, 0, 20);
$results = array_map(fn($t) => ['name' => $t['name'], 'artist' => $t['artist']], $tracks);
echo json_encode($results);
}
function extractSpotifyId($input) {
// Format: open.spotify.com/playlist/ID
if (preg_match('/spotify\.com\/playlist\/([a-zA-Z0-9]+)/', $input, $m)) return $m[1];
// Format: spotify:playlist:ID
if (preg_match('/spotify:playlist:([a-zA-Z0-9]+)/', $input, $m)) return $m[1];
// ID mentah
if (preg_match('/^[a-zA-Z0-9]{22}$/', trim($input), $m)) return trim($input);
return null;
}
function fetchEmbedTracks($playlistId) {
$url = "https://open.spotify.com/embed/playlist/{$playlistId}";
$context = stream_context_create([
'http' => [
'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\r\nAccept-Language: en-US,en;q=0.9\r\n",
'timeout' => 15,
]
]);
$html = @file_get_contents($url, false, $context);
if (!$html) return null;
// Strategy 1: Cari data JSON di script tag
preg_match_all('/<script[^>]*>(.*?)<\/script>/s', $html, $scriptMatches);
foreach ($scriptMatches[1] as $script) {
$script = trim($script);
// Coba parse sebagai JSON langsung
if (strpos($script, '{') === 0 || strpos($script, '[') === 0) {
$data = @json_decode($script, true);
if ($data) {
$found = digTracks($data);
if (!empty($found)) return $found;
}
}
// Coba format: window.__INITIAL_STATE__ = {...}
if (preg_match('/window\.__PRELOADED_STATE__\s*=\s*({.*?});/s', $script, $sm)) {
$data = @json_decode($sm[1], true);
if ($data && ($found = digTracks($data))) return $found;
}
}
// Strategy 2: Cari pola "title":"...","subtitle":"..." di HTML
$tracks = [];
if (preg_match_all('/"title"\s*:\s*"((?:[^"\\\\]|\\\\.)*)"\s*,\s*"subtitle"\s*:\s*"((?:[^"\\\\]|\\\\.)*)"/', $html, $matches, PREG_SET_ORDER)) {
foreach ($matches as $m) {
$name = json_decode('"' . $m[1] . '"');
$artist = json_decode('"' . $m[2] . '"');
if ($name && $artist) {
$tracks[] = ['name' => $name, 'artist' => $artist];
}
}
if (!empty($tracks)) return $tracks;
}
// Strategy 3: Cari JSON array di dalam script dengan keyword "track"
if (preg_match('/\[.*?"name".*?"artists".*?\]/s', $html, $jm)) {
$data = @json_decode($jm[0], true);
if ($data && ($found = digTracks($data))) return $found;
}
return [];
}
function digTracks($data) {
$tracks = [];
// Langsung ketemu track
if (isset($data['name'], $data['artists'][0]['name'])) {
return [['name' => $data['name'], 'artist' => $data['artists'][0]['name']]];
}
if (is_array($data)) {
foreach ($data as $key => $value) {
if (is_array($value)) {
// Cek apakah item ini adalah track
if (isset($value['track']['name'], $value['track']['artists'][0]['name'])) {
$tracks[] = ['name' => $value['track']['name'], 'artist' => $value['track']['artists'][0]['name']];
} elseif (isset($value['name'], $value['artists'][0]['name'])) {
$tracks[] = ['name' => $value['name'], 'artist' => $value['artists'][0]['name']];
} elseif (is_int($key)) {
// Array numerik — telusuri lebih dalam
$sub = digTracks($value);
$tracks = array_merge($tracks, $sub);
} else {
// Cari di level ini
$sub = digTracks($value);
if (!empty($sub)) {
$tracks = array_merge($tracks, $sub);
if (count($tracks) > 30) break;
}
}
}
}
}
return $tracks;
}
function searchYoutubeFirst($query) {
$q = urlencode($query);
$url = "https://www.youtube.com/results?search_query={$q}";
$context = stream_context_create([
'http' => [
'timeout' => 5,
'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\r\n"
]
]);
$html = @file_get_contents($url, false, $context);
if (!$html) return null;
if (preg_match('/\/watch\?v=([a-zA-Z0-9_-]{11})/', $html, $m)) {
return $m[1];
}
return null;
}