using System.Text.Json; using System.Text.Json.Serialization; namespace Bokhantarare; public class Book { [JsonPropertyName("ISBN")] public string ISBN { get; set; } [JsonPropertyName("title")] public string Title { get; set; } [JsonPropertyName("authors")] public string[] Authors { get; set; } [JsonPropertyName("publicationYear")] public string PubYear { get; set; } public Book() { } public Book(string ISBN, string title, string[] authors, string pubYear) { this.ISBN = ISBN; this.Title = title; this.Authors = authors; this.PubYear = pubYear; } public Book(string ISBN, string title, string author, string pubYear) : this(ISBN, title, [author], pubYear) { } public override string ToString() { return $"Title: {Title}, Authors: {string.Join(", ", Authors)}, PubDate: {PubYear}"; } public static Book? GetBookFromISBN(string ISBN) { ISBN = ISBN.Replace("-", "").Trim(); if (ISBN.Length != 10 && ISBN.Length != 13) { throw new ArgumentException("Invalid ISBN"); } Dictionary? responce = JsonSerializer.Deserialize>( Helper.Request($"https://openlibrary.org/api/books?bibkeys=ISBN:{ISBN}&jscmd=details&format=json")); if (responce == null) { return null; } Dictionary? book = JsonSerializer.Deserialize>(responce[$"ISBN:{ISBN}"].ToString()); Dictionary? details = JsonSerializer.Deserialize>(book["details"].ToString()); string title = ""; if (details.ContainsKey("full_title")) { title = details["full_title"].ToString(); } else if (details.ContainsKey("title")) { title = details["title"].ToString(); } else { title = "Missing title"; } List authors = new List(); if (details.ContainsKey("authors")) { foreach (Dictionary listAuthors in JsonSerializer.Deserialize[]>( details["authors"].ToString())) { authors.Add(listAuthors["name"].ToString()); } } else { authors.Add("Missing Authors"); } string pubDate = ""; if (details.ContainsKey("publish_date")) { details["publish_date"].ToString(); } else { pubDate = "No Publication Date"; } return new Book(ISBN, title, authors.ToArray(), pubDate); } public static BareBookInfo[]? GetBooksFromTitle(string title) { title = title.Trim(); Dictionary? responce = JsonSerializer.Deserialize>( Helper.Request($"https://openlibrary.org/search.json?q={title}")); if (responce == null) { return null; } List>? books = JsonSerializer.Deserialize>>(responce["docs"].ToString()); List bookInfos = new List(); foreach (Dictionary book in books) { if (book.TryGetValue("cover_edition_key", out var edition) && book.TryGetValue("title", out var value)) { bookInfos.Add(new BareBookInfo(edition.ToString(), value.ToString())); } else { // This is a debug line to list search results that where missing the cover_edition_key //Console.WriteLine(JsonSerializer.Serialize(book)); } } return bookInfos.ToArray(); } }