MusicServer/routes/ytm.ts

63 lines
2.3 KiB
TypeScript

import { Application } from "express";
import expressAsyncHandler from "express-async-handler";
import createHttpError from "http-errors";
import ytmApi from "../utils/ytmApi.js";
import downloadSong from "../utils/download.js";
import { existsSync, realpathSync } from 'fs';
import { dbRead, dbStore } from "../database.js";
import md5 from "md5";
import { SongDetailed, SongFull } from "ytmusic-api";
export default function routeYTM(app: Application) {
app.get('/music/search', expressAsyncHandler(
async (req, res) => {
if (typeof req.query.q !== 'string') throw createHttpError[400]();
var songs: SongDetailed[] | null = dbRead('cache', md5(req.query.q));
if (!songs) {
songs = await ytmApi.searchSongs(req.query.q);
dbStore('cache', md5(req.query.q), songs);
}
res.send(songs);
}
));
app.get('/music/get', expressAsyncHandler(
async (req, res) => {
if (typeof req.query.id !== 'string') throw createHttpError[400]();
var song: SongDetailed | SongFull | null = dbRead('cache', req.query.id);
if (!song) {
song = await ytmApi.getSong(req.query.id);
dbStore('cache', req.query.id, song);
}
res.send(song);
}
));
app.get('/music/lyrics', expressAsyncHandler(
async (req, res) => {
if (typeof req.query.id !== 'string') throw createHttpError[400]();
var lyrics = dbRead('cache', md5(`lyrics_${req.query.id}`));
if (!lyrics) {
lyrics = await ytmApi.getLyrics(req.query.id);
dbStore('cache', md5(`lyrics_${req.query.id}`), lyrics ?? 1);
}
if (lyrics === 1) throw createHttpError[404]();
res.send(lyrics);
}
));
app.get('/music/file', expressAsyncHandler(
async (req, res) => {
if (typeof req.query.id !== 'string') throw createHttpError[400]();
const filePath = `./tmpStore/${md5(req.query.id)}.mp3`;
if (!existsSync(filePath)) await downloadSong(req.query.id);
if (existsSync(filePath)) {
res.sendFile(realpathSync(filePath));
} else {
throw createHttpError[404]();
}
}
));
}