77 lines
1.8 KiB
JavaScript
77 lines
1.8 KiB
JavaScript
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 { port, trustProxy } from "./config";
|
|
import {
|
|
formatResponse,
|
|
formatResponseError,
|
|
publishMessage,
|
|
} from "./libs/Format";
|
|
|
|
let currentSongId = "";
|
|
let currentSong = {};
|
|
|
|
const pino = new Pino({
|
|
prettyPrint: true,
|
|
});
|
|
pino.logger.info(`Server started on port ${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", 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) {
|
|
const newSongId = req.body.now_playing.song.id;
|
|
if (newSongId !== currentSongId) {
|
|
currentSongId = newSongId;
|
|
currentSong = req.body.now_playing.song;
|
|
fs.writeFile("./currentSongId", currentSongId, (err) => {
|
|
if (err) {
|
|
req.log.error(err);
|
|
}
|
|
});
|
|
publishMessage(req.body.now_playing, req.log, (err, response) => {
|
|
if (err) {
|
|
req.log.error(err);
|
|
}
|
|
formatResponse(req, res, next, err, response);
|
|
});
|
|
}
|
|
} else {
|
|
formatResponseError(res, new Error("Missing now_playing object"));
|
|
}
|
|
});
|
|
|
|
app.get("/current", function (req, res, next) {
|
|
formatResponse(req, res, next, null, currentSong);
|
|
});
|
|
|
|
// Gestion des erreurs
|
|
app.use((err, req, res, next) => {
|
|
res.error = err;
|
|
if (res.headersSent) {
|
|
next(err);
|
|
} else {
|
|
formatResponseError(res, err);
|
|
}
|
|
});
|
|
|
|
module.exports = app;
|