-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextract-videos.js
More file actions
381 lines (328 loc) · 11.4 KB
/
extract-videos.js
File metadata and controls
381 lines (328 loc) · 11.4 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
const https = require('https');
const fs = require('fs');
const path = require('path');
// Load repositories
const repositories = require('../src/data/repositories.json');
// GitHub token from environment (optional, for higher rate limits)
const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
// Regular expressions to match video links
const VIDEO_PATTERNS = {
youtube: /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/g,
vimeo: /(?:https?:\/\/)?(?:www\.)?vimeo\.com\/(\d+)/g,
// GitHub user-attachments videos
githubVideo: /https:\/\/github\.com\/user-attachments\/assets\/([a-f0-9-]+)/g,
// Markdown image with video link
markdownVideo: /!\[([^\]]*)\]\(([^)]+\.(?:mp4|webm|ogg|gif))\)/g,
// HTML video tags
htmlVideo: /<video[^>]*src=["']([^"']+)["'][^>]*>/g,
// Embedded iframes
iframe: /<iframe[^>]*src=["']([^"']+)["'][^>]*>/g
};
/**
* Fetch README content from GitHub
*/
function fetchReadme(repoName) {
return new Promise((resolve, reject) => {
const options = {
hostname: 'api.github.com',
path: `/repos/DecisionsDev/${repoName}/readme`,
method: 'GET',
headers: {
'User-Agent': 'DecisionsDev-Video-Extractor',
'Accept': 'application/vnd.github.v3.raw'
}
};
if (GITHUB_TOKEN) {
options.headers['Authorization'] = `token ${GITHUB_TOKEN}`;
}
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
if (res.statusCode === 200) {
resolve(data);
} else if (res.statusCode === 404) {
resolve(null); // No README
} else {
reject(new Error(`HTTP ${res.statusCode}: ${data}`));
}
});
});
req.on('error', (error) => {
reject(error);
});
req.end();
});
}
/**
* Fetch contents of a folder from GitHub
*/
function fetchFolderContents(repoName, path) {
return new Promise((resolve, reject) => {
const options = {
hostname: 'api.github.com',
path: `/repos/DecisionsDev/${repoName}/contents/${path}`,
method: 'GET',
headers: {
'User-Agent': 'DecisionsDev-Video-Extractor',
'Accept': 'application/vnd.github.v3+json'
}
};
if (GITHUB_TOKEN) {
options.headers['Authorization'] = `token ${GITHUB_TOKEN}`;
}
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
if (res.statusCode === 200) {
resolve(JSON.parse(data));
} else if (res.statusCode === 404) {
resolve(null); // Folder not found
} else {
reject(new Error(`HTTP ${res.statusCode}: ${data}`));
}
});
});
req.on('error', (error) => {
reject(error);
});
req.end();
});
}
/**
* Recursively fetch all video files from a folder and its subfolders
*/
async function fetchVideosRecursively(repoName, folderPath, repoUrl) {
const videos = [];
try {
const contents = await fetchFolderContents(repoName, folderPath);
if (!contents || !Array.isArray(contents)) return videos;
for (const item of contents) {
if (item.type === 'file') {
const fileName = item.name.toLowerCase();
// Check for video file extensions (including animated GIFs)
if (fileName.endsWith('.mp4') || fileName.endsWith('.webm') || fileName.endsWith('.mov') || fileName.endsWith('.gif')) {
videos.push({
type: 'file',
id: item.sha,
url: item.download_url,
embedUrl: item.download_url,
fileName: item.name,
filePath: item.path,
repository: repoName,
repositoryUrl: repoUrl,
source: 'videos-folder'
});
}
} else if (item.type === 'dir') {
// Recursively search subdirectories
await new Promise(resolve => setTimeout(resolve, 100)); // Rate limiting
const subVideos = await fetchVideosRecursively(repoName, item.path, repoUrl);
videos.push(...subVideos);
}
}
} catch (error) {
// Silently handle errors for subfolders
console.error(` Error fetching ${folderPath}:`, error.message);
}
return videos;
}
/**
* Extract video links from README content
*/
function extractVideos(readmeContent, repoName, repoUrl) {
const videos = [];
if (!readmeContent) return videos;
// Extract YouTube videos
let match;
const youtubePattern = new RegExp(VIDEO_PATTERNS.youtube.source, 'g');
while ((match = youtubePattern.exec(readmeContent)) !== null) {
const videoId = match[1];
videos.push({
type: 'youtube',
id: videoId,
url: `https://www.youtube.com/watch?v=${videoId}`,
embedUrl: `https://www.youtube.com/embed/${videoId}`,
thumbnail: `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`,
repository: repoName,
repositoryUrl: repoUrl
});
}
// Extract Vimeo videos
const vimeoPattern = new RegExp(VIDEO_PATTERNS.vimeo.source, 'g');
while ((match = vimeoPattern.exec(readmeContent)) !== null) {
const videoId = match[1];
videos.push({
type: 'vimeo',
id: videoId,
url: `https://vimeo.com/${videoId}`,
embedUrl: `https://player.vimeo.com/video/${videoId}`,
repository: repoName,
repositoryUrl: repoUrl
});
}
// Extract GitHub user-attachments videos
const githubVideoPattern = new RegExp(VIDEO_PATTERNS.githubVideo.source, 'g');
while ((match = githubVideoPattern.exec(readmeContent)) !== null) {
const videoId = match[1];
const videoUrl = match[0];
videos.push({
type: 'github',
id: videoId,
url: videoUrl,
embedUrl: videoUrl, // GitHub videos can be embedded directly
repository: repoName,
repositoryUrl: repoUrl
});
}
// Extract iframe embeds (catch any we might have missed)
const iframePattern = new RegExp(VIDEO_PATTERNS.iframe.source, 'g');
while ((match = iframePattern.exec(readmeContent)) !== null) {
const src = match[1];
if (src.includes('youtube.com') || src.includes('youtu.be')) {
const ytMatch = src.match(/(?:embed\/|v=)([a-zA-Z0-9_-]{11})/);
if (ytMatch && !videos.find(v => v.id === ytMatch[1])) {
videos.push({
type: 'youtube',
id: ytMatch[1],
url: `https://www.youtube.com/watch?v=${ytMatch[1]}`,
embedUrl: `https://www.youtube.com/embed/${ytMatch[1]}`,
thumbnail: `https://img.youtube.com/vi/${ytMatch[1]}/maxresdefault.jpg`,
repository: repoName,
repositoryUrl: repoUrl
});
}
} else if (src.includes('vimeo.com')) {
const vimeoMatch = src.match(/vimeo\.com\/video\/(\d+)/);
if (vimeoMatch && !videos.find(v => v.id === vimeoMatch[1])) {
videos.push({
type: 'vimeo',
id: vimeoMatch[1],
url: `https://vimeo.com/${vimeoMatch[1]}`,
embedUrl: `https://player.vimeo.com/video/${vimeoMatch[1]}`,
repository: repoName,
repositoryUrl: repoUrl
});
}
}
}
// Extract markdown images/videos (including GIFs)
const markdownPattern = new RegExp(VIDEO_PATTERNS.markdownVideo.source, 'g');
while ((match = markdownPattern.exec(readmeContent)) !== null) {
const altText = match[1];
const url = match[2];
// Check if it's a GIF or video file
if (url.match(/\.(gif|mp4|webm|ogg)$/i)) {
const fileName = url.split('/').pop();
videos.push({
type: 'file',
id: fileName,
url: url,
embedUrl: url,
fileName: fileName,
filePath: url,
repository: repoName,
repositoryUrl: repoUrl,
source: 'readme-markdown'
});
}
}
// Extract HTML img tags with GIF/video sources
const imgTagPattern = /<img[^>]+src=["']([^"']+)["'][^>]*>/gi;
while ((match = imgTagPattern.exec(readmeContent)) !== null) {
const url = match[1];
// Check if it's a GIF or video file
if (url.match(/\.(gif|mp4|webm|ogg)$/i)) {
const fileName = url.split('/').pop().split('?')[0]; // Remove query params
// Avoid duplicates
if (!videos.find(v => v.url === url)) {
videos.push({
type: 'file',
id: fileName,
url: url,
embedUrl: url,
fileName: fileName,
filePath: url,
repository: repoName,
repositoryUrl: repoUrl,
source: 'readme-html-img'
});
}
}
}
return videos;
}
/**
* Process all repositories
*/
async function processRepositories() {
console.log(`Processing ${repositories.length} repositories...`);
console.log('');
const allVideos = [];
let processedCount = 0;
let errorCount = 0;
for (const repo of repositories) {
try {
process.stdout.write(`\rProcessing ${repo.name}... (${processedCount + 1}/${repositories.length})`);
// Check README for videos
const readme = await fetchReadme(repo.name);
let readmeVideos = [];
if (readme) {
readmeVideos = extractVideos(readme, repo.name, repo.url);
if (readmeVideos.length > 0) {
console.log(`\n ✓ Found ${readmeVideos.length} video(s) in README of ${repo.name}`);
allVideos.push(...readmeVideos);
}
}
// Rate limiting between requests
await new Promise(resolve => setTimeout(resolve, 100));
// Check videos folder recursively
const folderVideos = await fetchVideosRecursively(repo.name, 'videos', repo.url);
if (folderVideos.length > 0) {
console.log(`\n ✓ Found ${folderVideos.length} video file(s) in /videos folder (including subfolders) of ${repo.name}`);
allVideos.push(...folderVideos);
}
processedCount++;
// Rate limiting: wait 100ms between requests
await new Promise(resolve => setTimeout(resolve, 100));
} catch (error) {
console.error(`\n ✗ Error processing ${repo.name}:`, error.message);
errorCount++;
}
}
console.log('\n');
console.log('='.repeat(60));
console.log(`Processed: ${processedCount} repositories`);
console.log(`Errors: ${errorCount}`);
console.log(`Total videos found: ${allVideos.length}`);
console.log('='.repeat(60));
// Save to JSON file
const outputPath = path.join(__dirname, '../src/data/videos.json');
fs.writeFileSync(outputPath, JSON.stringify(allVideos, null, 2));
console.log(`\nVideos saved to: ${outputPath}`);
// Print summary by repository
if (allVideos.length > 0) {
console.log('\nVideos by repository:');
const videosByRepo = {};
allVideos.forEach(video => {
if (!videosByRepo[video.repository]) {
videosByRepo[video.repository] = [];
}
videosByRepo[video.repository].push(video);
});
Object.keys(videosByRepo).sort().forEach(repo => {
console.log(` ${repo}: ${videosByRepo[repo].length} video(s)`);
});
}
}
// Run the script
processRepositories().catch(error => {
console.error('Fatal error:', error);
process.exit(1);
});
// Made with Bob