protected bool SingleQuery(int id) { try { AnimeResult result = Extract.DownloadAnimeNames(id); switch (result.Response) { case AnimeResponse.Unknown: ProcessUnknownResult(id); return(false); case AnimeResponse.InvalidId: ProcessInvalidResult(id); return(false); case AnimeResponse.Successs: ProcessSuccess(id, result); return(true); } } catch (Exception ex) { ProcessException(id, ex); } return(false); }
public void TestSimple() { AnimeResult result = Extract.AnimeNamesFromSite(Helper.LoadFile(@"sites\anime\1.html")); Assert.AreEqual(AnimeResponse.Successs, result.Response); Assert.IsNotNull(result.Synonyms); Assert.AreEqual("Cowboy Bebop", result.RomajiName); }
public async Task SearchAlAnimeAsync([Summary("Title to search")][Remainder] string name = "Azur Lane") { Logger.LogInfo($"Searching for {name} on anilist"); AnimeResult animeResult = await AnilistClient.GetAnimeAsync(name); await ReplyAsync(embed : GetAnimeResultEmbed(animeResult, 0, new EmbedFooterBuilder())); }
public void TestComplex1() { AnimeResult result = Extract.AnimeNamesFromSite(Helper.LoadFile(@"sites\anime\100.html")); Assert.AreEqual(AnimeResponse.Successs, result.Response); Assert.IsNotNull(result.Synonyms); Assert.AreEqual("Prétear", result.RomajiName); Assert.AreEqual("Pretear", result.EnglishName); Assert.Contains("Shin Shirayuki Hime Densetsu Pretear", result.Synonyms.ToList()); }
public static AnimeResult GetAnime(string query) { try { var client = new HttpClient(); var responseText = client.HttpGet($"https://anilist.co/api/anime/search/{query}?access_token={AccessToken}"); dynamic responseObject = JsonConvert.DeserializeObject(responseText); dynamic firstResult = responseObject[0]; var result = new AnimeResult(); result.id = firstResult["id"]; result.jpTitle = firstResult["title_japanese"]; result.romanizedTitle = firstResult["title_romaji"]; result.englishTitle = firstResult["title_english"]; if (firstResult["synonyms"].Count > 0) { foreach (var synonym in firstResult["synonyms"]) { result.synonyms.Add((string)synonym); } } if (firstResult["genres"].Count > 0) { foreach (var genre in firstResult["genres"]) { result.genres.Add((string)genre); } } result.status = firstResult["airing_status"]; result.type = firstResult["type"]; result.averageScore = firstResult["average_score"]; result.totalEpisodes = firstResult["total_episodes"]; result.duration = firstResult["duration"] == null ? 0 : firstResult["duration"]; result.sourceMaterial = firstResult["source"]; result.description = ((string)firstResult["description"]).Truncate(500); result.description = Regex.Replace(result.description, @"\<.+?\>", ""); result.thumbnailUrl = firstResult["image_url_med"]; result.startDate = DateTime.Parse((string)firstResult["start_date"]); DateTime.TryParse((string)firstResult["end_date"], out result.endDate); return(result); } catch (Exception ex) { return(null); } }
private void ProcessSuccess(int id, AnimeResult result) { using (var conn = OpenConnection()) { var trans = conn.BeginTransaction(); conn.Execute("DELETE FROM \"Anime\" WHERE \"Id\" = :id;", new { id = id }, trans); conn.Execute("DELETE FROM \"Anime_Synonyms\" WHERE \"Anime_Id\" = :id;", new { id = id }, trans); conn.Execute("INSERT INTO \"Anime\" (\"Id\", \"RomajiName\", \"EnglishName\") VALUES (:id, :romajiName, :englishName)", new { id = id, romajiName = result.RomajiName, englishName = result.EnglishName }, trans); conn.Execute("INSERT INTO \"Anime_Synonyms\" (\"Text\", \"Anime_Id\") VALUES (:text, :id)", result.Synonyms.Select(syn => new { text = syn, id = id }), trans); trans.Commit(); } log.InfoFormat("<{0}> success", id); }
public static AnimeResult GetAnime(string searchQuery) { try { var result = new AnimeResult(); var httpClient = new HttpClient(); httpClient.SetBasicHttpCredentials((string)Shinoa.Config["mal_username"], (string)Shinoa.Config["mal_password"]); httpClient.BaseAddress = new Uri("https://myanimelist.net/api/"); var responseText = httpClient.HttpGet($"anime/search.xml?q={searchQuery}"); XElement root = XElement.Parse(responseText); var firstResult = (from el in root.Descendants("entry") select el).First(); result.title = firstResult.Descendants("title").First().Value; var englishTitle = firstResult.Descendants("english").First().Value; if (englishTitle.Length > 0) { result.englishTitle = englishTitle; } var synonyms = firstResult.Descendants("synonyms").First().Value; if (synonyms.Length > 0) { result.synonyms = synonyms; } result.type = firstResult.Descendants("type").First().Value; result.status = firstResult.Descendants("status").First().Value; result.score = float.Parse(firstResult.Descendants("score").First().Value); result.episodeCount = int.Parse(firstResult.Descendants("episodes").First().Value); result.startDate = DateTime.Parse(firstResult.Descendants("start_date").First().Value); var endDateString = firstResult.Descendants("end_date").First().Value; if (endDateString != "0000-00-00") { result.endDate = DateTime.Parse(endDateString); } result.id = int.Parse(firstResult.Descendants("id").First().Value); result.thumbnailUrl = firstResult.Descendants("image").First().Value; result.synopsis = GenerateSynopsisString(firstResult.Descendants("synopsis").First().Value); return(result); } catch (Exception e) { return(null); } }
public List <EpisodeResult> RetrieveEpisodeResults(AnimeResult animeResult) { var html = _client.DownloadString(animeResult.PageUrl); var dom = CQ.CreateDocument(html); var results = dom.Select("label:contains('RapidVideo')").Next().Find("a") .Select(element => new EpisodeResult { Title = element.Cq().Attr("data-base"), PageUrl = element.Cq().Attr("href") } ).ToList(); return(results); }
public void TestEmptySynonyms() { AnimeResult result = Extract.AnimeNamesFromSite(Helper.LoadFile(@"sites\anime\985.html")); Assert.AreEqual(AnimeResponse.Successs, result.Response); Assert.IsNotNull(result.Synonyms); Assert.AreEqual("Dragon Ball Z Special 2: The History of Trunks", result.RomajiName); Assert.AreEqual("Dragon Ball Z Special 2: The History of Trunks", result.EnglishName); Assert.AreEqual(2, result.Synonyms.Count); var synonyms = result.Synonyms.ToList(); Assert.Contains("Dragon Ball Z: Zetsubou e no Hankou!! Nokosareta Chousenshi - Gohan to Trunks", synonyms); Assert.Contains("Dragon Ball Z: Resist Despair!! The Surviving Fighters - Gohan and Trunks", synonyms); }
public List <EpisodeResult> RetrieveEpisodeResults(AnimeResult animeResult) { var html = _client.DownloadString(BaseUri + animeResult.PageUrl); var dom = CQ.CreateDocument(html); var results = dom.Select("[role='button']") .Select(element => new EpisodeResult { Title = $"{animeResult.Name} {Convert.ToInt32(element.Cq().Attr("data-episode")) + 1}", PageUrl = element.Cq().Attr("href") } ).ToList(); return(results); }
public List <EpisodeResult> RetrieveEpisodeResults(AnimeResult animeResult) { var html = _cloudHttpClient.GetStringAsync(BaseUri + animeResult.PageUrl).Result; var dom = CQ.CreateDocument(html); var results = dom.Select(".animeinfo-content") .Select(element => new EpisodeResult { Title = element.Cq().Find("b").Text(), Description = element.Cq().Find(".list-group-item-text").Text().Trim(), PageUrl = element.Cq().Attr("href") } ).ToList(); return(results); }
public void TestComplex2() { AnimeResult result = Extract.AnimeNamesFromSite(Helper.LoadFile(@"sites\anime\112.html")); Assert.AreEqual(AnimeResponse.Successs, result.Response); Assert.IsNotNull(result.Synonyms); Assert.AreEqual("Cosprayers", result.RomajiName); Assert.AreEqual("The Cosmopolitan Prayers", result.EnglishName); Assert.AreEqual(3, result.Synonyms.Count); var synonyms = result.Synonyms.ToList(); Assert.Contains("Chou Henshin Cos ? Prayer", synonyms); Assert.Contains("Super Transforming Cos ? Prayer", synonyms); Assert.Contains("Cho Henshin Cosprayers", synonyms); }
public List <EpisodeResult> RetrieveEpisodeResults(AnimeResult animeResult) { var html = _client.DownloadString(animeResult.PageUrl); var dom = CQ.CreateDocument(html); var animeId = dom.Select("input#movie_id").Val(); var episodeListHtml = _client.DownloadString(string.Format(EpisodeLookupApi, animeId)); dom = CQ.CreateDocument(episodeListHtml); var results = dom.Select("li") .Select(element => new EpisodeResult { Title = element.Cq().Find(".name").Text().Trim(), PageUrl = BaseUri + element.Cq().Find("a").Attr("href").Trim() }) .ToList(); return(results); }
public async Task SearchMalAnimeAsync([Summary("Title to search")][Remainder] string name = "Azur Lane") { Logger.LogInfo($"Searching for {name} on myanimelist"); ulong[] ids = await MalClient.GetAnimeIdAsync(name); AnimeResult[] resultCache = new AnimeResult[ids.Length]; await PaginatedMessageService.SendPaginatedDataAsyncMessageAsync(Context.Channel, ids, async (ulong id, int index, EmbedFooterBuilder footer) => { if (resultCache[index].MalId != 0) { return(GetAnimeResultEmbed(resultCache[index], index, footer)); } else { AnimeResult result = resultCache[index] = await MalClient.GetDetailedAnimeResultsAsync(id); return(GetAnimeResultEmbed(result, index, footer)); } }); }
private Embed GetAnimeResultEmbed(AnimeResult result, int index, EmbedFooterBuilder footer) => new EmbedBuilder() .WithColor(0x2E51A2) .WithAuthor(author => { author .WithName($"{result.Title}") .WithUrl($"{result.SiteUrl}") .WithIconUrl(result.ApiType.ToIconUrl()); }) .WithDescription($"" + $"__**Description:**__\n" + $"{result.Synopsis.ShortenText()}") .AddField("Details ▼", $"► Type: **{result.Type}** [Source: **{result.Source}**] \n" + $"► Status: **{result.Status}**\n" + $"► Episodes: **{"Unknown".IfTargetIsNullOrEmpty(result.Episodes?.ToString())} [{result.Duration} Min]** \n" + $"► Score: **{"NaN".IfTargetIsNullOrEmpty($"{result.Score?.ToString()}")}**☆\n" + $"► Studio: **[{"Unknown".IfTargetIsNullOrEmpty(result.Studio?.ToString())}]({result.StudioUrl})**\n" + $"Broadcast Time: **[{"Unknown".IfTargetIsNullOrEmpty(result.Broadcast?.ToString())}]**\n" + $"**{(result.TrailerUrl != null ? $"[Trailer]({result.TrailerUrl})" : "No trailer")}**\n") .WithFooter(footer) .WithImageUrl(result.ImageUrl) .Build();
public AnimeResult GetAnime(string searchQuery) { if (searchQuery == "grape") { Logging.LogError($"Could not find anime \"{searchQuery}\"").Wait(); return(null); } try { var result = new AnimeResult(); var responseText = httpClient.HttpGet($"anime/search.xml?q={searchQuery}").Result; if (responseText == null) { Logging.LogError($"Could not find anime \"{searchQuery}\"").Wait(); return(null); } var root = XElement.Parse(responseText); var firstResult = (from el in root.Descendants("entry") select el).First(); result.Title = firstResult.Descendants("title").First().Value; var englishTitle = firstResult.Descendants("english").First().Value; if (englishTitle.Length > 0) { result.EnglishTitle = englishTitle; } var synonyms = firstResult.Descendants("synonyms").First().Value; if (synonyms.Length > 0) { result.Synonyms = synonyms; } result.Type = firstResult.Descendants("type").First().Value; result.Status = firstResult.Descendants("status").First().Value; result.Score = float.Parse(firstResult.Descendants("score").First().Value); result.EpisodeCount = int.Parse(firstResult.Descendants("episodes").First().Value); var startDateString = firstResult.Descendants("start_date").First().Value; if (startDateString != "0000-00-00") { result.StartDate = DateTime.Parse(startDateString); } var endDateString = firstResult.Descendants("end_date").First().Value; if (endDateString != "0000-00-00") { result.EndDate = DateTime.Parse(endDateString); } result.Id = int.Parse(firstResult.Descendants("id").First().Value); result.ThumbnailUrl = firstResult.Descendants("image").First().Value; result.Synopsis = GenerateSynopsisString(firstResult.Descendants("synopsis").First().Value); return(result); } catch (Exception) { Logging.LogError($"Could not find anime \"{searchQuery}\"").Wait(); return(null); } }
public void TestInvalid() { AnimeResult result = Extract.AnimeNamesFromSite(Helper.LoadFile(@"sites\anime\2.html")); Assert.AreEqual(AnimeResponse.InvalidId, result.Response); }
public async Task TraceImageAsync([Summary("Image to search")][Remainder] string url = null) { Logger.LogInfo($"Tracing image {url}"); AnimeResult animeResult = new AnimeResult(); if (url == null) { if (Context.Message.Attachments.Count == 1) { IAttachment attachment = Context.Message.Attachments.ElementAt(0); using (WebClient wc = new WebClient()) { byte[] data = wc.DownloadData(attachment.Url); string base64Data = Convert.ToBase64String(data); TraceResult traceResult = (await Client.GetTraceResultsFromBase64Async(base64Data, 1))[0]; animeResult = await AnilistClient.GetAnimeAsync(traceResult.AlId); } } else { var messagesEnumerable = Context.Channel.GetMessagesAsync(2); IEnumerable <IMessage> messages = await messagesEnumerable.FlattenAsync(); if (messages.Count() < 2) { await ReplyAsync($"Too Few Messages"); return; } IMessage message = messages.ElementAt(1); if (message.Attachments.Count < 1) { await ReplyAsync("No Images Were Found On Previous Message"); return; } IAttachment attachment = message.Attachments.ElementAt(0); using (WebClient wc = new WebClient()) { byte[] data = wc.DownloadData(attachment.Url); string base64Data = Convert.ToBase64String(data); TraceResult traceResult = (await Client.GetTraceResultsFromBase64Async(base64Data, 1))[0]; animeResult = await AnilistClient.GetAnimeAsync(traceResult.AlId); } } } else { if (url.Contains("cdn.discordapp.com")) { await ReplyAsync("Discord image links are not supported, please send the image directly as an attachement"); return; } TraceResult traceResult = (await Client.GetTraceResultsAsync(url, 1))[0]; animeResult = await AnilistClient.GetAnimeAsync(traceResult.AlId); } await ReplyAsync(embed : GetAnimeResultEmbed(animeResult, 0, new EmbedFooterBuilder())); }
public List <EpisodeResult> RetrieveEpisodeResults(AnimeResult animeResult, string provider) { return(_animeProviders[provider].RetrieveEpisodeResults(animeResult)); }
public void TestEmpty() { AnimeResult result = Extract.AnimeNamesFromSite(""); Assert.AreEqual(AnimeResponse.Unknown, result.Response); }