fix: fixed search of tidal tracks using WebUtils
Some checks failed
Deploy / update (push) Has been cancelled
Build Project .NET / build (push) Has been cancelled

This commit is contained in:
Pavel-Savely Savianok 2025-05-12 21:37:29 +03:00
parent fd7a274e82
commit 4a95ba0d86
10 changed files with 59 additions and 24 deletions

View File

@ -27,5 +27,9 @@ public enum ServiceResult
/// <summary>
/// Returns on the unsuccessful executed state by service
/// </summary>
NotFound
NotFound,
/// <summary>
/// Returns on the unsuccessful executed state by TMR
/// </summary>
TooManyRequests
}

View File

@ -45,6 +45,10 @@ public class LinkController(LinksService linksService) : SwadController
case ServiceResult.NotFound:
return NotFound(ErrorResources.NotFound);
case ServiceResult.TooManyRequests:
return TooManyRequests("Yandex is shit, try again later.");
default:
throw new ApplicationException("Unknown response from service");
}

View File

@ -19,4 +19,10 @@ public abstract class ProblemsController : ControllerBase
return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Some problems in other side, dude!",
detail: detail);
}
protected ObjectResult TooManyRequests(string? detail)
{
return Problem(statusCode: StatusCodes.Status429TooManyRequests, title: "You are robot, dude!",
detail: detail);
}
}

View File

@ -0,0 +1,3 @@
namespace SWAD.API.Exceptions;
public class TooManyRequestsException(string message) : Exception(message);

View File

@ -117,5 +117,9 @@ public class LinksService
{
return (null, ServiceResult.NoResponse);
}
catch (TooManyRequestsException)
{
return (null, ServiceResult.TooManyRequests);
}
}
}

View File

@ -53,7 +53,7 @@ public class TidalService : ApiService
clientHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.api+json"));
searchUri.Scheme = "https";
searchUri.Path = Path.Combine(searchUri.Path, Config.ApiPaths.Search, WebUtility.UrlEncode(GetQuery(query)
searchUri.Path = Path.Combine(searchUri.Path, Config.ApiPaths.Search, Uri.EscapeDataString(GetQuery(query)
//TODO: Это нужно, разработчики TIDAL дауны
));
var url = new UriBuilder(searchUri.Uri)

View File

@ -1,4 +1,5 @@
using System.Net;
using System.Text.Json;
using System.Web;
using Microsoft.Extensions.Options;
using SWAD.API.Consts;
@ -39,12 +40,12 @@ public class YandexService : ApiService
var json = await response.Content.ReadFromJsonAsync<YandexSearchResponse>();
// ReSharper disable once NullableWarningSuppressionIsUsed
if (json.Entities.Count < 1)
if (json?.Entities.Count < 1)
{
throw new TrackNotFoundException($"Track is not found in {ServiceType}");
}
var results = json.Entities.FirstOrDefault(x => x.Type == "track").Results;
var results = json?.Entities.FirstOrDefault(x => x.Type == "track")?.Results;
/*
* ВНИМАНИЕ
* Yandex API писали шизы поэтому когда будешь добавлять поля в YandexSearchResponse и здесь их юзать
@ -52,9 +53,10 @@ public class YandexService : ApiService
* ЭТО ВЫЗОВЕТ ИСКЛЮЧЕНИЕ
* Думой
*/
var resultTrack = results.FirstOrDefault(x => x.Track.Title == query.Name) ??
results[0];
return $"{Config.Endpoints.MusicLink[0]}{resultTrack.Track.Id}";
var resultTrack = results?.FirstOrDefault(x => x.Track.Title == query.Name) ??
results?[0];
return $"{Config.Endpoints.MusicLink[0]}{resultTrack?.Track.Id ??
throw new TrackNotFoundException($"Track is not found in {ServiceType}")}";
}
public override async Task<TrackDto> GetQueryObject(string link, string countryCode = "RU")
@ -80,9 +82,16 @@ public class YandexService : ApiService
else
throw new HttpRequestException(ErrorResources.Unsuccessful);
var json = await response.Content.ReadFromJsonAsync<YandexTrackResponse>();
// ReSharper disable once NullableWarningSuppressionIsUsed
var artists = string.Join(", ", json!.Artists.ToList().ConvertAll(x => x.Name));
return new TrackDto(json.Track.Title, artists, json.Track.Albums[0].Title, ServiceType);
try
{
var json = await response.Content.ReadFromJsonAsync<YandexTrackResponse>();
// ReSharper disable once NullableWarningSuppressionIsUsed
var artists = string.Join(", ", json!.Artists.ToList().ConvertAll(x => x.Name));
return new TrackDto(json.Track.Title, artists, json.Track.Albums[0].Title, ServiceType);
}
catch (JsonException ex)
{
throw new TooManyRequestsException("Яндекс, похоже, считает что мы робот, что по сути является правдой. Попробуйте позже.");
}
}
}

View File

@ -44,13 +44,21 @@ public static class Program
private static void LoadConfig()
{
Logger.LogInformation("Loading config...");
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddJsonFile("telegramconfig.json", optional: false)
#if DEBUG
.AddJsonFile("telegramconfig.local.json", true, true)
#endif
.Build();
Config = configuration.GetSection("AppSettings").Get<AppSettings>() ?? throw new NullReferenceException();
var configuration = new ConfigurationBuilder();
if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
{
configuration.AddJsonFile("telegramconfig.local.json", false);
Logger.LogInformation("Local config loaded.");
}
else
{
configuration.AddJsonFile("telegramconfig.json", false);
}
var configurationRoot = configuration.Build();
Config = configurationRoot.GetSection("AppSettings").Get<AppSettings>() ?? throw new NullReferenceException();
}
private static CancellationTokenSource LoadBot()

View File

@ -11,7 +11,7 @@
<Version Condition=" '$(VersionSuffix)' == '' ">0.0.1.0</Version>
<Version Condition=" '$(VersionSuffix)' != '' ">$(VersionSuffix)</Version>
<Company>SpectruMTeamCode</Company>
<Authors>Lisoveliy, Sluppy(Gl3b4ty)</Authors>
<Authors>Lisoveliy</Authors>
<Copyright>Copyright © $(Company) $([System.DateTime]::UtcNow.ToString(yyyy))</Copyright>
<Product>SWAD Platform</Product>
<Description>Platform for sharing music links from one music service to another for free! (REST API Back-end)</Description>
@ -30,14 +30,12 @@
</ItemGroup>
<ItemGroup>
<None Remove="telegramconfig.json" />
<Content Include="telegramconfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="telegramconfig.local.json">
<Content Include="telegramconfig.local.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>

View File

@ -1,6 +1,5 @@
{
"AppSettings": {
"Token": "INSERT TOKEN HERE",
"ApiPath": "http://api:8080",
"StartMessage": "Привет. Я бот https://swapdude.pro! Я помогу отправить твоим друзьям ссылку на песню с других сервисов! Просто пришли ссылку (Spotify, Yandex, Tidal) и я сконвертирую её в 2 других сервиса.\n(BETA)",
"Changelog": [