From 9d022b02a542cb0c4ec59c869cf2c74cbfa80e20 Mon Sep 17 00:00:00 2001 From: tor4kichi Date: Tue, 15 Feb 2022 12:06:18 +0900 Subject: [PATCH 01/10] =?UTF-8?q?=E3=83=97=E3=83=AC=E3=82=A4=E3=83=A4?= =?UTF-8?q?=E3=83=BC=E7=94=A8Frame=E3=81=AE=E3=83=90=E3=83=83=E3=82=AF?= =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=83=E3=82=AF=E3=82=92=E5=B8=B8=E3=81=AB?= =?UTF-8?q?=E7=A9=BA=E3=81=AB=E3=81=99=E3=82=8B=E3=82=88=E3=81=86=E3=81=AB?= =?UTF-8?q?=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../PrimaryWindowCoreLayout.xaml.cs | 7 ++++ .../SecondaryWindowCoreLayout.xaml.cs | 32 +++++++++++++------ 2 files changed, 29 insertions(+), 10 deletions(-) diff --git a/Hohoema/Presentation.Views.Pages/PrimaryWindowCoreLayout.xaml.cs b/Hohoema/Presentation.Views.Pages/PrimaryWindowCoreLayout.xaml.cs index 4782f536c..3e2630b8f 100644 --- a/Hohoema/Presentation.Views.Pages/PrimaryWindowCoreLayout.xaml.cs +++ b/Hohoema/Presentation.Views.Pages/PrimaryWindowCoreLayout.xaml.cs @@ -207,6 +207,13 @@ Services.CurrentActiveWindowUIContextService currentActiveWindowUIContextService { Resources["NavigationViewPaneContentGridMargin"] = new Thickness(0, 27, 0, 27); } + + PlayerFrame.Navigated += PlayerFrame_Navigated; + } + + private void PlayerFrame_Navigated(object sender, NavigationEventArgs e) + { + PlayerFrame.BackStack.Clear(); } private void Current_Activated(object sender, WindowActivatedEventArgs e) diff --git a/Hohoema/Presentation.Views.Pages/SecondaryWindowCoreLayout.xaml.cs b/Hohoema/Presentation.Views.Pages/SecondaryWindowCoreLayout.xaml.cs index 5a5cf45c7..2552ff832 100644 --- a/Hohoema/Presentation.Views.Pages/SecondaryWindowCoreLayout.xaml.cs +++ b/Hohoema/Presentation.Views.Pages/SecondaryWindowCoreLayout.xaml.cs @@ -6,6 +6,7 @@ using Prism.Navigation; using Reactive.Bindings.Extensions; using System; +using System.Reactive.Disposables; using System.Threading; using Windows.UI; using Windows.UI.ViewManagement; @@ -22,26 +23,27 @@ public SecondaryWindowCoreLayout() { this.InitializeComponent(); - var appearanceSettings = App.Current.Container.Resolve(); - appearanceSettings.ObserveProperty(x => x.ApplicationTheme) - .Subscribe(theme => - { - ThemeChanged(theme); - }); - + _CurrentActiveWindowUIContextService = App.Current.Container.Resolve(); Loaded += SecondaryViewCoreLayout_Loaded; Unloaded += SecondaryViewCoreLayout_Unloaded; + + ContentFrame.Navigated += ContentFrame_Navigated; + } + + private void ContentFrame_Navigated(object sender, Windows.UI.Xaml.Navigation.NavigationEventArgs e) + { + ContentFrame.BackStack.Clear(); } - IDisposable _liteNotificationEventSubscriber; + CompositeDisposable _disposables; + private readonly CurrentActiveWindowUIContextService _CurrentActiveWindowUIContextService; private void SecondaryViewCoreLayout_Unloaded(object sender, RoutedEventArgs e) { - _liteNotificationEventSubscriber?.Dispose(); - _liteNotificationEventSubscriber = null; + _disposables.Dispose(); NavigationService.Instances.Remove(ContentFrame); WeakReferenceMessenger.Default.Unregister(this); @@ -49,6 +51,16 @@ private void SecondaryViewCoreLayout_Unloaded(object sender, RoutedEventArgs e) private void SecondaryViewCoreLayout_Loaded(object sender, RoutedEventArgs e) { + var appearanceSettings = App.Current.Container.Resolve(); + _disposables = new CompositeDisposable(new[] + { + appearanceSettings.ObserveProperty(x => x.ApplicationTheme) + .Subscribe(theme => + { + ThemeChanged(theme); + }) + }); + WeakReferenceMessenger.Default.Register(this, (r, m) => { if (_CurrentActiveWindowUIContextService.UIContext != UIContext) From db6f0aacb89dd8f9cb167c2eac56bb59899404b5 Mon Sep 17 00:00:00 2001 From: tor4kichi Date: Tue, 15 Feb 2022 21:57:56 +0900 Subject: [PATCH 02/10] =?UTF-8?q?AppCenter=E5=89=8A=E9=99=A4=E3=81=A8ZLogg?= =?UTF-8?q?er=E5=B0=8E=E5=85=A5=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Hohoema.sln | 4 +- Hohoema/.appcenter.resw | 123 -------- Hohoema/App.xaml.cs | 291 ++++++++++++------ Hohoema/Hohoema.csproj | 26 +- .../Models.UseCase/ErrorTrackingManager.cs | 147 --------- .../Hohoema.LocalMylist/LocalMylistManager.cs | 8 +- .../AppWindowSecondaryViewPlayerManager.cs | 17 +- .../Niconico.Player/Comment/CommentPlayer.cs | 59 ++-- .../PrimaryViewPlayerManager.cs | 76 +++-- .../SecondaryViewPlayerManager.cs | 15 +- .../PageNavigation/PageManager.cs | 16 +- .../Playlist/LoginUserOwnedMylistManager.cs | 10 +- .../SubscriptionUpdateManager.cs | 27 +- .../SyncWatchHistoryOnLoggedIn.cs | 7 +- .../VideoCacheDownloadOperationManager.cs | 72 +++-- .../VideoCache/VideoCacheFolderManager.cs | 21 +- .../HohoemaListingPageViewModelBase.cs | 20 +- .../Navigation.Commands/SearchCommand.cs | 2 +- .../Niconico.Follow/FollowContext.cs | 13 +- .../FollowListup/FollowGroupViewModel.cs | 8 +- .../Niconico.Likes/VideoLikesContext.cs | 2 +- .../LiveInfoListItemViewModel.cs | 14 +- .../Niconico.Share/CopyToClipboardCommand.cs | 7 +- .../CopyToClipboardWithShareTextCommand.cs | 7 +- .../Niconico.Share/OpenLinkCommand.cs | 7 +- .../Niconico.Share/OpenShareUICommand.cs | 9 +- .../Commands/HiddenVideoOwnerAddCommand.cs | 2 +- .../Commands/HiddenVideoOwnerRemoveCommand.cs | 2 +- .../Commands/LocalPlaylistAddItemCommand.cs | 2 +- .../Commands/LocalPlaylistCreateCommand.cs | 2 +- .../Commands/LocalPlaylistDeleteCommand.cs | 2 +- .../LocalPlaylistRemoveItemCommand.cs | 4 +- .../Commands/MylistAddItemCommand.cs | 2 +- .../Commands/MylistCopyItemCommand.cs | 2 +- .../Commands/MylistCreateCommand.cs | 2 +- .../Commands/MylistMoveItemCommand.cs | 2 +- .../Commands/MylistRemoveItemCommand.cs | 2 +- .../Commands/QueueAddItemCommand.cs | 2 +- .../Commands/QueueRemoveItemCommand.cs | 2 +- ...WatchedItemsInAfterWatchPlaylistCommand.cs | 2 +- .../Commands/VideoPlayCommand.cs | 8 +- .../Commands/WatchHistoryRemoveAllCommand.cs | 2 +- .../Commands/WatchHistoryRemoveItemCommand.cs | 2 +- .../LiveMenuSubPageContent.cs | 28 +- .../AddKeywordSearchSubscriptionCommand.cs | 9 +- .../Subscriptions/AddSubscriptionCommand.cs | 9 +- .../AddTagSearchSubscriptionCommand.cs | 9 +- .../CacheAddRequestCommand.cs | 2 +- .../CacheDeleteRequestCommand.cs | 2 +- .../DebugPage.xaml.cs | 3 +- .../LocalPlaylistPageViewModel.cs | 3 + .../Hohoema.Queue/VideoQueuePageViewModel.cs | 3 + .../SubscriptionManagementPageViewModel.cs | 53 ++-- .../WatchHistoryPageViewModel.cs | 11 +- .../ChannelVideoPageViewModel.cs | 3 + .../CommunityVideoPageViewModel.cs | 23 +- .../Niconico.Live/TimeshiftPageViewModel.cs | 9 +- .../Niconico.Mylist/MylistPageViewModel.cs | 50 ++- .../UserMylistPageViewModel.cs | 16 +- .../NicoRepoPageViewModel.cs | 3 + .../SearchResultKeywordPageViewModel.cs | 3 + .../SearchResultLivePageViewModel.cs | 3 + .../SearchResultTagPageViewModel.cs | 3 + .../Niconico.Series/SeriesPageViewModel.cs | 3 + .../Niconico.User/UserVideoPageViewModel.cs | 19 +- .../VideoInfomationPageViewModel.cs | 22 +- .../RankingCategoryPageViewModel.cs | 3 + .../PrimaryWindowCoreLayout.xaml | 4 +- .../PrimaryWindowCoreLayout.xaml.cs | 38 +-- .../PrimaryWindowCoreLayoutViewModel.cs | 40 ++- .../SettingsPage.xaml | 4 +- .../SettingsPageViewModel.cs | 39 ++- .../VideoPlayerPageViewModel.cs | 45 +-- .../VideoList/VideoItemsListView.xaml.cs | 2 + Hohoema/Properties/Default.rd.xml | 6 +- 75 files changed, 762 insertions(+), 758 deletions(-) delete mode 100644 Hohoema/.appcenter.resw delete mode 100644 Hohoema/Models.UseCase/ErrorTrackingManager.cs diff --git a/Hohoema.sln b/Hohoema.sln index 0442505f2..555cb8f39 100644 --- a/Hohoema.sln +++ b/Hohoema.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29025.244 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.32126.317 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Hohoema", "Hohoema\Hohoema.csproj", "{17BCCDA1-CE22-4306-8845-FDD7B346944D}" EndProject diff --git a/Hohoema/.appcenter.resw b/Hohoema/.appcenter.resw deleted file mode 100644 index 67750ae4e..000000000 --- a/Hohoema/.appcenter.resw +++ /dev/null @@ -1,123 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 57e1b8ec-83a7-4008-b0b4-369fdbfdbd38 - - \ No newline at end of file diff --git a/Hohoema/App.xaml.cs b/Hohoema/App.xaml.cs index 8fd54cc35..5d55714ac 100644 --- a/Hohoema/App.xaml.cs +++ b/Hohoema/App.xaml.cs @@ -20,9 +20,6 @@ using Hohoema.Models.UseCase.PageNavigation; using Hohoema.Presentation.ViewModels; using LiteDB; -using Microsoft.AppCenter; -using Microsoft.AppCenter.Analytics; -using Microsoft.AppCenter.Crashes; using Microsoft.Toolkit.Mvvm.Messaging; using Microsoft.Toolkit.Uwp.Helpers; using Prism; @@ -61,7 +58,6 @@ using Hohoema.Models.Domain.VideoCache; using Windows.Storage.AccessCache; using Microsoft.Toolkit.Uwp.Notifications; -using Microsoft.AppCenter.Utils; using Microsoft.Extensions.Logging; using Hohoema.Models.Infrastructure; using Hohoema.Models.UseCase.Playlist; @@ -72,6 +68,10 @@ using Hohoema.Models.Domain.Playlist; using Hohoema.Models.UseCase.Hohoema.LocalMylist; using DryIoc; +using Prism.Logging; +using ZLogger; +using Cysharp.Text; +using Windows.UI.Core; namespace Hohoema { @@ -113,10 +113,9 @@ public App() Microsoft.Toolkit.Uwp.UI.ImageCache.Instance.CacheDuration = TimeSpan.FromDays(7); Microsoft.Toolkit.Uwp.UI.ImageCache.Instance.MaxMemoryCacheCount = 0; Microsoft.Toolkit.Uwp.UI.ImageCache.Instance.RetryCount = 3; - - + this.InitializeComponent(); - } + } protected override Rules CreateContainerRules() { @@ -140,19 +139,7 @@ public override async Task OnStartAsync(StartArgs args) if (args.StartKind == StartKinds.Launch) { - // see@ https://www.typea.info/blog/index.php/2017/08/06/uwp_1/ - try - { - var appcenter_settings = new Windows.ApplicationModel.Resources.ResourceLoader(".appcenter"); - var appcenterSecrets = appcenter_settings.GetString("AppCenter_Secrets"); - - Crashes.SendingErrorReport += (sender, args) => { Debug.WriteLine(args.Report.ToString()); }; - Crashes.SentErrorReport += (sender, args) => { Debug.WriteLine(args.Report.ToString()); }; - AppCenter.SetUserId(Guid.NewGuid().ToString()); - AppCenter.Start(appcenterSecrets, typeof(Analytics), typeof(Crashes)); - Crashes.NotifyUserConfirmation(UserConfirmation.AlwaysSend); - } - catch { } + } else if (args.StartKind == StartKinds.Activate) { @@ -224,10 +211,6 @@ public override void RegisterTypes(IContainerRegistry container) LiteDatabase db = new LiteDatabase($"Filename={Path.Combine(ApplicationData.Current.LocalFolder.Path, "hohoema.db")};"); unityContainer.UseInstance(db); - var mainWindowsScheduler = new SynchronizationContextScheduler(SynchronizationContext.Current); - // 各ウィンドウごとのスケジューラを作るように - unityContainer.UseInstance(mainWindowsScheduler); -// unityContainer.RegisterInstance("MainWindowsScheduler", mainWindowsScheduler); unityContainer.RegisterDelegate(c => { @@ -318,10 +301,169 @@ public override void RegisterTypes(IContainerRegistry container) } + public class ZDebugLoggerFacade : ILoggerFacade + { + public ZDebugLoggerFacade(ILogger logger) + { + _logger = logger; + } + + + public void Log(string message, Category category, Priority priority) + { + _logger.ZLog(ToLogLevel(category, priority), "{0}: {1}. Priority:{2}. Timestamp:{3}.", CategoryText[(int)category], message, priority, DateTime.Now); + } + + private LogLevel ToLogLevel(Category category, Priority priority) + { + return (category, priority) switch + { + (Category.Exception, Priority.High) => LogLevel.Critical, + (Category.Debug, _) => LogLevel.Debug, + (Category.Exception, _) => LogLevel.Error, + (Category.Info, _) => LogLevel.Information, + (Category.Warn, _) => LogLevel.Warning, + _ => LogLevel.None, + }; + } + + private readonly string[] CategoryText = new[] + { + Category.Debug.ToString().ToUpper(), + Category.Exception.ToString().ToUpper(), + Category.Info.ToString().ToUpper(), + Category.Warn.ToString().ToUpper() + }; + private readonly ILogger _logger; + } + + + public class ZFileLoggerFacade : ILoggerFacade + { + private readonly ILogger _logger; + public ZFileLoggerFacade(ILogger logger) + { + _logger = logger; + } + + public void Log(string message, Category category, Priority priority) + { + throw new NotImplementedException(); + } + } + + public class EmptyLoggerFacade : ILoggerFacade + { + public void Log(string message, Category category, Priority priority) + { + + } + } + + public class DebugOutputStream : Stream + { + public DebugOutputStream(IScheduler scheduler) + { + _scheduler = scheduler; + } + + public override bool CanRead => false; + + public override bool CanSeek => false; + + public override bool CanWrite => true; + + long _length; + private readonly IScheduler _scheduler; + + public override long Length => _length; + + public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public override void Flush() + { + + } + + public override int Read(byte[] buffer, int offset, int count) + { + throw new NotImplementedException(); + } + + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotImplementedException(); + } + + public override void SetLength(long value) + { + + } + + public override void Write(byte[] buffer, int offset, int count) + { + _length = count; + Debug.Write(System.Text.Encoding.UTF8.GetString(buffer, offset, count)); + } + } + + private ILoggerFactory _loggerFactory; protected override void RegisterRequiredTypes(IContainerRegistry containerRegistry) { + base.RegisterRequiredTypes(containerRegistry); + + var mainWindowsScheduler = new SynchronizationContextScheduler(SynchronizationContext.Current); + containerRegistry.RegisterInstance(mainWindowsScheduler); + + _loggerFactory = LoggerFactory.Create(builder => + { + builder + .AddFilter("Microsoft", LogLevel.Warning) + .AddFilter("System", LogLevel.Warning) + .AddFilter("LoggingConsoleApp.Program", LogLevel.Debug) +#if DEBUG + .AddZLoggerStream(new DebugOutputStream(mainWindowsScheduler), "debug-plain", opt => { }) +#endif + ; + + if (IsDebugModeEnabled) + { + FileStream _logFileStream = new FileStream(ApplicationData.Current.TemporaryFolder.CreateSafeFileHandle("_log.txt", System.IO.FileMode.OpenOrCreate, FileAccess.Write), FileAccess.Write, 2 ^ 20); + _logFileStream.SetLength(0); + builder.AddFilter("Hohoema.App", DebugLogLevel) + .AddZLoggerStream(_logFileStream, "file-plain", opt => { opt.EnableStructuredLogging = false; }) + ; + } + else + { +#if DEBUG + builder.AddFilter("Hohoema.App", LogLevel.Debug); +#else + if (Debugger.IsAttached) + { + builder.AddFilter("Hohoema.App", LogLevel.Debug); + } + else + { + builder.AddFilter("Hohoema.App", LogLevel.Error); + } + +#endif + } + }); + + var logger = _loggerFactory.CreateLogger(); + containerRegistry.RegisterInstance(_loggerFactory); + containerRegistry.RegisterInstance(logger); + containerRegistry.RegisterInstance>(logger); +#if DEBUG + containerRegistry.RegisterSingleton(); +#else + containerRegistry.RegisterSingleton(); +#endif + containerRegistry.RegisterForNavigation(); containerRegistry.RegisterForNavigation(); containerRegistry.RegisterForNavigation(); @@ -355,8 +497,6 @@ protected override void RegisterRequiredTypes(IContainerRegistry containerRegist containerRegistry.RegisterForNavigation(); containerRegistry.RegisterForNavigation(); - - base.RegisterRequiredTypes(containerRegistry); } public bool IsTitleBarCustomized { get; } = DeviceTypeHelper.IsDesktop && InputCapabilityHelper.IsMouseCapable; @@ -370,6 +510,7 @@ private async Task EnsureInitializeAsync() if (isInitialized) { return; } isInitialized = true; + var logger = Container.Resolve(); async Task TryMigrationAsync(Type[] migrateTypes) { @@ -377,7 +518,7 @@ async Task TryMigrationAsync(Type[] migrateTypes) { try { - Debug.WriteLine($"Try migrate: {migrateType.Name}"); + logger.ZLogInformation("Try migrate: {0}", migrateType.Name); var migrater = Container.Resolve(migrateType); if (migrater is IMigrateSync migrateSycn) { @@ -388,12 +529,12 @@ async Task TryMigrationAsync(Type[] migrateTypes) await migrateAsync.MigrateAsync(); } - Debug.WriteLine("Migration complete : " + migrateType.Name); + logger.ZLogInformation("Migration complete : {0}", migrateType.Name); } catch (Exception e) { - Debug.WriteLine(e.ToString()); - Debug.WriteLine("Migration failed : " + migrateType.Name); + logger.ZLogError(e.ToString()); + logger.ZLogError("Migration failed : {0}",migrateType.Name); } } } @@ -596,7 +737,7 @@ await TryMigrationAsync(new Type[] var notificationService = Container.Resolve(); notificationService.ShowInAppNotification(new InAppNotificationPayload() { - Content = $"Hohoema v{version.Major}.{version.Minor}.{version.Build} に更新しました", + Content = ZString.Format("Hohoema v{0}.{1}.{2} に更新しました", version.Major, version.Minor, version.Build), ShowDuration = TimeSpan.FromSeconds(7), IsShowDismissButton = true, Commands = @@ -711,7 +852,7 @@ public override async void OnInitialized() } catch { - Debug.WriteLine("ログイン処理に失敗"); + Container.Resolve().ZLogError("ログイン処理に失敗"); } #if !DEBUG @@ -965,6 +1106,28 @@ public bool IsDebugModeEnabled _primaryWindowCoreLayout.IsDebugModeEnabled = value; } } + + const string DEBUG_LOG_LEVEL_KEY = "Hohoema_LogLevel"; + public LogLevel DebugLogLevel + { + get + { + var enabled = ApplicationData.Current.LocalSettings.Values[DEBUG_LOG_LEVEL_KEY]; + if (enabled != null) + { + return (LogLevel)enabled; + } + else + { + return LogLevel.Debug; + } + } + + set + { + ApplicationData.Current.LocalSettings.Values[DEBUG_LOG_LEVEL_KEY] = value; + } + } bool isFirstCrashe = true; @@ -992,68 +1155,8 @@ private void PrismUnityApplication_UnhandledException(object sender, Windows.UI. isFirstCrashe = false; e.Handled = true; - if (IsDebugModeEnabled) - { - bool isSentError = false; - var scheduler = Container.Resolve("MainWindowsScheduler"); - scheduler.Schedule(() => - { - var sentErrorCommand = new DelegateCommand(async () => - { - try - { - var dialogService = Container.Resolve(); - var rtb = await GetApplicationContentImage(); - var result = await Presentation.Views.Dialogs.HohoemaErrorReportDialog.ShowAsync(e.Exception, sendScreenshot: false, rtb); - - if (result.IsSendRequested is false) { return; } - - var attachmentLogs = new List(); - if (!string.IsNullOrEmpty(result.Data.InputText)) - { - attachmentLogs.Add(ErrorTrackingManager.CreateTextAttachmentLog(result.Data.InputText)); - - Debug.WriteLine("ReportLatestError: Add UserInputText Attachment"); - } - - if (result.Data.UseScreenshot) - { - try - { - attachmentLogs.Add(await ErrorTrackingManager.CreateScreenshotAttachmentLog(rtb)); - Debug.WriteLine("ReportLatestError: Add Screenshot Attachment"); - } - catch - { - Debug.WriteLine("エラー報告用のスクショ生成に失敗"); - } - } - - ErrorTrackingManager.TrackError(e.Exception, null, attachmentLogs.ToArray()); - - // isSentError を変更した後にErrorTeachingTipを閉じることでClose時の判定が走る - isSentError = true; - } - catch { } - finally - { - _primaryWindowCoreLayout.CloseErrorTeachingTip(); - } - }); - - _primaryWindowCoreLayout.OpenErrorTeachingTip(sentErrorCommand, () => - { - if (isSentError is false) - { - ErrorTrackingManager.TrackError(e.Exception); - } - }); - }); - } - else - { - ErrorTrackingManager.TrackError(e.Exception); - } + var logger = Container.Resolve(); + logger.ZLogError(e.Exception.ToString()); } // エラー報告用に画面のスクショを取れるように diff --git a/Hohoema/Hohoema.csproj b/Hohoema/Hohoema.csproj index a4bfc53de..4a439979b 100644 --- a/Hohoema/Hohoema.csproj +++ b/Hohoema/Hohoema.csproj @@ -138,7 +138,6 @@ - @@ -786,11 +785,6 @@ 1.0.1 - - 3.4.13 - runtime; build; native; contentfiles; analyzers; buildtransitive - all - 4.1.4 @@ -800,14 +794,11 @@ 4.2.0 - - 4.2.0 - - - 4.2.0 - - 5.0.0 + 6.0.0 + + + 1.1.2 5.0.5 @@ -872,6 +863,12 @@ 1.0.0 + + 1.6.1 + + + 2.4.4 + @@ -1261,9 +1258,6 @@ Designer - - - diff --git a/Hohoema/Models.UseCase/ErrorTrackingManager.cs b/Hohoema/Models.UseCase/ErrorTrackingManager.cs deleted file mode 100644 index 499ed70fd..000000000 --- a/Hohoema/Models.UseCase/ErrorTrackingManager.cs +++ /dev/null @@ -1,147 +0,0 @@ -using Hohoema.Models.Domain.Application; -using Hohoema.Models.Domain.Niconico; -using Hohoema.Models.Helpers; -using Hohoema.Models.UseCase.Niconico.Player; -using Hohoema.Models.UseCase.PageNavigation; -using Microsoft.AppCenter.Crashes; -using Prism.Ioc; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; -using System.Text.Json; -using System.Threading.Tasks; -using Windows.Graphics.Display; -using Windows.Graphics.Imaging; -using Windows.Storage.Streams; -using Windows.UI.Xaml.Media.Imaging; - -namespace Hohoema.Models.UseCase -{ - public static class ErrorTrackingManager - { - private static readonly PageManager _pageManager; - private static readonly NiconicoSession _niconicoSession; - private static readonly AppearanceSettings _appearanceSettings; - private static readonly PrimaryViewPlayerManager _primaryViewPlayerManager; - - public const int MAX_REPORT_COUNT = 10; - - static ErrorTrackingManager() - { - _pageManager = App.Current.Container.Resolve(); - _niconicoSession = App.Current.Container.Resolve(); - _appearanceSettings = App.Current.Container.Resolve(); - _primaryViewPlayerManager = App.Current.Container.Resolve(); - } - - public static Dictionary MakeReportParameters() - { - var pageName = _pageManager.CurrentPageType.ToString(); - var pageParameter = _pageManager.CurrentPageNavigationParameters is not null ? JsonSerializer.Serialize(_pageManager.CurrentPageNavigationParameters) : "null"; - - return new Dictionary - { - { "IsInternetAvailable", InternetConnection.IsInternet().ToString() }, - { "IsLoggedIn", _niconicoSession.IsLoggedIn.ToString() }, - { "IsPremiumAccount", _niconicoSession.IsPremiumAccount.ToString() }, - { "RecentOpenPageName", pageName }, - { "RecentOpenPageParameters", pageParameter }, - { "PrimaryWindowPlayerDisplayMode", _primaryViewPlayerManager.DisplayMode.ToString() }, - { "IsShowSecondaryView", (_appearanceSettings.PlayerDisplayView == PlayerDisplayView.SecondaryView).ToString() }, - }; - } - - - public static async Task CreateScreenshotAttachmentLog(RenderTargetBitmap screenshot) - { - using (var memoryStream = new InMemoryRandomAccessStream()) - { - BitmapEncoder encoder = - await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, memoryStream); - - IBuffer pixelBuffer = await screenshot.GetPixelsAsync(); - byte[] pixels = pixelBuffer.ToArray(); - - var displayInformation = DisplayInformation.GetForCurrentView(); - - encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, - (uint)screenshot.PixelWidth, (uint)screenshot.PixelHeight, displayInformation.RawDpiX, displayInformation.RawDpiY, pixels); - await encoder.FlushAsync(); - - byte[] imageBuffer = new byte[memoryStream.Size]; - await memoryStream.AsStreamForRead().ReadAsync(imageBuffer, 0, (int)memoryStream.Size); - - return ErrorAttachmentLog.AttachmentWithBinary(imageBuffer, "screenshot.png", "image/png"); - } - } - - public static ErrorAttachmentLog CreateTextAttachmentLog(string text) - { - return ErrorAttachmentLog.AttachmentWithText(text, "userInput.txt"); - } - - public static void TrackUnhandeledError(Windows.ApplicationModel.Core.UnhandledError unhandledError) - { - try - { - unhandledError.Propagate(); - } - catch (Exception e) - { - TrackError(e); - } - } - public static void TrackError(Exception exception, IDictionary parameters = null, params ErrorAttachmentLog[] logs) - { - var dict = MakeReportParameters(); - if (parameters != null) - { - foreach (var pair in parameters) - { - if (dict.ContainsKey(pair.Key)) - { - dict.Remove(pair.Key); - } - - dict.Add(pair.Key, pair.Value); - } - } - - Crashes.TrackError(exception, dict, logs.ToArray()); - } - } - - public enum ReportSendFailedReason - { - FailSendingToAppCenter, - AlreadyReported, - } - - public sealed class ReportSendResult - { - public static ReportSendResult Failed(ReportSendFailedReason reason) => new ReportSendResult(reason); - - public static ReportSendResult Success(ErrorReport errorReport) - { - return new ReportSendResult(errorReport); - } - - private ReportSendResult(ReportSendFailedReason reason) - { - IsSuccess = false; - FailedReason = reason; - } - - private ReportSendResult(ErrorReport errorReport) - { - IsSuccess = true; - Report = errorReport; - } - - public bool IsSuccess { get; } - public ErrorReport Report { get; } - public ReportSendFailedReason? FailedReason { get; } - } -} diff --git a/Hohoema/Models.UseCase/Hohoema.LocalMylist/LocalMylistManager.cs b/Hohoema/Models.UseCase/Hohoema.LocalMylist/LocalMylistManager.cs index 10f85277a..a078ecb40 100644 --- a/Hohoema/Models.UseCase/Hohoema.LocalMylist/LocalMylistManager.cs +++ b/Hohoema/Models.UseCase/Hohoema.LocalMylist/LocalMylistManager.cs @@ -20,6 +20,8 @@ using Hohoema.Models.Domain.Application; using Hohoema.Presentation.Services; using Hohoema.Models.Domain.LocalMylist; +using Microsoft.Extensions.Logging; +using ZLogger; namespace Hohoema.Models.UseCase.Hohoema.LocalMylist { @@ -32,11 +34,13 @@ void IRecipient.Receive(SettingsRestoredMessage message public LocalMylistManager( + ILogger logger, LocalMylistRepository playlistRepository, NicoVideoProvider nicoVideoProvider, INotificationService notificationService ) { + _logger = logger; _playlistRepository = playlistRepository; _nicoVideoProvider = nicoVideoProvider; _notificationService = notificationService; @@ -79,7 +83,7 @@ private void Load() } } - + private readonly ILogger _logger; private readonly LocalMylistRepository _playlistRepository; private readonly NicoVideoProvider _nicoVideoProvider; private readonly INotificationService _notificationService; @@ -183,7 +187,7 @@ public bool RemovePlaylist(LocalPlaylist localPlaylist) } catch (Exception e) { - ErrorTrackingManager.TrackError(e); + _logger.ZLogError(e.ToString()); } } , (p) => p != null && LocalPlaylists.Contains(p) diff --git a/Hohoema/Models.UseCase/Niconico.Player/AppWindowSecondaryViewPlayerManager.cs b/Hohoema/Models.UseCase/Niconico.Player/AppWindowSecondaryViewPlayerManager.cs index aaaf27a7d..96c16b4ba 100644 --- a/Hohoema/Models.UseCase/Niconico.Player/AppWindowSecondaryViewPlayerManager.cs +++ b/Hohoema/Models.UseCase/Niconico.Player/AppWindowSecondaryViewPlayerManager.cs @@ -2,7 +2,6 @@ using Hohoema.Models.Domain.Playlist; using Hohoema.Presentation.Services; using Hohoema.Presentation.Views.Pages; -using Microsoft.AppCenter.Analytics; using Microsoft.Toolkit.Mvvm.Input; using Microsoft.Toolkit.Uwp; using Prism.Mvvm; @@ -319,21 +318,7 @@ await _dispatcherQueue.EnqueueAsync(async () => catch { await CloseAsync(); - } - finally - { - _dispatcherQueue.TryEnqueue(() => - { - var presenterConfig = _appWindow.Presenter.GetConfiguration(); - Analytics.TrackEvent("PlayerNavigation", new Dictionary - { - { "PageType", pageName }, - { "ViewType", "Secondary" }, - { "CompactOverlay", (presenterConfig.Kind == AppWindowPresentationKind.CompactOverlay).ToString() }, - { "FullScreen", (presenterConfig.Kind == AppWindowPresentationKind.FullScreen).ToString()}, - }); - }); - } + } } public void SetTitle(string title) diff --git a/Hohoema/Models.UseCase/Niconico.Player/Comment/CommentPlayer.cs b/Hohoema/Models.UseCase/Niconico.Player/Comment/CommentPlayer.cs index 1f8d49aba..2867468cd 100644 --- a/Hohoema/Models.UseCase/Niconico.Player/Comment/CommentPlayer.cs +++ b/Hohoema/Models.UseCase/Niconico.Player/Comment/CommentPlayer.cs @@ -1,11 +1,12 @@ -using Hohoema.Models.Domain.Niconico.Video; +using Cysharp.Text; +using Hohoema.Models.Domain.Niconico.Video; using Hohoema.Models.Domain.Player; using Hohoema.Models.Domain.Player.Comment; using Hohoema.Models.Domain.Player.Video.Cache; using Hohoema.Models.Domain.Player.Video.Comment; using Hohoema.Models.Infrastructure; using Hohoema.Presentation.Services; -using Microsoft.AppCenter.Analytics; +using Microsoft.Extensions.Logging; using MvvmHelpers; using NiconicoToolkit; using NiconicoToolkit.Video.Watch.NMSG_Comment; @@ -24,6 +25,7 @@ using Uno.Threading; using Windows.Media.Playback; using Windows.System; +using ZLogger; namespace Hohoema.Models.UseCase.Niconico.Player.Comment { @@ -37,6 +39,7 @@ public class CommentPlayer : Prism.Mvvm.BindableBase, IDisposable private readonly NotificationService _notificationService; private readonly PlayerSettings _playerSettings; private INiconicoCommentSessionProvider _niconicoCommentSessionProvider; + private readonly ILogger _logger; private readonly MediaPlayer _mediaPlayer; public ObservableRangeCollection Comments { get; private set; } @@ -70,6 +73,7 @@ public bool NowCommentSubmitDisabledFromNicoScript event EventHandler CommentSubmitFailed; public CommentPlayer( + ILoggerFactory loggerFactory, MediaPlayer mediaPlayer, IScheduler scheduler, CommentDisplayingRangeExtractor commentDisplayingRangeExtractor, @@ -78,6 +82,7 @@ public CommentPlayer( PlayerSettings playerSettings ) { + _logger = loggerFactory.CreateLogger(); _mediaPlayer = mediaPlayer; _scheduler = scheduler; _commentDisplayingRangeExtractor = commentDisplayingRangeExtractor; @@ -232,9 +237,9 @@ public async Task UpdatePlayingCommentAsync(INiconicoCommentSessionProvider nico _CommentUpdateTimer.Start(); } - catch + catch (Exception e) { - + _logger.ZLogError(e, "コメント一覧の更新に失敗"); } } } @@ -279,7 +284,7 @@ private async Task SubmitComment() NowSubmittingComment.Value = true; - Debug.WriteLine($"try comment submit:{WritingComment.Value}"); + _logger.ZLogDebug("try comment submit: {0}", WritingComment.Value); var postComment = WritingComment.Value; var posision = _mediaPlayer.PlaybackSession.Position; @@ -291,7 +296,7 @@ private async Task SubmitComment() if (res.Status == ChatResultCode.Success) { - Debug.WriteLine("コメントの投稿に成功: " + res.CommentNo); + _logger.ZLogDebug("コメントの投稿に成功: {0}", WritingComment.Value); VideoComment videoComment = new() { @@ -318,18 +323,18 @@ private async Task SubmitComment() _notificationService.ShowLiteInAppNotification_Fail($"{_commentSession.ContentId} へのコメント投稿に失敗\n ステータスコード:{res.StatusCode}"); - ErrorTrackingManager.TrackError(new HohoemaExpception("SubmitComment Failed"), new Dictionary() + _logger.ZLogWarningWithPayload(new Dictionary() { { "ContentId", _commentSession.ContentId }, { "Command", command }, { "CommentLength", postComment?.Length.ToString() }, { "StatusCode", res.StatusCode.ToString() }, - }); + }, "SubmitComment Failed"); } } catch (NotSupportedException ex) { - Debug.WriteLine(ex.ToString()); + _logger.ZLogError(ex, "Submit comment failed."); } finally { @@ -369,13 +374,13 @@ IEnumerable commentsAction(IEnumerable comments) } catch (Exception e) { - Analytics.TrackEvent("CommentScript_ParseError", new Dictionary() + _logger.ZLogWarningWithPayload(e, new Dictionary() { - { "VideoId", commentSession.ContentId }, + { "VideoId", commentSession.ContentId }, { "CommentText", comment.CommentText }, { "Command", comment.Mail }, { "VideoPosition", comment.VideoPosition.ToString() }, - }); + }, "CommentScript_ParseError Failed"); } } @@ -388,14 +393,14 @@ IEnumerable commentsAction(IEnumerable comments) ResetDisplayingComments(Comments); _NicoScriptList.Sort((x, y) => (int)(x.BeginTime.Ticks - y.BeginTime.Ticks)); - System.Diagnostics.Debug.WriteLine($"コメント数:{Comments.Count}"); + _logger.ZLogDebug("コメント数:{0}", Comments.Count); } void ResetDisplayingComments(IReadOnlyCollection comments) { DisplayingComments.Clear(); - Debug.WriteLine($"CommentReset"); + _logger.ZLogDebug("CommentReset"); var displayingComments = _commentDisplayingRangeExtractor.ResetComments(comments, _mediaPlayer.PlaybackSession.Position); DisplayingComments.AddRange(EnumerateFilteredDisplayComment(displayingComments.ToArray())); @@ -486,24 +491,24 @@ void UpdateNicoScriptComment(TimeSpan position) { if (script.EndTime < position) { - Debug.WriteLine("nicoscript Enabling Skiped :" + script.Type); + _logger.ZLogDebug("nicoscript Enabling Skiped : {0}", script.Type); continue; } - Debug.WriteLine("nicoscript Enabling :" + script.Type); + _logger.ZLogDebug("nicoscript Enabling : {0}", script.Type); script.ScriptEnabling?.Invoke(); } else if (script.EndTime.HasValue) { if (_PrevPlaybackPosition <= script.BeginTime) { - Debug.WriteLine("nicoscript Disabling Skiped :" + script.Type); + _logger.ZLogDebug("nicoscript Disabling Skiped :{0}", script.Type); continue; } if (_PrevPlaybackPosition < script.EndTime && position > script.EndTime) { - Debug.WriteLine("nicoscript Disabling :" + script.Type); + _logger.ZLogDebug("nicoscript Disabling : {0}", script.Type); script.ScriptDisabling?.Invoke(); } } @@ -630,13 +635,13 @@ private bool TryAddNicoScript(VideoComment chat) _ReplaceNicoScirptList.Add(new ReplaceNicoScript(nicoScriptType) { - Commands = string.Join(" ", commandItems), + Commands = ZString.Join(" ", commandItems), BeginTime = beginTime, EndTime = beginTime + duration, }); - Debug.WriteLine($"置換を設定"); + _logger.ZLogDebug("置換を設定"); } break; case "ジャンプ": @@ -680,7 +685,7 @@ private bool TryAddNicoScript(VideoComment chat) } }); - Debug.WriteLine($"{beginTime.ToString()} に {condition} へのジャンプを設定"); + _logger.ZLogDebug("{0} に {1} へのジャンプを設定", beginTime, condition); } else if (NiconicoToolkit.ContentIdHelper.IsVideoId(condition)) { @@ -701,7 +706,7 @@ private bool TryAddNicoScript(VideoComment chat) EndTime = endTime, ScriptEnabling = () => { - Debug.WriteLine($"{beginTime.ToString()} に {condition} へのジャンプを設定"); + _logger.ZLogDebug("{0} に {1} へのジャンプを設定", beginTime, condition); NicoScriptJumpVideoRequested?.Invoke(this, condition); } }); @@ -726,11 +731,11 @@ private bool TryAddNicoScript(VideoComment chat) if (endTime.HasValue) { - Debug.WriteLine($"{beginTime.ToString()} ~ {endTime.ToString()} までシーク禁止を設定"); + _logger.ZLogDebug("{0} ~ {1} までシーク禁止を設定", beginTime, endTime); } else { - Debug.WriteLine($"{beginTime.ToString()} から動画終了までシーク禁止を設定"); + _logger.ZLogDebug("{0} から動画終了までシーク禁止を設定", beginTime); } } break; @@ -752,17 +757,17 @@ private bool TryAddNicoScript(VideoComment chat) #if DEBUG if (endTime.HasValue) { - Debug.WriteLine($"{beginTime.ToString()} ~ {endTime.ToString()} までコメント禁止を設定"); + _logger.ZLogDebug("{0} ~ {1} までコメント禁止を設定", beginTime, endTime); } else { - Debug.WriteLine($"{beginTime.ToString()} から動画終了までコメント禁止を設定"); + _logger.ZLogDebug("{0} から動画終了までコメント禁止を設定", beginTime); } #endif } break; default: - Debug.WriteLine($"Not support nico script type : {nicoScriptType}"); + _logger.ZLogDebug("Not support nico script type : {0}", nicoScriptType); break; } diff --git a/Hohoema/Models.UseCase/Niconico.Player/PrimaryViewPlayerManager.cs b/Hohoema/Models.UseCase/Niconico.Player/PrimaryViewPlayerManager.cs index d1842df0e..fd3a2aedd 100644 --- a/Hohoema/Models.UseCase/Niconico.Player/PrimaryViewPlayerManager.cs +++ b/Hohoema/Models.UseCase/Niconico.Player/PrimaryViewPlayerManager.cs @@ -16,13 +16,15 @@ using Hohoema.Models.Domain.PageNavigation; using Hohoema.Models.Domain.Niconico.Video; using Hohoema.Models.Domain.Niconico.Live; -using Microsoft.AppCenter.Analytics; using Hohoema.Presentation.Views.Player; using Hohoema.Presentation.Views.Pages; using NiconicoToolkit.Video; using NiconicoToolkit.Live; using Hohoema.Models.Domain.Playlist; using System.Windows.Input; +using Microsoft.Extensions.Logging; +using ZLogger; +using System.Text.Json; namespace Hohoema.Models.UseCase.Niconico.Player { @@ -41,6 +43,7 @@ public sealed class PrimaryViewPlayerManager : Prism.Mvvm.BindableBase, IPlayerV INavigationService _navigationService; private ApplicationView _view; + private readonly ILogger _logger; IScheduler _scheduler; // private readonly Lazy _navigationServiceLazy; private readonly RestoreNavigationManager _restoreNavigationManager; @@ -48,13 +51,16 @@ public sealed class PrimaryViewPlayerManager : Prism.Mvvm.BindableBase, IPlayerV Models.Helpers.AsyncLock _navigationLock = new Models.Helpers.AsyncLock(); - public PrimaryViewPlayerManager(IScheduler scheduler, + public PrimaryViewPlayerManager( + ILoggerFactory loggerFactory, + IScheduler scheduler, Lazy navigationServiceLazy, RestoreNavigationManager restoreNavigationManager, HohoemaPlaylistPlayer hohoemaPlaylistPlayer ) { _view = ApplicationView.GetForCurrentView(); + _logger = loggerFactory.CreateLogger(); _scheduler = scheduler; //_navigationServiceLazy = navigationServiceLazy; _restoreNavigationManager = restoreNavigationManager; @@ -100,49 +106,55 @@ public async Task ShowAsync() }); } + private readonly DrillInNavigationTransitionInfo _playerTransisionAnimation = new DrillInNavigationTransitionInfo(); public async Task NavigationAsync(string pageName, INavigationParameters parameters) { _scheduler.Schedule(async () => { - using (await _navigationLock.LockAsync()) + using var _ = await _navigationLock.LockAsync(); + + if (_navigationService == null) { - if (_navigationService == null) - { - _navigationService = App.Current.Container.Resolve("PrimaryPlayerNavigationService"); - } + _navigationService = App.Current.Container.Resolve("PrimaryPlayerNavigationService"); + } + + if (DisplayMode == PrimaryPlayerDisplayMode.Close) + { + DisplayMode = _lastPlayedDisplayMode; + } - if (DisplayMode == PrimaryPlayerDisplayMode.Close) + try + { + var result = await _navigationService.NavigateAsync(pageName, parameters, _playerTransisionAnimation); + if (!result.Success) { - DisplayMode = _lastPlayedDisplayMode; + DisplayMode = PrimaryPlayerDisplayMode.Close; + _view.Title = string.Empty; + throw result.Exception ?? new Models.Infrastructure.HohoemaExpception("unknown navigation error."); } - try + LastNavigatedPageName = pageName; + + _logger.ZLogInformationWithPayload(new Dictionary { - var result = await _navigationService.NavigateAsync(pageName, parameters, new DrillInNavigationTransitionInfo()); - if (!result.Success) - { - Debug.WriteLine(result.Exception?.ToString()); - DisplayMode = PrimaryPlayerDisplayMode.Close; - _view.Title = string.Empty; - throw result.Exception ?? new Models.Infrastructure.HohoemaExpception("unknown navigation error."); - } - - LastNavigatedPageName = pageName; - - Analytics.TrackEvent("PlayerNavigation", new Dictionary - { - { "PageType", pageName }, - { "DisplayMode", DisplayMode.ToString() }, - { "ViewType", "Primary" }, - { "CompactOverlay", (_view.ViewMode == ApplicationViewMode.CompactOverlay).ToString() }, - { "FullScreen", _view.IsFullScreenMode.ToString() } - }); - } - catch (Exception e) + { "PageType", pageName }, + { "DisplayMode", DisplayMode.ToString() }, + { "ViewType", "Primary" }, + { "CompactOverlay", (_view.ViewMode == ApplicationViewMode.CompactOverlay).ToString() }, + { "FullScreen", _view.IsFullScreenMode.ToString() } + }, "PlayerNavigation"); + } + catch (Exception e) + { + _logger.ZLogErrorWithPayload(e, new Dictionary() { - ErrorTrackingManager.TrackError(e); + { "PageName", pageName }, + { "Parameters", JsonSerializer.Serialize(parameters) }, } + , "PrimaryViewPlayer navigation failed." + ); } + }); await Task.Delay(50); diff --git a/Hohoema/Models.UseCase/Niconico.Player/SecondaryViewPlayerManager.cs b/Hohoema/Models.UseCase/Niconico.Player/SecondaryViewPlayerManager.cs index ec0f038c3..f2f51ff3d 100644 --- a/Hohoema/Models.UseCase/Niconico.Player/SecondaryViewPlayerManager.cs +++ b/Hohoema/Models.UseCase/Niconico.Player/SecondaryViewPlayerManager.cs @@ -15,7 +15,6 @@ using Windows.UI.Xaml; using Windows.UI.Xaml.Media.Animation; using Hohoema.Models.Domain.Niconico.Live; -using Microsoft.AppCenter.Analytics; using System.Collections.Generic; using System.Text; using System.Linq; @@ -271,13 +270,13 @@ await SecondaryCoreAppView.DispatcherQueue.EnqueueAsync(async () => throw result.Exception; } - Analytics.TrackEvent("PlayerNavigation", new Dictionary - { - { "PageType", pageName }, - { "ViewType", "Secondary" }, - { "CompactOverlay", (SecondaryAppView.ViewMode == ApplicationViewMode.CompactOverlay).ToString() }, - { "FullScreen", SecondaryAppView.IsFullScreenMode.ToString() }, - }); + //Analytics.TrackEvent("PlayerNavigation", new Dictionary + //{ + // { "PageType", pageName }, + // { "ViewType", "Secondary" }, + // { "CompactOverlay", (SecondaryAppView.ViewMode == ApplicationViewMode.CompactOverlay).ToString() }, + // { "FullScreen", SecondaryAppView.IsFullScreenMode.ToString() }, + //}); }); await ShowAsync(); diff --git a/Hohoema/Models.UseCase/PageNavigation/PageManager.cs b/Hohoema/Models.UseCase/PageNavigation/PageManager.cs index b97ecb44e..846a91298 100644 --- a/Hohoema/Models.UseCase/PageNavigation/PageManager.cs +++ b/Hohoema/Models.UseCase/PageNavigation/PageManager.cs @@ -34,6 +34,8 @@ using NiconicoToolkit.Channels; using NiconicoToolkit.Community; using Hohoema.Models.UseCase.Playlist; +using Microsoft.Extensions.Logging; +using ZLogger; namespace Hohoema.Models.UseCase.PageNavigation { @@ -63,7 +65,7 @@ public PageNavigationEvent(PageNavigationEventArgs value) : base(value) public class PageManager : BindableBase { private readonly IMessenger _messenger; - + private readonly ILogger _logger; public AppearanceSettings AppearanceSettings { get; } public VideoCacheSettings_Legacy CacheSettings { get; } @@ -89,12 +91,14 @@ public class PageManager : BindableBase public PageManager( IScheduler scheduler, IMessenger messenger, + ILoggerFactory loggerFactory, AppearanceSettings appearanceSettings, VideoCacheSettings_Legacy cacheSettings ) { Scheduler = scheduler; _messenger = messenger; + _logger = loggerFactory.CreateLogger(); AppearanceSettings = appearanceSettings; CacheSettings = cacheSettings; } @@ -298,9 +302,7 @@ public bool OpenPage(Uri uri) // is mylist url? if (path.StartsWith("http://www.nicovideo.jp/mylist/") || path.StartsWith("https://www.nicovideo.jp/mylist/")) { - var mylistId = uri.AbsolutePath.Split('/').Last(); - System.Diagnostics.Debug.WriteLine($"open Mylist: {mylistId}"); - + var mylistId = uri.AbsolutePath.Split('/').Last(); OpenPageWithId(HohoemaPageType.Mylist, mylistId); return true; } @@ -310,9 +312,7 @@ public bool OpenPage(Uri uri) { // is nico video url? var videoId = uri.AbsolutePath.Split('/').Last(); - System.Diagnostics.Debug.WriteLine($"open Video: {videoId}"); _messenger.Send(new VideoPlayRequestMessage() { VideoId = videoId }); - return true; } @@ -348,7 +348,7 @@ public bool OpenPage(Uri uri) return true; } - Debug.WriteLine($"Urlを処理できませんでした : " + uri.OriginalString); + _logger.ZLogWarning("Urlを処理できませんでした : {0}", uri.OriginalString); return false; } @@ -380,7 +380,7 @@ public void OpenPage(HohoemaPageType pageType, INavigationParameters parameter = } catch (Exception e) { - ErrorTrackingManager.TrackError(e); + _logger.ZLogError(e, "OpenPage failed."); } } diff --git a/Hohoema/Models.UseCase/Playlist/LoginUserOwnedMylistManager.cs b/Hohoema/Models.UseCase/Playlist/LoginUserOwnedMylistManager.cs index bbed751d0..b48ede821 100644 --- a/Hohoema/Models.UseCase/Playlist/LoginUserOwnedMylistManager.cs +++ b/Hohoema/Models.UseCase/Playlist/LoginUserOwnedMylistManager.cs @@ -3,6 +3,7 @@ using Hohoema.Models.Domain.Niconico.Mylist.LoginUser; using Hohoema.Presentation.Services; using I18NPortable; +using Microsoft.Extensions.Logging; using NiconicoToolkit.Mylist; using Prism.Mvvm; using System; @@ -12,6 +13,7 @@ using System.Threading.Tasks; using Uno.Extensions; using Uno.Threading; +using ZLogger; using static Hohoema.Models.Domain.Niconico.Mylist.LoginUser.LoginUserMylistProvider; namespace Hohoema.Models.UseCase.Playlist @@ -25,12 +27,14 @@ namespace Hohoema.Models.UseCase.Playlist public class LoginUserOwnedMylistManager : BindableBase { public LoginUserOwnedMylistManager( + ILoggerFactory loggerFactory, NiconicoSession niconicoSession, LoginUserMylistProvider loginUserMylistProvider, NotificationService notificationService, LoginUserMylistItemIdRepository loginUserMylistItemIdRepository ) { + _logger = loggerFactory.CreateLogger(); _niconicoSession = niconicoSession; _loginUserMylistProvider = loginUserMylistProvider; _notificationService = notificationService; @@ -55,7 +59,7 @@ LoginUserMylistItemIdRepository loginUserMylistItemIdRepository } catch (Exception ex) { - ErrorTrackingManager.TrackError(ex); + _logger.ZLogError(ex, "Login user mylist update failed."); } }; @@ -72,7 +76,7 @@ LoginUserMylistItemIdRepository loginUserMylistItemIdRepository } catch (Exception ex) { - ErrorTrackingManager.TrackError(ex); + _logger.ZLogError(ex, "Logout user mylist update failed."); } }; } @@ -89,7 +93,7 @@ public bool IsLoginUserMylistReady set { SetProperty(ref _IsLoginUserMylistReady, value); } } - + private readonly ILogger _logger; readonly private NiconicoSession _niconicoSession; readonly private LoginUserMylistProvider _loginUserMylistProvider; private readonly NotificationService _notificationService; diff --git a/Hohoema/Models.UseCase/Subscriptions/SubscriptionUpdateManager.cs b/Hohoema/Models.UseCase/Subscriptions/SubscriptionUpdateManager.cs index a593129b0..5a96b8b6b 100644 --- a/Hohoema/Models.UseCase/Subscriptions/SubscriptionUpdateManager.cs +++ b/Hohoema/Models.UseCase/Subscriptions/SubscriptionUpdateManager.cs @@ -10,7 +10,8 @@ using System.Threading; using System.Threading.Tasks; using Uno; -using Microsoft.AppCenter.Crashes; +using Microsoft.Extensions.Logging; +using ZLogger; namespace Hohoema.Models.UseCase.Subscriptions { @@ -25,6 +26,7 @@ public class SubscriptionUpdatedEventArgs public sealed class SubscriptionUpdateManager : BindableBase, IDisposable { + private readonly ILogger _logger; private readonly SubscriptionManager _subscriptionManager; private readonly SubscriptionSettings _subscriptionSettings; AsyncLock _timerLock = new AsyncLock(); @@ -83,10 +85,12 @@ public TimeSpan UpdateFrequency public SubscriptionUpdateManager( + ILoggerFactory loggerFactory, SubscriptionManager subscriptionManager, SubscriptionSettings subscriptionSettingsRepository ) { + _logger = loggerFactory.CreateLogger(); _subscriptionManager = subscriptionManager; _subscriptionSettings = subscriptionSettingsRepository; _subscriptionManager.Added += _subscriptionManager_Added; @@ -122,14 +126,20 @@ private async void Current_Suspending(object sender, Windows.ApplicationModel.Su _timerUpdateCancellationTokenSource?.Cancel(); _timerUpdateCancellationTokenSource = null; } - catch (Exception ex) { ErrorTrackingManager.TrackError(ex); } + catch (Exception ex) + { + _logger.ZLogError(ex, "subscription timer cancel faield."); + } try { await StopTimerAsync(); } - catch (Exception ex) { ErrorTrackingManager.TrackError(ex); } + catch (Exception ex) + { + _logger.ZLogError(ex, "subscription timer stop faield."); + } finally { deferral.Complete(); @@ -145,7 +155,10 @@ private async void Current_Resuming(object sender, object e) StartOrResetTimer(); } - catch (Exception ex) { ErrorTrackingManager.TrackError(ex); } + catch (Exception ex) + { + _logger.ZLogError(ex, "購読の定期更新の開始に失敗"); + } } @@ -157,9 +170,9 @@ public async Task UpdateAsync(CancellationToken cancellationToken = default) if (_timerDisposer == null) { return; } if (Helpers.InternetConnection.IsInternet() is false) { return; } - Debug.WriteLine($"[{nameof(SubscriptionUpdateManager)}] start update ------------------- "); + _logger.ZLogDebug("start update"); await _subscriptionManager.RefreshAllFeedUpdateResultAsync(cancellationToken); - Debug.WriteLine($"[{nameof(SubscriptionUpdateManager)}] end update ------------------- "); + _logger.ZLogDebug("end update"); // 次の自動更新周期を延長して設定 _subscriptionSettings.SubscriptionsLastUpdatedAt = DateTime.Now; @@ -203,7 +216,7 @@ async void StartOrResetTimer() { await StopTimerAsync(); - Debug.WriteLine("購読の更新にあまりに時間が掛かったため処理を中断し、また定期自動更新も停止しました"); + _logger.ZLogInformation("購読の更新にあまりに時間が掛かったため処理を中断し、また定期自動更新も停止しました"); } finally { diff --git a/Hohoema/Models.UseCase/Subscriptions/SyncWatchHistoryOnLoggedIn.cs b/Hohoema/Models.UseCase/Subscriptions/SyncWatchHistoryOnLoggedIn.cs index 974d69d6c..1bb8bb5f2 100644 --- a/Hohoema/Models.UseCase/Subscriptions/SyncWatchHistoryOnLoggedIn.cs +++ b/Hohoema/Models.UseCase/Subscriptions/SyncWatchHistoryOnLoggedIn.cs @@ -2,24 +2,29 @@ using Hohoema.Models.Domain.Niconico; using Hohoema.Models.Domain.Niconico.Video.WatchHistory.LoginUser; using Hohoema.Models.UseCase.Playlist; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using ZLogger; namespace Hohoema.Models.UseCase.Subscriptions { public sealed class SyncWatchHistoryOnLoggedIn : IDisposable { + private readonly ILogger _logger; private readonly NiconicoSession _niconicoSession; private readonly LoginUserVideoWatchHistoryProvider _LoginUserVideoWatchHistoryProvider; public SyncWatchHistoryOnLoggedIn( + ILoggerFactory loggerFactory, NiconicoSession niconicoSession, LoginUserVideoWatchHistoryProvider LoginUserVideoWatchHistoryProvider ) { + _logger = loggerFactory.CreateLogger(); _niconicoSession = niconicoSession; _LoginUserVideoWatchHistoryProvider = LoginUserVideoWatchHistoryProvider; @@ -39,7 +44,7 @@ private async void _niconicoSession_LogIn(object sender, NiconicoSessionLoginEve } catch (Exception ex) { - ErrorTrackingManager.TrackError(ex); + _logger.ZLogError(ex, "ログインユーザーの視聴履歴をアプリの視聴済みに同期する処理に失敗"); } } } diff --git a/Hohoema/Models.UseCase/VideoCache/VideoCacheDownloadOperationManager.cs b/Hohoema/Models.UseCase/VideoCache/VideoCacheDownloadOperationManager.cs index 151e5a4df..83f7dcf9e 100644 --- a/Hohoema/Models.UseCase/VideoCache/VideoCacheDownloadOperationManager.cs +++ b/Hohoema/Models.UseCase/VideoCache/VideoCacheDownloadOperationManager.cs @@ -18,8 +18,10 @@ using Windows.UI.Notifications; using Hohoema.Models.Domain.Niconico.Video; using Hohoema.Models.Domain.Application; -using Microsoft.AppCenter.Crashes; using NiconicoToolkit.Video; +using Microsoft.Extensions.Logging; +using ZLogger; +using Cysharp.Text; namespace Hohoema.Models.UseCase.VideoCache { @@ -31,8 +33,7 @@ public sealed class VideoCacheDownloadOperationManager public const int MAX_DOWNLOAD_LINE_ = 1; private static readonly ToastNotifierCompat _notifier = ToastNotificationManagerCompat.CreateToastNotifier(); - - + private readonly ILogger _logger; private readonly VideoCacheManager _videoCacheManager; private readonly NicoVideoSessionOwnershipManager _nicoVideoSessionOwnershipManager; private readonly VideoCacheSettings _videoCacheSettings; @@ -58,6 +59,7 @@ public bool IsAllowDownload private readonly CompositeDisposable _disposables = new CompositeDisposable(); public VideoCacheDownloadOperationManager( + ILoggerFactory loggerFactory, VideoCacheManager videoCacheManager, NicoVideoSessionOwnershipManager nicoVideoSessionOwnershipManager, VideoCacheSettings videoCacheSettings, @@ -65,6 +67,7 @@ public VideoCacheDownloadOperationManager( NicoVideoProvider nicoVideoProvider ) { + _logger = loggerFactory.CreateLogger(); _videoCacheManager = videoCacheManager; _nicoVideoSessionOwnershipManager = nicoVideoSessionOwnershipManager; _videoCacheSettings = videoCacheSettings; @@ -75,7 +78,7 @@ NicoVideoProvider nicoVideoProvider _videoCacheManager.Requested += (s, e) => { - Debug.WriteLine($"[VideoCache] Requested: Id= {e.VideoId}, RequestQuality= {e.RequestedQuality}"); + _logger.ZLogDebug("Requested: Id= {0}, RequestQuality= {1}", e.VideoId, e.RequestedQuality); LaunchDownaloadOperationLoop(); TriggerVideoCacheStatusChanged(e.VideoId); @@ -84,10 +87,11 @@ NicoVideoProvider nicoVideoProvider _videoCacheManager.Started += (s, e) => { - Debug.WriteLine($"[VideoCache] Started: Id= {e.Item.VideoId}, RequestQuality= {e.Item.RequestedVideoQuality}, DownloadQuality= {e.Item.DownloadedVideoQuality}"); + + _logger.ZLogDebug("Started: Id= {0}, RequestQuality= {1}, DownloadQuality= {2}", e.Item.VideoId, e.Item.RequestedVideoQuality, e.Item.DownloadedVideoQuality); TriggerVideoCacheStatusChanged(e.Item.VideoId); - _notificationService.ShowLiteInAppNotification($"{"CacheVideo_Notification_DownloadStarted".Translate()}\n{e.Item.Title}", symbol: Windows.UI.Xaml.Controls.Symbol.Download); + _notificationService.ShowLiteInAppNotification(ZString.Format("{0}\n{1}", "CacheVideo_Notification_DownloadStarted".Translate(), e.Item.Title), symbol: Windows.UI.Xaml.Controls.Symbol.Download); StartBackgroundCacheProgressToast(e.Item); }; @@ -96,7 +100,7 @@ NicoVideoProvider nicoVideoProvider { if (_nextProgressShowTime < DateTime.Now) { - Debug.WriteLine($"[VideoCache] Progress: Id= {e.Item.VideoId}, Progress= {e.Item.GetProgressNormalized():P}"); + _logger.ZLogDebug("Progress: Id= {0}, Progress= {1:P}", e.Item.VideoId, e.Item.GetProgressNormalized()); _nextProgressShowTime = DateTime.Now + PROGRESS_UPDATE_INTERVAL; TriggerVideoCacheProgressChanged(e.Item); @@ -107,12 +111,12 @@ NicoVideoProvider nicoVideoProvider _videoCacheManager.Completed += (s, e) => { - Debug.WriteLine($"[VideoCache] Completed: Id= {e.Item.VideoId}"); + _logger.ZLogDebug("Completed: Id= {0}", e.Item.VideoId); TriggerVideoCacheStatusChanged(e.Item.VideoId); if (e.Item.Status == VideoCacheStatus.Completed) { - _notificationService.ShowLiteInAppNotification_Success($"{"CacheVideo_Notification_Completed".Translate()}\n{e.Item.Title}"); + _notificationService.ShowLiteInAppNotification_Success(ZString.Format("{0}\n{1}", "CacheVideo_Notification_Completed".Translate(), e.Item.Title)); // 完了をトースト通知で知らせる PopCacheCompletedToast(e.Item); @@ -122,18 +126,18 @@ NicoVideoProvider nicoVideoProvider _videoCacheManager.Canceled += (s, e) => { - Debug.WriteLine($"[VideoCache] Canceled: Id= {e.VideoId}"); + _logger.ZLogDebug("Canceled: Id= {0}", e.VideoId); TriggerVideoCacheStatusChanged(e.VideoId); - _notificationService.ShowLiteInAppNotification_Success($"{"CacheVideo_Notification_RequestRemoved".Translate()}\n{e.VideoId}"); + _notificationService.ShowLiteInAppNotification_Success(ZString.Format("{0}\n{1}", "CacheVideo_Notification_RequestRemoved".Translate(), e.VideoId)); }; _videoCacheManager.Failed += (s, e) => { - Debug.WriteLine($"[VideoCache] Failed: Id= {e.Item.VideoId}, FailedReason= {e.VideoCacheDownloadOperationCreationFailedReason}"); + _logger.ZLogDebug("Failed: Id= {0}, FailedReason= {1}", e.Item.VideoId, e.VideoCacheDownloadOperationCreationFailedReason); TriggerVideoCacheStatusChanged(e.Item.VideoId); - _notificationService.ShowLiteInAppNotification_Success($"{"CacheVideo_Notification_Failed".Translate()}\n{e.Item.Title}"); + _notificationService.ShowLiteInAppNotification_Success(ZString.Format("{0}\n{1}", "CacheVideo_Notification_Failed".Translate(), e.Item.Title)); PopCacheFailedToast(e.Item); StopBackgroundCacheProgressToast(); @@ -153,10 +157,10 @@ or VideoCacheDownloadOperationFailedReason.VideoDeleteFromServer _videoCacheManager.Paused += (s, e) => { - Debug.WriteLine($"[VideoCache] Paused: Id= {e.Item.VideoId}"); + _logger.ZLogDebug("Paused: Id= {0}", e.Item.VideoId); TriggerVideoCacheStatusChanged(e.Item.VideoId); - _notificationService.ShowLiteInAppNotification($"{"CacheVideo_Notification_Paused".Translate()}\n{e.Item.Title}", symbol: Windows.UI.Xaml.Controls.Symbol.Pause); + _notificationService.ShowLiteInAppNotification(ZString.Format("{0}\n{1}", "CacheVideo_Notification_Paused".Translate(), e.Item.Title), symbol: Windows.UI.Xaml.Controls.Symbol.Pause); UpdateBackgroundCacheProgressToast(e.Item, isPause: true); }; @@ -164,7 +168,6 @@ or VideoCacheDownloadOperationFailedReason.VideoDeleteFromServer App.Current.Suspending += async (s, e) => { - Debug.WriteLine($"[VideoCache] App Suspending."); var defferl = e.SuspendingOperation.GetDeferral(); try { @@ -177,7 +180,10 @@ or VideoCacheDownloadOperationFailedReason.VideoDeleteFromServer await _videoCacheManager.PauseAllDownloadOperationAsync(); } - catch (Exception ex) { ErrorTrackingManager.TrackError(ex); } + catch (Exception ex) + { + _logger.ZLogError(ex, "Cache operation suspending failed."); + } finally { defferl.Complete(); @@ -186,18 +192,18 @@ or VideoCacheDownloadOperationFailedReason.VideoDeleteFromServer App.Current.Resuming += (s, e) => { - Debug.WriteLine($"[VideoCache] App Resuming."); try { LaunchDownaloadOperationLoop(); } - catch (Exception ex) { ErrorTrackingManager.TrackError(ex); } + catch (Exception ex) + { + _logger.ZLogError(ex, "Cache operation resuming failed."); + } }; _nicoVideoSessionOwnershipManager.AvairableOwnership += (s, e) => { - Debug.WriteLine($"[VideoCache] AvairableOwnership"); - LaunchDownaloadOperationLoop(); }; @@ -262,17 +268,17 @@ private bool CanLaunchDownloadOperationLoop() } if (_stopDownloadTaskWithDisallowMeteredNetworkDownload) { - Debug.WriteLine("CacheDL Looping: disallow download with metered network, loop exit."); + _logger.ZLogDebug("CacheDL Looping: disallow download with metered network, loop exit."); return false; } else if (_stopDownloadTaskWithChangingSaveFolder) { - Debug.WriteLine("CacheDL Looping: stopping download from save folder changing, loop exit."); + _logger.ZLogDebug("CacheDL Looping: stopping download from save folder changing, loop exit."); return false; } else if (IsAllowDownload is false) { - Debug.WriteLine("CacheDL Looping: stopping download from user action, loop exit."); + _logger.ZLogDebug("CacheDL Looping: stopping download from user action, loop exit."); return false; } @@ -285,14 +291,14 @@ private async void LaunchDownaloadOperationLoop() { if (_isRunning) { - Debug.WriteLine("CacheDL Looping: already running, loop skiped."); + _logger.ZLogDebug("CacheDL Looping: already running, loop skiped."); return; } _isRunning = true; } - Debug.WriteLine("CacheDL Looping: loop started."); + _logger.ZLogDebug("CacheDL Looping: loop started."); try { @@ -300,8 +306,7 @@ private async void LaunchDownaloadOperationLoop() } catch (Exception e) { - Debug.WriteLine("CacheDL Looping: exit with Exception."); - Debug.WriteLine(e.ToString()); + _logger.ZLogError(e,"CacheDL Looping: exit with Exception."); } using (await _runningFlagUpdateLock.LockAsync()) @@ -309,7 +314,7 @@ private async void LaunchDownaloadOperationLoop() _isRunning = false; } - Debug.WriteLine("CacheDL Looping: loop completed."); + _logger.ZLogDebug("CacheDL Looping: loop completed."); } private async Task DownloadLoopAsync() @@ -327,7 +332,7 @@ private async Task DownloadLoopAsync() { _downloadTasks.Add(DownloadNextAsync()); - Debug.WriteLine("CacheDL Looping: add task"); + _logger.ZLogDebug("CacheDL Looping: add task"); } while (_downloadTasks.Count > 0) @@ -337,7 +342,7 @@ private async Task DownloadLoopAsync() var doneTask = _downloadTasks[index]; _downloadTasks.Remove(doneTask); - Debug.WriteLine("CacheDL Looping: remove task"); + _logger.ZLogDebug("CacheDL Looping: remove task"); if (result && CanLaunchDownloadOperationLoop() @@ -346,7 +351,7 @@ private async Task DownloadLoopAsync() { _downloadTasks.Add(DownloadNextAsync()); - Debug.WriteLine("CacheDL Looping: add task"); + _logger.ZLogDebug("CacheDL Looping: add task"); } } } @@ -368,8 +373,7 @@ private async ValueTask DownloadNextAsync() } catch (Exception e) { - Debug.WriteLine("CacheDL Looping: has exception."); - Debug.WriteLine(e.ToString()); + _logger.ZLogError(e, e.Message); return false; } diff --git a/Hohoema/Models.UseCase/VideoCache/VideoCacheFolderManager.cs b/Hohoema/Models.UseCase/VideoCache/VideoCacheFolderManager.cs index 17a05d540..ff4848fa3 100644 --- a/Hohoema/Models.UseCase/VideoCache/VideoCacheFolderManager.cs +++ b/Hohoema/Models.UseCase/VideoCache/VideoCacheFolderManager.cs @@ -2,6 +2,7 @@ using Hohoema.Models.Domain.Niconico.Video; using Hohoema.Models.Domain.VideoCache; using Hohoema.Models.Helpers; +using Microsoft.Extensions.Logging; using Microsoft.Toolkit.Mvvm.Messaging; using Microsoft.Toolkit.Uwp.Helpers; using System; @@ -12,6 +13,7 @@ using System.Threading.Tasks; using Windows.Storage; using Windows.Storage.AccessCache; +using ZLogger; namespace Hohoema.Models.UseCase.VideoCache { @@ -19,14 +21,17 @@ public sealed class VideoCacheFolderManager { public const string CACHE_FOLDER_NAME = "Hohoema_Videos"; + private readonly ILogger _logger; private readonly VideoCacheManager _videoCacheManager; private readonly NicoVideoProvider _nicoVideoProvider; public VideoCacheFolderManager( + ILoggerFactory loggerFactory, VideoCacheManager vIdeoCacheManager, NicoVideoProvider nicoVideoProvider ) { + _logger = loggerFactory.CreateLogger(); _videoCacheManager = vIdeoCacheManager; _nicoVideoProvider = nicoVideoProvider; @@ -69,7 +74,7 @@ public async Task InitializeAsync() } catch (Exception e) { - ErrorTrackingManager.TrackError(e); + _logger.ZLogError(e, e.Message); } _isInitialized = true; @@ -112,6 +117,10 @@ public async Task ChangeVideoCacheFolder() // 新しい指定フォルダをFutureAccessListへ登録 StorageApplicationPermissions.FutureAccessList.AddOrReplace(CACHE_FOLDER_NAME, newFolder); } + catch (Exception e) + { + _logger.ZLogError(e, e.Message); + } finally { _messenger.Send(); @@ -145,6 +154,11 @@ private async Task ImportCacheRequestFromNewFolderItems(StorageFolder folder) progressCount += files.Count; } + + if (exceptions.Any()) + { + _logger.ZLogError(new AggregateException(exceptions), "Import cache contains error"); + } } private bool ExtractionVideoIdFromVideoFileName(StorageFile file, out string outVideoId, out NicoVideoQuality quality) @@ -208,6 +222,11 @@ private async Task MoveFolderItemsToDestination(StorageFolder source, StorageFol progressCount += files.Count; } + + if (exceptions.Any()) + { + _logger.ZLogError(new AggregateException(exceptions), "Folder move action contains some error."); + } } } } diff --git a/Hohoema/Presentation.ViewModels/HohoemaListingPageViewModelBase.cs b/Hohoema/Presentation.ViewModels/HohoemaListingPageViewModelBase.cs index ad213a1af..a0df5446d 100644 --- a/Hohoema/Presentation.ViewModels/HohoemaListingPageViewModelBase.cs +++ b/Hohoema/Presentation.ViewModels/HohoemaListingPageViewModelBase.cs @@ -21,6 +21,8 @@ using Microsoft.Toolkit.Collections; using Microsoft.Toolkit.Uwp; using Uno.Disposables; +using Microsoft.Extensions.Logging; +using ZLogger; namespace Hohoema.Presentation.ViewModels { @@ -110,12 +112,16 @@ protected override async Task> LoadDataAsync(CancellationTo public ReactiveProperty HasError { get; } - DispatcherQueue _dispatcherQueue; public DateTime LatestUpdateTime = DateTime.Now; - public HohoemaListingPageViewModelBase() - { + + private readonly DispatcherQueue _dispatcherQueue; + protected readonly ILogger _logger; + + + public HohoemaListingPageViewModelBase(ILogger logger) + { NowLoading = new ReactiveProperty(true) .AddTo(_CompositeDisposable); @@ -142,6 +148,7 @@ public HohoemaListingPageViewModelBase() .AddTo(_CompositeDisposable); _dispatcherQueue = DispatcherQueue.GetForCurrentThread(); + _logger = logger; } @@ -249,7 +256,6 @@ private void ResetList_Internal(CancellationToken ct) { NowLoading.Value = false; HasError.Value = true; - Debug.WriteLine("failed GenerateIncrementalSource."); throw; } @@ -257,7 +263,7 @@ private void ResetList_Internal(CancellationToken ct) private void OnLodingItemError(Exception e) { - ErrorTrackingManager.TrackError(e); + //ErrorTrackingManager.TrackError(e); } protected void ResetList() @@ -274,7 +280,7 @@ protected void ResetList() } catch (Exception e) { - ErrorTrackingManager.TrackError(e); + _logger.ZLogError(e, "failed GenerateIncrementalSource."); } }); } @@ -407,7 +413,7 @@ protected void ResetFilter() private DelegateCommand _RefreshCommand; - public DelegateCommand RefreshCommand + public DelegateCommand RefreshCommand { get { diff --git a/Hohoema/Presentation.ViewModels/Navigation.Commands/SearchCommand.cs b/Hohoema/Presentation.ViewModels/Navigation.Commands/SearchCommand.cs index 46a45f4c3..ef1e40222 100644 --- a/Hohoema/Presentation.ViewModels/Navigation.Commands/SearchCommand.cs +++ b/Hohoema/Presentation.ViewModels/Navigation.Commands/SearchCommand.cs @@ -31,7 +31,7 @@ protected override bool CanExecute(object parameter) protected override void Execute(object parameter) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); if (parameter is string text) { diff --git a/Hohoema/Presentation.ViewModels/Niconico.Follow/FollowContext.cs b/Hohoema/Presentation.ViewModels/Niconico.Follow/FollowContext.cs index dd26965dc..8b315731b 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Follow/FollowContext.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Follow/FollowContext.cs @@ -1,14 +1,17 @@ using Hohoema.Models.Domain.Niconico.Follow; using Hohoema.Models.Domain.Niconico.Follow.LoginUser; using Hohoema.Models.UseCase; +using Microsoft.Extensions.Logging; using NiconicoToolkit.Account; using Prism.Commands; +using Prism.Ioc; using Prism.Mvvm; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using ZLogger; namespace Hohoema.Presentation.ViewModels.Niconico.Follow { @@ -31,7 +34,7 @@ public static FollowContext Create(IFollowProvider provider, private readonly IFollowProvider _provider; private readonly ItemType _followable; - + private readonly ILogger> _logger; private bool _IsFollowing; public bool IsFollowing { @@ -61,10 +64,10 @@ public bool NowChanging private FollowContext() { - + _logger = App.Current.Container.Resolve().CreateLogger>(); } - private FollowContext(IFollowProvider provider, ItemType followable, bool isFollowing) + private FollowContext(IFollowProvider provider, ItemType followable, bool isFollowing) : this() { _provider = provider; _followable = followable; @@ -109,7 +112,7 @@ private async Task AddFollowAsync() } catch (Exception e) { - ErrorTrackingManager.TrackError(e); + _logger.ZLogError(e, e.Message); } finally { @@ -143,7 +146,7 @@ private async Task RemoveFollowAsync() } catch (Exception e) { - ErrorTrackingManager.TrackError(e); + _logger.ZLogError(e, e.Message); } finally { diff --git a/Hohoema/Presentation.ViewModels/Niconico.Follow/FollowListup/FollowGroupViewModel.cs b/Hohoema/Presentation.ViewModels/Niconico.Follow/FollowListup/FollowGroupViewModel.cs index 7cb5b6cab..f7a79b09b 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Follow/FollowListup/FollowGroupViewModel.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Follow/FollowListup/FollowGroupViewModel.cs @@ -9,6 +9,9 @@ using Prism.Commands; using Hohoema.Models.UseCase.PageNavigation; using Hohoema.Models.UseCase; +using Prism.Ioc; +using Microsoft.Extensions.Logging; +using ZLogger; namespace Hohoema.Presentation.ViewModels.Niconico.Follow { @@ -37,12 +40,15 @@ public long TotalCount public IncrementalLoadingCollection, ItemType> Items { get; } + private readonly ILogger> _logger; + public FollowGroupViewModel(FollowItemType followItemType, IFollowProvider followProvider, FollowIncrementalSourceBase loadingSource, PageManager pageManager) { FollowItemType = followItemType; _followProvider = followProvider; _pageManager = pageManager; Items = new IncrementalLoadingCollection, ItemType>(source: loadingSource); + _logger = App.Current.Container.Resolve().CreateLogger>(); loadingSource.ObserveProperty(x => x.MaxCount).Subscribe(x => MaxCount = x).AddTo(_disposables); loadingSource.ObserveProperty(x => x.TotalCount).Subscribe(x => TotalCount = x).AddTo(_disposables); @@ -64,7 +70,7 @@ public virtual void Dispose() } catch (Exception e) { - ErrorTrackingManager.TrackError(e); + _logger.ZLogError(e, e.Message); } } , (item) => FollowItemType is not FollowItemType.Community and not FollowItemType.Channel diff --git a/Hohoema/Presentation.ViewModels/Niconico.Likes/VideoLikesContext.cs b/Hohoema/Presentation.ViewModels/Niconico.Likes/VideoLikesContext.cs index 8089301e8..da212b166 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Likes/VideoLikesContext.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Likes/VideoLikesContext.cs @@ -77,7 +77,7 @@ private async Task ProcessLikeAsync(bool like) return; } - Microsoft.AppCenter.Analytics.Analytics.TrackEvent("VideoLikesContext#ProcessLikeAsync"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent("VideoLikesContext#ProcessLikeAsync"); NowLikeProcessing = true; diff --git a/Hohoema/Presentation.ViewModels/Niconico.Live/LiveInfoListItemViewModel.cs b/Hohoema/Presentation.ViewModels/Niconico.Live/LiveInfoListItemViewModel.cs index 46ffa2efd..44778ae6b 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Live/LiveInfoListItemViewModel.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Live/LiveInfoListItemViewModel.cs @@ -18,11 +18,14 @@ using Hohoema.Models.UseCase; using NiconicoToolkit.Live.Cas; using NiconicoToolkit.Live.Timeshift; +using Microsoft.Extensions.Logging; +using ZLogger; namespace Hohoema.Presentation.ViewModels.Niconico.Live { public class LiveInfoListItemViewModel : BindableBase, ILiveContent, ILiveContentProvider { + private static readonly ILogger _logger; public static PageManager PageManager { get; } public static OpenLiveContentCommand OpenLiveContentCommand { get; } @@ -33,6 +36,7 @@ public class LiveInfoListItemViewModel : BindableBase, ILiveContent, ILiveConten static LiveInfoListItemViewModel() { + _logger = App.Current.Container.Resolve().CreateLogger(); PageManager = App.Current.Container.Resolve(); OpenLiveContentCommand = App.Current.Container.Resolve(); OpenShareUICommand = App.Current.Container.Resolve(); @@ -298,10 +302,12 @@ public DelegateCommand DeleteReservationCommand AddReservationCommand.RaiseCanExecuteChanged(); } + + _logger.ZLogInformation("Reservation deletion result: {0}", isDeleted); } catch (Exception e) { - ErrorTrackingManager.TrackError(e); + _logger.ZLogError(e, "DeleteReservation failed"); } } , () => Reservation != null @@ -348,7 +354,7 @@ private async Task DeleteReservation(LiveId liveId, string liveTitle) var notificationService = App.Current.Container.Resolve(); notificationService.ShowLiteInAppNotification_Fail("InAppNotification_FailedDeleteTimeshift".Translate()); - Debug.Fail("タイムシフト削除に失敗しました: " + liveId); + _logger.ZLogWarning("タイムシフト削除に失敗しました: {0}", liveId); } } @@ -381,10 +387,12 @@ public DelegateCommand AddReservationCommand RaisePropertyChanged(nameof(Reservation)); RaisePropertyChanged(nameof(ReservationStatus)); } + + _logger.ZLogInformation("Reservation registration result: {0}", result); } catch (Exception e) { - ErrorTrackingManager.TrackError(e); + _logger.ZLogError(e, "Reservation registration failed."); } } , () => IsTimeshiftEnabled && (StartTime - TimeSpan.FromMinutes(30) > DateTime.Now || _niconicoSession.IsPremiumAccount) && Reservation == null diff --git a/Hohoema/Presentation.ViewModels/Niconico.Share/CopyToClipboardCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Share/CopyToClipboardCommand.cs index 950c0448c..0e7614b3a 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Share/CopyToClipboardCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Share/CopyToClipboardCommand.cs @@ -3,7 +3,6 @@ using Hohoema.Models.Helpers; using Hohoema.Presentation.Services; using I18NPortable; -using Microsoft.AppCenter.Analytics; using Prism.Commands; using System; using System.Collections.Generic; @@ -42,10 +41,10 @@ protected override void Execute(object content) _notificationService.ShowLiteInAppNotification_Success("Copy".Translate()); - Analytics.TrackEvent("CopyToClipboardCommand", new Dictionary - { + //Analytics.TrackEvent("CopyToClipboardCommand", new Dictionary + //{ - }); + //}); } } } diff --git a/Hohoema/Presentation.ViewModels/Niconico.Share/CopyToClipboardWithShareTextCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Share/CopyToClipboardWithShareTextCommand.cs index 5c1c4f0d0..8523c5344 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Share/CopyToClipboardWithShareTextCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Share/CopyToClipboardWithShareTextCommand.cs @@ -3,7 +3,6 @@ using Hohoema.Models.Helpers; using Hohoema.Presentation.Services; using I18NPortable; -using Microsoft.AppCenter.Analytics; using Prism.Commands; using System; using System.Collections.Generic; @@ -55,10 +54,10 @@ protected override void Execute(object content) _notificationService.ShowLiteInAppNotification_Success("Copy".Translate()); - Analytics.TrackEvent("CopyToClipboardWithShareTextCommand", new Dictionary - { + //Analytics.TrackEvent("CopyToClipboardWithShareTextCommand", new Dictionary + //{ - }); + //}); } } } diff --git a/Hohoema/Presentation.ViewModels/Niconico.Share/OpenLinkCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Share/OpenLinkCommand.cs index 7e198b1f3..af58d513f 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Share/OpenLinkCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Share/OpenLinkCommand.cs @@ -1,6 +1,5 @@ using Hohoema.Models.Domain.Niconico; using Hohoema.Models.Helpers; -using Microsoft.AppCenter.Analytics; using Prism.Commands; using System; using System.Collections.Generic; @@ -42,10 +41,10 @@ protected override void Execute(object content) { _ = Windows.System.Launcher.LaunchUriAsync(uri); - Analytics.TrackEvent("OpenLinkCommand", new Dictionary - { + //Analytics.TrackEvent("OpenLinkCommand", new Dictionary + //{ - }); + //}); } } } diff --git a/Hohoema/Presentation.ViewModels/Niconico.Share/OpenShareUICommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Share/OpenShareUICommand.cs index 435be42a3..493592d96 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Share/OpenShareUICommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Share/OpenShareUICommand.cs @@ -1,7 +1,6 @@ using Hohoema.Models.Domain.Application; using Hohoema.Models.Domain.Niconico; using Hohoema.Models.Helpers; -using Microsoft.AppCenter.Analytics; using Prism.Commands; using System; using System.Collections.Generic; @@ -30,10 +29,10 @@ protected override void Execute(object content) { ShareHelper.Share(nicoContent); - Analytics.TrackEvent("OpenShareUICommand", new Dictionary - { - { "ContentType", content.GetType().Name } - }); + //Analytics.TrackEvent("OpenShareUICommand", new Dictionary + //{ + // { "ContentType", content.GetType().Name } + //}); } } } diff --git a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/HiddenVideoOwnerAddCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/HiddenVideoOwnerAddCommand.cs index 01713cc5f..8185f68a5 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/HiddenVideoOwnerAddCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/HiddenVideoOwnerAddCommand.cs @@ -47,7 +47,7 @@ protected override bool CanExecute(object parameter) protected override async void Execute(object parameter) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); if (parameter is IVideoContentProvider provider) { diff --git a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/HiddenVideoOwnerRemoveCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/HiddenVideoOwnerRemoveCommand.cs index a5c97c585..af0c8e615 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/HiddenVideoOwnerRemoveCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/HiddenVideoOwnerRemoveCommand.cs @@ -34,7 +34,7 @@ protected override bool CanExecute(object parameter) protected override void Execute(object parameter) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); if (parameter is IVideoContentProvider provider) { diff --git a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/LocalPlaylistAddItemCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/LocalPlaylistAddItemCommand.cs index 27e4c256b..c1e98ce03 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/LocalPlaylistAddItemCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/LocalPlaylistAddItemCommand.cs @@ -33,7 +33,7 @@ protected override void Execute(IVideoContent content) protected override async void Execute(IEnumerable items) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); var playlist = Playlist; if (playlist == null) diff --git a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/LocalPlaylistCreateCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/LocalPlaylistCreateCommand.cs index 7478422f9..4f3d8fa02 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/LocalPlaylistCreateCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/LocalPlaylistCreateCommand.cs @@ -35,7 +35,7 @@ protected override bool CanExecute(object parameter) protected override async void Execute(object parameter) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); var result = await DialogService.GetTextAsync( "LocalPlaylistCreate".Translate(), diff --git a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/LocalPlaylistDeleteCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/LocalPlaylistDeleteCommand.cs index 0308663c7..3927825ef 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/LocalPlaylistDeleteCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/LocalPlaylistDeleteCommand.cs @@ -34,7 +34,7 @@ protected override bool CanExecute(object parameter) protected override async void Execute(object parameter) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); if (parameter is LocalPlaylist localPlaylist) { diff --git a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/LocalPlaylistRemoveItemCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/LocalPlaylistRemoveItemCommand.cs index 351801069..f0060c0ac 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/LocalPlaylistRemoveItemCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/LocalPlaylistRemoveItemCommand.cs @@ -22,7 +22,7 @@ public LocalPlaylistRemoveItemCommand(LocalPlaylist playlist) protected override void Execute(IVideoContent content) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); if (content is IPlaylistItemPlayable playableItem) _playlist.RemovePlaylistItem(playableItem.PlaylistItemToken); @@ -31,7 +31,7 @@ protected override void Execute(IVideoContent content) protected override void Execute(IEnumerable items) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); _playlist.RemovePlaylistItems(items.Select(x => (x as IPlaylistItemPlayable).PlaylistItemToken)); } diff --git a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistAddItemCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistAddItemCommand.cs index f9f4aa56b..95f46695b 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistAddItemCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistAddItemCommand.cs @@ -42,7 +42,7 @@ protected override void Execute(IVideoContent content) protected override async void Execute(IEnumerable items) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); +// Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); var targetMylist = _userMylistManager.Mylists.Any() ? await _dialogService.ShowSingleSelectDialogAsync( diff --git a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistCopyItemCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistCopyItemCommand.cs index f4061d62f..e8d508cb0 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistCopyItemCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistCopyItemCommand.cs @@ -41,7 +41,7 @@ protected override void Execute(IVideoContent content) protected override async void Execute(IEnumerable items) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); if (SourceMylist == null) { throw new NullReferenceException(); } diff --git a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistCreateCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistCreateCommand.cs index 4a55e48df..eb3202837 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistCreateCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistCreateCommand.cs @@ -34,7 +34,7 @@ protected override bool CanExecute(object parameter) protected override async void Execute(object parameter) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); var data = new Dialogs.MylistGroupEditData() { }; var result = await DialogService.ShowCreateMylistGroupDialogAsync(data); diff --git a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistMoveItemCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistMoveItemCommand.cs index a2c91bea3..4e1f07240 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistMoveItemCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistMoveItemCommand.cs @@ -41,7 +41,7 @@ protected override void Execute(IVideoContent content) protected override async void Execute(IEnumerable items) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); if (SourceMylist == null) { throw new NullReferenceException(); } diff --git a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistRemoveItemCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistRemoveItemCommand.cs index 69ff26fdb..626e528d3 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistRemoveItemCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/MylistRemoveItemCommand.cs @@ -21,7 +21,7 @@ public MylistRemoveItemCommand(LoginUserMylistPlaylist playlist) protected override void Execute(IVideoContent content) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); if (content is IPlaylistItemPlayable playlistItemPlayable && playlistItemPlayable.PlaylistItemToken != null) { diff --git a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/QueueAddItemCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/QueueAddItemCommand.cs index 9f64abfea..3d5b3e1e3 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/QueueAddItemCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/QueueAddItemCommand.cs @@ -34,7 +34,7 @@ protected override void Execute(IVideoContent content) protected override void Execute(IEnumerable items) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); foreach (var content in items) { diff --git a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/QueueRemoveItemCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/QueueRemoveItemCommand.cs index 8396d45de..c82b80c8f 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/QueueRemoveItemCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/QueueRemoveItemCommand.cs @@ -34,7 +34,7 @@ protected override void Execute(IVideoContent content) protected override void Execute(IEnumerable items) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); foreach (var content in items) { diff --git a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/RemoveWatchedItemsInAfterWatchPlaylistCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/RemoveWatchedItemsInAfterWatchPlaylistCommand.cs index cf243db95..f19faf588 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/RemoveWatchedItemsInAfterWatchPlaylistCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/RemoveWatchedItemsInAfterWatchPlaylistCommand.cs @@ -32,7 +32,7 @@ protected override bool CanExecute(object parameter) protected override void Execute(object parameter) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); int count = 0; foreach (var item in _queuePlaylist.ToArray()) diff --git a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/VideoPlayCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/VideoPlayCommand.cs index ff9e3db6e..4731465af 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/VideoPlayCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/VideoPlayCommand.cs @@ -2,6 +2,7 @@ using Hohoema.Models.Domain.Playlist; using Hohoema.Models.UseCase; using Hohoema.Presentation.ViewModels.VideoListPage; +using Microsoft.Extensions.Logging; using Microsoft.Toolkit.Mvvm.Messaging; using NiconicoToolkit.Video; using Prism.Commands; @@ -10,15 +11,18 @@ using System.Linq; using System.Text; using System.Threading.Tasks; +using ZLogger; namespace Hohoema.Presentation.ViewModels.Niconico.Video.Commands { public sealed class VideoPlayWithQueueCommand : DelegateCommandBase { + private readonly ILogger _logger; private readonly IMessenger _messenger; - public VideoPlayWithQueueCommand(IMessenger messenger) + public VideoPlayWithQueueCommand(ILoggerFactory loggerFactory, IMessenger messenger) { + _logger = loggerFactory.CreateLogger(); _messenger = messenger; } @@ -51,7 +55,7 @@ protected override void Execute(object item) } catch (Exception e) { - ErrorTrackingManager.TrackError(e); + _logger.ZLogError(e, "video play faield"); } } } diff --git a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/WatchHistoryRemoveAllCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/WatchHistoryRemoveAllCommand.cs index 761f44857..9a3664344 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/WatchHistoryRemoveAllCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/WatchHistoryRemoveAllCommand.cs @@ -28,7 +28,7 @@ protected override bool CanExecute(object parameter) protected override void Execute(object parameter) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); _ = _watchHistoryManager.RemoveAllHistoriesAsync(); } diff --git a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/WatchHistoryRemoveItemCommand.cs b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/WatchHistoryRemoveItemCommand.cs index f5213ae63..8815368ff 100644 --- a/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/WatchHistoryRemoveItemCommand.cs +++ b/Hohoema/Presentation.ViewModels/Niconico.Video/Commands/WatchHistoryRemoveItemCommand.cs @@ -32,7 +32,7 @@ protected override bool CanExecute(object parameter) protected override async void Execute(object parameter) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); if (parameter is IVideoContent watchHistory) { diff --git a/Hohoema/Presentation.ViewModels/PrimaryWindowCoreLayout/LiveMenuSubPageContent.cs b/Hohoema/Presentation.ViewModels/PrimaryWindowCoreLayout/LiveMenuSubPageContent.cs index 4c222665a..08864d804 100644 --- a/Hohoema/Presentation.ViewModels/PrimaryWindowCoreLayout/LiveMenuSubPageContent.cs +++ b/Hohoema/Presentation.ViewModels/PrimaryWindowCoreLayout/LiveMenuSubPageContent.cs @@ -32,28 +32,18 @@ PageManager pageManager ResetItems(); } - private async void ResetItems() + private void ResetItems() { - try - { - using (await NiconicoSession.SigninLock.LockAsync()) - { - MenuItems.Clear(); - - if (NiconicoSession.IsLoggedIn) - { - MenuItems.Add(new MenuItemViewModel(HohoemaPageType.Timeshift.Translate(), HohoemaPageType.Timeshift)); - MenuItems.Add(new MenuItemViewModel(HohoemaPageType.NicoRepo.Translate(), HohoemaPageType.NicoRepo)); - MenuItems.Add(new MenuItemViewModel(HohoemaPageType.FollowManage.Translate(), HohoemaPageType.FollowManage)); - } - - RaisePropertyChanged(nameof(MenuItems)); - } - } - catch (Exception ex) + MenuItems.Clear(); + + if (NiconicoSession.IsLoggedIn) { - ErrorTrackingManager.TrackError(ex); + MenuItems.Add(new MenuItemViewModel(HohoemaPageType.Timeshift.Translate(), HohoemaPageType.Timeshift)); + MenuItems.Add(new MenuItemViewModel(HohoemaPageType.NicoRepo.Translate(), HohoemaPageType.NicoRepo)); + MenuItems.Add(new MenuItemViewModel(HohoemaPageType.FollowManage.Translate(), HohoemaPageType.FollowManage)); } + + RaisePropertyChanged(nameof(MenuItems)); } diff --git a/Hohoema/Presentation.ViewModels/Subscriptions/AddKeywordSearchSubscriptionCommand.cs b/Hohoema/Presentation.ViewModels/Subscriptions/AddKeywordSearchSubscriptionCommand.cs index 0340c6172..669232875 100644 --- a/Hohoema/Presentation.ViewModels/Subscriptions/AddKeywordSearchSubscriptionCommand.cs +++ b/Hohoema/Presentation.ViewModels/Subscriptions/AddKeywordSearchSubscriptionCommand.cs @@ -1,5 +1,4 @@ using Hohoema.Models.Domain.Subscriptions; -using Microsoft.AppCenter.Analytics; using Prism.Commands; using System; using System.Collections.Generic; @@ -29,10 +28,10 @@ protected override void Execute(object parameter) var subscription = _subscriptionManager.AddKeywordSearchSubscription(keyword); if (subscription != null) { - Analytics.TrackEvent("Subscription_Added", new Dictionary - { - { "SourceType", SubscriptionSourceType.SearchWithKeyword.ToString() } - }); + //Analytics.TrackEvent("Subscription_Added", new Dictionary + //{ + // { "SourceType", SubscriptionSourceType.SearchWithKeyword.ToString() } + //}); } } } diff --git a/Hohoema/Presentation.ViewModels/Subscriptions/AddSubscriptionCommand.cs b/Hohoema/Presentation.ViewModels/Subscriptions/AddSubscriptionCommand.cs index a6275c0cc..743a2103f 100644 --- a/Hohoema/Presentation.ViewModels/Subscriptions/AddSubscriptionCommand.cs +++ b/Hohoema/Presentation.ViewModels/Subscriptions/AddSubscriptionCommand.cs @@ -7,7 +7,6 @@ using Hohoema.Models.Domain.Subscriptions; using Hohoema.Presentation.Services; using I18NPortable; -using Microsoft.AppCenter.Analytics; using NiconicoToolkit.Video; using Prism.Commands; using System; @@ -87,10 +86,10 @@ protected override async void Execute(object parameter) Debug.WriteLine($"subscription added: {subscription.Id} {subscription.Label} {subscription.Id}" ); _notificationService.ShowLiteInAppNotification_Success("Notification_SuccessAddSubscriptionSourceWithLabel".Translate(subscription.Label)); - Analytics.TrackEvent("Subscription_Added", new Dictionary - { - { "SourceType", result.sourceType.ToString() } - }); + //Analytics.TrackEvent("Subscription_Added", new Dictionary + // { + // { "SourceType", result.sourceType.ToString() } + // }); } } diff --git a/Hohoema/Presentation.ViewModels/Subscriptions/AddTagSearchSubscriptionCommand.cs b/Hohoema/Presentation.ViewModels/Subscriptions/AddTagSearchSubscriptionCommand.cs index 59770bd82..130b267e7 100644 --- a/Hohoema/Presentation.ViewModels/Subscriptions/AddTagSearchSubscriptionCommand.cs +++ b/Hohoema/Presentation.ViewModels/Subscriptions/AddTagSearchSubscriptionCommand.cs @@ -1,5 +1,4 @@ using Hohoema.Models.Domain.Subscriptions; -using Microsoft.AppCenter.Analytics; using Prism.Commands; using System; using System.Collections.Generic; @@ -29,10 +28,10 @@ protected override void Execute(object parameter) var subscription = _subscriptionManager.AddTagSearchSubscription(tag); if (subscription != null) { - Analytics.TrackEvent("Subscription_Added", new Dictionary - { - { "SourceType", SubscriptionSourceType.SearchWithTag.ToString() } - }); + //Analytics.TrackEvent("Subscription_Added", new Dictionary + //{ + // { "SourceType", SubscriptionSourceType.SearchWithTag.ToString() } + //}); } } } diff --git a/Hohoema/Presentation.ViewModels/VideoCache.Commands/CacheAddRequestCommand.cs b/Hohoema/Presentation.ViewModels/VideoCache.Commands/CacheAddRequestCommand.cs index 2d3173877..ffe101ef2 100644 --- a/Hohoema/Presentation.ViewModels/VideoCache.Commands/CacheAddRequestCommand.cs +++ b/Hohoema/Presentation.ViewModels/VideoCache.Commands/CacheAddRequestCommand.cs @@ -31,7 +31,7 @@ DialogService dialogService protected override void Execute(IVideoContent content) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); _ = _videoCacheManager.PushCacheRequestAsync(content.VideoId, VideoQuality); } diff --git a/Hohoema/Presentation.ViewModels/VideoCache.Commands/CacheDeleteRequestCommand.cs b/Hohoema/Presentation.ViewModels/VideoCache.Commands/CacheDeleteRequestCommand.cs index 09f72134d..50cb232ce 100644 --- a/Hohoema/Presentation.ViewModels/VideoCache.Commands/CacheDeleteRequestCommand.cs +++ b/Hohoema/Presentation.ViewModels/VideoCache.Commands/CacheDeleteRequestCommand.cs @@ -54,7 +54,7 @@ protected override async void Execute(IVideoContent content) protected override async void Execute(IEnumerable items) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + // Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); var anyCached = items.Any(x => _videoCacheManager.GetVideoCacheStatus(x.VideoId) is VideoCacheStatus.Completed); if (anyCached) diff --git a/Hohoema/Presentation.Views.Pages/DebugPage.xaml.cs b/Hohoema/Presentation.Views.Pages/DebugPage.xaml.cs index 6095642b9..10c4c2ed6 100644 --- a/Hohoema/Presentation.Views.Pages/DebugPage.xaml.cs +++ b/Hohoema/Presentation.Views.Pages/DebugPage.xaml.cs @@ -1,5 +1,4 @@ using Hohoema.Presentation.Services; -using Microsoft.AppCenter.Crashes; using System; using System.Collections.Generic; using System.IO; @@ -38,7 +37,7 @@ private void ForceThrowException(object sender, RoutedEventArgs e) private void TestCrashReport_Click(object sender, RoutedEventArgs e) { - Crashes.GenerateTestCrash(); + } private void TestInAppNotification(object sender, RoutedEventArgs e) diff --git a/Hohoema/Presentation.Views.Pages/Hohoema.LocalMylist/LocalPlaylistPageViewModel.cs b/Hohoema/Presentation.Views.Pages/Hohoema.LocalMylist/LocalPlaylistPageViewModel.cs index 0ed3cfa3c..f7621d38b 100644 --- a/Hohoema/Presentation.Views.Pages/Hohoema.LocalMylist/LocalPlaylistPageViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/Hohoema.LocalMylist/LocalPlaylistPageViewModel.cs @@ -29,6 +29,7 @@ using Hohoema.Models.UseCase.Hohoema.LocalMylist; using I18NPortable; using Reactive.Bindings; +using Microsoft.Extensions.Logging; namespace Hohoema.Presentation.ViewModels.Pages.Hohoema.LocalMylist { @@ -55,6 +56,7 @@ IObservable ITitleUpdatablePage.GetTitleObservable() private readonly IMessenger _messenger; public LocalPlaylistPageViewModel( + ILoggerFactory loggerFactory, IMessenger messenger, ApplicationLayoutManager applicationLayoutManager, PageManager pageManager, @@ -65,6 +67,7 @@ public LocalPlaylistPageViewModel( LocalPlaylistDeleteCommand localPlaylistDeleteCommand, SelectionModeToggleCommand selectionModeToggleCommand ) + : base(loggerFactory.CreateLogger()) { ApplicationLayoutManager = applicationLayoutManager; _pageManager = pageManager; diff --git a/Hohoema/Presentation.Views.Pages/Hohoema.Queue/VideoQueuePageViewModel.cs b/Hohoema/Presentation.Views.Pages/Hohoema.Queue/VideoQueuePageViewModel.cs index c9de3790b..822d68bc1 100644 --- a/Hohoema/Presentation.Views.Pages/Hohoema.Queue/VideoQueuePageViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/Hohoema.Queue/VideoQueuePageViewModel.cs @@ -4,6 +4,7 @@ using Hohoema.Models.UseCase.Playlist; using Hohoema.Presentation.ViewModels.Niconico.Video.Commands; using Hohoema.Presentation.ViewModels.VideoListPage; +using Microsoft.Extensions.Logging; using Microsoft.Toolkit.Collections; using Microsoft.Toolkit.Mvvm.Messaging; using Prism.Navigation; @@ -35,6 +36,7 @@ public sealed class VideoQueuePageViewModel : HohoemaListingPageViewModelBase()) { _messenger = messenger; QueuePlaylist = queuePlaylist; diff --git a/Hohoema/Presentation.Views.Pages/Hohoema.Subscription/SubscriptionManagementPageViewModel.cs b/Hohoema/Presentation.Views.Pages/Hohoema.Subscription/SubscriptionManagementPageViewModel.cs index 261a10156..ebf49231c 100644 --- a/Hohoema/Presentation.Views.Pages/Hohoema.Subscription/SubscriptionManagementPageViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/Hohoema.Subscription/SubscriptionManagementPageViewModel.cs @@ -25,12 +25,13 @@ using Hohoema.Models.Domain.Niconico.Video; using Hohoema.Models.Domain.PageNavigation; using Hohoema.Models.Domain.Application; -using Microsoft.AppCenter.Analytics; using Hohoema.Presentation.ViewModels.VideoListPage; using Microsoft.Toolkit.Mvvm.Messaging; using Hohoema.Models.UseCase; using NiconicoToolkit.Video; using Hohoema.Presentation.ViewModels.Niconico.Video.Commands; +using Microsoft.Extensions.Logging; +using ZLogger; namespace Hohoema.Presentation.ViewModels.Pages.Hohoema.Subscription { @@ -45,7 +46,7 @@ public sealed class SubscriptionManagementPageViewModel : HohoemaPageViewModelBa private readonly NicoVideoProvider _nicoVideoProvider; private readonly VideoPlayWithQueueCommand _VideoPlayWithQueueCommand; private readonly IScheduler _scheduler; - + private readonly IMessenger _messenger; public IReadOnlyReactiveProperty IsAutoUpdateRunning { get; } public IReactiveProperty AutoUpdateFrequency { get; } @@ -57,7 +58,9 @@ void IRecipient.Receive(SettingsRestoredMessage message } public SubscriptionManagementPageViewModel( + ILoggerFactory loggerFactory, IScheduler scheduler, + IMessenger messenger, SubscriptionManager subscriptionManager, SubscriptionUpdateManager subscriptionUpdateManager, DialogService dialogService, @@ -66,10 +69,19 @@ public SubscriptionManagementPageViewModel( VideoPlayWithQueueCommand videoPlayWithQueueCommand ) { - WeakReferenceMessenger.Default.Register(this); + _logger = loggerFactory.CreateLogger(); + _scheduler = scheduler; + _messenger = messenger; + _subscriptionManager = subscriptionManager; + _subscriptionUpdateManager = subscriptionUpdateManager; + _dialogService = dialogService; + _pageManager = pageManager; + _nicoVideoProvider = nicoVideoProvider; + _VideoPlayWithQueueCommand = videoPlayWithQueueCommand; - Subscriptions = new ObservableCollection(); + _messenger.Register(this); + Subscriptions = new ObservableCollection(); Subscriptions.CollectionChangedAsObservable() .Throttle(TimeSpan.FromSeconds(0.25)) .Subscribe(_ => @@ -83,14 +95,6 @@ VideoPlayWithQueueCommand videoPlayWithQueueCommand }) .AddTo(_CompositeDisposable); - _subscriptionManager = subscriptionManager; - _subscriptionUpdateManager = subscriptionUpdateManager; - _dialogService = dialogService; - _pageManager = pageManager; - _nicoVideoProvider = nicoVideoProvider; - _VideoPlayWithQueueCommand = videoPlayWithQueueCommand; - _scheduler = scheduler; - IsAutoUpdateRunning = _subscriptionUpdateManager.ObserveProperty(x => x.IsRunning) .ToReadOnlyReactiveProperty(false) .AddTo(_CompositeDisposable); @@ -102,7 +106,6 @@ VideoPlayWithQueueCommand videoPlayWithQueueCommand _subscriptionManager.Added += _subscriptionManager_Added; _subscriptionManager.Removed += _subscriptionManager_Removed; _subscriptionManager.Updated += _subscriptionManager_Updated; - } @@ -124,7 +127,7 @@ public override void OnNavigatingTo(INavigationParameters parameters) { foreach (var subscInfo in _subscriptionManager.GetAllSubscriptionInfo().OrderBy(x => x.entity.SortIndex)) { - var vm = new SubscriptionViewModel(subscInfo.entity, this, _subscriptionManager, _pageManager, _dialogService, _VideoPlayWithQueueCommand); + var vm = new SubscriptionViewModel(_logger, subscInfo.entity, this, _subscriptionManager, _pageManager, _dialogService, _VideoPlayWithQueueCommand); var items = _nicoVideoProvider.GetCachedVideoInfoItems(subscInfo.feedResult.Videos.Select(x => (VideoId)x.VideoId)); vm.UpdateFeedResult(items, subscInfo.feedResult.LastUpdatedAt); Subscriptions.Add(vm); @@ -175,7 +178,7 @@ private void _subscriptionManager_Added(object sender, SubscriptionSourceEntity { _scheduler.Schedule(() => { - var vm = new SubscriptionViewModel(e, this, _subscriptionManager, _pageManager, _dialogService, _VideoPlayWithQueueCommand); + var vm = new SubscriptionViewModel(_logger, e, this, _subscriptionManager, _pageManager, _dialogService, _VideoPlayWithQueueCommand); Subscriptions.Insert(0, vm); }); } @@ -242,11 +245,13 @@ void ExecuteAllUpdateCommand() _subscriptionUpdateManager.RestartIfTimerNotRunning(); }); - Analytics.TrackEvent("Subscription_Update"); + //Analytics.TrackEvent("Subscription_Update"); } private DelegateCommand _CancelUpdateCommand; + private ILogger _logger; + public DelegateCommand CancelUpdateCommand => _CancelUpdateCommand ?? (_CancelUpdateCommand = new DelegateCommand(ExecuteCancelUpdateCommand)); @@ -261,6 +266,7 @@ void ExecuteCancelUpdateCommand() public sealed class SubscriptionViewModel : BindableBase, IDisposable { public SubscriptionViewModel( + ILogger logger, SubscriptionSourceEntity source, SubscriptionManagementPageViewModel pageViewModel, SubscriptionManager subscriptionManager, @@ -269,6 +275,7 @@ public SubscriptionViewModel( VideoPlayWithQueueCommand videoPlayWithQueueCommand ) { + _logger = logger; _source = source; _pageViewModel = pageViewModel; _subscriptionManager = subscriptionManager; @@ -286,6 +293,7 @@ VideoPlayWithQueueCommand videoPlayWithQueueCommand } private readonly CompositeDisposable _disposables = new CompositeDisposable(); + private readonly ILogger _logger; internal readonly SubscriptionSourceEntity _source; private readonly SubscriptionManagementPageViewModel _pageViewModel; private readonly SubscriptionManager _subscriptionManager; @@ -346,17 +354,13 @@ internal async void ExecuteUpdateCommand() } catch (Exception e) { - ErrorTrackingManager.TrackError(e); + _logger.ZLogErrorWithPayload(e, _source, "Subscription update failed"); } finally { NowUpdating = false; } - - Analytics.TrackEvent("Subscription_Update", new Dictionary - { - }); - } + } private DelegateCommand _PlayUnwatchVideosCommand; public DelegateCommand PlayUnwatchVideosCommand => @@ -403,11 +407,6 @@ async void ExecuteDeleteSubscriptionCommand() if (result) { _subscriptionManager.RemoveSubscription(_source); - - Analytics.TrackEvent("Subscription_Removed", new Dictionary - { - { "SourceType", _source.SourceType.ToString() } - }); } } diff --git a/Hohoema/Presentation.Views.Pages/Niconico.Activity/WatchHistoryPageViewModel.cs b/Hohoema/Presentation.Views.Pages/Niconico.Activity/WatchHistoryPageViewModel.cs index c78254c90..df450b0b3 100644 --- a/Hohoema/Presentation.Views.Pages/Niconico.Activity/WatchHistoryPageViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/Niconico.Activity/WatchHistoryPageViewModel.cs @@ -19,12 +19,15 @@ using System.Threading; using System.Threading.Tasks; using Hohoema.Models.UseCase.Niconico.Video; +using Microsoft.Extensions.Logging; +using ZLogger; namespace Hohoema.Presentation.ViewModels.Pages.Niconico.Activity { public class WatchHistoryPageViewModel : HohoemaPageViewModelBase { public WatchHistoryPageViewModel( + ILoggerFactory loggerFactory, ApplicationLayoutManager applicationLayoutManager, NiconicoSession niconicoSession, WatchHistoryManager watchHistoryManager, @@ -34,6 +37,7 @@ public WatchHistoryPageViewModel( SelectionModeToggleCommand selectionModeToggleCommand ) { + _logger = loggerFactory.CreateLogger(); ApplicationLayoutManager = applicationLayoutManager; _niconicoSession = niconicoSession; _watchHistoryManager = watchHistoryManager; @@ -46,6 +50,7 @@ SelectionModeToggleCommand selectionModeToggleCommand private readonly NiconicoSession _niconicoSession; private readonly WatchHistoryManager _watchHistoryManager; + private readonly ILogger _logger; public ApplicationLayoutManager ApplicationLayoutManager { get; } public PageManager PageManager { get; } @@ -100,7 +105,7 @@ public DelegateCommand RefreshCommand ?? (_RefreshCommand = new DelegateCommand(async () => { Histories.Clear(); - + try { var items = await _watchHistoryManager.GetWatchHistoryItemsAsync(); @@ -136,13 +141,13 @@ public DelegateCommand RefreshCommand } catch (Exception e) { - ErrorTrackingManager.TrackError(e); + _logger.ZLogErrorWithPayload(e, x, "History item process error."); } } } catch (Exception e) { - ErrorTrackingManager.TrackError(e); + _logger.ZLogError(e, "History refresh failed."); } } , () => _niconicoSession.IsLoggedIn diff --git a/Hohoema/Presentation.Views.Pages/Niconico.Channel/ChannelVideoPageViewModel.cs b/Hohoema/Presentation.Views.Pages/Niconico.Channel/ChannelVideoPageViewModel.cs index 1bcdbf02d..47b58e77e 100644 --- a/Hohoema/Presentation.Views.Pages/Niconico.Channel/ChannelVideoPageViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/Niconico.Channel/ChannelVideoPageViewModel.cs @@ -30,6 +30,7 @@ using Hohoema.Models.Domain.Playlist; using Reactive.Bindings; using System.Reactive.Linq; +using Microsoft.Extensions.Logging; namespace Hohoema.Presentation.ViewModels.Pages.Niconico.Channel { @@ -62,6 +63,7 @@ IObservable ITitleUpdatablePage.GetTitleObservable() } public ChannelVideoPageViewModel( + ILoggerFactory loggerFactory, ApplicationLayoutManager applicationLayoutManager, NiconicoSession niconicoSession, ChannelProvider channelProvider, @@ -72,6 +74,7 @@ public ChannelVideoPageViewModel( OpenLinkCommand openLinkCommand, SelectionModeToggleCommand selectionModeToggleCommand ) + : base(loggerFactory.CreateLogger()) { ApplicationLayoutManager = applicationLayoutManager; NiconicoSession = niconicoSession; diff --git a/Hohoema/Presentation.Views.Pages/Niconico.Community/CommunityVideoPageViewModel.cs b/Hohoema/Presentation.Views.Pages/Niconico.Community/CommunityVideoPageViewModel.cs index d7e2ccb11..5900c3d8f 100644 --- a/Hohoema/Presentation.Views.Pages/Niconico.Community/CommunityVideoPageViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/Niconico.Community/CommunityVideoPageViewModel.cs @@ -25,6 +25,8 @@ using Hohoema.Presentation.ViewModels.Niconico.Video.Commands; using Hohoema.Models.Domain.Playlist; using Reactive.Bindings; +using Microsoft.Extensions.Logging; +using ZLogger; namespace Hohoema.Presentation.ViewModels.Pages.Niconico.Community { @@ -60,13 +62,15 @@ public CommunityFollowContext FollowContext public CommunityVideoPageViewModel( + ILoggerFactory loggerFactory, ApplicationLayoutManager applicationLayoutManager, CommunityProvider communityProvider, CommunityFollowProvider communityFollowProvider, PageManager pageManager, VideoPlayWithQueueCommand videoPlayWithQueueCommand ) - { + : base(loggerFactory.CreateLogger()) + { ApplicationLayoutManager = applicationLayoutManager; CommunityProvider = communityProvider; _communityFollowProvider = communityFollowProvider; @@ -186,7 +190,7 @@ public override async Task OnNavigatedToAsync(INavigationParameters parameters) protected override (int, IIncrementalSource) GenerateIncrementalSource() { - return (CommunityVideoIncrementalSource.OneTimeLoadCount, new CommunityVideoIncrementalSource(CommunityId, 1, CommunityVideoPlaylist, SelectedSortOption, CommunityProvider)); + return (CommunityVideoIncrementalSource.OneTimeLoadCount, new CommunityVideoIncrementalSource(CommunityId, 1, CommunityVideoPlaylist, SelectedSortOption, CommunityProvider, _logger)); } private DelegateCommand _OpenCommunityPageCommand; @@ -218,10 +222,18 @@ public class CommunityVideoIncrementalSource : IIncrementalSource> IIncrementalSource.GetPagedItemsAsync(int pageIndex, int pageSize, CancellationToken ct) { @@ -246,7 +259,7 @@ async Task> IIncrementalSource(); } } diff --git a/Hohoema/Presentation.Views.Pages/Niconico.Live/TimeshiftPageViewModel.cs b/Hohoema/Presentation.Views.Pages/Niconico.Live/TimeshiftPageViewModel.cs index 8236c99f6..ca6d49450 100644 --- a/Hohoema/Presentation.Views.Pages/Niconico.Live/TimeshiftPageViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/Niconico.Live/TimeshiftPageViewModel.cs @@ -7,6 +7,7 @@ using Hohoema.Presentation.Services; using Hohoema.Presentation.ViewModels.Niconico.Live; using I18NPortable; +using Microsoft.Extensions.Logging; using Microsoft.Toolkit.Collections; using NiconicoToolkit.Live.Timeshift; using Prism.Commands; @@ -21,19 +22,22 @@ using System.Runtime.InteropServices.WindowsRuntime; using System.Threading; using System.Threading.Tasks; +using ZLogger; namespace Hohoema.Presentation.ViewModels.Pages.Niconico.Live { public sealed class TimeshiftPageViewModel : HohoemaListingPageViewModelBase, INavigatedAwareAsync { public TimeshiftPageViewModel( + ILoggerFactory loggerFactory, ApplicationLayoutManager applicationLayoutManager, LoginUserLiveReservationProvider loginUserLiveReservationProvider, NicoLiveProvider nicoLiveProvider, NoUIProcessScreenContext noUIProcessScreenContext, Services.DialogService dialogService, OpenLiveContentCommand openLiveContentCommand - ) + ) + : base(loggerFactory.CreateLogger()) { ApplicationLayoutManager = applicationLayoutManager; LoginUserLiveReservationProvider = loginUserLiveReservationProvider; @@ -100,7 +104,8 @@ await _noUIProcessScreenContext.StartNoUIWork( } catch (Exception e) { - ErrorTrackingManager.TrackError(e); + _logger.ZLogError(e, "DeleteOutdatedReservations failed"); + //ErrorTrackingManager.TrackError(e); } })); } diff --git a/Hohoema/Presentation.Views.Pages/Niconico.Mylist/MylistPageViewModel.cs b/Hohoema/Presentation.Views.Pages/Niconico.Mylist/MylistPageViewModel.cs index b2e005b2c..eca9ed8ba 100644 --- a/Hohoema/Presentation.Views.Pages/Niconico.Mylist/MylistPageViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/Niconico.Mylist/MylistPageViewModel.cs @@ -33,13 +33,14 @@ using System.Threading.Tasks; using Windows.UI.Popups; using Hohoema.Presentation.ViewModels.Niconico.Follow; -using Microsoft.AppCenter.Crashes; using Microsoft.Toolkit.Collections; using Microsoft.Toolkit.Uwp; using Hohoema.Models.UseCase.Hohoema.LocalMylist; using Microsoft.Toolkit.Mvvm.Messaging; using Hohoema.Models.Domain.LocalMylist; using NiconicoToolkit.Video; +using Microsoft.Extensions.Logging; +using ZLogger; namespace Hohoema.Presentation.ViewModels.Pages.Niconico.Mylist { @@ -63,6 +64,7 @@ IObservable ITitleUpdatablePage.GetTitleObservable() } public MylistPageViewModel( + ILoggerFactory loggerFactory, IMessenger messenger, ApplicationLayoutManager applicationLayoutManager, PageManager pageManager, @@ -83,6 +85,7 @@ public MylistPageViewModel( VideoPlayWithQueueCommand videoPlayWithQueueCommand ) { + _logger = loggerFactory.CreateLogger(); _messenger = messenger; ApplicationLayoutManager = applicationLayoutManager; PageManager = pageManager; @@ -267,6 +270,7 @@ VideoPlayWithQueueCommand videoPlayWithQueueCommand public ReactiveProperty SelectedSortOptionItem { get; } + private readonly ILogger _logger; private readonly IMessenger _messenger; private readonly MylistFollowProvider _mylistFollowProvider; private readonly MylistResolver _mylistRepository; @@ -414,7 +418,7 @@ public DelegateCommand EditMylistGroupCommand { Mylist.ForceNotify(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent("Mylist_Edit"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent("Mylist_Edit"); break; } @@ -461,7 +465,7 @@ public DelegateCommand DeleteMylistCommand PageManager.OpenPage(HohoemaPageType.UserMylist, OwnerUserId); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent("Mylist_Removed"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent("Mylist_Removed"); })); dialog.Commands.Add(new UICommand("Cancel".Translate())); @@ -698,13 +702,13 @@ private ICollection CreateItemsSource(MylistPlayl if (mylist is LoginUserMylistPlaylist loginUserMylist) { return new HohoemaListingPageViewModelBase.HohoemaIncrementalLoadingCollection( - new LoginUserMylistIncrementalSource(loginUserMylist, sortOption) + new LoginUserMylistIncrementalSource(loginUserMylist, sortOption, _logger) ); } else { return new HohoemaListingPageViewModelBase.HohoemaIncrementalLoadingCollection( - new MylistIncrementalSource(mylist, sortOption) + new MylistIncrementalSource(mylist, sortOption, _logger) ); } } @@ -728,15 +732,18 @@ public class MylistIncrementalSource : IIncrementalSource> IIncrementalSource.GetPagedItemsAsync(int pageIndex, int pageSize, CancellationToken cancellationToken) @@ -749,7 +756,7 @@ async Task> IIncrementalSource(); } } @@ -759,33 +766,44 @@ public class LoginUserMylistIncrementalSource : IIncrementalSource> IIncrementalSource.GetPagedItemsAsync(int pageIndex, int pageSize, CancellationToken ct) { - if (isEndReached) + try { - return Enumerable.Empty(); - } + if (isEndReached) + { + return Enumerable.Empty(); + } - var items = await _mylist.GetItemsAsync(pageIndex, pageSize, _sortOption.SortKey, _sortOption.SortOrder); - isEndReached = items.NicoVideoItems.Count != pageSize; + var items = await _mylist.GetItemsAsync(pageIndex, pageSize, _sortOption.SortKey, _sortOption.SortOrder); + isEndReached = items.NicoVideoItems.Count != pageSize; - ct.ThrowIfCancellationRequested(); + ct.ThrowIfCancellationRequested(); - var start = pageIndex * pageSize; - return items.Items.Select((x, i) => new VideoListItemControlViewModel(x.Video) { PlaylistItemToken = new(_mylist, _sortOption, new NvapiVideoItemWrapped(x.Video)) }); + var start = pageIndex * pageSize; + return items.Items.Select((x, i) => new VideoListItemControlViewModel(x.Video) { PlaylistItemToken = new(_mylist, _sortOption, new NvapiVideoItemWrapped(x.Video)) }); + } + catch (Exception e) + { + _logger.ZLogErrorWithPayload(exception: e, (MylistId: _mylist.MylistId, SortOption: _sortOption), "LoginUserMylist items loading failed"); + return Enumerable.Empty(); + } } } diff --git a/Hohoema/Presentation.Views.Pages/Niconico.Mylist/UserMylistPageViewModel.cs b/Hohoema/Presentation.Views.Pages/Niconico.Mylist/UserMylistPageViewModel.cs index f38799127..ebb797baa 100644 --- a/Hohoema/Presentation.Views.Pages/Niconico.Mylist/UserMylistPageViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/Niconico.Mylist/UserMylistPageViewModel.cs @@ -21,6 +21,8 @@ using System.Threading; using System.Threading.Tasks; using Hohoema.Models.UseCase.Hohoema.LocalMylist; +using Microsoft.Extensions.Logging; +using ZLogger; namespace Hohoema.Presentation.ViewModels.Pages.Niconico.Mylist { @@ -42,6 +44,7 @@ IObservable ITitleUpdatablePage.GetTitleObservable() } public UserMylistPageViewModel( + ILoggerFactory loggerFactory, ApplicationLayoutManager applicationLayoutManager, PageManager pageManager, Services.DialogService dialogService, @@ -50,6 +53,7 @@ public UserMylistPageViewModel( MylistResolver mylistRepository, LocalMylistManager localMylistManager ) + : base(loggerFactory.CreateLogger()) { ApplicationLayoutManager = applicationLayoutManager; PageManager = pageManager; @@ -123,7 +127,7 @@ public override async Task OnNavigatedToAsync(INavigationParameters parameters) protected override (int, IIncrementalSource) GenerateIncrementalSource() { - return (25 /* 全件取得するため指定不要 */, new OtherUserMylistIncrementalLoadingSource(UserId, _mylistRepository)); + return (25 /* 全件取得するため指定不要 */, new OtherUserMylistIncrementalLoadingSource(UserId, _mylistRepository, _logger)); } } @@ -134,11 +138,17 @@ public sealed class OtherUserMylistIncrementalLoadingSource : IIncrementalSource public string UserId { get; } private readonly MylistResolver _mylistRepository; + private readonly ILogger _logger; - public OtherUserMylistIncrementalLoadingSource(string userId, MylistResolver mylistRepository) + public OtherUserMylistIncrementalLoadingSource( + string userId, + MylistResolver mylistRepository, + ILogger logger + ) { UserId = userId; _mylistRepository = mylistRepository; + _logger = logger; } async Task> IIncrementalSource.GetPagedItemsAsync(int pageIndex, int pageSize, CancellationToken cancellationToken) @@ -152,7 +162,7 @@ async Task> IIncrementalSource.GetPa } catch (Exception ex) { - ErrorTrackingManager.TrackError(ex); + _logger.ZLogErrorWithPayload(exception: ex, UserId, "UserMylists loading failed"); return Enumerable.Empty(); } diff --git a/Hohoema/Presentation.Views.Pages/Niconico.NicoRepo/NicoRepoPageViewModel.cs b/Hohoema/Presentation.Views.Pages/Niconico.NicoRepo/NicoRepoPageViewModel.cs index 42c11eb02..5cf8d803e 100644 --- a/Hohoema/Presentation.Views.Pages/Niconico.NicoRepo/NicoRepoPageViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/Niconico.NicoRepo/NicoRepoPageViewModel.cs @@ -31,12 +31,14 @@ using System.Windows.Input; using Uno.Extensions; using Hohoema.Presentation.ViewModels.Niconico.Video.Commands; +using Microsoft.Extensions.Logging; namespace Hohoema.Presentation.ViewModels.Pages.Niconico.NicoRepo { public class NicoRepoPageViewModel : HohoemaListingPageViewModelBase, INavigatedAwareAsync { public NicoRepoPageViewModel( + ILoggerFactory loggerFactory, IScheduler scheduler, ApplicationLayoutManager applicationLayoutManager, NicoVideoProvider nicoVideoProvider, @@ -47,6 +49,7 @@ public NicoRepoPageViewModel( OpenLiveContentCommand openLiveContentCommand, VideoPlayWithQueueCommand videoPlayWithQueueCommand ) + : base(loggerFactory.CreateLogger()) { _scheduler = scheduler; ApplicationLayoutManager = applicationLayoutManager; diff --git a/Hohoema/Presentation.Views.Pages/Niconico.Search/SearchResultKeywordPageViewModel.cs b/Hohoema/Presentation.Views.Pages/Niconico.Search/SearchResultKeywordPageViewModel.cs index f99feb801..ea7d19816 100644 --- a/Hohoema/Presentation.Views.Pages/Niconico.Search/SearchResultKeywordPageViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/Niconico.Search/SearchResultKeywordPageViewModel.cs @@ -22,6 +22,7 @@ using System.Reactive.Linq; using System.Threading.Tasks; using Hohoema.Models.Domain.Playlist; +using Microsoft.Extensions.Logging; namespace Hohoema.Presentation.ViewModels.Pages.Niconico.Search { @@ -77,6 +78,7 @@ public CeApiSearchVideoPlaylistSortOption SelectedSortOption public SearchResultKeywordPageViewModel( + ILoggerFactory loggerFactory, ApplicationLayoutManager applicationLayoutManager, SearchProvider searchProvider, SubscriptionManager subscriptionManager, @@ -87,6 +89,7 @@ public SearchResultKeywordPageViewModel( AddKeywordSearchSubscriptionCommand addKeywordSearchSubscriptionCommand, SelectionModeToggleCommand selectionModeToggleCommand ) + : base(loggerFactory.CreateLogger()) { FailLoading = new ReactiveProperty(false) .AddTo(_CompositeDisposable); diff --git a/Hohoema/Presentation.Views.Pages/Niconico.Search/SearchResultLivePageViewModel.cs b/Hohoema/Presentation.Views.Pages/Niconico.Search/SearchResultLivePageViewModel.cs index da29378f5..2752d5fc8 100644 --- a/Hohoema/Presentation.Views.Pages/Niconico.Search/SearchResultLivePageViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/Niconico.Search/SearchResultLivePageViewModel.cs @@ -26,6 +26,7 @@ using Hohoema.Models.Domain.Pins; using Microsoft.Toolkit.Collections; using NiconicoToolkit.Live.Timeshift; +using Microsoft.Extensions.Logging; namespace Hohoema.Presentation.ViewModels.Pages.Niconico.Search { @@ -48,6 +49,7 @@ IObservable ITitleUpdatablePage.GetTitleObservable() } public SearchResultLivePageViewModel( + ILoggerFactory loggerFactory, ApplicationLayoutManager applicationLayoutManager, NiconicoSession niconicoSession, SearchProvider searchProvider, @@ -56,6 +58,7 @@ public SearchResultLivePageViewModel( NicoLiveCacheRepository nicoLiveCacheRepository, OpenLiveContentCommand openLiveContentCommand ) + : base(loggerFactory.CreateLogger()) { ApplicationLayoutManager = applicationLayoutManager; NiconicoSession = niconicoSession; diff --git a/Hohoema/Presentation.Views.Pages/Niconico.Search/SearchResultTagPageViewModel.cs b/Hohoema/Presentation.Views.Pages/Niconico.Search/SearchResultTagPageViewModel.cs index 437c3c1ca..6ebe9a85e 100644 --- a/Hohoema/Presentation.Views.Pages/Niconico.Search/SearchResultTagPageViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/Niconico.Search/SearchResultTagPageViewModel.cs @@ -27,6 +27,7 @@ using NiconicoToolkit.SearchWithCeApi.Video; using Microsoft.Toolkit.Collections; using Hohoema.Models.Domain.Playlist; +using Microsoft.Extensions.Logging; namespace Hohoema.Presentation.ViewModels.Pages.Niconico.Search { @@ -50,6 +51,7 @@ IObservable ITitleUpdatablePage.GetTitleObservable() } public SearchResultTagPageViewModel( + ILoggerFactory loggerFactory, ApplicationLayoutManager applicationLayoutManager, NiconicoSession niconicoSession, SearchProvider searchProvider, @@ -63,6 +65,7 @@ public SearchResultTagPageViewModel( AddTagSearchSubscriptionCommand addTagSearchSubscriptionCommand, SelectionModeToggleCommand selectionModeToggleCommand ) + : base(loggerFactory.CreateLogger()) { SearchProvider = searchProvider; _tagFollowProvider = tagFollowProvider; diff --git a/Hohoema/Presentation.Views.Pages/Niconico.Series/SeriesPageViewModel.cs b/Hohoema/Presentation.Views.Pages/Niconico.Series/SeriesPageViewModel.cs index a6d94d254..e5070e669 100644 --- a/Hohoema/Presentation.Views.Pages/Niconico.Series/SeriesPageViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/Niconico.Series/SeriesPageViewModel.cs @@ -10,6 +10,7 @@ using Hohoema.Presentation.ViewModels.Niconico.Video.Commands; using Hohoema.Presentation.ViewModels.Subscriptions; using Hohoema.Presentation.ViewModels.VideoListPage; +using Microsoft.Extensions.Logging; using Microsoft.Toolkit.Collections; using NiconicoToolkit.Series; using NiconicoToolkit.User; @@ -47,12 +48,14 @@ public IObservable GetTitleObservable() public SeriesPageViewModel( + ILoggerFactory loggerFactory, SeriesProvider seriesRepository, VideoPlayWithQueueCommand videoPlayWithQueueCommand, AddSubscriptionCommand addSubscriptionCommand, SelectionModeToggleCommand selectionModeToggleCommand, PlaylistPlayAllCommand playlistPlayAllCommand ) + : base(loggerFactory.CreateLogger()) { _seriesProvider = seriesRepository; VideoPlayWithQueueCommand = videoPlayWithQueueCommand; diff --git a/Hohoema/Presentation.Views.Pages/Niconico.User/UserVideoPageViewModel.cs b/Hohoema/Presentation.Views.Pages/Niconico.User/UserVideoPageViewModel.cs index 6335dc2f0..54b58ed11 100644 --- a/Hohoema/Presentation.Views.Pages/Niconico.User/UserVideoPageViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/Niconico.User/UserVideoPageViewModel.cs @@ -27,6 +27,8 @@ using Hohoema.Models.Domain.Playlist; using System.Reactive.Linq; using Hohoema.Models.Domain.Video; +using Microsoft.Extensions.Logging; +using ZLogger; namespace Hohoema.Presentation.ViewModels.Pages.Niconico.User { @@ -48,6 +50,7 @@ IObservable ITitleUpdatablePage.GetTitleObservable() } public UserVideoPageViewModel( + ILoggerFactory loggerFactory, ApplicationLayoutManager applicationLayoutManager, UserProvider userProvider, SubscriptionManager subscriptionManager, @@ -57,6 +60,7 @@ public UserVideoPageViewModel( AddSubscriptionCommand addSubscriptionCommand, SelectionModeToggleCommand selectionModeToggleCommand ) + : base(loggerFactory.CreateLogger()) { SubscriptionManager = subscriptionManager; ApplicationLayoutManager = applicationLayoutManager; @@ -165,7 +169,7 @@ protected override (int, IIncrementalSource) Gene SelectedSortOption = UserVideoPlaylist.DefaultSortOption; } - return (UserVideoIncrementalSource.OneTimeLoadCount, new UserVideoIncrementalSource(UserId, User, UserProvider, UserVideoPlaylist, SelectedSortOption)); + return (UserVideoIncrementalSource.OneTimeLoadCount, new UserVideoIncrementalSource(UserId, User, UserProvider, UserVideoPlaylist, SelectedSortOption, _logger)); } @@ -210,18 +214,27 @@ public class UserVideoIncrementalSource : IIncrementalSource> IIncrementalSource(); } } diff --git a/Hohoema/Presentation.Views.Pages/Niconico.Video/VideoInfomationPageViewModel.cs b/Hohoema/Presentation.Views.Pages/Niconico.Video/VideoInfomationPageViewModel.cs index e8df21778..acf31aa13 100644 --- a/Hohoema/Presentation.Views.Pages/Niconico.Video/VideoInfomationPageViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/Niconico.Video/VideoInfomationPageViewModel.cs @@ -49,6 +49,8 @@ using AngleSharp.Html.Parser; using Hohoema.Models.UseCase.Hohoema.LocalMylist; using Hohoema.Models.Domain.LocalMylist; +using Microsoft.Extensions.Logging; +using ZLogger; namespace Hohoema.Presentation.ViewModels.Pages.Niconico.Video { @@ -70,6 +72,7 @@ IObservable ITitleUpdatablePage.GetTitleObservable() } public VideoInfomationPageViewModel( + ILoggerFactory loggerFactory, ApplicationLayoutManager applicationLayoutManager, AppearanceSettings appearanceSettings, VideoFilteringSettings ngSettings, @@ -96,6 +99,7 @@ public VideoInfomationPageViewModel( ChannelFollowProvider channelFollowProvider ) { + _logger = loggerFactory.CreateLogger(); ApplicationLayoutManager = applicationLayoutManager; AppearanceSettings = appearanceSettings; NgSettings = ngSettings; @@ -406,6 +410,9 @@ public List RelatedVideos public Services.NotificationService NotificationService { get; } + + private readonly ILogger _logger; + public ApplicationLayoutManager ApplicationLayoutManager { get; } public VideoFilteringSettings NgSettings { get; } public NiconicoSession NiconicoSession { get; } @@ -501,7 +508,6 @@ public async Task OnNavigatedToAsync(INavigationParameters parameters) } catch (Exception ex) { - Debug.WriteLine(ex.ToString()); FollowContext = FollowContext.Default; throw; } @@ -556,7 +562,7 @@ public async void InitializeIchibaItems() } catch (Exception e) { - ErrorTrackingManager.TrackError(e); + _logger.ZLogErrorWithPayload(exception: e, VideoInfo.Id, "Video ichiba items loading failed"); } finally { @@ -609,7 +615,7 @@ public async void InitializeRelatedVideos() } catch (Exception ex) { - ErrorTrackingManager.TrackError(ex); + _logger.ZLogErrorWithPayload(exception: ex, VideoInfo.Id, "Video recommand video items loading failed"); } finally { @@ -661,10 +667,10 @@ private async Task UpdateVideoDescription() } } } - catch + catch (Exception e) { IsLoadFailed.Value = true; - return; + throw; } @@ -674,10 +680,11 @@ private async Task UpdateVideoDescription() DescriptionHtml = await HtmlFileHelper.ToCompletlyHtmlAsync(VideoDetails.DescriptionHtml, appTheme); } - catch + catch (Exception e) { + _logger.ZLogErrorWithPayload(exception: e, VideoInfo.Id, "Video info next/prev videos detection failed"); IsLoadFailed.Value = true; - return; + throw; } @@ -724,7 +731,6 @@ private async Task UpdateVideoDescription() } catch { - Debug.WriteLine("動画説明からリンクを抜き出す処理に失敗"); throw; } } diff --git a/Hohoema/Presentation.Views.Pages/Niconico.VideoRanking/RankingCategoryPageViewModel.cs b/Hohoema/Presentation.Views.Pages/Niconico.VideoRanking/RankingCategoryPageViewModel.cs index 4e6d5e1de..99f0c5e74 100644 --- a/Hohoema/Presentation.Views.Pages/Niconico.VideoRanking/RankingCategoryPageViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/Niconico.VideoRanking/RankingCategoryPageViewModel.cs @@ -32,6 +32,7 @@ using NiconicoToolkit.Rss.Video; using Microsoft.Toolkit.Collections; using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Logging; namespace Hohoema.Presentation.ViewModels.Pages.Niconico.VideoRanking { @@ -160,6 +161,7 @@ public RankingGenre RankingGenre MemoryCache _rankingMemoryCache; public RankingCategoryPageViewModel( + ILoggerFactory loggerFactory, ApplicationLayoutManager applicationLayoutManager, NiconicoSession niconicoSession, PageManager pageManager, @@ -171,6 +173,7 @@ public RankingCategoryPageViewModel( VideoPlayWithQueueCommand videoPlayWithQueueCommand, SelectionModeToggleCommand selectionModeToggleCommand ) + : base(loggerFactory.CreateLogger()) { ApplicationLayoutManager = applicationLayoutManager; _niconicoSession = niconicoSession; diff --git a/Hohoema/Presentation.Views.Pages/PrimaryWindowCoreLayout.xaml b/Hohoema/Presentation.Views.Pages/PrimaryWindowCoreLayout.xaml index 47fac10ea..f0c0a21e1 100644 --- a/Hohoema/Presentation.Views.Pages/PrimaryWindowCoreLayout.xaml +++ b/Hohoema/Presentation.Views.Pages/PrimaryWindowCoreLayout.xaml @@ -711,9 +711,9 @@ + + - - diff --git a/Hohoema/Presentation.Views.Pages/PrimaryWindowCoreLayout.xaml.cs b/Hohoema/Presentation.Views.Pages/PrimaryWindowCoreLayout.xaml.cs index 3e2630b8f..f6711fe6e 100644 --- a/Hohoema/Presentation.Views.Pages/PrimaryWindowCoreLayout.xaml.cs +++ b/Hohoema/Presentation.Views.Pages/PrimaryWindowCoreLayout.xaml.cs @@ -22,8 +22,6 @@ using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Navigation; using Hohoema.Models.Domain.Application; -using Microsoft.AppCenter.Analytics; -using Microsoft.AppCenter.Crashes; using System.Windows.Input; using Hohoema.Models.Domain.Notification; using Windows.UI; @@ -41,6 +39,9 @@ using Windows.UI.WindowManagement; using Prism.Ioc; using Hohoema.Models.Domain.Niconico.Video; +using Prism.Logging; +using Microsoft.Extensions.Logging; +using ZLogger; // ユーザー コントロールの項目テンプレートについては、https://go.microsoft.com/fwlink/?LinkId=234236 を参照してください @@ -49,26 +50,27 @@ namespace Hohoema.Presentation.Views.Pages public sealed partial class PrimaryWindowCoreLayout : UserControl { private readonly PrimaryWindowCoreLayoutViewModel _viewModel; - - + private readonly Services.CurrentActiveWindowUIContextService _currentActiveWindowUIContextService; + private readonly ILogger _logger; private readonly DispatcherQueue _dispatcherQueue; + public PrimaryWindowCoreLayout( PrimaryWindowCoreLayoutViewModel viewModel, - Services.CurrentActiveWindowUIContextService currentActiveWindowUIContextService + Services.CurrentActiveWindowUIContextService currentActiveWindowUIContextService, + ILoggerFactory loggerFactory ) { DataContext = _viewModel = viewModel; this.InitializeComponent(); _dispatcherQueue = DispatcherQueue.GetForCurrentThread(); + _currentActiveWindowUIContextService = currentActiveWindowUIContextService; + _logger = loggerFactory.CreateLogger(); + ContentFrame.NavigationFailed += (_, e) => { - Debug.WriteLine("Page navigation failed!!"); - Debug.WriteLine(e.SourcePageType.AssemblyQualifiedName); - Debug.WriteLine(e.Exception.ToString()); - - ErrorTrackingManager.TrackError(e.Exception); + _logger.ZLogError(e.Exception, "Page navigation failed!!"); }; // Resolve Page Title @@ -200,8 +202,7 @@ Services.CurrentActiveWindowUIContextService currentActiveWindowUIContextService }); Window.Current.Activated += Current_Activated; - _currentActiveWindowUIContextService = currentActiveWindowUIContextService; - + // Xbox向けのメニュー表示、下部のマージンを追加する if (_viewModel.ApplicationLayoutManager.AppLayout == ApplicationLayout.TV) { @@ -331,12 +332,6 @@ void ContentFrameNavigation(PageNavigationEventArgs args) throw result.Exception ?? new HohoemaExpception("navigation error"); } - - Analytics.TrackEvent("PageNavigation", new Dictionary - { - { "PageType", pageName }, - }); - Debug.WriteLineIf(!result.Success, result.Exception?.ToString()); @@ -349,9 +344,7 @@ void ContentFrameNavigation(PageNavigationEventArgs args) } catch (Exception e) { - var errorPageParam = parameter.Select(x => (x.Key, x.Value.ToString())).ToDictionary(x => x.Key, x => x.Item2); - errorPageParam.Add("PageType", pageName); - ErrorTrackingManager.TrackError(e, errorPageParam); + _logger.ZLogError(e, "ContentFrame Navigation failed: {0}", pageName); } }); } @@ -947,8 +940,7 @@ public bool IsDebugModeEnabled // Using a DependencyProperty as the backing store for IsDebugModeEnabled. This enables animation, styling, binding, etc... public static readonly DependencyProperty IsDebugModeEnabledProperty = DependencyProperty.Register("IsDebugModeEnabled", typeof(bool), typeof(PrimaryWindowCoreLayout), new PropertyMetadata(false)); - private readonly Services.CurrentActiveWindowUIContextService _currentActiveWindowUIContextService; - + public void OpenErrorTeachingTip(ICommand sentErrorCommand, Action onClosing) { AppErrorTeachingTip.ActionButtonCommand = sentErrorCommand; diff --git a/Hohoema/Presentation.Views.Pages/PrimaryWindowCoreLayoutViewModel.cs b/Hohoema/Presentation.Views.Pages/PrimaryWindowCoreLayoutViewModel.cs index e5a834635..8201b59f8 100644 --- a/Hohoema/Presentation.Views.Pages/PrimaryWindowCoreLayoutViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/PrimaryWindowCoreLayoutViewModel.cs @@ -18,6 +18,7 @@ using Hohoema.Presentation.ViewModels.Niconico.Video; using Hohoema.Presentation.ViewModels.PrimaryWindowCoreLayout; using I18NPortable; +using Microsoft.Extensions.Logging; using Microsoft.Toolkit.Mvvm.Messaging; using NiconicoToolkit; using NiconicoToolkit.Live; @@ -34,7 +35,9 @@ using System.Threading.Tasks; using System.Windows.Input; using Uno.Extensions; +using Windows.Storage; using Windows.System; +using ZLogger; namespace Hohoema.Presentation.ViewModels { @@ -64,6 +67,7 @@ void IRecipient.Receive(SettingsRestoredMessage message private readonly LocalMylistManager _localMylistManager; public OpenLiveContentCommand OpenLiveContentCommand { get; } + private readonly ILogger _logger; private readonly DialogService _dialogService; private readonly NotificationService _notificationService; @@ -78,6 +82,7 @@ void IRecipient.Receive(SettingsRestoredMessage message public LocalMylistSubMenuItemViewModel _localMylistMenuSubItemViewModel { get; } public PrimaryWindowCoreLayoutViewModel( + ILoggerFactory loggerFactory, NiconicoSession niconicoSession, PageManager pageManager, PinSettings pinSettings, @@ -99,6 +104,7 @@ public PrimaryWindowCoreLayoutViewModel( OpenLiveContentCommand openLiveContentCommand ) { + _logger = loggerFactory.CreateLogger(); NiconicoSession = niconicoSession; PageManager = pageManager; PinSettings = pinSettings; @@ -148,7 +154,7 @@ OpenLiveContentCommand openLiveContentCommand { _pinsMenuSubItemViewModel, _queueMenuItemViewModel, - new LogginUserLiveSummaryItemViewModel(NiconicoSession, OpenLiveContentCommand), + new LogginUserLiveSummaryItemViewModel(NiconicoSession, _logger, OpenLiveContentCommand), new SeparatorMenuItemViewModel(), new MenuItemViewModel(HohoemaPageType.RankingCategoryList.Translate(), HohoemaPageType.RankingCategoryList), new MenuItemViewModel(HohoemaPageType.NicoRepo.Translate(), HohoemaPageType.NicoRepo), @@ -226,12 +232,24 @@ void ExecuteSuggestSelectedCommand(SearchAutoSuggestItemViewModel parameter) } - + #endregion #region - + private DelegateCommand _OpenDebugLogFileCommand; + public DelegateCommand OpenDebugLogFileCommand + { + get + { + return _OpenDebugLogFileCommand + ?? (_OpenDebugLogFileCommand = new DelegateCommand(async () => + { + var file = await ApplicationData.Current.TemporaryFolder.GetFileAsync("_log.txt"); + await Launcher.LaunchFolderAsync(ApplicationData.Current.TemporaryFolder, new FolderLauncherOptions() { ItemsToSelect = { file } }); + })); + } + } private DelegateCommand _RequestApplicationRestartCommand; public DelegateCommand RequestApplicationRestartCommand @@ -317,7 +335,7 @@ internal void AddPin(HohoemaPin pin) void ExecuteDeletePinCommand(PinMenuItemViewModel pinVM) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); Items.Remove(pinVM); _pinSettings.DeleteItem(pinVM.Pin.Id); @@ -335,7 +353,7 @@ void ExecuteDeletePinCommand(PinMenuItemViewModel pinVM) async void ExecuteOverridePinCommand(PinMenuItemViewModel item) { var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); - Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); + //Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{currentMethod.DeclaringType.Name}#{currentMethod.Name}"); var pin = item.Pin; @@ -600,6 +618,7 @@ public LocalMylistItemViewModel(LocalPlaylist localPlaylist) public sealed class LogginUserLiveSummaryItemViewModel : HohoemaListingPageItemBase { private readonly NiconicoSession _niconicoSession; + private readonly ILogger _logger; private readonly DispatcherQueueTimer _timer; private long _NotifyCount; @@ -620,9 +639,10 @@ public bool IsUnread public ObservableCollection Items { get; } public OpenLiveContentCommand OpenLiveContentCommand { get; } - public LogginUserLiveSummaryItemViewModel(NiconicoSession niconicoSession, OpenLiveContentCommand openLiveContentCommand) + public LogginUserLiveSummaryItemViewModel(NiconicoSession niconicoSession, ILogger logger, OpenLiveContentCommand openLiveContentCommand) { _niconicoSession = niconicoSession; + _logger = logger; OpenLiveContentCommand = openLiveContentCommand; Items = new ObservableCollection(); @@ -661,7 +681,7 @@ private void Current_Resuming(object sender, object e) _timer.Stop(); } } - catch (Exception ex) { Microsoft.AppCenter.Crashes.Crashes.TrackError(ex); } + catch (Exception ex) { _logger.ZLogError(ex.ToString()); } } private void Current_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) @@ -670,7 +690,7 @@ private void Current_Suspending(object sender, Windows.ApplicationModel.Suspendi { _timer.Stop(); } - catch (Exception ex) { Microsoft.AppCenter.Crashes.Crashes.TrackError(ex); } + catch (Exception ex) { _logger.ZLogError(ex.ToString()); } } @@ -690,7 +710,7 @@ private async void UpdateNotify() } catch (Exception ex) { - ErrorTrackingManager.TrackError(ex); + _logger.ZLogError(ex.ToString()); } } @@ -730,7 +750,7 @@ public async void RefreshItems() } catch (Exception ex) { - ErrorTrackingManager.TrackError(ex); + _logger.ZLogError(ex.ToString()); } } } diff --git a/Hohoema/Presentation.Views.Pages/SettingsPage.xaml b/Hohoema/Presentation.Views.Pages/SettingsPage.xaml index ccccd163a..73cba2050 100644 --- a/Hohoema/Presentation.Views.Pages/SettingsPage.xaml +++ b/Hohoema/Presentation.Views.Pages/SettingsPage.xaml @@ -142,7 +142,7 @@ - + @@ -567,7 +567,7 @@ - + diff --git a/Hohoema/Presentation.Views.Pages/SettingsPageViewModel.cs b/Hohoema/Presentation.Views.Pages/SettingsPageViewModel.cs index 8545d5562..ab41474c6 100644 --- a/Hohoema/Presentation.Views.Pages/SettingsPageViewModel.cs +++ b/Hohoema/Presentation.Views.Pages/SettingsPageViewModel.cs @@ -10,8 +10,6 @@ using Hohoema.Presentation.Services; using Hohoema.Models.UseCase.PageNavigation; using I18NPortable; -using Microsoft.AppCenter.Analytics; -using Microsoft.AppCenter.Crashes; using Microsoft.Services.Store.Engagement; using Microsoft.UI.Xaml.Controls; using Prism.Commands; @@ -45,6 +43,8 @@ using System.Text; using Microsoft.Toolkit.Uwp.Helpers; using Xamarin.Essentials; +using Microsoft.Extensions.Logging; +using ZLogger; namespace Hohoema.Presentation.ViewModels.Pages.Hohoema { @@ -64,7 +64,8 @@ public SettingsPageViewModel( VideoCacheFolderManager videoCacheFolderManager, ApplicationLayoutManager applicationLayoutManager, VideoFilteringSettings videoFilteringRepository, - BackupManager backupManager + BackupManager backupManager, + ILoggerFactory loggerFactory ) { _notificationService = toastService; @@ -78,6 +79,7 @@ BackupManager backupManager ApplicationLayoutManager = applicationLayoutManager; _videoFilteringRepository = videoFilteringRepository; _backupManager = backupManager; + _logger = loggerFactory.CreateLogger(); // NG Video Owner User Id NGVideoOwnerUserIdEnable = _videoFilteringRepository.ToReactivePropertyAsSynchronized(x => x.NGVideoOwnerUserIdEnable) @@ -221,15 +223,15 @@ BackupManager backupManager // アプリの使用状況 - this.ObserveProperty(x => x.IsEnableCrashReport, isPushCurrentValueAtFirst: false) - .Where(x => !_NowNavigateProccess) - .Subscribe(async x => { await Crashes.SetEnabledAsync(x); }) - .AddTo(_CompositeDisposable); + //this.ObserveProperty(x => x.IsEnableCrashReport, isPushCurrentValueAtFirst: false) + // .Where(x => !_NowNavigateProccess) + // .Subscribe(async x => { await Crashes.SetEnabledAsync(x); }) + // .AddTo(_CompositeDisposable); - this.ObserveProperty(x => x.IsEnableAnalyticsReport, isPushCurrentValueAtFirst: false) - .Where(x => !_NowNavigateProccess) - .Subscribe(async x => { await Analytics.SetEnabledAsync(x); }) - .AddTo(_CompositeDisposable); + //this.ObserveProperty(x => x.IsEnableAnalyticsReport, isPushCurrentValueAtFirst: false) + // .Where(x => !_NowNavigateProccess) + // .Subscribe(async x => { await Analytics.SetEnabledAsync(x); }) + // .AddTo(_CompositeDisposable); StringBuilder sb = new StringBuilder(); @@ -255,6 +257,7 @@ BackupManager backupManager private readonly VideoCacheFolderManager _videoCacheFolderManager; private readonly VideoFilteringSettings _videoFilteringRepository; private readonly BackupManager _backupManager; + private readonly ILogger _logger; private readonly CommentFilteringFacade _commentFiltering; public NotificationService _notificationService { get; private set; } @@ -264,7 +267,7 @@ BackupManager backupManager public AppearanceSettings AppearanceSettings { get; } public VideoCacheSettings VideoCacheSettings { get; } public ApplicationLayoutManager ApplicationLayoutManager { get; } - + // フィルタ public ReactiveProperty NGVideoOwnerUserIdEnable { get; private set; } @@ -562,9 +565,11 @@ public DelegateCommand AddTransparencySecondaryTile secondaryTile.VisualElements.ShowNameOnSquare310x310Logo = true; secondaryTile.VisualElements.ShowNameOnWide310x150Logo = true; + + if (false == await secondaryTile.RequestCreateAsync()) { - throw new Models.Infrastructure.HohoemaExpception("Failed secondary tile creation."); + _logger.ZLogError("Failed secondary tile creation."); } } )); @@ -585,8 +590,8 @@ public async Task OnNavigatedToAsync(INavigationParameters parameters) new VideoFilteringTitleViewModel(x, OnRemoveVideoTitleFilterEntry, _videoFilteringRepository, TestText)) ); - IsEnableCrashReport = await Crashes.IsEnabledAsync(); - IsEnableAnalyticsReport = await Analytics.IsEnabledAsync(); + //IsEnableCrashReport = await Crashes.IsEnabledAsync(); + //IsEnableAnalyticsReport = await Analytics.IsEnabledAsync(); try { @@ -662,7 +667,7 @@ async void ExecuteExportBackupCommand() } catch (Exception e) { - ErrorTrackingManager.TrackError(e); + _logger.ZLogError(e, "Backup export failed"); } } @@ -737,7 +742,7 @@ async void ExecuteImportBackupCommand() } catch (Exception e) { - ErrorTrackingManager.TrackError(e); + _logger.ZLogError(e, "Backup import failed"); } } diff --git a/Hohoema/Presentation.Views.Player/VideoPlayerPageViewModel.cs b/Hohoema/Presentation.Views.Player/VideoPlayerPageViewModel.cs index affebd012..e2109a691 100644 --- a/Hohoema/Presentation.Views.Player/VideoPlayerPageViewModel.cs +++ b/Hohoema/Presentation.Views.Player/VideoPlayerPageViewModel.cs @@ -45,6 +45,8 @@ using Hohoema.Presentation.ViewModels.Player.Video; using Reactive.Bindings; using Hohoema.Models.Domain.Application; +using Microsoft.Extensions.Logging; +using ZLogger; namespace Hohoema.Presentation.ViewModels.Player { @@ -57,6 +59,7 @@ public class VideoPlayerPageViewModel : HohoemaPageViewModelBase, INavigatedAwar private readonly HohoemaPlaylistPlayer _hohoemaPlaylistPlayer; public VideoPlayerPageViewModel( + ILoggerFactory loggerFactory, IScheduler scheduler, IPlayerView playerView, NiconicoSession niconicoSession, @@ -103,6 +106,7 @@ public VideoPlayerPageViewModel( RelatedVideosSidePaneContentViewModel relatedVideosSidePaneContentViewModel ) { + _logger = loggerFactory.CreateLogger(); CurrentPlayerDisplayView = appearanceSettings .ObserveProperty(x => x.PlayerDisplayView) .ToReadOnlyReactivePropertySlim() @@ -189,6 +193,7 @@ RelatedVideosSidePaneContentViewModel relatedVideosSidePaneContentViewModel } + private readonly ILogger _logger; public ReadOnlyReactivePropertySlim CurrentPlayerDisplayView { get; } @@ -360,16 +365,14 @@ public override void Dispose() public async Task OnNavigatedToAsync(INavigationParameters parameters) { - Debug.WriteLine("VideoPlayer OnNavigatedToAsync start."); - _hohoemaPlaylistPlayer.ObserveProperty(x => x.CurrentQuality) .Subscribe(quality => _scheduler.Schedule(() => CurrentQuality = quality)) .AddTo(_NavigatingCompositeDisposable); _hohoemaPlaylistPlayer.ObserveProperty(x => x.CurrentPlaylistItem) - .Subscribe(x => + .Subscribe(item => { - if (x == null) { return; } + if (item == null) { return; } _scheduler.ScheduleAsync(async (s, ct) => { @@ -383,7 +386,7 @@ public async Task OnNavigatedToAsync(INavigationParameters parameters) } - if (x == null) + if (item == null) { VideoInfo = null; VideoId = null; @@ -399,7 +402,7 @@ public async Task OnNavigatedToAsync(INavigationParameters parameters) return; } - if (VideoInfo != null && VideoInfo.VideoId == x.VideoId) + if (VideoInfo != null && VideoInfo.VideoId == item.VideoId) { return; } @@ -411,7 +414,7 @@ public async Task OnNavigatedToAsync(INavigationParameters parameters) CommentPlayer.ClearCurrentSession(); // 削除状態をチェック(再生準備より先に行う) - var (res, video) = await NicoVideoProvider.GetVideoInfoAsync(x.VideoId); + var (res, video) = await NicoVideoProvider.GetVideoInfoAsync(item.VideoId); VideoInfo = video; CheckDeleted(res); @@ -443,8 +446,7 @@ public async Task OnNavigatedToAsync(INavigationParameters parameters) RaisePropertyChanged(nameof(VideoContent)); VideoEndedRecommendation.SetCurrentVideoSeries(VideoDetails); - Debug.WriteLine("次シリーズ動画: " + VideoDetails.Series?.Video.Next?.Title); - + VideoSeries = VideoDetails.Series is not null and var series ? new VideoSeriesViewModel(series) : null; RaisePropertyChanged(nameof(VideoSeries)); @@ -465,14 +467,12 @@ public async Task OnNavigatedToAsync(INavigationParameters parameters) } catch (Exception ex) { - ErrorTrackingManager.TrackError(ex, new Dictionary() { { "VideoId", x?.VideoId.ToString() } } ); + _logger.ZLogErrorWithPayload(exception: ex, item.VideoId, "Video playing item display content update failed"); } }); }) .AddTo(_NavigatingCompositeDisposable); - Debug.WriteLine("VideoPlayer OnNavigatedToAsync done."); - App.Current.Resuming += Current_Resuming; App.Current.Suspending += Current_Suspending; } @@ -486,7 +486,7 @@ private void CheckDeleted(VideoIdSearchSingleResponse res) // 動画が削除されていた場合 if (res.Video.IsDeleted) { - Debug.WriteLine($"cant playback{VideoId}. due to denied access to watch page, or connection offline."); + _logger.ZLogInformation("Video deleted : {0}", VideoId); _scheduler.ScheduleAsync(async (scheduler, cancelToken) => { @@ -514,10 +514,9 @@ private void CheckDeleted(VideoIdSearchSingleResponse res) } } } - catch (Exception exception) + catch (Exception ex) { - // 動画情報の取得に失敗 - System.Diagnostics.Debug.Write(exception.Message); + _logger.ZLogErrorWithPayload(exception: ex, res.Video.Id, "Video deleted process failed"); return; } } @@ -525,8 +524,6 @@ private void CheckDeleted(VideoIdSearchSingleResponse res) public override void OnNavigatedFrom(INavigationParameters parameters) { - Debug.WriteLine("VideoPlayer OnNavigatingFromAsync start."); - //MediaPlayer.Source = null; CommentPlayer.ClearCurrentSession(); @@ -546,8 +543,6 @@ public override void OnNavigatedFrom(INavigationParameters parameters) App.Current.Resuming -= Current_Resuming; App.Current.Suspending -= Current_Suspending; - Debug.WriteLine("VideoPlayer OnNavigatingFromAsync done."); - IsNotSupportVideoType = false; CannotPlayReason = null; @@ -571,7 +566,10 @@ private void Current_Suspending(object sender, Windows.ApplicationModel.Suspendi MediaPlayer.Source = null; } } - catch (Exception ex) { ErrorTrackingManager.TrackError(ex); } + catch (Exception ex) + { + _logger.ZLogError(ex, "Video player suspending failed"); + } finally { defferal.Complete(); @@ -583,7 +581,10 @@ private void Current_Resuming(object sender, object e) try { } - catch (Exception ex) { ErrorTrackingManager.TrackError(ex); } + catch (Exception ex) + { + _logger.ZLogError(ex, "Video player resuming failed"); + } } #region SidePaneContent diff --git a/Hohoema/Presentation.Views/Controls/VideoList/VideoItemsListView.xaml.cs b/Hohoema/Presentation.Views/Controls/VideoList/VideoItemsListView.xaml.cs index f7a59ecef..0c4ac4948 100644 --- a/Hohoema/Presentation.Views/Controls/VideoList/VideoItemsListView.xaml.cs +++ b/Hohoema/Presentation.Views/Controls/VideoList/VideoItemsListView.xaml.cs @@ -412,6 +412,8 @@ private void ItemsList_ContextRequested(UIElement sender, ContextRequestedEventA var fe = args.OriginalSource as FrameworkElement; var container = list.ContainerFromItem(fe.DataContext) as ListViewItem; + if (container == null) { return; } + container.DataContext = fe.DataContext; if (args.TryGetPosition(container, out var pt)) diff --git a/Hohoema/Properties/Default.rd.xml b/Hohoema/Properties/Default.rd.xml index ad1328899..884fec874 100644 --- a/Hohoema/Properties/Default.rd.xml +++ b/Hohoema/Properties/Default.rd.xml @@ -22,11 +22,13 @@ すべてのアセンブリに適用されます。アスタリスクはワイルドカードではありません。 --> - - + + + + \ No newline at end of file From 2926600620a28925771c72b8658629d937dbd839 Mon Sep 17 00:00:00 2001 From: tor4kichi Date: Thu, 17 Feb 2022 14:45:57 +0900 Subject: [PATCH 03/10] =?UTF-8?q?=E5=8B=95=E7=94=BB=E5=90=91=E3=81=91?= =?UTF-8?q?=E3=81=AE=E3=82=B5=E3=83=A0=E3=83=8D=E3=82=A4=E3=83=AB=E3=81=AE?= =?UTF-8?q?=E3=82=AD=E3=83=A3=E3=83=83=E3=82=B7=E3=83=A5=E6=A9=9F=E8=83=BD?= =?UTF-8?q?=E3=82=92=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Hohoema.Models/Hohoema.Models.csproj | 1 + .../Application/ThumbnailCacheManager.cs | 144 +++++++++++++++ Hohoema/App.xaml | 6 +- Hohoema/App.xaml.cs | 167 +++++++++++------- Hohoema/Hohoema.csproj | 4 + .../VideoThumbnailImageCacheMaintenance.cs | 27 +++ .../CacheManagementPage.xaml | 2 +- .../Niconico.Activity/WatchHistoryPage.xaml | 2 +- .../Niconico.Channel/ChannelVideoPage.xaml | 2 +- .../CommunityVideoPage.xaml | 2 +- .../Niconico.NicoRepo/NicoRepoPage.xaml | 2 +- .../RankingCategoryPage.xaml | 2 +- .../PlaylistSidePaneContent.xaml | 2 +- .../VideoList/VideoListItem/VideoListItem.cs | 22 ++- .../VideoListItemControl.cs | 10 +- .../VideoListItemControl.xaml | 2 +- .../VideoListItemControlDefaultTemplate.xaml | 2 +- 17 files changed, 315 insertions(+), 84 deletions(-) create mode 100644 Hohoema.Models/Models.Domain/Application/ThumbnailCacheManager.cs create mode 100644 Hohoema/Models.UseCase/Maintenance/VideoThumbnailImageCacheMaintenance.cs diff --git a/Hohoema.Models/Hohoema.Models.csproj b/Hohoema.Models/Hohoema.Models.csproj index 1f6020ae7..540efdead 100644 --- a/Hohoema.Models/Hohoema.Models.csproj +++ b/Hohoema.Models/Hohoema.Models.csproj @@ -133,6 +133,7 @@ + diff --git a/Hohoema.Models/Models.Domain/Application/ThumbnailCacheManager.cs b/Hohoema.Models/Models.Domain/Application/ThumbnailCacheManager.cs new file mode 100644 index 000000000..5d325396d --- /dev/null +++ b/Hohoema.Models/Models.Domain/Application/ThumbnailCacheManager.cs @@ -0,0 +1,144 @@ +using LiteDB; +using Microsoft.Toolkit.Mvvm.DependencyInjection; +using System; +using System.Buffers; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Windows.Storage.Streams; +using Windows.UI.Xaml.Data; +using Windows.UI.Xaml.Media.Imaging; +using Windows.Web.Http; + +namespace Hohoema.Models.Domain.Application +{ + public class UrlToCachedImageConverter : IValueConverter + { + private readonly ThumbnailCacheManager _thumbnailCacheManager; + + public UrlToCachedImageConverter() + { + _thumbnailCacheManager = Ioc.Default.GetService(); + } + + public object Convert(object value, Type targetType, object parameter, string language) + { + if (value is string url) + { + var bitmap = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); + _thumbnailCacheManager.ResolveImage(bitmap, url); + return bitmap; + } + else if (value is Uri uri) + { + var bitmap = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); + _thumbnailCacheManager.ResolveImage(bitmap, uri.OriginalString); + return bitmap; + } + else + { + throw new NotSupportedException(); + } + } + + public object ConvertBack(object value, Type targetType, object parameter, string language) + { + throw new NotImplementedException(); + } + } + + public sealed class ThumbnailCacheManager + { + private readonly LiteStorage _fileStorage; + private readonly HttpClient _httpClient; + + public ThumbnailCacheManager( + LiteDatabase liteDatabase + ) + { + _fileStorage = liteDatabase.FileStorage; +#if DEBUG && true + foreach (var file in _fileStorage.FindAll().ToArray()) + { + _fileStorage.Delete(file.Id); + } +#endif + _httpClient = new HttpClient(); + } + + public void Maitenance(TimeSpan expiredTime, int maxCount) + { + DateTime expiredDateTime = DateTime.Now - expiredTime; + foreach (var fileInfo in _fileStorage.FindAll().Where(x => x.Metadata.TryGetValue("updateAt", out var val) && (DateTime)val < expiredDateTime).ToArray()) + { + _fileStorage.Delete(fileInfo.Id); + } + + foreach (var fileInfo in _fileStorage.FindAll().OrderByDescending(x => x.UploadDate).Skip(maxCount).ToArray()) + { + _fileStorage.Delete(fileInfo.Id); + } + } + + public async void ResolveImage(BitmapImage image, string imageUrl) + { + var id = imageUrl.Replace("https://nicovideo.cdn.nimg.jp/thumbnails/", ""); + if (TryGetCacheImageStream(id, imageUrl, out var stream)) + { + using var _ = stream; + image.SetSource(stream.AsRandomAccessStream()); + } + else + { + using var res = await _httpClient.GetAsync(new Uri(imageUrl)); + if (!res.Content.TryComputeLength(out var length)) { throw new InvalidOperationException(); } + using var memoryStream = new MemoryStream((int)length); + await res.Content.WriteToStreamAsync(memoryStream.AsOutputStream()); + memoryStream.Seek(0, SeekOrigin.Begin); + image.SetSource(memoryStream.AsRandomAccessStream()); + memoryStream.Seek(0, SeekOrigin.Begin); + SetCacheImage(id, imageUrl, memoryStream.AsInputStream()); + } + } + + private bool TryGetCacheImageStream(string id, string imageUrl, out Stream outImageStream) + { + id = $"$/{id}"; + if (_fileStorage.Exists(id)) + { + var file = _fileStorage.FindById(id); + var stream = new MemoryStream((int)file.Length); + try + { + file.CopyTo(stream); + stream.Seek(0, SeekOrigin.Begin); + _fileStorage.SetMetadata(id, new BsonDocument(new Dictionary() { { "updateAt", DateTime.Now } })); + outImageStream = stream; + return true; + } + catch + { + stream.Dispose(); + throw; + } + } + else + { + outImageStream = null; + return false; + } + + } + + + private bool SetCacheImage(string id, string imageUrl, IInputStream stream) + { + id = $"$/{id}"; + var file = _fileStorage.Upload(id, imageUrl, stream.AsStreamForRead()); + _fileStorage.SetMetadata(id, new BsonDocument(new Dictionary() { { "updateAt", DateTime.Now } })); + return true; + } + } +} diff --git a/Hohoema/App.xaml b/Hohoema/App.xaml index da669a5d4..026808add 100644 --- a/Hohoema/App.xaml +++ b/Hohoema/App.xaml @@ -92,8 +92,10 @@ - False - + False + + + #F8B400 diff --git a/Hohoema/App.xaml.cs b/Hohoema/App.xaml.cs index 5d55714ac..ffa866faa 100644 --- a/Hohoema/App.xaml.cs +++ b/Hohoema/App.xaml.cs @@ -72,6 +72,8 @@ using ZLogger; using Cysharp.Text; using Windows.UI.Core; +using Microsoft.Toolkit.Mvvm.DependencyInjection; +using DryIoc.Microsoft.DependencyInjection; namespace Hohoema { @@ -87,13 +89,13 @@ sealed partial class App : PrismApplication private bool _IsPreLaunch; - public const string ACTIVATION_WITH_ERROR = "error"; + public const string ACTIVATION_WITH_ERROR = "error"; public const string ACTIVATION_WITH_ERROR_OPEN_LOG = "error_open_log"; public const string ACTIVATION_WITH_ERROR_COPY_LOG = "error_copy_log"; internal const string IS_COMPLETE_INTRODUCTION = "is_first_launch"; - + /// /// 単一アプリケーション オブジェクトを初期化します。これは、実行される作成したコードの ///最初の行であるため、main() または WinMain() と論理的に等価です。 @@ -109,17 +111,14 @@ public App() // テーマ設定 // ThemeResourceの切り替えはアプリの再起動が必要 RequestedTheme = GetTheme(); - - Microsoft.Toolkit.Uwp.UI.ImageCache.Instance.CacheDuration = TimeSpan.FromDays(7); - Microsoft.Toolkit.Uwp.UI.ImageCache.Instance.MaxMemoryCacheCount = 0; - Microsoft.Toolkit.Uwp.UI.ImageCache.Instance.RetryCount = 3; - + this.InitializeComponent(); - } + } protected override Rules CreateContainerRules() { - return base.CreateContainerRules().WithoutThrowOnRegisteringDisposableTransient(); + return base.CreateContainerRules() + .WithoutThrowOnRegisteringDisposableTransient(); } public override async Task OnStartAsync(StartArgs args) @@ -139,7 +138,7 @@ public override async Task OnStartAsync(StartArgs args) if (args.StartKind == StartKinds.Launch) { - + } else if (args.StartKind == StartKinds.Activate) { @@ -155,7 +154,7 @@ public override async Task OnStartAsync(StartArgs args) UIElement CreateShell() { - + // Grid // |- HohoemaInAppNotification // |- PlayerWithPageContainerViewModel @@ -202,7 +201,7 @@ public override void RegisterTypes(IContainerRegistry container) { var unityContainer = container.GetContainer(); -// unityContainer.Register(made: Made.Of().Parameters.Name("navigationServiceLazy", x => new Lazy(() => unityContainer.Resolve(serviceKey: "PrimaryPlayerNavigationService")))); + // unityContainer.Register(made: Made.Of().Parameters.Name("navigationServiceLazy", x => new Lazy(() => unityContainer.Resolve(serviceKey: "PrimaryPlayerNavigationService")))); unityContainer.UseInstance(new LocalObjectStorageHelper(new SystemTextJsonSerializer())); @@ -211,8 +210,11 @@ public override void RegisterTypes(IContainerRegistry container) LiteDatabase db = new LiteDatabase($"Filename={Path.Combine(ApplicationData.Current.LocalFolder.Path, "hohoema.db")};"); unityContainer.UseInstance(db); + LiteDatabase thumbDb = new LiteDatabase($"Filename={Path.Combine(ApplicationData.Current.TemporaryFolder.Path, "thumbnail_cache.db")};"); + unityContainer.Register(reuse: new SingletonReuse(), made: Made.Of(() => new ThumbnailCacheManager(thumbDb))); - unityContainer.RegisterDelegate(c => + + unityContainer.RegisterDelegate(c => { var appearanceSettings = c.Resolve(); if (appearanceSettings.PlayerDisplayView == PlayerDisplayView.PrimaryView) @@ -322,7 +324,7 @@ private LogLevel ToLogLevel(Category category, Priority priority) (Category.Debug, _) => LogLevel.Debug, (Category.Exception, _) => LogLevel.Error, (Category.Info, _) => LogLevel.Information, - (Category.Warn, _) => LogLevel.Warning, + (Category.Warn, _) => LogLevel.Warning, _ => LogLevel.None, }; } @@ -357,7 +359,7 @@ public class EmptyLoggerFacade : ILoggerFacade { public void Log(string message, Category category, Priority priority) { - + } } @@ -383,7 +385,7 @@ public DebugOutputStream(IScheduler scheduler) public override void Flush() { - + } public override int Read(byte[] buffer, int offset, int count) @@ -398,16 +400,16 @@ public override long Seek(long offset, SeekOrigin origin) public override void SetLength(long value) { - + } public override void Write(byte[] buffer, int offset, int count) - { + { _length = count; Debug.Write(System.Text.Encoding.UTF8.GetString(buffer, offset, count)); } } - + private ILoggerFactory _loggerFactory; protected override void RegisterRequiredTypes(IContainerRegistry containerRegistry) @@ -422,18 +424,18 @@ protected override void RegisterRequiredTypes(IContainerRegistry containerRegist builder .AddFilter("Microsoft", LogLevel.Warning) .AddFilter("System", LogLevel.Warning) - .AddFilter("LoggingConsoleApp.Program", LogLevel.Debug) + .AddFilter("LoggingConsoleApp.Program", LogLevel.Debug) #if DEBUG .AddZLoggerStream(new DebugOutputStream(mainWindowsScheduler), "debug-plain", opt => { }) #endif - ; - + ; + if (IsDebugModeEnabled) { - FileStream _logFileStream = new FileStream(ApplicationData.Current.TemporaryFolder.CreateSafeFileHandle("_log.txt", System.IO.FileMode.OpenOrCreate, FileAccess.Write), FileAccess.Write, 2 ^ 20); + FileStream _logFileStream = new FileStream(ApplicationData.Current.TemporaryFolder.CreateSafeFileHandle("_log.txt", System.IO.FileMode.OpenOrCreate, FileAccess.Write), FileAccess.Write, 65536); _logFileStream.SetLength(0); builder.AddFilter("Hohoema.App", DebugLogLevel) - .AddZLoggerStream(_logFileStream, "file-plain", opt => { opt.EnableStructuredLogging = false; }) + .AddZLoggerStream(_logFileStream, "file-plain", opt => { opt.EnableStructuredLogging = false; }) ; } else @@ -476,7 +478,7 @@ protected override void RegisterRequiredTypes(IContainerRegistry containerRegist containerRegistry.RegisterForNavigation(); containerRegistry.RegisterForNavigation(); containerRegistry.RegisterForNavigation(); - containerRegistry.RegisterForNavigation(); + containerRegistry.RegisterForNavigation(); containerRegistry.RegisterForNavigation(); containerRegistry.RegisterForNavigation(); containerRegistry.RegisterForNavigation(); @@ -494,63 +496,108 @@ protected override void RegisterRequiredTypes(IContainerRegistry containerRegist containerRegistry.RegisterForNavigation(); containerRegistry.RegisterForNavigation(); containerRegistry.RegisterForNavigation(); - + containerRegistry.RegisterForNavigation(); containerRegistry.RegisterForNavigation(); + + Ioc.Default.ConfigureServices(new DryIocServiceProvider(Container.GetContainer(), (type) => false)); } public bool IsTitleBarCustomized { get; } = DeviceTypeHelper.IsDesktop && InputCapabilityHelper.IsMouseCapable; Models.Helpers.AsyncLock InitializeLock = new Models.Helpers.AsyncLock(); bool isInitialized = false; - private async Task EnsureInitializeAsync() - { - using var initializeLock = await InitializeLock.LockAsync(); - if (isInitialized) { return; } - isInitialized = true; - - var logger = Container.Resolve(); + async Task MigrationProcessAsync() + { + Type[] migrateTypes = new Type[] + { + //typeof(MigrationCommentFilteringSettings), + //typeof(CommentFilteringNGScoreZeroFixture), + //typeof(SettingsMigration_V_0_23_0), + //typeof(SearchPageQueryMigrate_0_26_0), + typeof(VideoCacheDatabaseMigration_V_0_29_0), + typeof(SearchTargetMigration_V_1_1_0), + }; - async Task TryMigrationAsync(Type[] migrateTypes) + async Task TryMigrationAsync(Type migrateType) { - foreach (var migrateType in migrateTypes) + var logger = _loggerFactory.CreateLogger(migrateType); + try { - try + logger.ZLogInformation("Try migrate: {0}", migrateType.Name); + var migrater = Container.Resolve(migrateType); + if (migrater is IMigrateSync migrateSycn) { - logger.ZLogInformation("Try migrate: {0}", migrateType.Name); - var migrater = Container.Resolve(migrateType); - if (migrater is IMigrateSync migrateSycn) - { - migrateSycn.Migrate(); - } - else if (migrater is IMigrateAsync migrateAsync) - { - await migrateAsync.MigrateAsync(); - } - - logger.ZLogInformation("Migration complete : {0}", migrateType.Name); + migrateSycn.Migrate(); } - catch (Exception e) + else if (migrater is IMigrateAsync migrateAsync) { - logger.ZLogError(e.ToString()); - logger.ZLogError("Migration failed : {0}",migrateType.Name); + await migrateAsync.MigrateAsync(); } + + logger.ZLogInformation("Migration complete : {0}", migrateType.Name); + } + catch (Exception e) + { + logger.ZLogError(e.ToString()); + logger.ZLogError("Migration failed : {0}", migrateType.Name); } } - if (Microsoft.Toolkit.Uwp.Helpers.SystemInformation.Instance.IsAppUpdated) + foreach (var migrateType in migrateTypes) + { + await TryMigrationAsync(migrateType); + } + } + + async Task MaintenanceProcessAsync() + { + Type[] maintenanceTypes = new Type[] + { + typeof(Models.UseCase.Maintenance.VideoThumbnailImageCacheMaintenance), + }; + + async Task TryMaintenanceAsync(Type maintenanceType) { - await TryMigrationAsync(new Type[] + var logger = _loggerFactory.CreateLogger(maintenanceType); + + try { - //typeof(MigrationCommentFilteringSettings), - //typeof(CommentFilteringNGScoreZeroFixture), - //typeof(SettingsMigration_V_0_23_0), - //typeof(SearchPageQueryMigrate_0_26_0), - typeof(VideoCacheDatabaseMigration_V_0_29_0), - typeof(SearchTargetMigration_V_1_1_0), - }); + logger.ZLogInformation("Try maintenance: {0}", maintenanceType.Name); + var migrater = Container.Resolve(maintenanceType); + if (migrater is Models.UseCase.Maintenance.IMaintenance maintenance) + { + maintenance.Maitenance(); + } + + logger.ZLogInformation("Maintenance complete : {0}", maintenanceType.Name); + } + catch (Exception e) + { + logger.ZLogError(e, "Maintenance failed : {0}", maintenanceType.Name); + } } + + foreach (var maintenanceType in maintenanceTypes) + { + await TryMaintenanceAsync(maintenanceType); + } + } + + private async Task EnsureInitializeAsync() + { + using var initializeLock = await InitializeLock.LockAsync(); + + if (isInitialized) { return; } + isInitialized = true; + + if (Microsoft.Toolkit.Uwp.Helpers.SystemInformation.Instance.IsAppUpdated) + { + await MigrationProcessAsync(); + } + + await MaintenanceProcessAsync(); // 機能切り替え管理クラスをDIコンテナに登録 // Xaml側で扱いやすくするためApp.xaml上でインスタンス生成させている { diff --git a/Hohoema/Hohoema.csproj b/Hohoema/Hohoema.csproj index 4a439979b..dfdf4dbfb 100644 --- a/Hohoema/Hohoema.csproj +++ b/Hohoema/Hohoema.csproj @@ -138,6 +138,7 @@ + @@ -782,6 +783,9 @@ 0.16.0 + + 2.1.0 + 1.0.1 diff --git a/Hohoema/Models.UseCase/Maintenance/VideoThumbnailImageCacheMaintenance.cs b/Hohoema/Models.UseCase/Maintenance/VideoThumbnailImageCacheMaintenance.cs new file mode 100644 index 000000000..dadd36797 --- /dev/null +++ b/Hohoema/Models.UseCase/Maintenance/VideoThumbnailImageCacheMaintenance.cs @@ -0,0 +1,27 @@ +using Hohoema.Models.Domain.Application; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Hohoema.Models.UseCase.Maintenance +{ + public interface IMaintenance + { + void Maitenance(); + } + internal class VideoThumbnailImageCacheMaintenance : IMaintenance + { + private readonly ThumbnailCacheManager _thumbanilCacheManager; + + public VideoThumbnailImageCacheMaintenance(ThumbnailCacheManager thumbanilCacheManager) + { + _thumbanilCacheManager = thumbanilCacheManager; + } + public void Maitenance() + { + _thumbanilCacheManager.Maitenance(TimeSpan.FromDays(7), 1000); + } + } +} diff --git a/Hohoema/Presentation.Views.Pages/Hohoema.VideoCache/CacheManagementPage.xaml b/Hohoema/Presentation.Views.Pages/Hohoema.VideoCache/CacheManagementPage.xaml index 3f49948b6..e0de26388 100644 --- a/Hohoema/Presentation.Views.Pages/Hohoema.VideoCache/CacheManagementPage.xaml +++ b/Hohoema/Presentation.Views.Pages/Hohoema.VideoCache/CacheManagementPage.xaml @@ -133,7 +133,7 @@ diff --git a/Hohoema/Presentation.Views/Controls/VideoList/VideoListItem/VideoListItem.cs b/Hohoema/Presentation.Views/Controls/VideoList/VideoListItem/VideoListItem.cs index f1d3b230c..9b44c14c8 100644 --- a/Hohoema/Presentation.Views/Controls/VideoList/VideoListItem/VideoListItem.cs +++ b/Hohoema/Presentation.Views/Controls/VideoList/VideoListItem/VideoListItem.cs @@ -1,5 +1,4 @@ -using Hohoema.Models.Domain.Niconico.Video; -using Hohoema.Models.Domain.VideoCache; +using Hohoema.Models.Domain.VideoCache; using Hohoema.Models.Helpers; using System; using System.Collections.Generic; @@ -40,24 +39,29 @@ protected override void OnApplyTemplate() _templateChildImage = GetTemplateChild("ImagePart") as Image; } - public string ImageUrl + public object ImageSource { - get { return (string)GetValue(ImageUrlProperty); } - set { SetValue(ImageUrlProperty, value); } + get { return GetValue(ImageSourceProperty); } + set { SetValue(ImageSourceProperty, value); } } // Using a DependencyProperty as the backing store for ThumbnailUrl. This enables animation, styling, binding, etc... - public static readonly DependencyProperty ImageUrlProperty = - DependencyProperty.Register("ImageUrl", typeof(string), typeof(VideoListItem), new PropertyMetadata(null, OnImageUrlChanged)); + public static readonly DependencyProperty ImageSourceProperty = + DependencyProperty.Register("ImageSource", typeof(object), typeof(VideoListItem), new PropertyMetadata(null, OnImageSourceChanged)); - private static void OnImageUrlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + private static void OnImageSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (((VideoListItem)d)._templateChildImage is not null and var templatedChildImage) { if (e.NewValue is string strUrl && !string.IsNullOrEmpty(strUrl)) { + templatedChildImage.Source = new BitmapImage(new Uri(strUrl)); } + else if (e.NewValue is BitmapImage image) + { + templatedChildImage.Source = image; + } else { templatedChildImage.Source = null; @@ -65,6 +69,8 @@ private static void OnImageUrlChanged(DependencyObject d, DependencyPropertyChan } } + + public string ImageSubText { get { return (string)GetValue(ImageSubTextProperty); } diff --git a/Hohoema/Presentation.Views/Controls/VideoList/VideoListItemControl/VideoListItemControl.cs b/Hohoema/Presentation.Views/Controls/VideoList/VideoListItemControl/VideoListItemControl.cs index f3081e376..5d706f6a6 100644 --- a/Hohoema/Presentation.Views/Controls/VideoList/VideoListItemControl/VideoListItemControl.cs +++ b/Hohoema/Presentation.Views/Controls/VideoList/VideoListItemControl/VideoListItemControl.cs @@ -95,15 +95,15 @@ private static void OnIsHiddenPropertyChanged(DependencyObject d, DependencyProp - public string ThumbnailUrl + public object ImageSource { - get { return (string)GetValue(ThumbnailUrlProperty); } - set { SetValue(ThumbnailUrlProperty, value); } + get { return GetValue(ImageSourceProperty); } + set { SetValue(ImageSourceProperty, value); } } // Using a DependencyProperty as the backing store for ThumbnailUrl. This enables animation, styling, binding, etc... - public static readonly DependencyProperty ThumbnailUrlProperty = - DependencyProperty.Register("ThumbnailUrl", typeof(string), typeof(VideoListItemControl), new PropertyMetadata(null)); + public static readonly DependencyProperty ImageSourceProperty = + DependencyProperty.Register("ImageSource", typeof(object), typeof(VideoListItemControl), new PropertyMetadata(null)); diff --git a/Hohoema/Presentation.Views/Controls/VideoList/VideoListItemControl/VideoListItemControl.xaml b/Hohoema/Presentation.Views/Controls/VideoList/VideoListItemControl/VideoListItemControl.xaml index 50caf3267..9fc8349b0 100644 --- a/Hohoema/Presentation.Views/Controls/VideoList/VideoListItemControl/VideoListItemControl.xaml +++ b/Hohoema/Presentation.Views/Controls/VideoList/VideoListItemControl/VideoListItemControl.xaml @@ -23,7 +23,7 @@ Date: Thu, 17 Feb 2022 18:48:05 +0900 Subject: [PATCH 04/10] =?UTF-8?q?=E5=8B=95=E7=94=BB=E3=83=97=E3=83=AC?= =?UTF-8?q?=E3=82=A4=E3=83=A4=E3=83=BC=E3=81=A7=E3=81=AEIComment=E3=81=8C?= =?UTF-8?q?=E5=AE=9F=E8=B3=AAVideoComment=E3=81=A8=E3=81=97=E3=81=A6?= =?UTF-8?q?=E7=89=B9=E5=8C=96=E5=AF=BE=E5=BF=9C=E5=8F=AF=E8=83=BD=E3=81=AA?= =?UTF-8?q?=E3=81=AE=E3=81=A7=E3=82=AD=E3=83=A3=E3=82=B9=E3=83=88=E3=82=92?= =?UTF-8?q?=E6=B8=9B=E3=82=89=E3=81=99=E3=82=88=E3=81=86=E3=81=AB=E4=BF=AE?= =?UTF-8?q?=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Player/Comment/ICommentService.cs | 6 ++--- .../Player/INiconicoVideoSessionProvider.cs | 4 +-- .../Player/Video/Comment/CommentClient.cs | 26 +++++-------------- .../Video/Comment/VideoCommentService.cs | 6 ++--- .../Player/Video/NicoVideoSessionProvider.cs | 8 +++--- .../VideoStreamingOriginOrchestrator.cs | 4 +-- Hohoema/App.xaml.cs | 2 +- Hohoema/Hohoema.csproj | 2 +- ...CommentPlayer.cs => VideoCommentPlayer.cs} | 19 +++++++------- .../VideoStreamingOriginOrchestrator.cs | 4 +-- .../VideoPlayerPageViewModel.cs | 4 +-- .../VideoCommentSidePaneContentViewModel.cs | 4 +-- 12 files changed, 37 insertions(+), 52 deletions(-) rename Hohoema/Models.UseCase/Niconico.Player/Comment/{CommentPlayer.cs => VideoCommentPlayer.cs} (98%) diff --git a/Hohoema.Models/Models.Domain/Player/Comment/ICommentService.cs b/Hohoema.Models/Models.Domain/Player/Comment/ICommentService.cs index 98289d8ca..549410557 100644 --- a/Hohoema.Models/Models.Domain/Player/Comment/ICommentService.cs +++ b/Hohoema.Models/Models.Domain/Player/Comment/ICommentService.cs @@ -20,14 +20,14 @@ public struct CommentPostResult public ChatResultCode Status => StatusCode; } - public interface ICommentSession : IDisposable + public interface ICommentSession : IDisposable where TComment : IComment { string ContentId { get; } string UserId { get; } - event EventHandler RecieveComment; + event EventHandler RecieveComment; - Task> GetInitialComments(); + Task> GetInitialComments(); bool CanPostComment { get; } diff --git a/Hohoema.Models/Models.Domain/Player/INiconicoVideoSessionProvider.cs b/Hohoema.Models/Models.Domain/Player/INiconicoVideoSessionProvider.cs index cfa18411e..1956dbfdc 100644 --- a/Hohoema.Models/Models.Domain/Player/INiconicoVideoSessionProvider.cs +++ b/Hohoema.Models/Models.Domain/Player/INiconicoVideoSessionProvider.cs @@ -10,10 +10,10 @@ namespace Hohoema.Models.Domain.Player { - public interface INiconicoCommentSessionProvider + public interface INiconicoCommentSessionProvider where TComment : IComment { VideoId ContentId { get; } - Task CreateCommentSessionAsync(); + Task> CreateCommentSessionAsync(); } public interface INiconicoVideoSessionProvider diff --git a/Hohoema.Models/Models.Domain/Player/Video/Comment/CommentClient.cs b/Hohoema.Models/Models.Domain/Player/Video/Comment/CommentClient.cs index 7e57cbddb..bef30cdf3 100644 --- a/Hohoema.Models/Models.Domain/Player/Video/Comment/CommentClient.cs +++ b/Hohoema.Models/Models.Domain/Player/Video/Comment/CommentClient.cs @@ -93,36 +93,22 @@ public bool CanSubmitComment } - public async Task> GetCommentsAsync() + public async Task> GetCommentsAsync() { - List comments = null; - if (CanGetCommentsFromNMSG) { - try - { - var res = await GetCommentsFromNMSG(); - - var rawComments = res.Comments; - - comments = rawComments.Select(x => ChatToComment(x)).ToList(); - } - catch - { - } + var res = await GetCommentsFromNMSG(); + return res.Comments.Select(x => ChatToComment(x)); } - - if (comments == null) + else { - throw new HohoemaExpception("コメント取得に失敗"); + throw new NotSupportedException(); } - - return comments; } public string VideoOwnerId { get; set; } - private IComment ChatToComment(NMSG_Chat rawComment) + private VideoComment ChatToComment(NMSG_Chat rawComment) { return new VideoComment() { diff --git a/Hohoema.Models/Models.Domain/Player/Video/Comment/VideoCommentService.cs b/Hohoema.Models/Models.Domain/Player/Video/Comment/VideoCommentService.cs index 64cac980d..1ea309aa9 100644 --- a/Hohoema.Models/Models.Domain/Player/Video/Comment/VideoCommentService.cs +++ b/Hohoema.Models/Models.Domain/Player/Video/Comment/VideoCommentService.cs @@ -5,7 +5,7 @@ namespace Hohoema.Models.Domain.Player.Video.Comment { - public class VideoCommentService : ICommentSession + public class VideoCommentService : ICommentSession { CommentClient CommentClient; @@ -19,14 +19,14 @@ public VideoCommentService(CommentClient commentClient, string userId) } - public event EventHandler RecieveComment; + public event EventHandler RecieveComment; void IDisposable.Dispose() { } - public async Task> GetInitialComments() + public async Task> GetInitialComments() { return await CommentClient.GetCommentsAsync(); } diff --git a/Hohoema.Models/Models.Domain/Player/Video/NicoVideoSessionProvider.cs b/Hohoema.Models/Models.Domain/Player/Video/NicoVideoSessionProvider.cs index cba6c59bd..202a569f7 100644 --- a/Hohoema.Models/Models.Domain/Player/Video/NicoVideoSessionProvider.cs +++ b/Hohoema.Models/Models.Domain/Player/Video/NicoVideoSessionProvider.cs @@ -129,7 +129,7 @@ public enum PreparePlayVideoFailedReason NotPlayPermit_RequirePremiumMember, } - public class PreparePlayVideoResult : INiconicoVideoSessionProvider, INiconicoCommentSessionProvider + public class PreparePlayVideoResult : INiconicoVideoSessionProvider, INiconicoCommentSessionProvider { public Exception Exception { get; } public bool IsSuccess { get; } @@ -272,7 +272,7 @@ public async Task CreateVideoSessionAsync(NicoVideoQuality qu - public Task CreateCommentSessionAsync() + public Task> CreateCommentSessionAsync() { if (_dmcWatchData != null) { @@ -284,7 +284,7 @@ public Task CreateCommentSessionAsync() } } - Task CreateCommentSession(string contentId, DmcWatchApiData watchData) + Task> CreateCommentSession(string contentId, DmcWatchApiData watchData) { var commentClient = new CommentClient(_niconicoSession, contentId); var dmcRes = watchData; @@ -308,7 +308,7 @@ Task CreateCommentSession(string contentId, DmcWatchApiData wat commentClient.CommentServerInfo.CommunityThreadId = communityThread.Id; } - return Task.FromResult(new VideoCommentService(commentClient, _niconicoSession.UserId) as ICommentSession); + return Task.FromResult(new VideoCommentService(commentClient, _niconicoSession.UserId) as ICommentSession); } diff --git a/Hohoema.Models/Models.Domain/Player/VideoStreamingOriginOrchestrator.cs b/Hohoema.Models/Models.Domain/Player/VideoStreamingOriginOrchestrator.cs index d21e281de..f3c82783b 100644 --- a/Hohoema.Models/Models.Domain/Player/VideoStreamingOriginOrchestrator.cs +++ b/Hohoema.Models/Models.Domain/Player/VideoStreamingOriginOrchestrator.cs @@ -75,7 +75,7 @@ internal PlayingOrchestrateResult(Exception exception) Exception = exception; } - internal PlayingOrchestrateResult(INiconicoVideoSessionProvider vss, INiconicoCommentSessionProvider cs, INicoVideoDetails videoDetails) + internal PlayingOrchestrateResult(INiconicoVideoSessionProvider vss, INiconicoCommentSessionProvider cs, INicoVideoDetails videoDetails) { IsSuccess = vss != null; VideoSessionProvider = vss; @@ -88,7 +88,7 @@ internal PlayingOrchestrateResult(INiconicoVideoSessionProvider vss, INiconicoCo public INiconicoVideoSessionProvider VideoSessionProvider { get; } - public INiconicoCommentSessionProvider CommentSessionProvider { get; } + public INiconicoCommentSessionProvider CommentSessionProvider { get; } public INicoVideoDetails VideoDetails { get; } diff --git a/Hohoema/App.xaml.cs b/Hohoema/App.xaml.cs index ffa866faa..db62aa7e1 100644 --- a/Hohoema/App.xaml.cs +++ b/Hohoema/App.xaml.cs @@ -268,7 +268,7 @@ public override void RegisterTypes(IContainerRegistry container) container.RegisterSingleton(); // UseCase - unityContainer.Register(); + unityContainer.Register(); container.RegisterSingleton(); container.RegisterSingleton(); container.RegisterSingleton(); diff --git a/Hohoema/Hohoema.csproj b/Hohoema/Hohoema.csproj index dfdf4dbfb..b3b890171 100644 --- a/Hohoema/Hohoema.csproj +++ b/Hohoema/Hohoema.csproj @@ -171,7 +171,7 @@ - + diff --git a/Hohoema/Models.UseCase/Niconico.Player/Comment/CommentPlayer.cs b/Hohoema/Models.UseCase/Niconico.Player/Comment/VideoCommentPlayer.cs similarity index 98% rename from Hohoema/Models.UseCase/Niconico.Player/Comment/CommentPlayer.cs rename to Hohoema/Models.UseCase/Niconico.Player/Comment/VideoCommentPlayer.cs index 2867468cd..304f10378 100644 --- a/Hohoema/Models.UseCase/Niconico.Player/Comment/CommentPlayer.cs +++ b/Hohoema/Models.UseCase/Niconico.Player/Comment/VideoCommentPlayer.cs @@ -29,7 +29,7 @@ namespace Hohoema.Models.UseCase.Niconico.Player.Comment { - public class CommentPlayer : Prism.Mvvm.BindableBase, IDisposable + public class VideoCommentPlayer : Prism.Mvvm.BindableBase, IDisposable { CompositeDisposable _disposables = new CompositeDisposable(); @@ -38,7 +38,7 @@ public class CommentPlayer : Prism.Mvvm.BindableBase, IDisposable private readonly CommentFilteringFacade _commentFiltering; private readonly NotificationService _notificationService; private readonly PlayerSettings _playerSettings; - private INiconicoCommentSessionProvider _niconicoCommentSessionProvider; + private INiconicoCommentSessionProvider _niconicoCommentSessionProvider; private readonly ILogger _logger; private readonly MediaPlayer _mediaPlayer; @@ -49,7 +49,7 @@ public class CommentPlayer : Prism.Mvvm.BindableBase, IDisposable public ReactiveProperty NowSubmittingComment { get; private set; } public AsyncReactiveCommand CommentSubmitCommand { get; } - ICommentSession _commentSession; + ICommentSession _commentSession; FastAsyncLock _commentUpdateLock = new FastAsyncLock(); @@ -72,7 +72,7 @@ public bool NowCommentSubmitDisabledFromNicoScript event EventHandler NicoScriptJumpTimeRequested; event EventHandler CommentSubmitFailed; - public CommentPlayer( + public VideoCommentPlayer( ILoggerFactory loggerFactory, MediaPlayer mediaPlayer, IScheduler scheduler, @@ -82,7 +82,7 @@ public CommentPlayer( PlayerSettings playerSettings ) { - _logger = loggerFactory.CreateLogger(); + _logger = loggerFactory.CreateLogger(); _mediaPlayer = mediaPlayer; _scheduler = scheduler; _commentDisplayingRangeExtractor = commentDisplayingRangeExtractor; @@ -215,7 +215,7 @@ public void ClearCurrentSession() } - public async Task UpdatePlayingCommentAsync(INiconicoCommentSessionProvider niconicoCommentSessionProvider, CancellationToken ct = default) + public async Task UpdatePlayingCommentAsync(INiconicoCommentSessionProvider niconicoCommentSessionProvider, CancellationToken ct = default) { using (await _commentUpdateLock.LockAsync(ct)) { @@ -346,7 +346,7 @@ private async Task SubmitComment() - private async Task UpdateComments_Internal(ICommentSession commentSession) + private async Task UpdateComments_Internal(ICommentSession commentSession) { // ニコスクリプトの状態を初期化 ClearNicoScriptState(); @@ -355,8 +355,6 @@ private async Task UpdateComments_Internal(ICommentSession commentSession) DisplayingComments.Clear(); HiddenCommentIds.Clear(); - var comments = await commentSession.GetInitialComments(); - IEnumerable commentsAction(IEnumerable comments) { foreach (var comment in comments) @@ -387,8 +385,9 @@ IEnumerable commentsAction(IEnumerable comments) yield return comment; } } + var comments = await commentSession.GetInitialComments(); - Comments.AddRange(commentsAction(comments.Cast().OrderBy(x => x.VideoPosition))); + Comments.AddRange(commentsAction(comments.OrderBy(x => x.VideoPosition))); ResetDisplayingComments(Comments); diff --git a/Hohoema/Models.UseCase/Niconico.Player/VideoStreamingOriginOrchestrator.cs b/Hohoema/Models.UseCase/Niconico.Player/VideoStreamingOriginOrchestrator.cs index 84abafd03..162ac41d3 100644 --- a/Hohoema/Models.UseCase/Niconico.Player/VideoStreamingOriginOrchestrator.cs +++ b/Hohoema/Models.UseCase/Niconico.Player/VideoStreamingOriginOrchestrator.cs @@ -76,7 +76,7 @@ internal PlayingOrchestrateResult(Exception exception) Exception = exception; } - internal PlayingOrchestrateResult(INiconicoVideoSessionProvider vss, INiconicoCommentSessionProvider cs, INicoVideoDetails videoDetails) + internal PlayingOrchestrateResult(INiconicoVideoSessionProvider vss, INiconicoCommentSessionProvider cs, INicoVideoDetails videoDetails) { IsSuccess = vss != null; VideoSessionProvider = vss; @@ -89,7 +89,7 @@ internal PlayingOrchestrateResult(INiconicoVideoSessionProvider vss, INiconicoCo public INiconicoVideoSessionProvider VideoSessionProvider { get; } - public INiconicoCommentSessionProvider CommentSessionProvider { get; } + public INiconicoCommentSessionProvider CommentSessionProvider { get; } public INicoVideoDetails VideoDetails { get; } diff --git a/Hohoema/Presentation.Views.Player/VideoPlayerPageViewModel.cs b/Hohoema/Presentation.Views.Player/VideoPlayerPageViewModel.cs index e2109a691..f126f6bd0 100644 --- a/Hohoema/Presentation.Views.Player/VideoPlayerPageViewModel.cs +++ b/Hohoema/Presentation.Views.Player/VideoPlayerPageViewModel.cs @@ -86,7 +86,7 @@ public VideoPlayerPageViewModel( LocalPlaylistAddItemCommand localPlaylistAddItemCommand, MylistCreateCommand createMylistCommand, VideoStreamingOriginOrchestrator videoStreamingOriginOrchestrator, - CommentPlayer commentPlayer, + VideoCommentPlayer commentPlayer, CommentCommandEditerViewModel commentCommandEditerViewModel, KeepActiveDisplayWhenPlaying keepActiveDisplayWhenPlaying, ObservableMediaPlayer observableMediaPlayer, @@ -220,7 +220,7 @@ RelatedVideosSidePaneContentViewModel relatedVideosSidePaneContentViewModel public VideoTogglePlayPauseCommand VideoTogglePlayPauseCommand { get; } public IPlayerView PlayerView { get; } public NiconicoSession NiconicoSession { get; } - public CommentPlayer CommentPlayer { get; } + public VideoCommentPlayer CommentPlayer { get; } public CommentCommandEditerViewModel CommentCommandEditerViewModel { get; } public PrimaryViewPlayerManager PrimaryViewPlayerManager { get; } public TogglePlayerDisplayViewCommand TogglePlayerDisplayViewCommand { get; } diff --git a/Hohoema/Presentation.Views.Player/_PlayerSidePaneContent/VideoCommentSidePaneContentViewModel.cs b/Hohoema/Presentation.Views.Player/_PlayerSidePaneContent/VideoCommentSidePaneContentViewModel.cs index e43147be2..b047c66b8 100644 --- a/Hohoema/Presentation.Views.Player/_PlayerSidePaneContent/VideoCommentSidePaneContentViewModel.cs +++ b/Hohoema/Presentation.Views.Player/_PlayerSidePaneContent/VideoCommentSidePaneContentViewModel.cs @@ -21,7 +21,7 @@ public sealed class VideoCommentSidePaneContentViewModel : BindableBase, IDispos public CommentFilteringFacade CommentFiltering { get; } public VideoCommentSidePaneContentViewModel( - CommentPlayer commentPlayer, + VideoCommentPlayer commentPlayer, CommentFilteringFacade commentFiltering, Services.DialogService dialogService ) @@ -74,7 +74,7 @@ void HandleCommentFilterConditionChanged() } - public CommentPlayer CommentPlayer { get; } + public VideoCommentPlayer CommentPlayer { get; } public AdvancedCollectionView Comments { get; } private CompositeDisposable _disposables = new CompositeDisposable(); private readonly DialogService _dialogService; From 9ca490da8bc2d1d98a899aa41ce41c4d3be9078d Mon Sep 17 00:00:00 2001 From: tor4kichi Date: Thu, 17 Feb 2022 23:25:26 +0900 Subject: [PATCH 05/10] =?UTF-8?q?=E5=8B=95=E7=94=BB=E3=81=AE=E3=82=B3?= =?UTF-8?q?=E3=83=A1=E3=83=B3=E3=83=88=E6=8F=8F=E7=94=BB=E3=81=AE=E6=AD=A3?= =?UTF-8?q?=E7=A2=BA=E6=80=A7=E3=82=92=E6=94=B9=E5=96=84=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Comment/VideoCommentPlayer.cs | 6 +- .../_CommentRenderer/CommentRenderer.xaml.cs | 237 +++++++++++------- .../_CommentRenderer/CommentUI.xaml.cs | 7 +- 3 files changed, 145 insertions(+), 105 deletions(-) diff --git a/Hohoema/Models.UseCase/Niconico.Player/Comment/VideoCommentPlayer.cs b/Hohoema/Models.UseCase/Niconico.Player/Comment/VideoCommentPlayer.cs index 304f10378..0dd626256 100644 --- a/Hohoema/Models.UseCase/Niconico.Player/Comment/VideoCommentPlayer.cs +++ b/Hohoema/Models.UseCase/Niconico.Player/Comment/VideoCommentPlayer.cs @@ -257,7 +257,7 @@ private void _CommentUpdateTimer_Tick(DispatcherQueueTimer sender, object args) CurrentComment = null; } - TickNextDisplayingComments(currentPosition); + //TickNextDisplayingComments(currentPosition); UpdateNicoScriptComment(currentPosition); RefreshCurrentPlaybackPositionComment(currentPosition); @@ -401,8 +401,8 @@ void ResetDisplayingComments(IReadOnlyCollection comments) DisplayingComments.Clear(); _logger.ZLogDebug("CommentReset"); - var displayingComments = _commentDisplayingRangeExtractor.ResetComments(comments, _mediaPlayer.PlaybackSession.Position); - DisplayingComments.AddRange(EnumerateFilteredDisplayComment(displayingComments.ToArray())); + //var displayingComments = _commentDisplayingRangeExtractor.ResetComments(comments, _mediaPlayer.PlaybackSession.Position); + DisplayingComments.AddRange(EnumerateFilteredDisplayComment(comments)); } diff --git a/Hohoema/Presentation.Views.Player/_CommentRenderer/CommentRenderer.xaml.cs b/Hohoema/Presentation.Views.Player/_CommentRenderer/CommentRenderer.xaml.cs index 04136d869..d264cd320 100644 --- a/Hohoema/Presentation.Views.Player/_CommentRenderer/CommentRenderer.xaml.cs +++ b/Hohoema/Presentation.Views.Player/_CommentRenderer/CommentRenderer.xaml.cs @@ -53,6 +53,7 @@ public CommentUI Create() public bool Return(CommentUI commentUI) { commentUI.Comment = null; + commentUI.Opacity = 1.0; return true; } } @@ -66,7 +67,7 @@ public CommentRenderer() Loaded += CommentRenderer_Loaded; Unloaded += CommentRenderer_Unloaded; - _commentUIObjectPool = new DefaultObjectPool(new CommentUIObjectPoolPolicy(), 500); + _commentUIObjectPool = new DefaultObjectPool(new CommentUIObjectPoolPolicy(), 200); _windowResizeTimer = DispatcherQueue.GetForCurrentThread().CreateTimer(); _windowResizeTimer.Interval = TimeSpan.FromSeconds(0.25); @@ -252,74 +253,91 @@ await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => return; } + var prev = PlaybackState; PlaybackState = sender?.PlaybackState ?? null; Debug.WriteLine("state changed " + PlaybackState); - - ResetScrollCommentsAnimation(GetRenderFrameData()); + if (prev != PlaybackState) + { + ResetScrollCommentsAnimation(GetRenderFrameData()); + } }); } void ResetScrollCommentsAnimation(in CommentRenderFrameData frame) { - if (PlaybackState == MediaPlaybackState.Playing) + if (Math.Abs((float)(frame.CurrentVpos - _prevPosition).TotalSeconds) > 0.5f) + { + Debug.WriteLine("seeked!"); + ResetComments(); + } + else { - var ct = GetScrollCommentAnimationCancellationToken(); - foreach (var renderComment in CommentCanvas.Children.Cast()) + if (PlaybackState == MediaPlaybackState.Playing) { - if (renderComment.DisplayMode == CommentDisplayMode.Scrolling) + var ct = GetScrollCommentAnimationCancellationToken(); + foreach (var renderComment in CommentCanvas.Children.Cast()) { - var comment = renderComment.Comment; - if (renderComment.EndPosition > frame.CurrentVpos) + if (renderComment.DisplayMode == CommentDisplayMode.Scrolling) { - var duration = (renderComment.EndPosition - frame.CurrentVpos) * frame.PlaybackRateInverse; - if (duration <= TimeSpan.Zero) + var comment = renderComment.Comment; + if (renderComment.EndPosition > frame.CurrentVpos) { - continue; - } + var duration = (renderComment.EndPosition - frame.CurrentVpos) * frame.PlaybackRateInverse; + if (duration <= TimeSpan.Zero) + { + renderComment.Opacity = 0.0; + continue; + } - var ab = AnimationBuilder.Create() - .Translation(Axis.Y) - .NormalizedKeyFrames(b => b - .KeyFrame(0.0, renderComment.VerticalPosition)) - .Translation(Axis.X, - from: renderComment.GetPosition(frame.CanvasWidth, frame.CurrentVpos), - to: -renderComment.TextWidth, - duration: duration, - easingType: EasingType.Linear - ) - ; - - _ = ab.StartAsync(renderComment, ct); + var ab = AnimationBuilder.Create() + .Translation(Axis.Y) + .NormalizedKeyFrames(b => b + .KeyFrame(0.0, renderComment.VerticalPosition)) + .Translation(Axis.X, + from: renderComment.GetPosition(frame.CanvasWidth, frame.CurrentVpos), + to: -renderComment.TextWidth, + duration: duration, + easingType: EasingType.Linear + ) + ; + + ab.StartAsync(renderComment, ct); + } + else + { + renderComment.Opacity = 0.0; + } } } } - } - else - { - StopScrollCommentAnimation(); - - foreach (var renderComment in CommentCanvas.Children.Cast()) + else { - if (renderComment.DisplayMode == CommentDisplayMode.Scrolling) + StopScrollCommentAnimation(); + + foreach (var renderComment in CommentCanvas.Children.Cast()) { - // 現在時間での横位置を求める - // lerp 現在時間における位置の比率 - //var val = renderComment.GetPosition(frame.CanvasWidth, frame.CurrentVpos); - //if (val.HasValue) - //{ - // renderComment.Translation((float)val.Value, duration: 0).Start(); - //} - var ab = AnimationBuilder.Create() - .Translation(Axis.Y) - .NormalizedKeyFrames(b => b - .KeyFrame(0.0, renderComment.VerticalPosition)) - ; - ab.Start(renderComment); + if (renderComment.DisplayMode == CommentDisplayMode.Scrolling) + { + // 現在時間での横位置を求める + // lerp 現在時間における位置の比率 + //var val = renderComment.GetPosition(frame.CanvasWidth, frame.CurrentVpos); + //if (val.HasValue) + //{ + // renderComment.Translation((float)val.Value, duration: 0).Start(); + //} + var ab = AnimationBuilder.Create() + .Translation(Axis.Y) + .NormalizedKeyFrames(b => b + .KeyFrame(0.0, renderComment.VerticalPosition)) + ; + ab.Start(renderComment); + } } } } + } IDisposable CommentItemsChangedSubscriber; @@ -435,8 +453,8 @@ class CommentRenderFrameData public Visibility Visibility { get; set; } public TimeSpan CommentDisplayDuration { get; internal set; } public MediaPlaybackState PlaybackState { get; set; } - public double PlaybackRate { get; set; } - public double PlaybackRateInverse { get; set; } + public float PlaybackRate { get; set; } + public float PlaybackRateInverse { get; set; } public CancellationToken ScrollCommentAnimationCancelToken { get; set; } } @@ -503,22 +521,52 @@ private void CommentRenderer_Loaded(object sender, RoutedEventArgs e) this.SizeChanged += CommentRenderer_SizeChanged; } + private TimeSpan _prevPosition; private void PlaybackSession_PositionChanged(MediaPlaybackSession sender, object args) { _ = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { if (_nowWindowSizeChanging) { return; } - var frame = GetRenderFrameData(); - for (int i = _pendingRenderComments.Count - 1; i >= 0; i--) + if (_pendingRenderComments.Any() is false) { return; } + + var frame = GetRenderFrameData(true); + + if (Math.Abs((float)(frame.CurrentVpos - _prevPosition).TotalSeconds) > 0.5f) + { + Debug.WriteLine("seeked!"); + ResetComments(); + } + else { - var comment = _pendingRenderComments[i]; - if (comment.VideoPosition <= frame.CurrentVpos) + // 表示期間を過ぎたコメントを削除 + for (int i = 0; i < CommentCanvas.Children.Count; i++) { - _pendingRenderComments.RemoveAt(i); - AddCommentToCanvas(comment, in frame); + var comment = CommentCanvas.Children[i] as CommentUI; + if (comment.EndPosition <= frame.CurrentVpos) + { + RemoveCommentFromCanvas(comment.Comment); + --i; + } + else + { + break; + } + } + + // 追加待機中のコメントをチェック + for (int i = _pendingRenderComments.Count - 1; i >= 0; i--) + { + var comment = _pendingRenderComments[i]; + if (comment.VideoPosition <= (frame.CurrentVpos + TimeSpan.FromSeconds(1))) + { + _pendingRenderComments.RemoveAt(i); + AddCommentToCanvas(comment, in frame); + } } } + + _prevPosition = frame.CurrentVpos; }); } @@ -564,20 +612,8 @@ private void CommentRenderer_SizeChanged(object sender, SizeChangedEventArgs e) private void CommentRenderer_Unloaded(object sender, RoutedEventArgs e) { - _disposables.Dispose(); - _disposables = null; Window.Current.SizeChanged -= WindowSizeChanged; this.SizeChanged -= CommentRenderer_SizeChanged; - - _windowResizeTimer.Stop(); - - _unloadedCts.Cancel(); - _unloadedCts.Dispose(); - _unloadedCts = null; - - StopScrollCommentAnimation(); - - CommentCanvas.Children.Clear(); var mediaPlayer = MediaPlayer; if (mediaPlayer != null) @@ -585,11 +621,20 @@ private void CommentRenderer_Unloaded(object sender, RoutedEventArgs e) mediaPlayer.PlaybackSession.PlaybackStateChanged -= PlaybackSession_PlaybackStateChanged; mediaPlayer.PlaybackSession.PositionChanged -= PlaybackSession_PositionChanged; } + + _disposables.Dispose(); + _disposables = null; + _windowResizeTimer.Stop(); + _unloadedCts.Cancel(); + _unloadedCts.Dispose(); + _unloadedCts = null; + StopScrollCommentAnimation(); + ClearComments(); } static CommentRenderFrameData _frameData = new CommentRenderFrameData(); - private CommentRenderFrameData GetRenderFrameData() + private CommentRenderFrameData GetRenderFrameData(bool isRefresh = false) { _frameData.CommentDisplayDuration = DefaultDisplayDuration; _frameData.PlaybackState = MediaPlayer.PlaybackSession.PlaybackState; @@ -600,8 +645,8 @@ private CommentRenderFrameData GetRenderFrameData() _frameData.HalfCanvasWidth = CommentCanvas.ActualWidth * 0.5; _frameData.FontScale = (float)CommentSizeScale; _frameData.Visibility = Visibility; - _frameData.PlaybackRate = MediaPlayer.PlaybackSession.PlaybackRate; - _frameData.PlaybackRateInverse = 1d / MediaPlayer.PlaybackSession.PlaybackRate; + _frameData.PlaybackRate = (float)MediaPlayer.PlaybackSession.PlaybackRate; + _frameData.PlaybackRateInverse = 1f / (float)MediaPlayer.PlaybackSession.PlaybackRate; _frameData.ScrollCommentAnimationCancelToken = GetScrollCommentAnimationCancellationToken(); return _frameData; @@ -619,6 +664,7 @@ void ClearComments() CommentCanvas.Children.Clear(); _commentToRenderCommentMap.Clear(); + _pendingRenderComments.Clear(); PrevRenderCommentEachLine_Stream.Clear(); PrevRenderCommentEachLine_Top.Clear(); @@ -636,7 +682,7 @@ private void ResetComments() { if (Comments != null) { - AddCommentToCanvas(Comments.Cast().ToArray()); + AddCommentToCanvas(Comments.Cast()); } } } @@ -650,25 +696,25 @@ static double CulcCommentFontSize(IComment comment, in CommentRenderFrameData fr { // フォントサイズの計算 // 画面サイズの10分の1*ベーススケール*フォントスケール - float commentFontScale = 1.0f; + const float PixelToPoint = 0.75f; + const float SmallFontScaleWithPtP = 0.75f * PixelToPoint; + const float BigFontScaleWithPtP = 1.25f * PixelToPoint; + float commentFontScale; switch (comment.SizeMode) { - case CommentSizeMode.Normal: - commentFontScale = 1.0f; - break; case CommentSizeMode.Big: - commentFontScale = 1.25f; + commentFontScale = BigFontScaleWithPtP; break; case CommentSizeMode.Small: - commentFontScale = 0.75f; + commentFontScale = SmallFontScaleWithPtP; break; default: + commentFontScale = PixelToPoint; break; } var baseSize = Math.Max(frame.CanvasHeight * BaseCommentSizeRatioByCanvasHeight, 24); - const float PixelToPoint = 0.75f; - return baseSize * frame.FontScale * commentFontScale * PixelToPoint; + return baseSize * frame.FontScale * commentFontScale; } private void AddCommentToCanvas(IComment comment, in CommentRenderFrameData frame) @@ -759,7 +805,6 @@ CommentUI MakeCommentUI(IComment comment, in CommentRenderFrameData frame) { var leftEdge = prevComment.EndPosition < currentCommentReachLeftEdgeTime; var rightEdge = prevComment.CalcTextShowRightEdgeTime(frame.CanvasWidth) < frame.CurrentVpos; - if (leftEdge && rightEdge) { // コリジョンしない @@ -767,10 +812,12 @@ CommentUI MakeCommentUI(IComment comment, in CommentRenderFrameData frame) insertPosition = i; break; } - - // コリジョンする - // 追加できない - verticalPos += prevComment.TextHeight + prevComment.TextHeight * CommentVerticalMarginRatio; + else + { + // コリジョンする + // 追加できない + verticalPos += prevComment.TextHeight + prevComment.TextHeight * CommentVerticalMarginRatio; + } } } @@ -784,9 +831,9 @@ CommentUI MakeCommentUI(IComment comment, in CommentRenderFrameData frame) renderComment.Opacity = 1.0; renderComment.VerticalPosition = verticalPos; - if (frame.PlaybackState != MediaPlaybackState.Paused) - { - double displayDuration = Math.Min(renderComment.EndPosition.TotalMilliseconds - frame.CurrentVpos.TotalMilliseconds, frame.CommentDisplayDuration.TotalMilliseconds) * frame.PlaybackRateInverse; + TimeSpan displayDuration = (renderComment.EndPosition - frame.CurrentVpos) * frame.PlaybackRateInverse; + if (frame.PlaybackState == MediaPlaybackState.Playing) + { var ab = AnimationBuilder.Create() .Translation(Axis.Y) .NormalizedKeyFrames(b => b @@ -794,21 +841,25 @@ CommentUI MakeCommentUI(IComment comment, in CommentRenderFrameData frame) .Translation(Axis.X, from: (float)initialCanvasLeft, to: -renderComment.TextWidth, - duration: TimeSpan.FromMilliseconds(displayDuration), + duration: displayDuration, easingType: EasingType.Linear ); - _ = ab.StartAsync(renderComment, frame.ScrollCommentAnimationCancelToken); + ab.Start(renderComment, frame.ScrollCommentAnimationCancelToken); } else { var ab = AnimationBuilder.Create() .Translation(Axis.Y) .NormalizedKeyFrames(b => b - .KeyFrame(0.0, renderComment.VerticalPosition)) + .KeyFrame(0.0, renderComment.VerticalPosition) + , duration: displayDuration + ) .Translation(Axis.X) .NormalizedKeyFrames(b => b - .KeyFrame(0.0, (float)initialCanvasLeft)) + .KeyFrame(0.0, (float)initialCanvasLeft) + , duration: displayDuration + ) ; ab.Start(renderComment); @@ -862,7 +913,6 @@ CommentUI MakeCommentUI(IComment comment, in CommentRenderFrameData frame) .KeyFrame(0.0, left)) .Start(renderComment); - if (insertPosition == -1) { // 最後尾に追加 @@ -991,11 +1041,6 @@ private void RemoveCommentFromCanvas(IComment comment) if (_commentToRenderCommentMap.Remove(comment, out var renderComment)) { CommentCanvas.Children.Remove(renderComment); - if (renderComment.DisplayMode == CommentDisplayMode.Scrolling) - { - PrevRenderCommentEachLine_Stream.Remove(renderComment); - } - _commentUIObjectPool.Return(renderComment); } diff --git a/Hohoema/Presentation.Views.Player/_CommentRenderer/CommentUI.xaml.cs b/Hohoema/Presentation.Views.Player/_CommentRenderer/CommentUI.xaml.cs index f492073aa..5edf50154 100644 --- a/Hohoema/Presentation.Views.Player/_CommentRenderer/CommentUI.xaml.cs +++ b/Hohoema/Presentation.Views.Player/_CommentRenderer/CommentUI.xaml.cs @@ -187,12 +187,7 @@ private float MoveSpeedPer1MilliSeconds(int canvasWidth) public double? GetPosition(int canvasWidth, TimeSpan currentVPos) { - if (VideoPosition > currentVPos) { return null; } - if (EndPosition < currentVPos) { return null; } - - var speed = MoveSpeedPer1MilliSeconds(canvasWidth); - var delta = currentVPos - VideoPosition; - return (canvasWidth) - (double)(speed * delta.TotalMilliseconds); + return (canvasWidth + TextWidth) * (EndPosition - currentVPos) / CommentDisplayDuration; } public TimeSpan CalcTextShowRightEdgeTime(int canvasWidth) From d3367be3cf2d48fca4277412e44921bc91eafa9c Mon Sep 17 00:00:00 2001 From: tor4kichi Date: Fri, 18 Feb 2022 17:20:26 +0900 Subject: [PATCH 06/10] =?UTF-8?q?=E3=82=B3=E3=83=A1=E3=83=B3=E3=83=88?= =?UTF-8?q?=E6=8F=8F=E7=94=BB=E3=82=92=E6=94=B9=E5=96=84=E3=80=82=E4=BD=8D?= =?UTF-8?q?=E7=BD=AE=E3=83=85=E3=83=AC=E8=A7=A3=E6=B6=88=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../_CommentRenderer/CommentRenderer.xaml.cs | 61 +++++++++++++------ .../_CommentRenderer/CommentUI.xaml.cs | 12 ++-- 2 files changed, 50 insertions(+), 23 deletions(-) diff --git a/Hohoema/Presentation.Views.Player/_CommentRenderer/CommentRenderer.xaml.cs b/Hohoema/Presentation.Views.Player/_CommentRenderer/CommentRenderer.xaml.cs index d264cd320..2d7dac9fc 100644 --- a/Hohoema/Presentation.Views.Player/_CommentRenderer/CommentRenderer.xaml.cs +++ b/Hohoema/Presentation.Views.Player/_CommentRenderer/CommentRenderer.xaml.cs @@ -256,9 +256,9 @@ await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => var prev = PlaybackState; PlaybackState = sender?.PlaybackState ?? null; - Debug.WriteLine("state changed " + PlaybackState); if (prev != PlaybackState) { + Debug.WriteLine("state changed " + PlaybackState); ResetScrollCommentsAnimation(GetRenderFrameData()); } }); @@ -273,7 +273,8 @@ void ResetScrollCommentsAnimation(in CommentRenderFrameData frame) } else { - if (PlaybackState == MediaPlaybackState.Playing) + StopScrollCommentAnimation(); + if (frame.PlaybackState == MediaPlaybackState.Playing) { var ct = GetScrollCommentAnimationCancellationToken(); foreach (var renderComment in CommentCanvas.Children.Cast()) @@ -313,8 +314,6 @@ void ResetScrollCommentsAnimation(in CommentRenderFrameData frame) } else { - StopScrollCommentAnimation(); - foreach (var renderComment in CommentCanvas.Children.Cast()) { if (renderComment.DisplayMode == CommentDisplayMode.Scrolling) @@ -326,10 +325,15 @@ void ResetScrollCommentsAnimation(in CommentRenderFrameData frame) //{ // renderComment.Translation((float)val.Value, duration: 0).Start(); //} + var posX = renderComment.GetPosition(frame.CanvasWidth, frame.CurrentVpos); var ab = AnimationBuilder.Create() .Translation(Axis.Y) .NormalizedKeyFrames(b => b .KeyFrame(0.0, renderComment.VerticalPosition)) + .Translation(Axis.X) + .NormalizedKeyFrames(b => b + .KeyFrame(0.0, posX)) + ; ab.Start(renderComment); @@ -452,6 +456,7 @@ class CommentRenderFrameData public Color CommentDefaultColor { get; set; } //= CommentDefaultColor; public Visibility Visibility { get; set; } public TimeSpan CommentDisplayDuration { get; internal set; } + public float InverseCommentDisplayDurationInMs { get; internal set; } public MediaPlaybackState PlaybackState { get; set; } public float PlaybackRate { get; set; } public float PlaybackRateInverse { get; set; } @@ -527,12 +532,11 @@ private void PlaybackSession_PositionChanged(MediaPlaybackSession sender, object _ = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { if (_nowWindowSizeChanging) { return; } - if (_pendingRenderComments.Any() is false) { return; } - var frame = GetRenderFrameData(true); - if (Math.Abs((float)(frame.CurrentVpos - _prevPosition).TotalSeconds) > 0.5f) + TimeSpan currentVpos = VideoPosition + VideoPositionOffset; + if (Math.Abs((float)(currentVpos - _prevPosition).TotalSeconds) > 0.5f) { Debug.WriteLine("seeked!"); ResetComments(); @@ -543,7 +547,7 @@ private void PlaybackSession_PositionChanged(MediaPlaybackSession sender, object for (int i = 0; i < CommentCanvas.Children.Count; i++) { var comment = CommentCanvas.Children[i] as CommentUI; - if (comment.EndPosition <= frame.CurrentVpos) + if (comment.EndPosition <= currentVpos) { RemoveCommentFromCanvas(comment.Comment); --i; @@ -555,18 +559,25 @@ private void PlaybackSession_PositionChanged(MediaPlaybackSession sender, object } // 追加待機中のコメントをチェック - for (int i = _pendingRenderComments.Count - 1; i >= 0; i--) + CommentRenderFrameData frame = null; + for (int i = 0; i < _pendingRenderComments.Count; i++) { var comment = _pendingRenderComments[i]; - if (comment.VideoPosition <= (frame.CurrentVpos + TimeSpan.FromSeconds(1))) + if (comment.VideoPosition <= (currentVpos + TimeSpan.FromSeconds(1))) { + frame ??= GetRenderFrameData(); _pendingRenderComments.RemoveAt(i); + --i; AddCommentToCanvas(comment, in frame); } + else + { + break; + } } } - _prevPosition = frame.CurrentVpos; + _prevPosition = currentVpos; }); } @@ -634,9 +645,10 @@ private void CommentRenderer_Unloaded(object sender, RoutedEventArgs e) static CommentRenderFrameData _frameData = new CommentRenderFrameData(); - private CommentRenderFrameData GetRenderFrameData(bool isRefresh = false) + private CommentRenderFrameData GetRenderFrameData() { _frameData.CommentDisplayDuration = DefaultDisplayDuration; + _frameData.InverseCommentDisplayDurationInMs = 1.0f / (float)DefaultDisplayDuration.TotalMilliseconds; _frameData.PlaybackState = MediaPlayer.PlaybackSession.PlaybackState; _frameData.CommentDefaultColor = CommentDefaultColor; _frameData.CurrentVpos = VideoPosition + VideoPositionOffset; @@ -648,7 +660,7 @@ private CommentRenderFrameData GetRenderFrameData(bool isRefresh = false) _frameData.PlaybackRate = (float)MediaPlayer.PlaybackSession.PlaybackRate; _frameData.PlaybackRateInverse = 1f / (float)MediaPlayer.PlaybackSession.PlaybackRate; _frameData.ScrollCommentAnimationCancelToken = GetScrollCommentAnimationCancellationToken(); - + return _frameData; } @@ -717,6 +729,7 @@ static double CulcCommentFontSize(IComment comment, in CommentRenderFrameData fr return baseSize * frame.FontScale * commentFontScale; } + private void AddCommentToCanvas(IComment comment, in CommentRenderFrameData frame) { CommentUI MakeCommentUI(IComment comment, in CommentRenderFrameData frame) @@ -749,6 +762,8 @@ CommentUI MakeCommentUI(IComment comment, in CommentRenderFrameData frame) commentUI.CommentFontSize = commentFontSize; commentUI.IsVisible = !comment.IsInvisible; commentUI.DisplayMode = comment.DisplayMode; + commentUI.CommentDisplayDuration = frame.CommentDisplayDuration; + commentUI.InverseCommentDisplayDurationInMs= frame.InverseCommentDisplayDurationInMs; } return commentUI; @@ -803,9 +818,9 @@ CommentUI MakeCommentUI(IComment comment, in CommentRenderFrameData frame) } else { - var leftEdge = prevComment.EndPosition < currentCommentReachLeftEdgeTime; - var rightEdge = prevComment.CalcTextShowRightEdgeTime(frame.CanvasWidth) < frame.CurrentVpos; - if (leftEdge && rightEdge) + bool isCollisionLeftEdge = prevComment.EndPosition > currentCommentReachLeftEdgeTime; + bool isCollisionRightEdge = prevComment.CalcTextShowRightEdgeTime(frame.CanvasWidth) > comment.VideoPosition; + if (isCollisionLeftEdge is false && isCollisionRightEdge is false) { // コリジョンしない // 追加可能 @@ -826,11 +841,12 @@ CommentUI MakeCommentUI(IComment comment, in CommentRenderFrameData frame) if (isOutBoundComment is false) { // 最初は右端に配置 - double initialCanvasLeft = renderComment.GetPosition(frame.CanvasWidth, frame.CurrentVpos) ?? frame.CanvasWidth; + float initialCanvasLeft = renderComment.GetPosition(frame.CanvasWidth, frame.CurrentVpos); renderComment.Opacity = 1.0; renderComment.VerticalPosition = verticalPos; + float posToMovingRatio = initialCanvasLeft / (frame.CanvasWidth + renderComment.TextWidth); TimeSpan displayDuration = (renderComment.EndPosition - frame.CurrentVpos) * frame.PlaybackRateInverse; if (frame.PlaybackState == MediaPlaybackState.Playing) { @@ -990,7 +1006,7 @@ CommentUI MakeCommentUI(IComment comment, in CommentRenderFrameData frame) } } - List _pendingRenderComments = new List(); + List _pendingRenderComments = new (); private void AddOrPushPending(IComment comment, in CommentRenderFrameData frame) @@ -1016,6 +1032,7 @@ private void AddCommentToCanvas(IComment comment) private void AddCommentToCanvas(IEnumerable comments) { if (Visibility ==Visibility.Collapsed) { return; } + if (comments.Any() is false) { return; } var frame = GetRenderFrameData(); foreach (var comment in comments) @@ -1042,6 +1059,14 @@ private void RemoveCommentFromCanvas(IComment comment) { CommentCanvas.Children.Remove(renderComment); _commentUIObjectPool.Return(renderComment); + + for (int i = 0; i < PrevRenderCommentEachLine_Stream.Count; i++) + { + if (PrevRenderCommentEachLine_Stream[i] == renderComment) + { + PrevRenderCommentEachLine_Stream[i] = null; + } + } } _pendingRenderComments.Remove(comment); diff --git a/Hohoema/Presentation.Views.Player/_CommentRenderer/CommentUI.xaml.cs b/Hohoema/Presentation.Views.Player/_CommentRenderer/CommentUI.xaml.cs index 5edf50154..15c1c2233 100644 --- a/Hohoema/Presentation.Views.Player/_CommentRenderer/CommentUI.xaml.cs +++ b/Hohoema/Presentation.Views.Player/_CommentRenderer/CommentUI.xaml.cs @@ -158,7 +158,8 @@ public bool IsEndDisplay(TimeSpan currentVpos) } - public TimeSpan CommentDisplayDuration => EndPosition - VideoPosition; + public TimeSpan CommentDisplayDuration { get; set; } + public float InverseCommentDisplayDurationInMs { get; set; } private TimeSpan? _MoveCommentWidthTimeInVPos = null; @@ -172,7 +173,8 @@ private TimeSpan CalcMoveCommentWidthTimeInVPos(int canvasWidth) var speed = MoveSpeedPer1MilliSeconds(canvasWidth); // 時間 = 距離 ÷ 速さ - var timeToSecondCommentWidthMove = TimeSpan.FromMilliseconds((int)(TextWidth / speed)); + var time = (TextWidth / speed); + var timeToSecondCommentWidthMove = TimeSpan.FromMilliseconds(time); _MoveCommentWidthTimeInVPos = timeToSecondCommentWidthMove; return timeToSecondCommentWidthMove; @@ -181,13 +183,13 @@ private TimeSpan CalcMoveCommentWidthTimeInVPos(int canvasWidth) private float MoveSpeedPer1MilliSeconds(int canvasWidth) { // 1 Vposあたりのコメントの移動量 - return (canvasWidth + TextWidth) / (float)CommentDisplayDuration.TotalMilliseconds; + return (canvasWidth + TextWidth) * InverseCommentDisplayDurationInMs; } - public double? GetPosition(int canvasWidth, TimeSpan currentVPos) + public float GetPosition(int canvasWidth, TimeSpan currentVPos) { - return (canvasWidth + TextWidth) * (EndPosition - currentVPos) / CommentDisplayDuration; + return (canvasWidth + TextWidth) * (float)(((float)EndPosition.TotalMilliseconds - (float)currentVPos.TotalMilliseconds) * InverseCommentDisplayDurationInMs) - TextWidth; } public TimeSpan CalcTextShowRightEdgeTime(int canvasWidth) From 6a571161d43f97b07166bc2ea8fb5713c867b313 Mon Sep 17 00:00:00 2001 From: tor4kichi Date: Fri, 18 Feb 2022 17:21:28 +0900 Subject: [PATCH 07/10] =?UTF-8?q?=E5=8B=95=E7=94=BB=E3=81=AEMediaSource?= =?UTF-8?q?=E3=81=8C=E3=82=AF=E3=83=AD=E3=83=BC=E3=82=BA=E3=81=97=E3=81=9F?= =?UTF-8?q?=E9=9A=9B=E3=81=AE=E5=86=8D=E3=82=AA=E3=83=BC=E3=83=97=E3=83=B3?= =?UTF-8?q?=E3=81=8C=E3=83=97=E3=83=AC=E3=82=A4=E3=83=AA=E3=82=B9=E3=83=88?= =?UTF-8?q?=E6=8C=87=E5=AE=9A=E3=81=8C=E3=81=AA=E3=81=84=E5=86=8D=E7=94=9F?= =?UTF-8?q?=E3=81=AE=E5=A0=B4=E5=90=88=E3=81=AB=E5=A4=B1=E6=95=97=E3=81=97?= =?UTF-8?q?=E3=81=A6=E3=81=84=E3=81=9F=E5=95=8F=E9=A1=8C=E3=82=92=E8=A7=A3?= =?UTF-8?q?=E6=B6=88=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Hohoema.Models/Models.Domain/Playlist/HohoemaPlaylistPlayer.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Hohoema.Models/Models.Domain/Playlist/HohoemaPlaylistPlayer.cs b/Hohoema.Models/Models.Domain/Playlist/HohoemaPlaylistPlayer.cs index ef2cab651..2b515680b 100644 --- a/Hohoema.Models/Models.Domain/Playlist/HohoemaPlaylistPlayer.cs +++ b/Hohoema.Models/Models.Domain/Playlist/HohoemaPlaylistPlayer.cs @@ -599,8 +599,7 @@ private void StopPlaybackMedia() public async Task ReopenAsync(TimeSpan? position = null) { - if (CurrentPlaylist != null - && CurrentPlaylistItem != null) + if (CurrentPlaylistItem != null) { if (position == null) { From d0b6d075ec82b90d340e9c4d87c32dbe306a93f8 Mon Sep 17 00:00:00 2001 From: tor4kichi Date: Fri, 18 Feb 2022 17:47:43 +0900 Subject: [PATCH 08/10] =?UTF-8?q?=E5=8B=95=E7=94=BB=E3=83=97=E3=83=AC?= =?UTF-8?q?=E3=82=A4=E3=83=A4=E3=83=BC=E3=81=AE=E3=82=B3=E3=83=B3=E3=83=88?= =?UTF-8?q?=E3=83=AD=E3=83=BC=E3=83=ABUI=E8=83=8C=E6=99=AF=E3=81=AB?= =?UTF-8?q?=E3=81=82=E3=82=8B=E3=82=B0=E3=83=A9=E3=83=87=E3=83=BC=E3=82=B7?= =?UTF-8?q?=E3=83=A7=E3=83=B3=E3=81=AB=E3=82=8F=E3=81=9A=E3=81=8B=E3=81=AA?= =?UTF-8?q?=E9=9A=99=E9=96=93=E3=81=8C=E7=A9=BA=E3=81=84=E3=81=A6=E3=81=84?= =?UTF-8?q?=E3=81=9F=E5=95=8F=E9=A1=8C=E3=82=92=E8=A7=A3=E6=B6=88=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Hohoema/Presentation.Views.Player/VideoPlayerPage.xaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Hohoema/Presentation.Views.Player/VideoPlayerPage.xaml b/Hohoema/Presentation.Views.Player/VideoPlayerPage.xaml index a75a121c5..a52092252 100644 --- a/Hohoema/Presentation.Views.Player/VideoPlayerPage.xaml +++ b/Hohoema/Presentation.Views.Player/VideoPlayerPage.xaml @@ -701,7 +701,7 @@ - + From 3b424cceec3667b13e18f5b27c75138770a53ce3 Mon Sep 17 00:00:00 2001 From: tor4kichi Date: Fri, 18 Feb 2022 19:54:50 +0900 Subject: [PATCH 09/10] =?UTF-8?q?=E8=A8=AD=E5=AE=9A=E3=83=9A=E3=83=BC?= =?UTF-8?q?=E3=82=B8=E3=81=AE=E3=83=AC=E3=82=A4=E3=82=A2=E3=82=A6=E3=83=88?= =?UTF-8?q?=E3=82=92=E5=B7=A6=E5=AF=84=E3=81=9B=E3=81=AB=E4=BF=AE=E6=AD=A3?= =?UTF-8?q?=E3=80=82=E3=82=AF=E3=83=A9=E3=83=83=E3=82=B7=E3=83=A5=E3=83=AC?= =?UTF-8?q?=E3=83=9D=E3=83=BC=E3=83=88=E7=AD=89=E3=81=AE=E8=A8=AD=E5=AE=9A?= =?UTF-8?q?=E9=A0=85=E7=9B=AE=E3=82=92=E5=89=8A=E9=99=A4=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SettingsPage.xaml | 20 +---------- .../SettingsPageViewModel.cs | 33 ------------------- 2 files changed, 1 insertion(+), 52 deletions(-) diff --git a/Hohoema/Presentation.Views.Pages/SettingsPage.xaml b/Hohoema/Presentation.Views.Pages/SettingsPage.xaml index 73cba2050..1005cb187 100644 --- a/Hohoema/Presentation.Views.Pages/SettingsPage.xaml +++ b/Hohoema/Presentation.Views.Pages/SettingsPage.xaml @@ -142,7 +142,7 @@ - + @@ -362,24 +362,6 @@