466 lines
13 KiB
C++
466 lines
13 KiB
C++
#include "echoion/core/sources/YandexMusicSource.hpp"
|
|
|
|
#include <Void/Data/Json.hpp>
|
|
#include <Void/Log/Log.hpp>
|
|
#include <Void/Text/Url.hpp>
|
|
#include <format>
|
|
#include <openssl/evp.h>
|
|
#include <regex>
|
|
|
|
namespace Echoion::Core
|
|
{
|
|
namespace
|
|
{
|
|
constexpr const char* kDefaultEndpoint = "https://api.music.yandex.net";
|
|
// The signing salt of the classic get-mp3 scheme (public knowledge,
|
|
// same value every unofficial client uses).
|
|
constexpr const char* kSignSalt = "XGRlBW9FXlekgbPrRHuSiA";
|
|
|
|
std::string md5hex(const std::string& data)
|
|
{
|
|
unsigned char digest[EVP_MAX_MD_SIZE];
|
|
unsigned int length = 0;
|
|
if (EVP_Digest(data.data(), data.size(), digest, &length, EVP_md5(),
|
|
nullptr) != 1) {
|
|
return {};
|
|
}
|
|
static constexpr char hex[] = "0123456789abcdef";
|
|
std::string out;
|
|
out.reserve(length * 2);
|
|
for (unsigned int i = 0; i < length; ++i) {
|
|
out.push_back(hex[digest[i] >> 4]);
|
|
out.push_back(hex[digest[i] & 0xF]);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// music.yandex.ru/album/123/track/456 and friends.
|
|
std::optional<std::string> extractTrackId(const std::string& url)
|
|
{
|
|
static const std::regex albumTrack(
|
|
R"(music\.yandex\.[a-z]+/album/\d+/track/(\d+))");
|
|
static const std::regex bareTrack(
|
|
R"(music\.yandex\.[a-z]+/track/(\d+))");
|
|
std::smatch match;
|
|
if (std::regex_search(url, match, albumTrack) ||
|
|
std::regex_search(url, match, bareTrack)) {
|
|
return match[1].str();
|
|
}
|
|
return std::nullopt;
|
|
}
|
|
|
|
bool isAlbumUrl(const std::string& url)
|
|
{
|
|
static const std::regex albumOnly(
|
|
R"(music\.yandex\.[a-z]+/album/\d+/?($|\?))");
|
|
return std::regex_search(url, albumOnly);
|
|
}
|
|
|
|
bool isPlaylistUrl(const std::string& url)
|
|
{
|
|
static const std::regex playlist(
|
|
R"(music\.yandex\.[a-z]+/users/[^/]+/playlists/\d+)");
|
|
return std::regex_search(url, playlist);
|
|
}
|
|
|
|
std::string str(const Void::Json::Value& v, const char* key)
|
|
{
|
|
const auto* f = v.find(key);
|
|
return (f && f->is_string()) ? f->as_string() : std::string{};
|
|
}
|
|
|
|
int64_t num(const Void::Json::Value& v, const char* key)
|
|
{
|
|
const auto* f = v.find(key);
|
|
if (!f) {
|
|
return 0;
|
|
}
|
|
if (f->is_number()) {
|
|
return static_cast<int64_t>(f->as_number());
|
|
}
|
|
if (f->is_string()) {
|
|
try {
|
|
return std::stoll(f->as_string());
|
|
} catch (const std::exception&) {
|
|
return 0;
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
Api::TrackInfo toTrackInfo(const Void::Json::Value& track)
|
|
{
|
|
Api::TrackInfo t;
|
|
t.id = "yandex:" + std::format("{}", num(track, "id"));
|
|
if (const auto* idField = track.find("id");
|
|
idField && idField->is_string()) {
|
|
t.id = "yandex:" + idField->as_string();
|
|
}
|
|
t.title = str(track, "title");
|
|
if (const auto* artists = track.find("artists");
|
|
artists && artists->is_array()) {
|
|
for (const auto& artist : artists->as_array()) {
|
|
if (!t.artist.empty()) {
|
|
t.artist += ", ";
|
|
}
|
|
t.artist += str(artist, "name");
|
|
}
|
|
}
|
|
const auto durationMs = num(track, "durationMs");
|
|
if (durationMs > 0) {
|
|
t.duration = std::chrono::milliseconds(durationMs);
|
|
}
|
|
auto cover = str(track, "coverUri");
|
|
if (!cover.empty()) {
|
|
if (auto pos = cover.find("%%"); pos != std::string::npos) {
|
|
cover.replace(pos, 2, "200x200");
|
|
}
|
|
t.thumbnailUrl = "https://" + cover;
|
|
}
|
|
// Track id is enough to rebuild a canonical URL.
|
|
std::string plainId = t.id.substr(std::string("yandex:").size());
|
|
int64_t albumId = 0;
|
|
if (const auto* albums = track.find("albums");
|
|
albums && albums->is_array() && !albums->as_array().empty()) {
|
|
albumId = num(albums->as_array().front(), "id");
|
|
}
|
|
t.originalUrl =
|
|
albumId > 0
|
|
? std::format("https://music.yandex.com/album/{}/track/{}",
|
|
albumId, plainId)
|
|
: std::format("https://music.yandex.com/track/{}", plainId);
|
|
t.source = Api::TrackSource::Yandex;
|
|
t.addedAt = std::chrono::system_clock::now();
|
|
return t;
|
|
}
|
|
} // namespace
|
|
|
|
YandexMusicSource::YandexMusicSource(std::shared_ptr<NetworkClient> network,
|
|
std::string endpointOverride)
|
|
: network_(std::move(network)),
|
|
endpoint_(endpointOverride.empty() ? kDefaultEndpoint
|
|
: std::move(endpointOverride))
|
|
{
|
|
}
|
|
|
|
void YandexMusicSource::configure(bool enabled, std::string token)
|
|
{
|
|
enabled_ = enabled;
|
|
std::lock_guard<std::mutex> lock(tokenMutex_);
|
|
token_ = std::move(token);
|
|
}
|
|
|
|
std::string YandexMusicSource::tokenSnapshot() const
|
|
{
|
|
std::lock_guard<std::mutex> lock(tokenMutex_);
|
|
return token_;
|
|
}
|
|
|
|
bool YandexMusicSource::canHandle(const std::string& query) const
|
|
{
|
|
if (!isAvailable()) {
|
|
return false;
|
|
}
|
|
return extractTrackId(query).has_value() || isAlbumUrl(query) ||
|
|
isPlaylistUrl(query);
|
|
}
|
|
|
|
bool YandexMusicSource::isAvailable() const
|
|
{
|
|
return enabled_.load() && !tokenSnapshot().empty();
|
|
}
|
|
|
|
Api::Result<Api::SearchResult>
|
|
YandexMusicSource::search(std::string_view query)
|
|
{
|
|
if (!isAvailable()) {
|
|
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
|
"Yandex Music not configured");
|
|
}
|
|
|
|
auto body = apiGet("/search?type=track&page=0&text=" +
|
|
Void::Encoding::Url::encode(query));
|
|
if (!body) {
|
|
return std::unexpected(body.error());
|
|
}
|
|
auto parsed = Void::Json::parse(*body);
|
|
if (!parsed) {
|
|
return Api::fail(Api::ErrorCode::ParseError,
|
|
"Invalid Yandex search response");
|
|
}
|
|
|
|
Api::SearchResult result;
|
|
result.query = std::string(query);
|
|
const auto* root = parsed->find("result");
|
|
const auto* tracks = root ? root->find("tracks") : nullptr;
|
|
const auto* items = tracks ? tracks->find("results") : nullptr;
|
|
if (items && items->is_array()) {
|
|
for (const auto& item : items->as_array()) {
|
|
auto track = toTrackInfo(item);
|
|
if (!track.title.empty()) {
|
|
result.tracks.push_back(std::move(track));
|
|
}
|
|
}
|
|
}
|
|
result.totalResults = static_cast<uint32_t>(result.tracks.size());
|
|
return result;
|
|
}
|
|
|
|
Api::Result<std::vector<Api::TrackInfo>>
|
|
YandexMusicSource::related(const std::string& trackId, size_t limit)
|
|
{
|
|
if (!isAvailable()) {
|
|
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
|
"Yandex Music not configured");
|
|
}
|
|
|
|
// /tracks/{id}/similar returns result.similarTracks[] — the same
|
|
// track shape toTrackInfo already understands.
|
|
auto body = apiGet("/tracks/" + trackId + "/similar");
|
|
if (!body) {
|
|
return std::unexpected(body.error());
|
|
}
|
|
auto parsed = Void::Json::parse(*body);
|
|
if (!parsed) {
|
|
return Api::fail(Api::ErrorCode::ParseError,
|
|
"Invalid Yandex similar-tracks response");
|
|
}
|
|
|
|
std::vector<Api::TrackInfo> tracks;
|
|
const auto* root = parsed->find("result");
|
|
const auto* items = root ? root->find("similarTracks") : nullptr;
|
|
if (items && items->is_array()) {
|
|
for (const auto& item : items->as_array()) {
|
|
if (tracks.size() >= limit) {
|
|
break;
|
|
}
|
|
auto track = toTrackInfo(item);
|
|
if (!track.title.empty()) {
|
|
track.requestedBy = "radio\\autoplay";
|
|
tracks.push_back(std::move(track));
|
|
}
|
|
}
|
|
}
|
|
return tracks;
|
|
}
|
|
|
|
std::optional<std::string>
|
|
YandexMusicSource::trackIdFromUrl(const std::string& url) const
|
|
{
|
|
return extractTrackId(url);
|
|
}
|
|
|
|
Api::Result<std::string> YandexMusicSource::apiGet(const std::string& path)
|
|
{
|
|
// Deliberately proxy-less (getDirect): Yandex may geo-block foreign
|
|
// proxy exits, and it is reachable directly here.
|
|
auto resp = network_->getDirect(
|
|
endpoint_ + path, {{"Authorization", "OAuth " + tokenSnapshot()}});
|
|
if (!resp) {
|
|
return std::unexpected(resp.error());
|
|
}
|
|
if (resp->status != 200) {
|
|
return Api::fail(
|
|
Api::ErrorCode::NetworkError,
|
|
std::format("Yandex API returned HTTP {}", resp->status));
|
|
}
|
|
return resp->body;
|
|
}
|
|
|
|
Api::Result<Api::TrackInfo>
|
|
YandexMusicSource::resolve(const std::string& urlOrId)
|
|
{
|
|
auto trackId = extractTrackId(urlOrId);
|
|
if (!trackId) {
|
|
// Collections resolve to their first track (the router contract
|
|
// wants one TrackInfo; full import goes through playlistTracks).
|
|
if (isCollectionUrl(urlOrId)) {
|
|
auto tracks = playlistTracks(urlOrId);
|
|
if (!tracks) {
|
|
return std::unexpected(tracks.error());
|
|
}
|
|
if (tracks->empty()) {
|
|
return Api::fail(Api::ErrorCode::NotFound,
|
|
"Collection is empty");
|
|
}
|
|
return tracks->front();
|
|
}
|
|
return Api::fail(Api::ErrorCode::InvalidArgument,
|
|
"Not a Yandex Music URL");
|
|
}
|
|
|
|
auto body = apiGet("/tracks/" + *trackId);
|
|
if (!body) {
|
|
return std::unexpected(body.error());
|
|
}
|
|
auto parsed = Void::Json::parse(*body);
|
|
if (!parsed) {
|
|
return Api::fail(Api::ErrorCode::ParseError,
|
|
"Invalid Yandex track response");
|
|
}
|
|
const auto* result = parsed->find("result");
|
|
if (!result || !result->is_array() || result->as_array().empty()) {
|
|
return Api::fail(Api::ErrorCode::NotFound, "Track not found");
|
|
}
|
|
return toTrackInfo(result->as_array().front());
|
|
}
|
|
|
|
Api::Result<StreamHandle>
|
|
YandexMusicSource::getStream(const Api::TrackInfo& track)
|
|
{
|
|
auto trackId = extractTrackId(track.originalUrl);
|
|
if (!trackId && track.id.starts_with("yandex:")) {
|
|
trackId = track.id.substr(std::string("yandex:").size());
|
|
}
|
|
if (!trackId) {
|
|
return Api::fail(Api::ErrorCode::InvalidArgument,
|
|
"Not a Yandex track");
|
|
}
|
|
|
|
// 1) Pick the best MP3 download option.
|
|
auto infoBody = apiGet("/tracks/" + *trackId + "/download-info");
|
|
if (!infoBody) {
|
|
return std::unexpected(infoBody.error());
|
|
}
|
|
auto parsed = Void::Json::parse(*infoBody);
|
|
if (!parsed) {
|
|
return Api::fail(Api::ErrorCode::ParseError,
|
|
"Invalid download-info response");
|
|
}
|
|
const auto* result = parsed->find("result");
|
|
if (!result || !result->is_array()) {
|
|
return Api::fail(Api::ErrorCode::NotFound, "No download options");
|
|
}
|
|
std::string infoUrl;
|
|
int64_t bestBitrate = -1;
|
|
for (const auto& option : result->as_array()) {
|
|
if (str(option, "codec") != "mp3") {
|
|
continue;
|
|
}
|
|
const auto bitrate = num(option, "bitrateInKbps");
|
|
if (bitrate > bestBitrate) {
|
|
bestBitrate = bitrate;
|
|
infoUrl = str(option, "downloadInfoUrl");
|
|
}
|
|
}
|
|
if (infoUrl.empty()) {
|
|
return Api::fail(Api::ErrorCode::NotFound,
|
|
"No MP3 download option");
|
|
}
|
|
|
|
// 2) Fetch the XML descriptor and build the signed URL.
|
|
auto xmlResp = network_->getDirect(infoUrl);
|
|
if (!xmlResp || xmlResp->status != 200) {
|
|
return Api::fail(Api::ErrorCode::NetworkError,
|
|
"Failed to fetch download descriptor");
|
|
}
|
|
const std::string& xml = xmlResp->body;
|
|
auto field = [&xml](const char* tag) -> std::string {
|
|
const std::regex re(std::format("<{0}>([^<]*)</{0}>", tag));
|
|
std::smatch match;
|
|
if (std::regex_search(xml, match, re)) {
|
|
return match[1].str();
|
|
}
|
|
return {};
|
|
};
|
|
const std::string host = field("host");
|
|
const std::string path = field("path");
|
|
const std::string ts = field("ts");
|
|
const std::string s = field("s");
|
|
if (host.empty() || path.empty() || s.empty()) {
|
|
return Api::fail(Api::ErrorCode::ParseError,
|
|
"Malformed download descriptor");
|
|
}
|
|
|
|
const std::string sign = md5hex(kSignSalt + path.substr(1) + s);
|
|
if (sign.empty()) {
|
|
return Api::fail(Api::ErrorCode::UnknownError, "MD5 failed");
|
|
}
|
|
|
|
std::string url =
|
|
std::format("https://{}/get-mp3/{}/{}{}", host, sign, ts, path);
|
|
Void::Log::info("YandexMusicSource", "{}",
|
|
std::format("Resolved stream for track {}", *trackId));
|
|
return StreamHandle{.url = std::move(url),
|
|
.isLocalFile = false,
|
|
.sourceName = "yandex"};
|
|
}
|
|
|
|
bool YandexMusicSource::isCollectionUrl(const std::string& url) const
|
|
{
|
|
return isAlbumUrl(url) || isPlaylistUrl(url);
|
|
}
|
|
|
|
Api::Result<std::vector<Api::TrackInfo>>
|
|
YandexMusicSource::playlistTracks(const std::string& url)
|
|
{
|
|
std::vector<Api::TrackInfo> tracks;
|
|
|
|
if (isAlbumUrl(url)) {
|
|
static const std::regex albumRe(
|
|
R"(music\.yandex\.[a-z]+/album/(\d+))");
|
|
std::smatch match;
|
|
if (!std::regex_search(url, match, albumRe)) {
|
|
return Api::fail(Api::ErrorCode::InvalidArgument,
|
|
"Bad album URL");
|
|
}
|
|
auto body = apiGet("/albums/" + match[1].str() + "/with-tracks");
|
|
if (!body) {
|
|
return std::unexpected(body.error());
|
|
}
|
|
auto parsed = Void::Json::parse(*body);
|
|
if (!parsed) {
|
|
return Api::fail(Api::ErrorCode::ParseError,
|
|
"Invalid album response");
|
|
}
|
|
const auto* result = parsed->find("result");
|
|
const auto* volumes = result ? result->find("volumes") : nullptr;
|
|
if (volumes && volumes->is_array()) {
|
|
for (const auto& volume : volumes->as_array()) {
|
|
if (!volume.is_array()) {
|
|
continue;
|
|
}
|
|
for (const auto& track : volume.as_array()) {
|
|
tracks.push_back(toTrackInfo(track));
|
|
}
|
|
}
|
|
}
|
|
return tracks;
|
|
}
|
|
|
|
if (isPlaylistUrl(url)) {
|
|
static const std::regex playlistRe(
|
|
R"(music\.yandex\.[a-z]+/users/([^/]+)/playlists/(\d+))");
|
|
std::smatch match;
|
|
if (!std::regex_search(url, match, playlistRe)) {
|
|
return Api::fail(Api::ErrorCode::InvalidArgument,
|
|
"Bad playlist URL");
|
|
}
|
|
auto body = apiGet("/users/" + match[1].str() + "/playlists/" +
|
|
match[2].str());
|
|
if (!body) {
|
|
return std::unexpected(body.error());
|
|
}
|
|
auto parsed = Void::Json::parse(*body);
|
|
if (!parsed) {
|
|
return Api::fail(Api::ErrorCode::ParseError,
|
|
"Invalid playlist response");
|
|
}
|
|
const auto* result = parsed->find("result");
|
|
const auto* items = result ? result->find("tracks") : nullptr;
|
|
if (items && items->is_array()) {
|
|
for (const auto& item : items->as_array()) {
|
|
if (const auto* track = item.find("track")) {
|
|
tracks.push_back(toTrackInfo(*track));
|
|
}
|
|
}
|
|
}
|
|
return tracks;
|
|
}
|
|
|
|
return Api::fail(Api::ErrorCode::InvalidArgument,
|
|
"Not a Yandex collection URL");
|
|
}
|
|
|
|
} // namespace Echoion::Core
|