Added podcast support, only from subsonic API for now, ref #726

This commit is contained in:
emeric
2025-09-13 15:04:13 +02:00
parent 1d584ebcc6
commit 932e7715f5
111 changed files with 4717 additions and 188 deletions
@@ -34,7 +34,6 @@ namespace lms::api::subsonic
};
static inline constexpr ProtocolVersion defaultServerProtocolVersion{ 1, 16, 0 };
static inline constexpr std::string_view serverVersion{ "8" };
} // namespace lms::api::subsonic
namespace lms::core::stringUtils
+42 -2
View File
@@ -19,8 +19,6 @@
#include "SubsonicId.hpp"
#include "core/String.hpp"
namespace lms::api::subsonic
{
std::string idToString(db::ArtistId id)
@@ -33,6 +31,16 @@ namespace lms::api::subsonic
return "dir-" + id.toString();
}
std::string idToString(db::PodcastEpisodeId id)
{
return "podep-" + id.toString();
}
std::string idToString(db::PodcastId id)
{
return "pod-" + id.toString();
}
std::string idToString(db::ReleaseId id)
{
return "al-" + id.toString();
@@ -92,6 +100,38 @@ namespace lms::core::stringUtils
return std::nullopt;
}
template<>
std::optional<db::PodcastEpisodeId> readAs(std::string_view str)
{
std::vector<std::string_view> values{ core::stringUtils::splitString(str, '-') };
if (values.size() != 2)
return std::nullopt;
if (values[0] != "podep")
return std::nullopt;
if (const auto value{ core::stringUtils::readAs<db::PodcastEpisodeId::ValueType>(values[1]) })
return db::PodcastEpisodeId{ *value };
return std::nullopt;
}
template<>
std::optional<db::PodcastId> readAs(std::string_view str)
{
std::vector<std::string_view> values{ core::stringUtils::splitString(str, '-') };
if (values.size() != 2)
return std::nullopt;
if (values[0] != "pod")
return std::nullopt;
if (const auto value{ core::stringUtils::readAs<db::PodcastId::ValueType>(values[1]) })
return db::PodcastId{ *value };
return std::nullopt;
}
template<>
std::optional<db::ReleaseId> readAs(std::string_view str)
{
+10
View File
@@ -23,6 +23,8 @@
#include "database/objects/ArtistId.hpp"
#include "database/objects/DirectoryId.hpp"
#include "database/objects/MediaLibraryId.hpp"
#include "database/objects/PodcastEpisodeId.hpp"
#include "database/objects/PodcastId.hpp"
#include "database/objects/ReleaseId.hpp"
#include "database/objects/TrackId.hpp"
#include "database/objects/TrackListId.hpp"
@@ -31,6 +33,8 @@ namespace lms::api::subsonic
{
std::string idToString(db::ArtistId id);
std::string idToString(db::DirectoryId id);
std::string idToString(db::PodcastEpisodeId id);
std::string idToString(db::PodcastId id);
std::string idToString(db::ReleaseId id);
std::string idToString(db::TrackId id);
std::string idToString(db::TrackListId id);
@@ -48,6 +52,12 @@ namespace lms::core::stringUtils
template<>
std::optional<db::MediaLibraryId> readAs(std::string_view str);
template<>
std::optional<db::PodcastEpisodeId> readAs(std::string_view str);
template<>
std::optional<db::PodcastId> readAs(std::string_view str);
template<>
std::optional<db::ReleaseId> readAs(std::string_view str);
+20 -9
View File
@@ -46,6 +46,7 @@
#include "endpoints/MediaLibraryScanning.hpp"
#include "endpoints/MediaRetrieval.hpp"
#include "endpoints/Playlists.hpp"
#include "endpoints/Podcast.hpp"
#include "endpoints/Searching.hpp"
#include "endpoints/System.hpp"
#include "endpoints/UserManagement.hpp"
@@ -97,8 +98,13 @@ namespace lms::api::subsonic
std::string res;
bool firstParameter{ true };
for (const auto& [type, values] : parameterMap)
{
if (!firstParameter)
res += ", ";
firstParameter = false;
res += "{" + type + "=";
if (values.size() == 1)
{
@@ -107,14 +113,18 @@ namespace lms::api::subsonic
else
{
res += "{";
bool firstValue{ true };
for (const std::string& value : values)
{
if (!firstValue)
res += ',';
firstValue = false;
res += redactValueIfNeeded(type, value);
res += ',';
}
res += "}";
}
res += "}, ";
res += "}";
}
return res;
@@ -210,13 +220,14 @@ namespace lms::api::subsonic
{ "/deleteShare", { handleNotImplemented } },
// Podcast
{ "/getPodcasts", { handleNotImplemented } },
{ "/getNewestPodcasts", { handleNotImplemented } },
{ "/refreshPodcasts", { handleNotImplemented } },
{ "/createPodcastChannel", { handleNotImplemented } },
{ "/deletePodcastChannel", { handleNotImplemented } },
{ "/deletePodcastEpisode", { handleNotImplemented } },
{ "/downloadPodcastEpisode", { handleNotImplemented } },
{ "/getPodcasts", { handleGetPodcasts } },
{ "/getNewestPodcasts", { handleGetNewestPodcasts } },
{ "/refreshPodcasts", { handleRefreshPodcasts, AuthenticationMode::Authenticated, { db::UserType::ADMIN } } },
{ "/createPodcastChannel", { handleCreatePodcastChannel, AuthenticationMode::Authenticated, { db::UserType::ADMIN } } },
{ "/deletePodcastChannel", { handleDeletePodcastChannel, AuthenticationMode::Authenticated, { db::UserType::ADMIN } } },
{ "/deletePodcastEpisode", { handleDeletePodcastEpisode, AuthenticationMode::Authenticated, { db::UserType::ADMIN } } },
{ "/downloadPodcastEpisode", { handleDownloadPodcastEpisode, AuthenticationMode::Authenticated, { db::UserType::ADMIN } } },
{ "/getPodcastEpisode", { handleGetPodcastEpisode } },
// Jukebox
{ "/jukeboxControl", { handleNotImplemented } },
+2 -2
View File
@@ -26,6 +26,7 @@
#include <boost/property_tree/xml_parser.hpp>
#include "core/String.hpp"
#include "core/Version.hpp"
#include "ProtocolVersion.hpp"
@@ -140,7 +141,7 @@ namespace lms::api::subsonic
// OpenSubsonic mandatory fields
// No big deal to send them even for legacy clients
responseNode.setAttribute("type", "lms");
responseNode.setAttribute("serverVersion", serverVersion);
responseNode.setAttribute("serverVersion", core::getVersion());
responseNode.setAttribute("openSubsonic", true);
return response;
@@ -362,5 +363,4 @@ namespace lms::api::subsonic
JsonSerializer serializer;
serializer.serializeNode(os, _root);
}
} // namespace lms::api::subsonic
@@ -19,31 +19,37 @@
#include "MediaRetrieval.hpp"
#include "av/Exception.hpp"
#include "av/IAudioFile.hpp"
#include <chrono>
#include "core/FileResourceHandlerCreator.hpp"
#include "core/ILogger.hpp"
#include "core/IResourceHandler.hpp"
#include "core/String.hpp"
#include "core/Utils.hpp"
#include "av/Exception.hpp"
#include "av/IAudioFile.hpp"
#include "database/Session.hpp"
#include "database/objects/PodcastEpisode.hpp"
#include "database/objects/PodcastEpisodeId.hpp"
#include "database/objects/Track.hpp"
#include "database/objects/TrackEmbeddedImageId.hpp"
#include "database/objects/TrackLyrics.hpp"
#include "database/objects/User.hpp"
#include "services/artwork/IArtworkService.hpp"
#include "services/podcast/IPodcastService.hpp"
#include "services/transcoding/ITranscodingService.hpp"
#include "CoverArtId.hpp"
#include "ParameterParsing.hpp"
#include "RequestContext.hpp"
#include "SubsonicId.hpp"
#include "SubsonicResponse.hpp"
#include "responses/Lyrics.hpp"
namespace lms::api::subsonic
{
using namespace db;
namespace
{
std::optional<transcoding::OutputFormat> subsonicStreamFormatToAvOutputFormat(std::string_view format)
@@ -100,8 +106,8 @@ namespace lms::api::subsonic
struct StreamParameters
{
transcoding::InputParameters inputParameters;
std::string inputMimeType; // set if known
std::optional<transcoding::OutputParameters> outputParameters;
std::filesystem::path trackPath;
bool estimateContentLength{};
};
@@ -125,10 +131,57 @@ namespace lms::api::subsonic
}
}
using AudioFileId = std::variant<db::TrackId, db::PodcastEpisodeId>;
struct AudioFileInfo
{
std::filesystem::path path;
std::chrono::milliseconds duration{};
std::size_t bitrate{};
std::string mimeType; // set if known
};
AudioFileInfo getAudioFileInfo(db::Session& session, AudioFileId audioFileId)
{
AudioFileInfo res;
auto transaction{ session.createReadTransaction() };
if (const db::TrackId * trackId{ std::get_if<db::TrackId>(&audioFileId) })
{
const db::Track::pointer track{ db::Track::find(session, *trackId) };
if (!track)
throw RequestedDataNotFoundError{};
res.path = track->getAbsoluteFilePath();
res.duration = track->getDuration();
res.bitrate = track->getBitrate();
}
else if (const db::PodcastEpisodeId * episodeId{ std::get_if<db::PodcastEpisodeId>(&audioFileId) })
{
const db::PodcastEpisode::pointer episode{ db::PodcastEpisode::find(session, *episodeId) };
if (!episode)
throw RequestedDataNotFoundError{};
std::filesystem::path podcastCachePath{ core::Service<podcast::IPodcastService>::get()->getCachePath() };
res.path = podcastCachePath / episode->getAudioRelativeFilePath();
res.duration = episode->getDuration();
res.bitrate = episode->getEnclosureLength() / std::chrono::duration_cast<std::chrono::seconds>(episode->getDuration()).count() * 8;
res.mimeType = episode->getEnclosureContentType();
}
return res;
}
StreamParameters getStreamParameters(RequestContext& context)
{
// Mandatory params
const TrackId id{ getMandatoryParameterAs<TrackId>(context.parameters, "id") };
const auto trackId{ getParameterAs<db::TrackId>(context.parameters, "id") };
const auto podcastEpisodeId{ getParameterAs<db::PodcastEpisodeId>(context.parameters, "id") };
if (!trackId && !podcastEpisodeId)
throw RequiredParameterMissingError{ "id" };
const AudioFileId audioId{ trackId ? AudioFileId{ *trackId } : AudioFileId{ *podcastEpisodeId } };
// Optional params
std::size_t maxBitRate{ getParameterAs<std::size_t>(context.parameters, "maxBitRate").value_or(0) * 1000 }; // "If set to zero, no limit is imposed", given in kpbs
@@ -136,21 +189,18 @@ namespace lms::api::subsonic
std::size_t timeOffset{ getParameterAs<std::size_t>(context.parameters, "timeOffset").value_or(0) };
bool estimateContentLength{ getParameterAs<bool>(context.parameters, "estimateContentLength").value_or(false) };
const AudioFileInfo audioFileInfo{ getAudioFileInfo(context.dbSession, audioId) };
StreamParameters parameters;
auto transaction{ context.dbSession.createReadTransaction() };
const auto track{ Track::find(context.dbSession, id) };
if (!track)
throw RequestedDataNotFoundError{};
parameters.inputParameters.trackId = id;
parameters.inputParameters.filePath = audioFileInfo.path;
parameters.inputParameters.duration = audioFileInfo.duration;
parameters.inputParameters.offset = std::chrono::seconds{ timeOffset };
parameters.inputMimeType = audioFileInfo.mimeType;
parameters.estimateContentLength = estimateContentLength;
parameters.trackPath = track->getAbsoluteFilePath();
if (format == "raw") // raw => no transcoding
return parameters;
if (format == "raw") // raw => no transcoding
return parameters; // TODO: what if offset is not 0?
std::optional<transcoding::OutputFormat> requestedFormat{ subsonicStreamFormatToAvOutputFormat(format) };
if (!requestedFormat)
@@ -159,7 +209,7 @@ namespace lms::api::subsonic
requestedFormat = userTranscodeFormatToAvFormat(context.user->getSubsonicDefaultTranscodingOutputFormat());
}
if (!requestedFormat && (maxBitRate == 0 || track->getBitrate() <= maxBitRate))
if (!requestedFormat && (maxBitRate == 0 || audioFileInfo.bitrate <= maxBitRate))
{
LMS_LOG(API_SUBSONIC, DEBUG, "File's bitrate is compatible with parameters => no transcoding");
return parameters; // no transcoding needed
@@ -169,9 +219,9 @@ namespace lms::api::subsonic
// same codec => apply max bitrate
// otherwise => apply default bitrate (because we can't really compare bitrates between formats) + max bitrate)
std::size_t bitrate{};
if (requestedFormat && isOutputFormatCompatible(track->getAbsoluteFilePath(), *requestedFormat))
if (requestedFormat && isOutputFormatCompatible(audioFileInfo.path, *requestedFormat))
{
if (maxBitRate == 0 || track->getBitrate() <= maxBitRate)
if (maxBitRate == 0 || audioFileInfo.bitrate <= maxBitRate)
{
LMS_LOG(API_SUBSONIC, DEBUG, "File's bitrate and format are compatible with parameters => no transcoding");
return parameters; // no transcoding needed
@@ -218,7 +268,7 @@ namespace lms::api::subsonic
// Choice: we return only the first lyrics if the track has many lyrics
db::TrackLyrics::FindParameters lyricsParams;
lyricsParams.setTrack(tracks.results[0]);
lyricsParams.setSortMethod(TrackLyricsSortMethod::ExternalFirst);
lyricsParams.setSortMethod(db::TrackLyricsSortMethod::ExternalFirst);
lyricsParams.setRange(db::Range{ 0, 1 });
db::TrackLyrics::find(context.dbSession, lyricsParams, [&](const db::TrackLyrics::pointer& lyrics) {
@@ -278,7 +328,7 @@ namespace lms::api::subsonic
{
auto transaction{ context.dbSession.createReadTransaction() };
auto track{ Track::find(context.dbSession, id) };
auto track{ db::Track::find(context.dbSession, id) };
if (!track)
throw RequestedDataNotFoundError{};
@@ -310,7 +360,7 @@ namespace lms::api::subsonic
if (streamParameters.outputParameters)
resourceHandler = core::Service<transcoding::ITranscodingService>::get()->createResourceHandler(streamParameters.inputParameters, *streamParameters.outputParameters, streamParameters.estimateContentLength);
else
resourceHandler = core::createFileResourceHandler(streamParameters.trackPath);
resourceHandler = core::createFileResourceHandler(streamParameters.inputParameters.filePath, streamParameters.inputMimeType);
}
else
{
@@ -323,6 +373,7 @@ namespace lms::api::subsonic
}
catch (const av::Exception& e)
{
response.setStatus(404); // report not found if something wrong happened
LMS_LOG(API_SUBSONIC, ERROR, "Caught Av exception: " << e.what());
}
}
@@ -0,0 +1,158 @@
/*
* Copyright (C) 2025 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Podcast.hpp"
#include "database/Session.hpp"
#include "database/objects/Podcast.hpp"
#include "database/objects/PodcastEpisode.hpp"
#include "services/podcast/IPodcastService.hpp"
#include "ParameterParsing.hpp"
#include "RequestContext.hpp"
#include "SubsonicId.hpp"
#include "SubsonicResponse.hpp"
#include "responses/Podcast.hpp"
namespace lms::api::subsonic
{
Response handleGetPodcasts(RequestContext& context)
{
const bool includeEpisodes{ getParameterAs<bool>(context.parameters, "includeEpisodes").value_or(true) };
const std::optional<db::PodcastId> podcastId{ getParameterAs<db::PodcastId>(context.parameters, "id") };
Response response{ Response::createOkResponse(context.serverProtocolVersion) };
Response::Node& podcastsNode{ response.createNode("podcasts") };
podcastsNode.createEmptyArrayChild("channel");
auto transaction{ context.dbSession.createReadTransaction() };
auto processPodcast{ [&](const db::Podcast::pointer& podcast) {
podcastsNode.addArrayChild("channel", createPodcastNode(context, podcast, includeEpisodes));
} };
if (podcastId.has_value())
{
db::Podcast::pointer podcast{ db::Podcast::find(context.dbSession, podcastId.value()) };
if (!podcast)
throw RequestedDataNotFoundError{};
processPodcast(podcast);
}
else
db::Podcast::find(context.dbSession, processPodcast);
return response;
}
Response handleGetNewestPodcasts(RequestContext& context)
{
std::size_t count{ getParameterAs<std::size_t>(context.parameters, "count").value_or(20) };
count = std::min<std::size_t>(count, 100);
Response response{ Response::createOkResponse(context.serverProtocolVersion) };
Response::Node& newestPodcastsNode{ response.createNode("newestPodcasts") };
newestPodcastsNode.createEmptyArrayChild("episode");
{
auto transaction{ context.dbSession.createReadTransaction() };
db::PodcastEpisode::FindParameters findParameters;
findParameters.setRange(db::Range{ .offset = 0, .size = count });
db::PodcastEpisode::find(context.dbSession, findParameters, [&](const db::PodcastEpisode::pointer& episode) {
newestPodcastsNode.addArrayChild("episode", createPodcastEpisodeNode(episode));
});
}
return response;
}
Response handleRefreshPodcasts(RequestContext& context)
{
core::Service<podcast::IPodcastService>::get()->refreshPodcasts();
return Response::createOkResponse(context.serverProtocolVersion);
}
Response handleCreatePodcastChannel(RequestContext& context)
{
// Mandatory parameters
const std::string url{ getMandatoryParameterAs<std::string>(context.parameters, "url") };
if (url.empty() || !(url.starts_with("http://") || url.starts_with("https://")))
throw BadParameterGenericError{ "Invalid url" };
// no effect if podcast already exists
core::Service<podcast::IPodcastService>::get()->addPodcast(url);
return Response::createOkResponse(context.serverProtocolVersion);
}
Response handleDeletePodcastChannel(RequestContext& context)
{
// Mandatory parameters
const db::PodcastId podcastId{ getMandatoryParameterAs<db::PodcastId>(context.parameters, "id") };
if (!core::Service<podcast::IPodcastService>::get()->removePodcast(podcastId))
throw RequestedDataNotFoundError{};
return Response::createOkResponse(context.serverProtocolVersion);
}
Response handleDeletePodcastEpisode(RequestContext& context)
{
// Mandatory parameters
const db::PodcastEpisodeId episodeId{ getMandatoryParameterAs<db::PodcastEpisodeId>(context.parameters, "id") };
if (!core::Service<podcast::IPodcastService>::get()->deletePodcastEpisode(episodeId))
throw RequestedDataNotFoundError{};
return Response::createOkResponse(context.serverProtocolVersion);
}
Response handleDownloadPodcastEpisode(RequestContext& context)
{
// Mandatory parameters
const db::PodcastEpisodeId episodeId{ getMandatoryParameterAs<db::PodcastEpisodeId>(context.parameters, "id") };
if (!core::Service<podcast::IPodcastService>::get()->downloadPodcastEpisode(episodeId))
throw RequestedDataNotFoundError{};
return Response::createOkResponse(context.serverProtocolVersion);
}
Response handleGetPodcastEpisode(RequestContext& context)
{
// Mandatory parameters
const db::PodcastEpisodeId episodeId{ getMandatoryParameterAs<db::PodcastEpisodeId>(context.parameters, "id") };
Response response{ Response::createOkResponse(context.serverProtocolVersion) };
auto transaction{ context.dbSession.createReadTransaction() };
const db::PodcastEpisode::pointer episode{ db::PodcastEpisode::find(context.dbSession, episodeId) };
if (!episode)
throw RequestedDataNotFoundError{};
response.addNode("podcastEpisode", createPodcastEpisodeNode(episode));
return response;
}
} // namespace lms::api::subsonic
@@ -0,0 +1,35 @@
/*
* Copyright (C) 2025 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "RequestContext.hpp"
#include "SubsonicResponse.hpp"
namespace lms::api::subsonic
{
Response handleGetPodcasts(RequestContext& context);
Response handleGetNewestPodcasts(RequestContext& context);
Response handleRefreshPodcasts(RequestContext& context);
Response handleCreatePodcastChannel(RequestContext& context);
Response handleDeletePodcastChannel(RequestContext& context);
Response handleDeletePodcastEpisode(RequestContext& context);
Response handleDownloadPodcastEpisode(RequestContext& context);
Response handleGetPodcastEpisode(RequestContext& context);
} // namespace lms::api::subsonic
@@ -47,6 +47,12 @@ namespace lms::api::subsonic
apiKeyAuthentication.addArrayValue("versions", 1);
}
{
Response::Node& apiKeyAuthentication{ response.createArrayNode("openSubsonicExtensions") };
apiKeyAuthentication.setAttribute("name", "getPodcastEpisode");
apiKeyAuthentication.addArrayValue("versions", 1);
}
return response;
};
} // namespace lms::api::subsonic
@@ -0,0 +1,135 @@
/*
* Copyright (C) 2025 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Podcast.hpp"
#include <chrono>
#include <Wt/WDate.h>
#include "core/String.hpp"
#include "database/objects/Artwork.hpp"
#include "database/objects/Podcast.hpp"
#include "database/objects/PodcastEpisode.hpp"
#include "CoverArtId.hpp"
#include "RequestContext.hpp"
#include "SubsonicId.hpp"
namespace lms::api::subsonic
{
std::string_view getStatus(const db::PodcastEpisode::pointer& episode)
{
if (episode->getManualDownloadState() == db::PodcastEpisode::ManualDownloadState::DeleteRequested)
return "deleted";
if (!episode->getAudioRelativeFilePath().empty())
return "completed";
return "new";
}
Response::Node createPodcastEpisodeNode(const db::PodcastEpisode::pointer& episode)
{
Response::Node episodeNode;
// Child attributes
episodeNode.setAttribute("id", idToString(episode->getId()));
episodeNode.setAttribute("title", episode->getTitle());
if (episode->getPubDate().isValid())
episodeNode.setAttribute("year", std::to_string(episode->getPubDate().date().year()));
if (!episode->getEnclosureContentType().empty())
episodeNode.setAttribute("contentType", episode->getEnclosureContentType());
episodeNode.setAttribute("duration", std::chrono::duration_cast<std::chrono::seconds>(episode->getDuration()).count());
if (episode->getEnclosureLength() > 0)
episodeNode.setAttribute("size", episode->getEnclosureLength());
episodeNode.setAttribute("isDir", "false"); // TODO parent?
if (!episode->getEnclosureUrl().empty())
{
const auto pos{ episode->getEnclosureUrl().find_last_of('.') };
if (pos != std::string_view::npos)
episodeNode.setAttribute("suffix", episode->getEnclosureUrl().substr(pos + 1));
}
// estimated bitrate
if (episode->getEnclosureLength() > 0 && episode->getDuration() > std::chrono::milliseconds::zero())
episodeNode.setAttribute("bitrate", episode->getEnclosureLength() * 8 / std::chrono::duration_cast<std::chrono::milliseconds>(episode->getDuration()).count());
if (const auto artwork{ episode->getArtwork() })
{
CoverArtId coverArtId{ artwork->getId(), artwork->getLastWrittenTime().toTime_t() };
episodeNode.setAttribute("coverArt", idToString(coverArtId));
}
// Podcast specific attributes
// Expose the streamId only if the episode is actually downloaded
if (!episode->getAudioRelativeFilePath().empty())
episodeNode.setAttribute("streamId", idToString(episode->getId())); // Use this ID for streaming the podcast
episodeNode.setAttribute("channelId", idToString(episode->getPodcastId()));
episodeNode.setAttribute("description", episode->getDescription());
episodeNode.setAttribute("status", getStatus(episode));
if (episode->getPubDate().isValid())
episodeNode.setAttribute("publishDate", core::stringUtils::toISO8601String(episode->getPubDate()));
return episodeNode;
}
std::string_view getStatus(const db::Podcast::pointer& podcast)
{
if (podcast->getTitle().empty())
return "new";
return "completed";
}
Response::Node createPodcastNode(RequestContext& context, const db::Podcast::pointer& podcast, bool includeEpisodes)
{
Response::Node podcastNode;
podcastNode.setAttribute("id", idToString(podcast->getId()));
podcastNode.setAttribute("url", podcast->getLink()); // TODO
if (!podcast->getTitle().empty())
podcastNode.setAttribute("title", podcast->getTitle());
if (!podcast->getDescription().empty())
podcastNode.setAttribute("description", podcast->getDescription());
if (!podcast->getImageUrl().empty())
podcastNode.setAttribute("originalImageUrl", podcast->getImageUrl());
podcastNode.setAttribute("status", getStatus(podcast));
if (const auto artwork{ podcast->getArtwork() })
{
CoverArtId coverArtId{ artwork->getId(), artwork->getLastWrittenTime().toTime_t() };
podcastNode.setAttribute("coverArt", idToString(coverArtId));
}
if (includeEpisodes)
{
podcastNode.createEmptyArrayChild("episode ");
db::PodcastEpisode::FindParameters params;
params.setPodcast(podcast->getId());
params.setSortMode(db::PodcastEpisodeSortMode::PubDateDesc);
db::PodcastEpisode::find(context.dbSession, params, [&](const db::PodcastEpisode::pointer& episode) {
podcastNode.addArrayChild("episode", createPodcastEpisodeNode(episode));
});
}
return podcastNode;
}
} // namespace lms::api::subsonic
@@ -0,0 +1,38 @@
/*
* Copyright (C) 2025 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "database/Object.hpp"
#include "SubsonicResponse.hpp"
namespace lms::db
{
class Podcast;
class PodcastEpisode;
} // namespace lms::db
namespace lms::api::subsonic
{
struct RequestContext;
Response::Node createPodcastEpisodeNode(const db::ObjectPtr<db::PodcastEpisode>& episode);
Response::Node createPodcastNode(RequestContext& context, const db::ObjectPtr<db::Podcast>& podcast, bool includeEpisodes);
} // namespace lms::api::subsonic
+11 -11
View File
@@ -33,17 +33,17 @@ namespace lms::api::subsonic
userNode.setAttribute("username", user->getLoginName());
userNode.setAttribute("scrobblingEnabled", true);
userNode.setAttribute("adminRole", user->isAdmin());
userNode.setAttribute("settingsRole", true);
userNode.setAttribute("downloadRole", true);
userNode.setAttribute("uploadRole", false);
userNode.setAttribute("playlistRole", true);
userNode.setAttribute("coverArtRole", false);
userNode.setAttribute("commentRole", false);
userNode.setAttribute("podcastRole", false); // not supported
userNode.setAttribute("streamRole", true);
userNode.setAttribute("jukeboxRole", false); // not supported
userNode.setAttribute("shareRole", false); // not supported
userNode.setAttribute("adminRole", user->isAdmin()); // Whether the user is administrator
userNode.setAttribute("settingsRole", true); // Whether the user is allowed to change personal settings and password
userNode.setAttribute("downloadRole", true); // Whether the user is allowed to download files
userNode.setAttribute("uploadRole", false); // Whether the user is allowed to upload files
userNode.setAttribute("playlistRole", true); // Whether the user is allowed to create and delete playlists
userNode.setAttribute("coverArtRole", false); // Whether the user is allowed to change cover art and tags.
userNode.setAttribute("commentRole", false); // Whether the user is allowed to create and edit comments and ratings
userNode.setAttribute("podcastRole", user->isAdmin()); // Whether the user is allowed to administrate Podcasts
userNode.setAttribute("streamRole", true); // Whether the user is allowed to play files
userNode.setAttribute("jukeboxRole", false); // not supported
userNode.setAttribute("shareRole", false); // not supported
// users can access all libraries
db::MediaLibrary::find(context.dbSession, [&](const db::MediaLibrary::pointer& library) {