Skip to content

Commit

Permalink
Annict APIのWorks実装 silane#7
Browse files Browse the repository at this point in the history
  • Loading branch information
noriokun4649 committed Feb 18, 2021
1 parent c8e7dc8 commit 86034b1
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
56 changes: 56 additions & 0 deletions TVTComment/Model/TwitterUtils/AnnictUtils/AnnictApis.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

namespace TVTComment.Model.TwitterUtils.AnnictUtils
{
class AnnictApis
{
private readonly string HOST = $"https://api.annict.com/";
private readonly string ACCESSTOKEN;

public AnnictApis(string accsestoken)
{
ACCESSTOKEN = accsestoken;
}

public async Task<string> GetTwitterHashtagAsync(string title)
{
const string endpoint = "v1/works";
using var client = new HttpClient();
Stream stream;
try
{
stream = await client.GetStreamAsync($"{HOST}{endpoint}?access_token={ACCESSTOKEN}&filter_title={title}&fields=title,media_text,twitter_hashtag&sort_season=desc").ConfigureAwait(false);
var jsonDocument = await JsonDocument.ParseAsync(stream).ConfigureAwait(false);
var result = jsonDocument.RootElement.GetProperty("works").EnumerateArray().Where(x => x.GetProperty("media_text").GetString().Equals("TV")).First();
Debug.WriteLine(result);
return result.GetProperty("twitter_hashtag").GetString();
}
catch (InvalidOperationException e) {
throw new AnnictNotFoundResponseException("Annictでアニメが見つかりませんでした");
}
catch (HttpRequestException e)
{
var message = e.Message;
switch (e.StatusCode)
{
case HttpStatusCode.Unauthorized:
message += "\nアクセストークンが無効か失効しています";
break;
}
throw new AnnictException($"Annict API {endpoint} の処理に失敗しました\n\n{message}");
}
catch (Exception e) when (e is KeyNotFoundException || e is JsonException)
{
throw new AnnictResponseException("Annict APIからのレスポンスを正しく処理できませんでした", e);
}
}
}
}
15 changes: 15 additions & 0 deletions TVTComment/Model/TwitterUtils/AnnictUtils/AnnictException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,19 @@ public AnnictResponseException(string message, Exception innerException) : base(
{
}
}

class AnnictNotFoundResponseException : AnnictException
{
public AnnictNotFoundResponseException()
{
}

public AnnictNotFoundResponseException(string message) : base(message)
{
}

public AnnictNotFoundResponseException(string message, Exception innerException) : base(message, innerException)
{
}
}
}

0 comments on commit 86034b1

Please sign in to comment.