Add Subsonic API support for compatibility with CarPlay apps like Amperfy and play:Sub

This commit is contained in:
2025-12-07 22:33:36 +00:00
parent 58bb44dfb0
commit ebb434c30a
4 changed files with 560 additions and 2 deletions

371
src/routes/subsonic.js Normal file
View File

@@ -0,0 +1,371 @@
import express from 'express';
import crypto from 'crypto';
import { all, get } from '../database/db.js';
const router = express.Router();
// Subsonic API version
const API_VERSION = '1.16.1';
// Simple auth for now - you can enhance this later
const USERS = {
admin: { password: 'admin', salt: '' } // Change these!
};
// Middleware to handle Subsonic authentication
function authenticateSubsonic(req, res, next) {
const { u: username, p: password, t: token, s: salt } = req.query;
if (!username) {
return sendSubsonicError(res, 10, 'Required parameter is missing');
}
const user = USERS[username];
if (!user) {
return sendSubsonicError(res, 40, 'Wrong username or password');
}
// Check authentication
let authenticated = false;
if (token && salt) {
// Token-based auth: token = md5(password + salt)
const expectedToken = crypto.createHash('md5').update(user.password + salt).digest('hex');
authenticated = token === expectedToken;
} else if (password) {
// Plain password or enc: prefix
const plainPassword = password.startsWith('enc:')
? Buffer.from(password.slice(4), 'hex').toString()
: password;
authenticated = plainPassword === user.password;
}
if (!authenticated) {
return sendSubsonicError(res, 40, 'Wrong username or password');
}
req.subsonicUser = username;
next();
}
// Helper to send Subsonic XML response
function sendSubsonicResponse(res, data) {
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<subsonic-response xmlns="http://subsonic.org/restapi" status="ok" version="${API_VERSION}">
${data}
</subsonic-response>`;
res.type('application/xml').send(xml);
}
// Helper to send Subsonic error
function sendSubsonicError(res, code, message) {
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<subsonic-response xmlns="http://subsonic.org/restapi" status="failed" version="${API_VERSION}">
<error code="${code}" message="${message}"/>
</subsonic-response>`;
res.type('application/xml').send(xml);
}
// Ping - test connectivity
router.get('/ping.view', (req, res) => {
sendSubsonicResponse(res, '');
});
// Get license info
router.get('/getLicense.view', authenticateSubsonic, (req, res) => {
sendSubsonicResponse(res, `
<license valid="true" email="user@example.com" licenseExpires="2099-12-31T23:59:59"/>
`);
});
// Get music folders
router.get('/getMusicFolders.view', authenticateSubsonic, async (req, res) => {
sendSubsonicResponse(res, `
<musicFolders>
<musicFolder id="1" name="Music Library"/>
</musicFolders>
`);
});
// Get indexes (artists)
router.get('/getIndexes.view', authenticateSubsonic, async (req, res) => {
try {
const artists = await all(`
SELECT DISTINCT artist, COUNT(*) as album_count
FROM tracks
GROUP BY artist
ORDER BY artist
`);
// Group by first letter
const grouped = {};
artists.forEach(artist => {
const firstChar = (artist.artist || 'Unknown')[0].toUpperCase();
const letter = /[A-Z]/.test(firstChar) ? firstChar : '#';
if (!grouped[letter]) grouped[letter] = [];
const artistId = crypto.createHash('md5').update(`artist-${artist.artist}`).digest('hex');
grouped[letter].push({ id: artistId, name: artist.artist, albumCount: artist.album_count });
});
let indexXml = '<indexes lastModified="0" ignoredArticles="The El La Los Las Le Les">\n';
Object.keys(grouped).sort().forEach(letter => {
indexXml += ` <index name="${letter}">\n`;
grouped[letter].forEach(artist => {
indexXml += ` <artist id="${artist.id}" name="${escapeXml(artist.name)}" albumCount="${artist.albumCount}"/>\n`;
});
indexXml += ` </index>\n`;
});
indexXml += '</indexes>';
sendSubsonicResponse(res, indexXml);
} catch (error) {
sendSubsonicError(res, 0, error.message);
}
});
// Get artist
router.get('/getArtist.view', authenticateSubsonic, async (req, res) => {
try {
const { id } = req.query;
// Extract artist name from ID (we encoded it)
const albums = await all(`
SELECT DISTINCT album, album_artist, year,
(SELECT artwork_path FROM tracks t2 WHERE t2.album = tracks.album LIMIT 1) as artwork_path,
COUNT(*) as track_count
FROM tracks
GROUP BY album, album_artist
ORDER BY year DESC, album
`);
let artistXml = `<artist id="${id}" name="Artist" albumCount="${albums.length}">\n`;
albums.forEach(album => {
const albumId = crypto.createHash('md5').update(`album-${album.album}-${album.album_artist}`).digest('hex');
const coverArt = album.artwork_path ? albumId : '';
artistXml += ` <album id="${albumId}" name="${escapeXml(album.album)}" artist="${escapeXml(album.album_artist || 'Unknown')}" `;
artistXml += `coverArt="${coverArt}" songCount="${album.track_count}" created="2024-01-01T00:00:00" `;
artistXml += `year="${album.year || ''}" genre=""/>\n`;
});
artistXml += '</artist>';
sendSubsonicResponse(res, artistXml);
} catch (error) {
sendSubsonicError(res, 0, error.message);
}
});
// Get album
router.get('/getAlbum.view', authenticateSubsonic, async (req, res) => {
try {
const { id } = req.query;
// Get album info from first track
const firstTrack = await get(`
SELECT album, album_artist, year, genre
FROM tracks
LIMIT 1
`);
const tracks = await all(`
SELECT * FROM tracks
ORDER BY disc_number, track_number, title
`);
const coverArt = tracks[0]?.artwork_path ? id : '';
let albumXml = `<album id="${id}" name="${escapeXml(firstTrack?.album || 'Unknown')}" `;
albumXml += `artist="${escapeXml(firstTrack?.album_artist || 'Unknown')}" `;
albumXml += `coverArt="${coverArt}" songCount="${tracks.length}" `;
albumXml += `duration="${Math.floor(tracks.reduce((sum, t) => sum + (t.duration || 0), 0))}" `;
albumXml += `created="2024-01-01T00:00:00" year="${firstTrack?.year || ''}" genre="${escapeXml(firstTrack?.genre || '')}">\n`;
tracks.forEach(track => {
albumXml += buildSongXml(track, req);
});
albumXml += '</album>';
sendSubsonicResponse(res, albumXml);
} catch (error) {
sendSubsonicError(res, 0, error.message);
}
});
// Get random songs
router.get('/getRandomSongs.view', authenticateSubsonic, async (req, res) => {
try {
const size = parseInt(req.query.size) || 10;
const tracks = await all(`
SELECT * FROM tracks
ORDER BY RANDOM()
LIMIT ?
`, [size]);
let songsXml = '<randomSongs>\n';
tracks.forEach(track => {
songsXml += buildSongXml(track, req);
});
songsXml += '</randomSongs>';
sendSubsonicResponse(res, songsXml);
} catch (error) {
sendSubsonicError(res, 0, error.message);
}
});
// Stream audio file
router.get('/stream.view', authenticateSubsonic, async (req, res) => {
try {
const { id } = req.query;
const track = await get('SELECT * FROM tracks WHERE id = ?', [id]);
if (!track) {
return sendSubsonicError(res, 70, 'Song not found');
}
const filePath = `${process.cwd()}/audio_library/${track.file_path}`;
res.sendFile(filePath);
} catch (error) {
sendSubsonicError(res, 0, error.message);
}
});
// Get cover art
router.get('/getCoverArt.view', authenticateSubsonic, async (req, res) => {
try {
const { id } = req.query;
// Try to find artwork by album ID or track ID
const track = await get('SELECT artwork_path FROM tracks WHERE id = ? OR id IN (SELECT id FROM tracks LIMIT 1)', [id]);
if (!track || !track.artwork_path) {
return res.status(404).send('Cover art not found');
}
const artworkPath = `${process.cwd()}/artwork/${track.artwork_path}`;
res.sendFile(artworkPath);
} catch (error) {
res.status(404).send('Cover art not found');
}
});
// Get playlists
router.get('/getPlaylists.view', authenticateSubsonic, async (req, res) => {
try {
const playlists = await all('SELECT * FROM playlists ORDER BY name');
let playlistsXml = '<playlists>\n';
for (const playlist of playlists) {
const trackCount = await get(
'SELECT COUNT(*) as count FROM playlist_tracks WHERE playlist_id = ?',
[playlist.id]
);
playlistsXml += ` <playlist id="${playlist.id}" name="${escapeXml(playlist.name)}" `;
playlistsXml += `songCount="${trackCount.count}" duration="0" `;
playlistsXml += `created="${playlist.created_at}" changed="${playlist.updated_at}" owner="admin"/>\n`;
}
playlistsXml += '</playlists>';
sendSubsonicResponse(res, playlistsXml);
} catch (error) {
sendSubsonicError(res, 0, error.message);
}
});
// Get playlist
router.get('/getPlaylist.view', authenticateSubsonic, async (req, res) => {
try {
const { id } = req.query;
const playlist = await get('SELECT * FROM playlists WHERE id = ?', [id]);
if (!playlist) {
return sendSubsonicError(res, 70, 'Playlist not found');
}
const tracks = await all(`
SELECT t.* FROM tracks t
JOIN playlist_tracks pt ON t.id = pt.track_id
WHERE pt.playlist_id = ?
ORDER BY pt.position
`, [id]);
let playlistXml = `<playlist id="${playlist.id}" name="${escapeXml(playlist.name)}" `;
playlistXml += `songCount="${tracks.length}" duration="0" owner="admin">\n`;
tracks.forEach(track => {
playlistXml += buildSongXml(track, req);
});
playlistXml += '</playlist>';
sendSubsonicResponse(res, playlistXml);
} catch (error) {
sendSubsonicError(res, 0, error.message);
}
});
// Search
router.get('/search3.view', authenticateSubsonic, async (req, res) => {
try {
const { query } = req.query;
const searchTerm = `%${query}%`;
const tracks = await all(`
SELECT * FROM tracks
WHERE title LIKE ? OR artist LIKE ? OR album LIKE ?
LIMIT 20
`, [searchTerm, searchTerm, searchTerm]);
let searchXml = '<searchResult3>\n';
tracks.forEach(track => {
searchXml += buildSongXml(track, req);
});
searchXml += '</searchResult3>';
sendSubsonicResponse(res, searchXml);
} catch (error) {
sendSubsonicError(res, 0, error.message);
}
});
// Helper to build song XML
function buildSongXml(track, req) {
const albumId = crypto.createHash('md5').update(`album-${track.album}-${track.album_artist}`).digest('hex');
const artistId = crypto.createHash('md5').update(`artist-${track.artist}`).digest('hex');
const coverArt = track.artwork_path ? track.id : '';
let xml = ` <song id="${track.id}" parent="${albumId}" `;
xml += `title="${escapeXml(track.title)}" album="${escapeXml(track.album || '')}" `;
xml += `artist="${escapeXml(track.artist || '')}" track="${track.track_number || ''}" `;
xml += `year="${track.year || ''}" genre="${escapeXml(track.genre || '')}" `;
xml += `coverArt="${coverArt}" size="${track.file_size || 0}" `;
xml += `contentType="audio/${track.format || 'mpeg'}" suffix="${track.format || 'mp3'}" `;
xml += `duration="${Math.floor(track.duration || 0)}" bitRate="${Math.floor((track.bitrate || 0) / 1000)}" `;
xml += `path="${escapeXml(track.file_path)}" isDir="false" `;
xml += `albumId="${albumId}" artistId="${artistId}" type="music"/>\n`;
return xml;
}
// Helper to escape XML
function escapeXml(unsafe) {
if (!unsafe) return '';
return unsafe.toString()
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
export default router;