-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathupdate.php
More file actions
272 lines (233 loc) Β· 8.46 KB
/
update.php
File metadata and controls
272 lines (233 loc) Β· 8.46 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
<?php
if (!isset($argv[1])) {
die("Usage: php script.php <API_KEY>\n");
}
$apiKey = $argv[1];
$content = file_get_contents('README.md');
$lines = explode("\n", $content);
$youtubers = [];
function getFollowers($url, $apiKey): array
{
try {
// Try to get channel ID from the original URL
try {
$content = get_content_with_retry($url, 2);
} catch (Exception $e) {
$alternativeUrls = generateAlternativeUrls($url);
foreach ($alternativeUrls as $altUrl) {
echo "Trying alternative URL: {$altUrl}\n";
try {
$content = get_content_with_retry($altUrl, 1);
if (preg_match('/channel_id=([a-zA-Z0-9_-]+)/', $content, $matches)) {
// Found a working URL, update the original URL
echo "URL corrected: {$url} -> {$altUrl}\n";
$url = $altUrl;
break;
}
} catch (Exception $e) {
echo "Alternative URL failed: {$altUrl}\n";
continue;
}
}
}
if (!preg_match('/channel_id=([a-zA-Z0-9_-]+)/', $content, $matches)) {
if (!isset($matches[1])) {
throw new Exception("Could not extract channel ID from {$url}");
}
}
$channelId = $matches[1];
$json_url = "https://www.googleapis.com/youtube/v3/channels?part=statistics&id={$channelId}&key={$apiKey}";
$data = json_decode(get_content_with_retry($json_url, 2), true);
if (!isset($data['items'][0]['statistics']['subscriberCount'])) {
throw new Exception("Could not get subscriber count for {$url}");
}
$subscriberCount = $data['items'][0]['statistics']['subscriberCount'];
echo "Got {$subscriberCount} subs for {$url}\n";
return [
'count' => $subscriberCount,
'url' => $url // Return the potentially corrected URL
];
} catch (Exception $e) {
// Log the error
$errorMessage = date('Y-m-d H:i:s') . " - Error: " . $e->getMessage() . "\n";
file_put_contents('script_errors.log', $errorMessage, FILE_APPEND);
echo "Error: " . $e->getMessage() . "\n";
// Return default values
return [
'count' => 0,
'url' => $url
];
}
}
/**
* Generate alternative URL formats for a YouTube channel
*
* @param string $url Original URL
* @return array Array of alternative URLs
*/
function generateAlternativeUrls($url)
{
$alternatives = [];
// Extract handle or channel ID from URL
if (preg_match('/@([a-zA-Z0-9_-]+)/', $url, $matches)) {
$handle = $matches[1];
// Try /c/ format
$alternatives[] = "https://www.youtube.com/c/{$handle}";
// Try /channel/ format if it looks like a channel ID
if (strlen($handle) > 20) {
$alternatives[] = "https://www.youtube.com/channel/{$handle}";
}
// Try /user/ format
$alternatives[] = "https://www.youtube.com/user/{$handle}";
} elseif (preg_match('/\/c\/([a-zA-Z0-9_-]+)/', $url, $matches)) {
$handle = $matches[1];
// Try @ format
$alternatives[] = "https://www.youtube.com/@{$handle}";
// Try /user/ format
$alternatives[] = "https://www.youtube.com/user/{$handle}";
} elseif (preg_match('/\/channel\/([a-zA-Z0-9_-]+)/', $url, $matches)) {
$channelId = $matches[1];
// Not much we can do with channel IDs, but try @ format if it's not a typical channel ID
if (strlen($channelId) < 20) {
$alternatives[] = "https://www.youtube.com/@{$channelId}";
}
} elseif (preg_match('/\/user\/([a-zA-Z0-9_-]+)/', $url, $matches)) {
$username = $matches[1];
// Try @ format
$alternatives[] = "https://www.youtube.com/@{$username}";
// Try /c/ format
$alternatives[] = "https://www.youtube.com/c/{$username}";
}
return $alternatives;
}
function get_content_with_retry($url, $maxRetries)
{
$retryCount = 0;
while ($retryCount < $maxRetries) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
curl_setopt($ch, CURLOPT_TIMEOUT, 15); //timeout in seconds
$content = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($content === false || $info['http_code'] != 200) {
$retryCount++;
sleep(5);
} else {
return $content;
}
}
throw new Exception($url . ' - failed after ' . $maxRetries . ' attempts.');
}
/**
* Parse a line with followers information
*
* @param string $line Line from README.md
* @param string $apiKey YouTube API key
* @return array Parsed information
*/
function parseWithFollowers($line, $apiKey): array
{
// Extract handle from markdown link format
$handle = extractHandle($line);
// Extract URL from markdown link format
$url = extractUrl($line);
// Extract segments (followers, name, description)
$segments = explode(' β§ ', substr($line, strpos($line, '**:') + 4));
$description = null;
$name = null;
if (count($segments) === 3) {
// Line Format: followers β§ name β§ description
$name = $segments[1] ?? null;
$description = $segments[2] ?? null;
} elseif (count($segments) === 2) {
// Line Format: followers β§ description
$description = $segments[1] ?? null;
}
// Get followers and potentially corrected URL
$result = getFollowers($url, $apiKey);
$followers = $result['count'];
$url = $result['url']; // Use potentially corrected URL
return compact('handle', 'url', 'name', 'description', 'followers');
}
function extractHandle(string $line): string
{
if (preg_match('/\[([^\]]+)\]/', $line, $matches)) {
return $matches[1];
}
return '';
}
function extractUrl(string $line): string
{
if (preg_match('/\(([^)]+)\)/', $line, $matches)) {
return $matches[1];
}
return '';
}
function parseWithoutFollowers(string $line, string $apiKey): array
{
// Extract handle from markdown link format
$handle = extractHandle($line);
// Extract URL from markdown link format
$url = extractUrl($line);
// Extract description and name
$descriptionAndName = substr($line, strpos($line, '**:') + 4);
$splitPos = strpos($descriptionAndName, ' β§ ');
if ($splitPos !== false) {
$name = substr($descriptionAndName, 0, $splitPos);
$description = substr($descriptionAndName, $splitPos + 3);
} else {
$name = null;
$description = $descriptionAndName;
}
// Get followers and potentially corrected URL
$result = getFollowers($url, $apiKey);
$followers = $result['count'];
$url = $result['url']; // Use potentially corrected URL
return compact('handle', 'url', 'name', 'description', 'followers');
}
foreach ($lines as $line) {
if (empty($line = trim($line))) {
continue;
}
if (preg_match('/[0-9.]*[KM]? β§/i', $line)) {
$youtubers[] = parseWithFollowers($line, $apiKey);
} else {
$youtubers[] = parseWithoutFollowers($line, $apiKey);
}
}
function followersCount($count)
{
if ($count > 1000000) {
return round($count / 1000000, 1) . 'M';
}
if ($count > 1000) {
return round($count / 1000, 1) . 'K';
}
return $count;
}
function formatReadmeContent(array $youtubers): string
{
$sortedList = '';
foreach ($youtubers as $youtuber) {
// Format description with name if available
if ($youtuber['name'] !== null) {
$description = followersCount($youtuber['followers']) . " β§ {$youtuber['name']} β§ {$youtuber['description']}";
} else {
$description = followersCount($youtuber['followers']) . " β§ " . $youtuber['description'];
}
// Use the potentially corrected URL
$sortedList .= "- **[{$youtuber['handle']}]({$youtuber['url']})**: {$description}\n";
}
return $sortedList;
}
// Sort youtubers by follower count
uasort($youtubers, function ($a, $b) {
return $b['followers'] <=> $a['followers'];
});
// Format and write to README.md
$sortedList = formatReadmeContent($youtubers);
file_put_contents('README.md', $sortedList);
echo "README.md updated successfully with " . count($youtubers) . " youtubers.\n";