surf/index.js
hazy 0789b75fbd Add README.md, add /api/videos-found endpoint
Also added start script to package.json
2022-05-01 23:56:59 -05:00

105 lines
3.2 KiB
JavaScript

import ytsr from 'ytsr'
import fs from 'fs'
import express from 'express'
const app = express()
const playerHtml = fs.readFileSync('site.html', 'utf-8')
const port = process.env.PORT??3500
let list = []
if (fs.existsSync('videolist')) list = fs.readFileSync('videolist', 'utf-8').split('\n')
app.get('/', (req, res) => {
res.send(playerHtml.replace('{{VIDEO_ID_HERE}}', list[Math.floor(Math.random()*list.length)]))
})
app.get('/api/random', (req, res) => {
let amount = req.query.count??1
let selection = []
for (let i = 0; i < amount; i++) {
selection.push(list[Math.floor(Math.random()*list.length)])
}
res.json(selection)
})
app.get('/api/videos-found', (req, res) => {
res.json(list.length)
})
app.listen(port, () => {console.log(`Listening at http://localhost:${port}`)})
function random(chars, length = 8) {
chars = chars??'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let str = '';
for (let i = 0; i < length; i++) {
str += chars.charAt(Math.floor(Math.random() * chars.length));
}
return str
}
function titleGen(category) {
category = category??Math.round(Math.random()*6)
let title
switch (category) {
case 0:
// Random GoPro filename generator
title = `G${random('HX', 1)}01${random('0123456789', 4)}`
break;
case 1:
// Random DSC filename generator
title = `DSC ${random('0123456789', 4)}`
break;
case 2:
// Random IMG filename generator
title = `IMG ${random('0123456789', 4)}`
break;
case 3:
// Random keymash generator
title = random('abcdefghijklmnopqrstuvwxyz', 2+Math.round(Math.random()*6))
break;
default:
// Random screen recording filename generator
let year = 2017+Math.floor(Math.random()*4)
let month = Math.round(Math.random()*12).toString().padStart(2, '0')
let day = Math.round(Math.random()*25).toString().padStart(2, '0')
title = `screen-${year}${month}${day}`
}
return title
}
function shuffleArray(array) {
let curId = array.length;
while (0 !== curId) {
let randId = Math.floor(Math.random() * curId);
curId -= 1;
let tmp = array[curId];
array[curId] = array[randId];
array[randId] = tmp;
}
return array;
}
async function writeList(count) {
let found = []
for (let i = 0; i < count; i++) {
let title = titleGen()
let items = (await ytsr(title, { pages: 1 })).items
let fewViews = items.filter(e => {
return e.type=='video'&&e.views<10
}).map(e => {
return e.id
})
found.push(...fewViews)
}
found = shuffleArray(found)
list.push(...found)
let urls = found.join('\n')
if (!fs.existsSync('videolist')) fs.writeFileSync('videolist', urls)
else {
let currentList = fs.readFileSync('videolist', 'utf-8')
fs.writeFileSync('videolist', currentList+'\n'+urls)
}
console.log('Wrote list to file.')
}
setInterval(() => {writeList(100)}, 10*60*1000)
writeList(200)