-
Notifications
You must be signed in to change notification settings - Fork 0
/
yt-titles.js
52 lines (52 loc) · 1.59 KB
/
yt-titles.js
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
const fs = require('fs');
const https = require('https');
let htmlContent = fs.readFileSync('index.html', 'utf8');
const regex = /<y-t\s+v="([^"]+)"(?:(?!t).)*?>/g;
async function fetchTitle(videoId) {
const response = await new Promise((resolve, reject) => {
https.get(`https://noembed.com/embed?url=https://www.youtube.com/watch?v=${videoId.split('?')[0]}`, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
resolve(JSON.parse(data));
});
}).on('error', (err) => {
reject(err);
});
});
return response.title;
}
async function updateTitles() {
let matches = [...htmlContent.matchAll(regex)];
const replacements = await Promise.all(Array.from(matches).map(async match => {
const videoId = match[1];
const title = await fetchTitle(videoId);
let newTag = `<y-t`;
const existingAttributes = match[0].match(/\w+="[^"]*"/g);
existingAttributes.forEach(attr => {
newTag += ` ${attr}`;
});
if (match[0].includes('t="')) {
const existingTitle = match[0].match(/t="([^"]*)"/)[1];
if (existingTitle) {
newTag += ` t="${existingTitle}"`;
} else {
newTag += ` t="${title}"`;
}
} else {
newTag += ` t="${title}"`;
}
newTag += '>';
return {
old: match[0],
new: newTag
};
}));
replacements.forEach(replacement => {
htmlContent = htmlContent.replace(replacement.old, replacement.new);
});
fs.writeFileSync('index.html', htmlContent, 'utf8');
}
updateTitles().then(() => console.log('Titles updated.'));