azurcast-to-mastodon/app.js

79 lines
1.8 KiB
JavaScript
Raw 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";
import config from "./config";
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,
});
pino.logger.info(`Server started on port ${config.port}`);
const app = express();
app.use(cors());
app.use(pino);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.set("trust proxy", config.trustProxy);
// 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) {
2020-05-08 13:30:03 +02:00
console.log("Received:", req.body.now_playing);
2020-05-01 14:20:02 +02:00
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);
}
});
publishMessage(req.body.now_playing, (err, response) => {
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;