forked from silane/TVTComment
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c8e7dc8
commit 86034b1
Showing
2 changed files
with
71 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters