diff --git a/SWAD.API/Consts/Enums/ServiceResult.cs b/SWAD.API/Consts/Enums/ServiceResult.cs index 11f2f89..f1406d7 100644 --- a/SWAD.API/Consts/Enums/ServiceResult.cs +++ b/SWAD.API/Consts/Enums/ServiceResult.cs @@ -27,5 +27,9 @@ public enum ServiceResult /// /// Returns on the unsuccessful executed state by service /// - NotFound + NotFound, + /// + /// Returns on the unsuccessful executed state by TMR + /// + TooManyRequests } \ No newline at end of file diff --git a/SWAD.API/Controllers/LinkController.cs b/SWAD.API/Controllers/LinkController.cs index 2ed50d7..df92c70 100644 --- a/SWAD.API/Controllers/LinkController.cs +++ b/SWAD.API/Controllers/LinkController.cs @@ -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"); } diff --git a/SWAD.API/Controllers/ProblemsController.cs b/SWAD.API/Controllers/ProblemsController.cs index e18a01f..ed7068d 100644 --- a/SWAD.API/Controllers/ProblemsController.cs +++ b/SWAD.API/Controllers/ProblemsController.cs @@ -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); + } } \ No newline at end of file diff --git a/SWAD.API/Exceptions/TooManyRequestsException.cs b/SWAD.API/Exceptions/TooManyRequestsException.cs new file mode 100644 index 0000000..f2ad9de --- /dev/null +++ b/SWAD.API/Exceptions/TooManyRequestsException.cs @@ -0,0 +1,3 @@ +namespace SWAD.API.Exceptions; + +public class TooManyRequestsException(string message) : Exception(message); \ No newline at end of file diff --git a/SWAD.API/Services/Links/LinksService.cs b/SWAD.API/Services/Links/LinksService.cs index 5472137..2fed444 100644 --- a/SWAD.API/Services/Links/LinksService.cs +++ b/SWAD.API/Services/Links/LinksService.cs @@ -117,5 +117,9 @@ public class LinksService { return (null, ServiceResult.NoResponse); } + catch (TooManyRequestsException) + { + return (null, ServiceResult.TooManyRequests); + } } } \ No newline at end of file diff --git a/SWAD.API/Services/MusicAPI/Api/TidalService.cs b/SWAD.API/Services/MusicAPI/Api/TidalService.cs index 36032d1..10b82dd 100644 --- a/SWAD.API/Services/MusicAPI/Api/TidalService.cs +++ b/SWAD.API/Services/MusicAPI/Api/TidalService.cs @@ -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) diff --git a/SWAD.API/Services/MusicAPI/Api/YandexService.cs b/SWAD.API/Services/MusicAPI/Api/YandexService.cs index 5d05167..2d17384 100644 --- a/SWAD.API/Services/MusicAPI/Api/YandexService.cs +++ b/SWAD.API/Services/MusicAPI/Api/YandexService.cs @@ -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(); // 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 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(); - // 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(); + // 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("Яндекс, похоже, считает что мы робот, что по сути является правдой. Попробуйте позже."); + } } } \ No newline at end of file diff --git a/TelegramBot/Program.cs b/TelegramBot/Program.cs index 6950bad..4eb093f 100644 --- a/TelegramBot/Program.cs +++ b/TelegramBot/Program.cs @@ -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() ?? 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() ?? throw new NullReferenceException(); } private static CancellationTokenSource LoadBot() diff --git a/TelegramBot/TelegramBot.csproj b/TelegramBot/TelegramBot.csproj index 4858e32..b40ab71 100644 --- a/TelegramBot/TelegramBot.csproj +++ b/TelegramBot/TelegramBot.csproj @@ -11,7 +11,7 @@ 0.0.1.0 $(VersionSuffix) SpectruMTeamCode - Lisoveliy, Sluppy(Gl3b4ty) + Lisoveliy Copyright © $(Company) $([System.DateTime]::UtcNow.ToString(yyyy)) SWAD Platform Platform for sharing music links from one music service to another for free! (REST API Back-end) @@ -30,14 +30,12 @@ - Always - + Always - - + diff --git a/TelegramBot/telegramconfig.json b/TelegramBot/telegramconfig.json index ef467be..7ccb97a 100644 --- a/TelegramBot/telegramconfig.json +++ b/TelegramBot/telegramconfig.json @@ -1,6 +1,5 @@ { "AppSettings": { - "Token": "INSERT TOKEN HERE", "ApiPath": "http://api:8080", "StartMessage": "Привет. Я бот https://swapdude.pro! Я помогу отправить твоим друзьям ссылку на песню с других сервисов! Просто пришли ссылку (Spotify, Yandex, Tidal) и я сконвертирую её в 2 других сервиса.\n(BETA)", "Changelog": [