Dwelling/radio/index.js

84 lines
2.3 KiB
JavaScript
Raw Normal View History

2021-02-10 01:01:50 +04:00
const fs = require("fs");
const path = require("path");
const uti = require("util");
const exec = uti.promisify(require("child_process").exec);
2021-02-10 01:01:50 +04:00
const Koa = require("koa");
const koaPug = require("koa-pug");
const koaRouter = require("koa-router");
const fetch = require("node-fetch");
const config = require("./config");
const util = require("../shared/util");
2021-02-10 01:01:50 +04:00
async function getRadioStatus() {
try {
let status = await fetch('http://radio.arav.home/status-json.xsl').then(r => r.json());
return {
server_start_iso8601: status.icestats.server_start_iso8601,
server_start_date: util.datetime(status.icestats.server_start_iso8601, util.post_date_format),
song: `${status.icestats.source.artist} - ${status.icestats.source.title}`,
listener_peak: status.icestats.source.listener_peak,
listeners: status.icestats.source.listeners
}
} catch {
return {
server_start_iso8601: "n/a",
server_start_date: "n/a",
song: "n/a",
listener_peak: "n/a",
listeners: "n/a"
}
}
}
async function getLastSongs(count=11) {
const { stdout, stderr } = await exec(`tail -n ${count} /var/log/icecast/playlist.log | awk -F '|' '{ print $4 }'`);
let songs = stdout.trim().split("\n");
songs.pop();
for (let i = 0; i < songs.length; ++i)
songs[i] = songs[i].split(' - ');
return songs;
}
function setRoutes() {
return koaRouter().get('/', async ctx => {
2021-02-10 01:01:50 +04:00
await ctx.render('index', {
title: "/ Radio",
2021-02-10 01:01:50 +04:00
description: "Internet-radio broadcasting from under my desk.",
main_site: util.getServiceByHost(ctx.header.host),
radio_status: await getRadioStatus(),
last_songs: await getLastSongs()
2021-02-10 01:01:50 +04:00
});
})
.get('/filelist', async ctx => {
ctx.type = 'text/html';
ctx.body = fs.readFileSync(
path.join(__dirname, '/static/radio_filelist.html'));
2021-02-10 01:01:50 +04:00
})
.get('/playlist', async ctx => {
ctx.attachment('radio.arav.top.m3u');
ctx.body = fs.readFileSync(
path.join(__dirname, '/static/assets/files/radio.arav.top.m3u'));
2021-02-10 01:01:50 +04:00
})
.get('/stats', async ctx => {
ctx.body = await getRadioStatus();
})
.get('/lastplayed', async ctx => {
ctx.body = await getLastSongs();
2021-02-10 01:01:50 +04:00
});
}
const app = new Koa();
const pug = new koaPug({
viewPath: path.join(__dirname, "views"),
locals: {
moment: util.datetime },
app: app
});
2021-02-10 01:01:50 +04:00
app.proxy = true;
app
.use(setRoutes().routes())
.listen(config.port, config.host);