| | | 1 | | using System.Net.Http.Json; |
| | | 2 | | using System.Text.Json.Serialization; |
| | | 3 | | |
| | | 4 | | namespace Chronicis.Client.Services; |
| | | 5 | | |
| | | 6 | | public class QuoteService : IQuoteService |
| | | 7 | | { |
| | | 8 | | private readonly HttpClient _httpClient; |
| | | 9 | | private readonly ILogger<QuoteService> _logger; |
| | | 10 | | |
| | | 11 | | public QuoteService(HttpClient httpClient, ILogger<QuoteService> logger) |
| | | 12 | | { |
| | | 13 | | _httpClient = httpClient; |
| | | 14 | | _logger = logger; |
| | | 15 | | } |
| | | 16 | | |
| | | 17 | | public async Task<Quote?> GetRandomQuoteAsync() |
| | | 18 | | { |
| | | 19 | | try |
| | | 20 | | { |
| | | 21 | | // Use CORS proxy to bypass CORS restrictions |
| | | 22 | | var response = await _httpClient.GetFromJsonAsync<List<ZenQuote>>( |
| | | 23 | | "https://corsproxy.io/?https://zenquotes.io/api/random"); |
| | | 24 | | |
| | | 25 | | if (response?.Any() ?? false) |
| | | 26 | | { |
| | | 27 | | var zenQuote = response.First(); |
| | | 28 | | return new Quote |
| | | 29 | | { |
| | | 30 | | Content = zenQuote.Quote, |
| | | 31 | | Author = zenQuote.Author |
| | | 32 | | }; |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | _logger.LogWarning("No quote received from Zen Quotes API"); |
| | | 36 | | } |
| | | 37 | | catch (Exception ex) |
| | | 38 | | { |
| | | 39 | | _logger.LogError(ex, "Error fetching quote from Zen Quotes API"); |
| | | 40 | | } |
| | | 41 | | |
| | | 42 | | // Fallback quote if API fails |
| | | 43 | | return new Quote |
| | | 44 | | { |
| | | 45 | | Content = "The world is indeed full of peril, and in it there are many dark places; but still there is much |
| | | 46 | | Author = "J.R.R. Tolkien" |
| | | 47 | | }; |
| | | 48 | | } |
| | | 49 | | } |
| | | 50 | | |
| | | 51 | | // Response model for Zen Quotes API |
| | | 52 | | public class ZenQuote |
| | | 53 | | { |
| | | 54 | | [JsonPropertyName("q")] |
| | 0 | 55 | | public string Quote { get; set; } = string.Empty; |
| | | 56 | | |
| | | 57 | | [JsonPropertyName("a")] |
| | 0 | 58 | | public string Author { get; set; } = string.Empty; |
| | | 59 | | |
| | | 60 | | [JsonPropertyName("h")] |
| | 0 | 61 | | public string Html { get; set; } = string.Empty; |
| | | 62 | | } |
| | | 63 | | |
| | | 64 | | // Our internal quote model |
| | | 65 | | public class Quote |
| | | 66 | | { |
| | | 67 | | public string Content { get; set; } = string.Empty; |
| | | 68 | | public string Author { get; set; } = string.Empty; |
| | | 69 | | } |