Skip to content

Commit

Permalink
Merge pull request #34 from noriokun4649/add_annict_util
Browse files Browse the repository at this point in the history
Add annict util silane#7
  • Loading branch information
noriokun4649 authored Aug 26, 2021
2 parents 7bb11e4 + 0950df0 commit 2d5c872
Show file tree
Hide file tree
Showing 20 changed files with 940 additions and 27 deletions.
17 changes: 16 additions & 1 deletion TVTComment/App.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System.Windows;
using Microsoft.Extensions.Configuration;
using System.IO;
using System.Windows;

namespace TVTComment
{
Expand All @@ -7,6 +9,19 @@ namespace TVTComment
/// </summary>
public partial class App : Application
{
public static IConfiguration Configuration { get; private set; }

protected override void OnStartup(StartupEventArgs e)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddUserSecrets<App>(optional: false);

Configuration = builder.Build();

base.OnStartup(e);
}

private void Application_Startup(object sender, StartupEventArgs e)
{
new Bootstrapper().Run();
Expand Down
2 changes: 1 addition & 1 deletion TVTComment/Model/ChatCollectService/IChatCollectService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public interface IChatCollectService : IDisposable
/// <param name="channel">コメントを取得したい対象チャンネル</param>
/// <param name="time">コメントを取得したい対象時刻</param>
/// <returns>取得したコメント</returns>
IEnumerable<Chat> GetChats(ChannelInfo channel, DateTime time);
IEnumerable<Chat> GetChats(ChannelInfo channel,EventInfo events , DateTime time);

/// <summary>
/// コメント投稿に対応しているか
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,11 @@ NiconicoUtils.NiconicoLoginSession niconicoLoginSession
commentSender = new NiconicoUtils.NicoLiveCommentSender(niconicoLoginSession);
}

public IEnumerable<Chat> GetChats(ChannelInfo channel, EventInfo _, DateTime time)
{
return GetChats(channel, time);
}

public IEnumerable<Chat> GetChats(ChannelInfo channel, DateTime time)
{
if (chatCollectTask?.IsFaulted ?? false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,11 @@ public string GetInformationText()
return ret + "サーバーに接続中";
}

public IEnumerable<Chat> GetChats(ChannelInfo channel, EventInfo _, DateTime time)
{
return GetChats(channel, time);
}

public IEnumerable<Chat> GetChats(ChannelInfo channel, DateTime time)
{
if (chatCollectTask != null && chatCollectTask.IsFaulted)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ public string GetInformationText()
return $"生放送ID: {originalLiveId}" + (liveId != "" ? $" ({liveId})" : "");
}

public IEnumerable<Chat> GetChats(ChannelInfo channel, EventInfo _, DateTime time)
{
return GetChats(channel, time);
}

public IEnumerable<Chat> GetChats(ChannelInfo channel, DateTime time)
{
if (chatCollectTask.IsCanceled)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ protected OnceASecondChatCollectService(TimeSpan continuousCallLimit)
this.continuousCallLimit = continuousCallLimit;
}

public IEnumerable<Chat> GetChats(ChannelInfo channel, DateTime time)
public IEnumerable<Chat> GetChats(ChannelInfo channel, EventInfo _, DateTime time)
{
return GetChats(channel, time);
}

public IEnumerable<Chat> GetChats(ChannelInfo channel, DateTime time)
{
List<Chat> ret = new List<Chat>();
if (lastTime <= time && time < lastTime + continuousCallLimit)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using TVTComment.Model.ChatCollectServiceEntry;
using TVTComment.Model.NiconicoUtils;
using TVTComment.Model.TwitterUtils;
using TVTComment.Model.TwitterUtils.AnnictUtils;
using static TVTComment.Model.ChatCollectServiceEntry.TwitterLiveChatCollectServiceEntry.ChatCollectServiceCreationOption;

namespace TVTComment.Model.ChatCollectService
Expand All @@ -37,32 +38,45 @@ public ChatPostObject(string text, string suffixtext) : base(text)
private readonly ConcurrentQueue<Status> statusQueue = new ConcurrentQueue<Status>();
private readonly CancellationTokenSource cancel = new CancellationTokenSource();
private readonly ObservableValue<string> SearchWord = new ObservableValue<string>("");
private readonly ObservableValue<string> EventTextWord = new ObservableValue<string>("");
private readonly SearchWordResolver SearchWordResolver;
private readonly ModeSelectMethod ModeSelect;

private readonly AnnictApis Annict;

public TwitterLiveChatCollectService(IChatCollectServiceEntry serviceEntry, string searchWord, ModeSelectMethod modeSelect, SearchWordResolver searchWordResolver, TwitterAuthentication twitter)
{
Twitter = twitter;
ServiceEntry = serviceEntry;
SearchWord.Value = searchWord;
Twitter = twitter;
ModeSelect = modeSelect;
SearchWordResolver = searchWordResolver;
switch (modeSelect)
{
case ModeSelectMethod.Auto:
case ModeSelectMethod.Preset:
SearchWord.Where(x => x != null && !x.Equals("")).Subscribe(res => chatCollectTask = SearchStreamAsync(res, cancel.Token));
break;

case ModeSelectMethod.Manual:
chatCollectTask = SearchStreamAsync(searchWord, cancel.Token);
break;
case ModeSelectMethod.Auto:
if (Twitter.AnnictToken != null && !Twitter.AnnictToken.Equals(""))
{
Annict = new(Twitter.AnnictToken);
EventTextWord.Where(x => x != null && !x.Equals("")).Subscribe(res => _ = annictSearch(EventTextWord.Value));
}
else
{
throw new ChatCollectServiceCreationException("AnnictAPIの認証設定がされていません");
}
break;
}
}

public string GetInformationText()
{
return $"検索モード:{ModeSelect}\n検索ワード:{SearchWord.Value}";
var modename = new string[] { "自動(アニメ用・Annictからハッシュタグ取得)", "プリセット", "手動"};
return $"検索モード:{modename[ModeSelect.GetHashCode()]}\n検索ワード:{SearchWord.Value}";
}

private async Task SearchStreamAsync(string searchWord, CancellationToken cancel)
Expand All @@ -82,12 +96,26 @@ await Task.Run(() =>
}, cancel);
}

public IEnumerable<Chat> GetChats(ChannelInfo channel, DateTime time)
private async Task annictSearch(string evetnText)
{
if (ModeSelect == ModeSelectMethod.Auto)
try
{
var result = await Annict.GetTwitterHashtagAsync(evetnText);
SearchWord.Value = result != null && !result.Equals("") ? $"#{result}" : "";
}
catch (AnnictException)
{
SearchWord.Value = "";
}
}

SearchWord.Value = SearchWordResolver.Resolve(channel.NetworkId, channel.ServiceId);
public IEnumerable<Chat> GetChats(ChannelInfo channel,EventInfo events, DateTime time)
{
if (ModeSelect == ModeSelectMethod.Preset || (SearchWord.Value != null && SearchWord.Value.Equals(""))) SearchWord.Value = SearchWordResolver.Resolve(channel.NetworkId, channel.ServiceId);
if (ModeSelect == ModeSelectMethod.Auto)
{
var result = AnnimeTitleGetter.Convert(events.EventName);
if (result != null && !result.Equals("")) EventTextWord.Value = result;
}
if (chatCollectTask != null)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using ObservableUtils;
using System;
using TVTComment.Model.ChatCollectService;
using TVTComment.Model.ChatService;
using TVTComment.Model.NiconicoUtils;
using TVTComment.Model.TwitterUtils;
using static TVTComment.Model.ChatCollectServiceEntry.TwitterLiveChatCollectServiceEntry.ChatCollectServiceCreationOption;
Expand All @@ -11,7 +12,7 @@ class TwitterLiveChatCollectServiceEntry : IChatCollectServiceEntry
{
public class ChatCollectServiceCreationOption : IChatCollectServiceCreationOption
{
public enum ModeSelectMethod { Auto, Manual }
public enum ModeSelectMethod { Auto, Preset, Manual }
public string SearchWord { get; }
public ModeSelectMethod Method;
public ChatCollectServiceCreationOption(ModeSelectMethod method, string searchWord)
Expand All @@ -21,7 +22,7 @@ public ChatCollectServiceCreationOption(ModeSelectMethod method, string searchWo
}
}

public ChatService.IChatService Owner { get; }
public IChatService Owner { get; }
public string Id => "TwitterLive";
public string Name => "Twitterリアルタイム実況";
public string Description => "指定した検索ワードでTwitter実況";
Expand All @@ -30,7 +31,7 @@ public ChatCollectServiceCreationOption(ModeSelectMethod method, string searchWo
private readonly ObservableValue<TwitterAuthentication> Session;
private readonly SearchWordResolver searchWordResolver;

public TwitterLiveChatCollectServiceEntry(ChatService.TwitterChatService Owner, SearchWordResolver searchWordResolver, ObservableValue<TwitterAuthentication> Session)
public TwitterLiveChatCollectServiceEntry(TwitterChatService Owner, SearchWordResolver searchWordResolver, ObservableValue<TwitterAuthentication> Session)
{
this.Owner = Owner;
this.searchWordResolver = searchWordResolver;
Expand All @@ -39,7 +40,9 @@ public TwitterLiveChatCollectServiceEntry(ChatService.TwitterChatService Owner,

public IChatCollectService GetNewService(IChatCollectServiceCreationOption creationOption)
{
creationOption ??= new ChatCollectServiceCreationOption(ModeSelectMethod.Auto, "");
var annictmode = false;
if (this.Owner is TwitterChatService twitter) annictmode = twitter.AnnictAutoEnable;
creationOption ??= annictmode ? new ChatCollectServiceCreationOption(ModeSelectMethod.Auto, "") : new ChatCollectServiceCreationOption(ModeSelectMethod.Preset, "");
if (creationOption == null || creationOption is not ChatCollectServiceCreationOption co)
throw new ArgumentException($"Type of {nameof(creationOption)} must be {nameof(TwitterLiveChatCollectServiceEntry)}.{nameof(ChatCollectServiceCreationOption)}", nameof(creationOption));
var session = Session.Value;
Expand Down
5 changes: 3 additions & 2 deletions TVTComment/Model/ChatCollectServiceModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,9 @@ public ChatCollectServiceModule(ChannelInformationModule channelInformationManag
private void TimerCallback(object state)
{
var channel = channelInformationManager.CurrentChannel.Value;
var events = channelInformationManager.CurrentEvent.Value;
var time = channelInformationManager.CurrentTime.Value;
if (channel != null && time.HasValue)
if (channel != null && time.HasValue && events != null)
{
SynchronizationContext.Post((_) =>
{
Expand All @@ -78,7 +79,7 @@ private void TimerCallback(object state)
ChatCollectService.IChatCollectService service = RegisteredServices[i];
try
{
NewChatProduced?.Invoke(service.GetChats(channel, time.Value + TimeAdjustment.Value).Select(chat =>
NewChatProduced?.Invoke(service.GetChats(channel, events, time.Value + TimeAdjustment.Value).Select(chat =>
{
chat.SetSourceService(service.ServiceEntry);
return chat;
Expand Down
18 changes: 17 additions & 1 deletion TVTComment/Model/ChatService/TwitterChatService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class TwitterChatServiceSettings
public string ApiAccessToken { get; set; } = "";
public string ApiAccessSecret { get; set; } = "";
public string AnnictAccessToken { get; set; } = "";
public bool AnnictAutoEnable { get; set; } = false;
}

class TwitterChatService : IChatService
Expand Down Expand Up @@ -53,6 +54,12 @@ public string AnnictAccessToken
get { return settings.AnnictAccessToken; }
}

public bool AnnictAutoEnable
{
get { return settings.AnnictAutoEnable; }
set { settings.AnnictAutoEnable = value; }
}

public TwitterChatService(TwitterChatServiceSettings settings, ChannelDatabase channelDatabase, string filepath)
{
this.settings = settings;
Expand Down Expand Up @@ -106,6 +113,7 @@ public async Task LoginAccessTokens(string apiKey, string apiSecret, string apiA
settings.ApiAccessToken = apiAccessToken;
settings.ApiAccessSecret = apiAccessSecret;
twitterSession.Value = twitterAuthentication;
twitterSession.Value.AnnictSet(settings.AnnictAccessToken);
}
public TwitterAuthentication InitOAuthPin(string apiKey, string apiSecret)
{
Expand Down Expand Up @@ -140,6 +148,7 @@ public async Task LoginOAuthPin(TwitterAuthentication twitterAuthentication, str
IsLoggedin = true;
UserName = userResponse.Name;
twitterSession.Value = twitterAuthentication;
twitterSession.Value.AnnictSet(settings.AnnictAccessToken);
settings.ApiAccessToken = tokens.AccessToken;
settings.ApiAccessSecret = tokens.AccessTokenSecret;
}
Expand All @@ -155,7 +164,14 @@ public void Logout()

public void SetAnnictToken(string token)
{
settings.AnnictAccessToken = token;
if (twitterSession.Value != null) {
settings.AnnictAccessToken = token;
twitterSession.Value.AnnictSet(token);
}
else
{
throw new ArgumentException($"先にTwitterへのログインが必要です。");
}
}

public void Dispose()
Expand Down
6 changes: 5 additions & 1 deletion TVTComment/Model/TwitterUtils/AnnictUtils/AnnictApis.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System;
using CSharp.Japanese.Kanaxs;
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
Expand Down Expand Up @@ -30,6 +32,8 @@ public async Task<string> GetTwitterHashtagAsync(string title)
using var client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", UA);

title = KanaEx.ToHankaku(title);

Stream stream;
try
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace TVTComment.Model.TwitterUtils.AnnictUtils
{
class AnnictAuthentication
{
private readonly string HOST = $"https://annict.jp/";
private readonly string HOST = $"https://api.annict.com/";
private readonly string ResponseType = "code";
private readonly string RedirectUri = "urn:ietf:wg:oauth:2.0:oob";
private readonly string Scope = "read";
Expand Down
Loading

0 comments on commit 2d5c872

Please sign in to comment.