Ejemplo n.º 1
0
        private async Task MarkEpWatched(string episodeId)
        {
            try
            {
                BangumiApi.Init(
                    Constants.ClientId,
                    Constants.ClientSecret,
                    Constants.RedirectUrl,
                    ApplicationData.Current.LocalFolder.Path,
                    ApplicationData.Current.LocalCacheFolder.Path,
                    EncryptionHelper.EncryptionAsync,
                    EncryptionHelper.DecryptionAsync);

                await BangumiApi.BgmApi.UpdateProgress(episodeId, Api.Models.EpStatusType.watched);
            }
            catch (Exception e)
            {
                ToastNotificationHelper.Toast("操作失败", e.Message, "重试", _queryString);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// The Run method is the entry point of a background task.
        /// </summary>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting...");

            // Query BackgroundWorkCost
            // Guidance: If BackgroundWorkCost is high, then perform only the minimum amount
            // of work in the background task and return immediately.
            var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;

            // Associate a cancellation handler with the background task.
            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

            // Get the deferral object from the task instance, and take a reference to the taskInstance;
            _deferral     = taskInstance.GetDeferral();
            _taskInstance = taskInstance;

            try
            {
                BangumiApi.Init(
                    Constants.ClientId,
                    Constants.ClientSecret,
                    Constants.RedirectUrl,
                    ApplicationData.Current.LocalFolder.Path,
                    ApplicationData.Current.LocalCacheFolder.Path,
                    EncryptionHelper.EncryptionAsync,
                    EncryptionHelper.DecryptionAsync);

                await BangumiApi.BgmOAuth.CheckToken();

                if (SettingHelper.EnableBangumiAirToast)
                {
                    // 初始化 BangumiData 对象
                    BangumiData.Init(Path.Combine(ApplicationData.Current.LocalFolder.Path, "bangumi-data"),
                                     SettingHelper.UseBiliApp);

                    if (!BangumiApi.BgmCache.IsUpdatedToday)
                    {
                        // 加载缓存,后面获取新数据后比较需要使用
                        var cachedWatchings = BangumiApi.BgmCache.Watching();

                        // 加载新的收视进度
                        var newWatching = await BangumiApi.BgmApi.Watching();

                        var subjectTasks  = new List <Task <SubjectLarge> >();
                        var progressTasks = new List <Task <Progress> >();
                        // 新的收视进度与缓存的不同或未缓存的条目
                        var watchingsNotCached = BangumiApi.BgmCache.IsUpdatedToday ?
                                                 newWatching.Where(it => cachedWatchings.All(it2 => !it2.EqualsExT(it))).ToList() :
                                                 newWatching;
                        using (var semaphore = new SemaphoreSlim(10))
                        {
                            foreach (var item in watchingsNotCached)
                            {
                                await semaphore.WaitAsync();

                                subjectTasks.Add(BangumiApi.BgmApi.SubjectEp(item.SubjectId.ToString())
                                                 .ContinueWith(t =>
                                {
                                    semaphore.Release();
                                    return(t.Result);
                                }));
                                await semaphore.WaitAsync();

                                progressTasks.Add(BangumiApi.BgmApi.Progress(item.SubjectId.ToString())
                                                  .ContinueWith(t =>
                                {
                                    semaphore.Release();
                                    return(t.Result);
                                }));
                            }
                            await Task.WhenAll(subjectTasks);

                            await Task.WhenAll(progressTasks);
                        }
                        BangumiApi.BgmCache.IsUpdatedToday = true;
                        await BangumiApi.BgmCache.WriteToFile();
                    }

                    ToastNotificationHelper.RemoveAllScheduledToasts();
                    foreach (var item in CachedWatchProgress())
                    {
                        await item.ScheduleToast();
                    }
                }
            }
            catch (BgmUnauthorizedException e)
            {
                // 取消所有后台任务
                foreach (var cur in BackgroundTaskRegistration.AllTasks)
                {
                    cur.Value.Unregister(true);
                }
                ToastNotificationHelper.Toast("后台任务", "用户认证过期,后台任务已取消。");
                Debug.WriteLine(e.StackTrace);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.StackTrace);
            }
            finally
            {
                _deferral.Complete();
            }

            IEnumerable <WatchProgress> CachedWatchProgress()
            {
                foreach (var watching in BangumiApi.BgmCache.Watching())
                {
                    var subject  = BangumiApi.BgmCache.Subject(watching.SubjectId.ToString());
                    var progress = BangumiApi.BgmCache.Progress(watching.SubjectId.ToString());

                    var item = WatchProgress.FromWatching(watching);
                    item.ProcessEpisode(subject);
                    item.ProcessProgress(progress);
                    if (subject == null || progress == null)
                    {
                        // 标记以重新加载
                        watching.Subject.Eps = -1;
                    }
                    yield return(item);
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Handles background task cancellation.
        /// </summary>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            ToastNotificationHelper.Toast("任务被取消", reason.ToString(), "重试", _queryString, ToastActivationType.Background);

            Debug.WriteLine("Background " + sender.Task.Name + " Cancel Requested...");
        }
Ejemplo n.º 4
0
        private async void OnLaunchedOrActivated(IActivatedEventArgs e)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            // 不要在窗口已包含内容时重复应用程序初始化,
            // 只需确保窗口处于活动状态
            if (rootFrame == null)
            {
                // 创建要充当导航上下文的框架,并导航到第一页
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: 从之前挂起的应用程序加载状态
                }

                // 将框架放在当前窗口中
                Window.Current.Content = rootFrame;
            }

            // 处理正常启动
            if (e is LaunchActivatedEventArgs launchActivatedArgs && launchActivatedArgs.PrelaunchActivated == false)
            {
                if (rootFrame.Content == null)
                {
                    // 当导航堆栈尚未还原时,导航到第一页,
                    // 并通过将所需信息作为导航参数传入来配置
                    // 参数
                    rootFrame.Navigate(typeof(MainPage), launchActivatedArgs.Arguments);
                }
            }

            // Handle toast activation
            if (e is ToastNotificationActivatedEventArgs toastActivationArgs)
            {
                if (rootFrame.Content == null)
                {
                    rootFrame.Navigate(typeof(MainPage));
                }

                // 等待加载完成
                while (true)
                {
                    if (MainPage.RootPage.IsLoaded)
                    {
                        break;
                    }
                    await Task.Delay(500);
                }

                // Parse the query string (using QueryString.NET)
                QueryString args = QueryString.Parse(toastActivationArgs.Argument);

                if (args.Contains("action"))
                {
                    string id = string.Empty;
                    // See what action is being requested
                    switch (args["action"])
                    {
                    // Open the subject
                    case "viewSubject":
                        id = args["subjectId"];
                        MainPage.RootPage.ResetFrameBackStack();
                        MainPage.RootPage.NavigateToPage(typeof(EpisodePage), args["subjectId"], null);
                        break;

                    case "gotoPlaySite":
                        id = args["url"];
                        var sites = await BangumiData.GetAirSitesByBangumiIdAsync(id);

                        await Launcher.LaunchUriAsync(new Uri(args["url"]));

                        var episode = JsonConvert.DeserializeObject <EpisodeForSort>(args["episode"]);
                        ToastNotificationHelper.Toast("看完了吗?",
                                                      $"Ep.{episode.Sort} {Converters.StringOneOrTwo(episode.NameCn, episode.Name)}", "看完了!看完了!",
                                                      "markEpWatched", "episodeId", episode.Id.ToString(), string.Empty, string.Empty,
                                                      Microsoft.Toolkit.Uwp.Notifications.ToastActivationType.Background, true);
                        break;
                    }
                }
            }

            // 处理其它激活方式

            // 确保当前窗口处于活动状态
            Window.Current.Activate();
        }