#!/usr/bin/env babel-node import path from 'path' import sqlite from 'sqlite' import Promise from 'bluebird' import express from 'express' require('express-async-errors') const values = require(path.join(__dirname, 'values.json')) const tracksPerPage = 100 const dbPromise = Promise.resolve() .then(() => sqlite.open(path.join(__dirname, values.database), { Promise, cache: true })) .then(db => db.migrate()) const app = express() const port = process.env.PORT || 3000 const router = express.Router() router.get('/tracks', async (req, res) => { let page = parseInt(req.query.page) || 1 if (isNaN(page)) { page = 1 } let db = await dbPromise let count = (await db.get('SELECT COUNT(*) FROM Track'))['COUNT(*)'] let pageCount = Math.ceil(count / tracksPerPage) if (page > pageCount) page = pageCount let offset = (page - 1) * tracksPerPage let tracks = await db.all('SELECT * FROM Track LIMIT ? OFFSET ?', tracksPerPage, offset) for (let i in tracks) { delete tracks[i].file } res.jsonp({ page, count, pageCount, tracks }) }) router.get('/tracks/search', async (req, res) => { let query = req.query.string let db = await dbPromise let tracks = await db.all('SELECT * FROM Track WHERE title || ifnull(artist,\'\') || ifnull(album,\'\') LIKE ? LIMIT 100', `%${query}%`) for (let i in tracks) { delete tracks[i].file } res.jsonp(tracks) }) router.get('/track/:id', async (req, res, next) => { let id = req.params.id let db = await dbPromise let track = await db.get('SELECT * FROM Track WHERE id = ?', id) if (!track) return next(new Error('404 file not found')) delete track.file res.jsonp(track) }) router.get('/playlists', async (req, res, next) => { let db = await dbPromise let playlists = await db.all('SELECT * FROM Playlist') res.jsonp(playlists) }) router.get('/playlist/:id', async (req, res, next) => { let id = req.params.id let db = await dbPromise let playlist = await db.get('SELECT title FROM Playlist WHERE id = ?', id) if (!playlist) return next(new Error('404 file not found')) let tracks = await db.all('SELECT trackId FROM PlaylistEntry WHERE playlistId = ?', id) playlist.tracks = tracks res.jsonp(playlist) }) router.get('/serve/by-id/:id', async (req, res, next) => { let id = req.params.id let db = await dbPromise let track = await db.get('SELECT file FROM Track WHERE id = ?', id) if (!track) return next(new Error('404 file not found')) res.set('Cache-Control', 'public, max-age=31557600') res.sendFile(path.resolve(track.file)) }) router.use((err, req, res, next) => { console.error(err) res.status(404).jsonp({error: 404}) }) app.use('/api', router) app.use('/', express.static(path.join(__dirname, 'public'))) app.listen(port, '127.0.0.1', function () { console.log(`app running on port ${port}`) })