azurcast-to-mastodon/app.js

78 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2020-05-01 14:20:02 +02:00
import express from "express";
import fs from "fs";
import cookieParser from "cookie-parser";
import bodyParser from "body-parser";
import Pino from "express-pino-logger";
import cors from "cors";
2020-12-16 14:06:25 +01:00
import { port, trustProxy } from "./config";
2020-05-01 14:20:02 +02:00
import {
formatResponse,
formatResponseError,
publishMessage,
} from "./libs/Format";
let currentSongId = "";
2020-05-02 10:14:17 +02:00
let currentSong = {};
2020-05-01 14:20:02 +02:00
const pino = new Pino({
prettyPrint: true,
});
2020-12-16 14:06:25 +01:00
pino.logger.info(`Server started on port ${port}`);
2020-05-01 14:20:02 +02:00
const app = express();
app.use(cors());
app.use(pino);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
2020-12-16 14:06:25 +01:00
app.set("trust proxy", trustProxy);
2020-05-01 14:20:02 +02:00
// Get last saved song id on load
fs.readFile("./currentSongId", "utf8", (err, data) => {
if (!err) {
currentSongId = data;
}
});
app.post("/post", function (req, res, next) {
if (req.body && req.body.now_playing && req.body.now_playing.song) {
const newSongId = req.body.now_playing.song.id;
if (newSongId !== currentSongId) {
currentSongId = newSongId;
2020-05-02 10:14:17 +02:00
currentSong = req.body.now_playing.song;
2020-05-01 14:20:02 +02:00
fs.writeFile("./currentSongId", currentSongId, (err) => {
if (err) {
req.log.error(err);
}
});
2020-12-16 14:06:25 +01:00
publishMessage(req.body.now_playing, req.log, (err, response) => {
2020-05-01 14:20:02 +02:00
if (err) {
req.log.error(err);
}
formatResponse(req, res, next, err, response);
});
}
} else {
formatResponseError(res, new Error("Missing now_playing object"));
}
});
2020-05-02 10:14:17 +02:00
app.get("/current", function (req, res, next) {
formatResponse(req, res, next, null, currentSong);
});
2020-05-01 14:20:02 +02:00
// Gestion des erreurs
app.use((err, req, res, next) => {
res.error = err;
if (res.headersSent) {
next(err);
} else {
formatResponseError(res, err);
}
});
module.exports = app;