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.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.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) { 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 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 8fd54cc35..db62aa7e1 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,12 @@ 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; +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,18 +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) @@ -140,19 +138,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) { @@ -168,7 +154,7 @@ public override async Task OnStartAsync(StartArgs args) UIElement CreateShell() { - + // Grid // |- HohoemaInAppNotification // |- PlayerWithPageContainerViewModel @@ -215,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())); @@ -224,12 +210,11 @@ 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); + 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) @@ -283,7 +268,7 @@ public override void RegisterTypes(IContainerRegistry container) container.RegisterSingleton(); // UseCase - unityContainer.Register(); + unityContainer.Register(); container.RegisterSingleton(); container.RegisterSingleton(); container.RegisterSingleton(); @@ -318,10 +303,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, 65536); + _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(); @@ -334,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(); @@ -352,64 +496,108 @@ protected override void RegisterRequiredTypes(IContainerRegistry containerRegist containerRegistry.RegisterForNavigation(); containerRegistry.RegisterForNavigation(); containerRegistry.RegisterForNavigation(); - + containerRegistry.RegisterForNavigation(); containerRegistry.RegisterForNavigation(); - base.RegisterRequiredTypes(containerRegistry); + 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; + 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) { - Debug.WriteLine($"Try migrate: {migrateType.Name}"); - var migrater = Container.Resolve(migrateType); - if (migrater is IMigrateSync migrateSycn) - { - migrateSycn.Migrate(); - } - else if (migrater is IMigrateAsync migrateAsync) - { - await migrateAsync.MigrateAsync(); - } - - Debug.WriteLine("Migration complete : " + migrateType.Name); + migrateSycn.Migrate(); } - catch (Exception e) + else if (migrater is IMigrateAsync migrateAsync) { - Debug.WriteLine(e.ToString()); - Debug.WriteLine("Migration failed : " + 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(new Type[] + await TryMigrationAsync(migrateType); + } + } + + async Task MaintenanceProcessAsync() + { + Type[] maintenanceTypes = new Type[] + { + typeof(Models.UseCase.Maintenance.VideoThumbnailImageCacheMaintenance), + }; + + async Task TryMaintenanceAsync(Type maintenanceType) + { + 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上でインスタンス生成させている { @@ -596,7 +784,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 +899,7 @@ public override async void OnInitialized() } catch { - Debug.WriteLine("ログイン処理に失敗"); + Container.Resolve().ZLogError("ログイン処理に失敗"); } #if !DEBUG @@ -965,6 +1153,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 +1202,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..b3b890171 100644 --- a/Hohoema/Hohoema.csproj +++ b/Hohoema/Hohoema.csproj @@ -138,7 +138,7 @@ - + @@ -171,7 +171,7 @@ - + @@ -783,14 +783,12 @@ 0.16.0 + + 2.1.0 + 1.0.1 - - 3.4.13 - runtime; build; native; contentfiles; analyzers; buildtransitive - all - 4.1.4 @@ -800,14 +798,11 @@ 4.2.0 - - 4.2.0 - - - 4.2.0 - - 5.0.0 + 6.0.0 + + + 1.1.2 5.0.5 @@ -872,6 +867,12 @@ 1.0.0 + + 1.6.1 + + + 2.4.4 + @@ -1261,9 +1262,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/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/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/VideoCommentPlayer.cs similarity index 90% rename from Hohoema/Models.UseCase/Niconico.Player/Comment/CommentPlayer.cs rename to Hohoema/Models.UseCase/Niconico.Player/Comment/VideoCommentPlayer.cs index 1f8d49aba..0dd626256 100644 --- a/Hohoema/Models.UseCase/Niconico.Player/Comment/CommentPlayer.cs +++ b/Hohoema/Models.UseCase/Niconico.Player/Comment/VideoCommentPlayer.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,10 +25,11 @@ using Uno.Threading; using Windows.Media.Playback; using Windows.System; +using ZLogger; 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(); @@ -36,7 +38,8 @@ 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; public ObservableRangeCollection Comments { get; private set; } @@ -46,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(); @@ -69,7 +72,8 @@ public bool NowCommentSubmitDisabledFromNicoScript event EventHandler NicoScriptJumpTimeRequested; event EventHandler CommentSubmitFailed; - public CommentPlayer( + public VideoCommentPlayer( + 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; @@ -210,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)) { @@ -232,9 +237,9 @@ public async Task UpdatePlayingCommentAsync(INiconicoCommentSessionProvider nico _CommentUpdateTimer.Start(); } - catch + catch (Exception e) { - + _logger.ZLogError(e, "コメント一覧の更新に失敗"); } } } @@ -252,7 +257,7 @@ private void _CommentUpdateTimer_Tick(DispatcherQueueTimer sender, object args) CurrentComment = null; } - TickNextDisplayingComments(currentPosition); + //TickNextDisplayingComments(currentPosition); UpdateNicoScriptComment(currentPosition); RefreshCurrentPlaybackPositionComment(currentPosition); @@ -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 { @@ -341,7 +346,7 @@ private async Task SubmitComment() - private async Task UpdateComments_Internal(ICommentSession commentSession) + private async Task UpdateComments_Internal(ICommentSession commentSession) { // ニコスクリプトの状態を初期化 ClearNicoScriptState(); @@ -350,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) @@ -369,36 +372,37 @@ 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"); } } 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); _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())); + //var displayingComments = _commentDisplayingRangeExtractor.ResetComments(comments, _mediaPlayer.PlaybackSession.Position); + DisplayingComments.AddRange(EnumerateFilteredDisplayComment(comments)); } @@ -486,24 +490,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 +634,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 +684,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 +705,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 +730,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 +756,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/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/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/Package.appxmanifest b/Hohoema/Package.appxmanifest index 77a3899d5..f599a827a 100644 --- a/Hohoema/Package.appxmanifest +++ b/Hohoema/Package.appxmanifest @@ -1,6 +1,6 @@  - + Hohoema 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/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 @@ (); 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/ChannelVideoPage.xaml b/Hohoema/Presentation.Views.Pages/Niconico.Channel/ChannelVideoPage.xaml index 8a0e19ac3..4e0dcf489 100644 --- a/Hohoema/Presentation.Views.Pages/Niconico.Channel/ChannelVideoPage.xaml +++ b/Hohoema/Presentation.Views.Pages/Niconico.Channel/ChannelVideoPage.xaml @@ -113,7 +113,7 @@ 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/CommunityVideoPage.xaml b/Hohoema/Presentation.Views.Pages/Niconico.Community/CommunityVideoPage.xaml index e64bffe53..f903b24cf 100644 --- a/Hohoema/Presentation.Views.Pages/Niconico.Community/CommunityVideoPage.xaml +++ b/Hohoema/Presentation.Views.Pages/Niconico.Community/CommunityVideoPage.xaml @@ -114,7 +114,7 @@ ()) + { 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/NicoRepoPage.xaml b/Hohoema/Presentation.Views.Pages/Niconico.NicoRepo/NicoRepoPage.xaml index 211543017..97bdb45ae 100644 --- a/Hohoema/Presentation.Views.Pages/Niconico.NicoRepo/NicoRepoPage.xaml +++ b/Hohoema/Presentation.Views.Pages/Niconico.NicoRepo/NicoRepoPage.xaml @@ -39,7 +39,7 @@ , 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/RankingCategoryPage.xaml b/Hohoema/Presentation.Views.Pages/Niconico.VideoRanking/RankingCategoryPage.xaml index 0022083a9..f952ceab1 100644 --- a/Hohoema/Presentation.Views.Pages/Niconico.VideoRanking/RankingCategoryPage.xaml +++ b/Hohoema/Presentation.Views.Pages/Niconico.VideoRanking/RankingCategoryPage.xaml @@ -104,7 +104,7 @@ ()) { 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 4782f536c..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,13 +202,19 @@ Services.CurrentActiveWindowUIContextService currentActiveWindowUIContextService }); Window.Current.Activated += Current_Activated; - _currentActiveWindowUIContextService = currentActiveWindowUIContextService; - + // Xbox向けのメニュー表示、下部のマージンを追加する if (_viewModel.ApplicationLayoutManager.AppLayout == ApplicationLayout.TV) { 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) @@ -324,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()); @@ -342,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); } }); } @@ -940,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/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) diff --git a/Hohoema/Presentation.Views.Pages/SettingsPage.xaml b/Hohoema/Presentation.Views.Pages/SettingsPage.xaml index ccccd163a..1005cb187 100644 --- a/Hohoema/Presentation.Views.Pages/SettingsPage.xaml +++ b/Hohoema/Presentation.Views.Pages/SettingsPage.xaml @@ -142,7 +142,7 @@ - + @@ -362,24 +362,6 @@