Esempio n. 1
0
        public async IAsyncEnumerable <DriveItem> GetChildrenAsync(IAccount account, string parentId)
        {
            BeforeTaskExecuted?.Invoke(this, null);
            var userId = GetUserId(account);

            using var cts = new CancellationTokenSource(Timeouts.Silent);
            var request = graphClient.Users[userId].Drive.Items[parentId].Children.Request();

            do
            {
                IDriveItemChildrenCollectionPage page;
                try {
                    page = await request.GetAsync(cts.Token).ConfigureAwait(false);
                } catch (TaskCanceledException ex) {
                    logger?.LogError(ex, "Use canncel the task.");
                    TaskExecuted?.Invoke(this, null);
                    yield break;
                } catch (ServiceException ex) {
                    logger?.LogError(ex, "onedrive server error.");
                    TaskExecuted?.Invoke(this, null);
                    yield break;
                }
                foreach (var file in page)
                {
                    yield return(file);
                }
                request = page?.NextPageRequest;
            } while (request != null);
            TaskExecuted?.Invoke(this, null);
        }
Esempio n. 2
0
        /// <summary>
        /// This method can only be used with <see cref="Authority.Organizations"/>
        /// Only used in test.
        /// </summary>
        public async Task <AuthenticationResult> LoginWithUsernamePassword(string username = null, string password = null)
        {
            this.username = username ?? this.username;
            this.password = password ?? this.password;
            if (this.username == null || this.password == null)
            {
                return(null);
            }
            BeforeTaskExecuted?.Invoke(this, null);
            using var cts = new CancellationTokenSource(Timeouts.Silent);
            var secureString = new SecureString();

            foreach (var c in this.password ?? "")
            {
                secureString.AppendChar(c);
            }
            var result = await msalClient
                         .AcquireTokenByUsernamePassword(scopes, this.username, secureString)
                         .ExecuteAsync(cts.Token).ConfigureAwait(false);

            var account = result?.Account;

            RegisterUser(account);

            TaskExecuted?.Invoke(this, null);
            return(result);
        }
Esempio n. 3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="taskExecuter"></param>
        /// <returns></returns>
        private bool InternalExecuteTask(TaskExecuter taskExecuter)
        {
            var result = taskExecuter.Execute();

            TaskExecuted?.Invoke(taskExecuter);

            return(result);
        }
Esempio n. 4
0
        /// <summary>
        /// 通知工作线程执行任务完成。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="ObjectDisposedException"></exception>
        protected void OnTaskExecuted(object sender, TaskExecutedEventArgs <TTask> e)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(nameof(BackgroundTaskThreadService <TTask, TThread>));
            }

            DecrementWorkThread();
            TaskExecuted?.Invoke(sender, e);
        }
Esempio n. 5
0
        public async Task <Stream> GetFileContentAsync(IAccount account, string fileId)
        {
            BeforeTaskExecuted?.Invoke(this, null);
            var userId = GetUserId(account);
            var cts    = new CancellationTokenSource(Timeouts.Silent);

            try {
                return(await graphClient.Users[userId].Drive.Items[fileId].Content.Request().GetAsync(cts.Token).ConfigureAwait(false));
            } catch (ServiceException ex) {
                logger?.LogError(ex, "onedrive server error");
                return(null);
            } finally {
                TaskExecuted?.Invoke(this, null);
            }
        }
Esempio n. 6
0
        public async Task <bool> LogoutAsync(IAccount account)
        {
            BeforeTaskExecuted?.Invoke(this, null);
            try {
                // TODO: this method just clears the cache without truely logout the user!!
                await msalClient.RemoveAsync(account).ConfigureAwait(false);

                accountList.Remove(account);
                return(true);
            } catch (Exception ex) {
                logger?.LogError(ex, "");
                return(false);
            } finally {
                TaskExecuted?.Invoke(this, null);
            }
        }
Esempio n. 7
0
        public async Task <User> GetUserAsync(IAccount account)
        {
            BeforeTaskExecuted?.Invoke(this, null);
            var userId = GetUserId(account);

            using var cts = new CancellationTokenSource(Timeouts.Silent);
            try {
                var user = await graphClient.Users[userId].Request().GetAsync(cts.Token).ConfigureAwait(false);
                return(user);
            } catch (ServiceException ex) {
                logger?.LogError(ex, "onedrive server error");
                return(null);
            } finally {
                TaskExecuted?.Invoke(this, null);
            }
        }
Esempio n. 8
0
        public async Task <AuthenticationResult> LoginInteractively(CancellationToken token)
        {
            BeforeTaskExecuted?.Invoke(this, null);
            var requestBuilder = msalClient.AcquireTokenInteractive(scopes);

            try {
                var result = await requestBuilder
                             .ExecuteAsync(token)
                             .ConfigureAwait(false);

                RegisterUser(result?.Account);
                return(result);
            } catch (MsalClientException) {
                logger?.LogInformation("User cancelled.");
            } catch (MsalException ex) {
                logger?.LogWarning(ex, "Masl exception.");
            } catch (InvalidOperationException ex) {
                logger?.LogError(ex, "");
            }
            TaskExecuted?.Invoke(this, null);
            return(null);
        }
Esempio n. 9
0
        public async IAsyncEnumerable <AuthenticationResult> LoginAllUserSilently()
        {
            BeforeTaskExecuted?.Invoke(this, null);
            var accounts = await msalClient.GetAccountsAsync().ConfigureAwait(false);

            foreach (var account in accounts)
            {
                AuthenticationResult result;
                try {
                    using var cts = new CancellationTokenSource(Timeouts.Silent);
                    result        = await msalClient.AcquireTokenSilent(scopes, account)
                                    .ExecuteAsync(cts.Token)
                                    .ConfigureAwait(false);

                    RegisterUser(result?.Account);
                } catch (Exception ex) {
                    logger?.LogError(ex, "onedrive server error");
                    continue;
                }
                yield return(result);
            }
            TaskExecuted?.Invoke(this, null);
        }
Esempio n. 10
0
        public async Task <bool> ExecuteAsync(OfflineTask task)
        {
            _loggingService.WriteLine($"Executing task {task.Id} with action {task.Action} for item {task.ItemId}.");
            int placeholderId = -1;

            if (_platform.InternetConnectionIsAvailable == false)
            {
                _loggingService.WriteLine("No internet connection available. Cancelled.");
                TaskExecuted?.Invoke(this, new OfflineTaskExecutedEventArgs(task, -1, false));
                return(false);
            }

            bool executionIsSuccessful = false;

            switch (task.Action)
            {
            case OfflineTaskAction.MarkAsRead:
                executionIsSuccessful = await _client.ArchiveAsync(task.ItemId);

                break;

            case OfflineTaskAction.UnmarkAsRead:
                executionIsSuccessful = await _client.UnarchiveAsync(task.ItemId);

                break;

            case OfflineTaskAction.MarkAsStarred:
                executionIsSuccessful = await _client.FavoriteAsync(task.ItemId);

                break;

            case OfflineTaskAction.UnmarkAsStarred:
                executionIsSuccessful = await _client.UnfavoriteAsync(task.ItemId);

                break;

            case OfflineTaskAction.EditTags:
                var item = _database.Find <Item>(i => i.Id == task.ItemId);

                if (item == null)
                {
                    /* This can happen in several cases even if it shouldn't.
                     * In the case the item is already deleted, the task will be marked as success so it's removed asap. */
                    executionIsSuccessful = true;
                    break;
                }

                if (task.AddedTags?.Count > 0)
                {
                    var newTags = await _client.AddTagsAsync(task.ItemId, task.AddedTags.ToStringArray());

                    if (newTags != null)
                    {
                        var convertedTags = new ObservableCollection <Tag>();
                        foreach (var tag in newTags)
                        {
                            convertedTags.Add(tag);
                        }

                        _database.InsertOrReplaceAll(convertedTags);
                        item.Tags.Replace(convertedTags);
                    }
                }
                if (task.RemovedTags?.Count > 0)
                {
                    var tagsToRemove = new List <WallabagTag>();
                    foreach (var tag in task.RemovedTags)
                    {
                        tagsToRemove.Add(tag);
                    }

                    if (await _client.RemoveTagsAsync(task.ItemId, tagsToRemove))
                    {
                        foreach (var tag in task.RemovedTags)
                        {
                            if (item.Tags.Contains(tag))
                            {
                                item.Tags.Remove(tag);
                            }
                        }
                    }
                }

                executionIsSuccessful = _database.Update(item) == 1;
                break;

            case OfflineTaskAction.AddItem:
                placeholderId = _database.FindWithQuery <Item>("select Id from Item where Content=?", m_PLACEHOLDER_PREFIX + task.Id)?.Id ?? -1;

                if (placeholderId >= 0)
                {
                    _database.Delete <Item>(placeholderId);
                }

                var newItem = await _client.AddAsync(new Uri(task.Url), task.Tags);

                if (newItem != null)
                {
                    _database.InsertOrReplace((Item)newItem);
                    task.ItemId = newItem.Id;
                }

                executionIsSuccessful = newItem != null;
                break;

            case OfflineTaskAction.Delete:
                executionIsSuccessful = await _client.DeleteAsync(task.ItemId);

                break;

            default:
                break;
            }

            if (executionIsSuccessful)
            {
                _loggingService.WriteLine($"Execution of task {task.Id} was successful.");
                _database.Delete(task);
            }
            _loggingService.WriteLineIf(!executionIsSuccessful, "Execution was not successful.", LoggingCategory.Warning);

            TaskExecuted?.Invoke(this, new OfflineTaskExecutedEventArgs(task, placeholderId, executionIsSuccessful));

            return(executionIsSuccessful);
        }
 /// <summary>
 /// 通知工作线程执行任务完成。
 /// </summary>
 /// <param name="e"></param>
 protected virtual void OnTaskExecuted(TaskExecutedEventArgs <TTask> e)
 {
     TaskExecuted?.Invoke(this, e);
 }
Esempio n. 12
0
        private async Task Next(CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return;
            }

            if (!_isBusy)
            {
                if (queue.Count > 0)
                {
                    // Optional delay.

                    if (Delay > default(TimeSpan))
                    {
                        await Task.Delay(Delay);
                    }

                    // Peek the current task.

                    var context = queue.Peek();

                    try
                    {
                        _isRunning = true;
                        _isBusy    = true;

                        // Execute the current task.

                        TaskExecuting?.Invoke(this, new TaskEventArgs(context.Tag));

                        await context.Action(context, cts.Token);
                    }
                    catch (Exception exc)
                    {
                        // Handle any exception thrown inside a task.
                        // Invoke the Exception event handlers.

                        TaskException?.Invoke(this, new TaskEventArgs(context.Tag, exc));

                        if (CancelOnException)
                        {
                            // Cancel the queue.

                            ClearInternal();
                        }
                    }

                    TaskExecuted?.Invoke(this, new TaskEventArgs(context.Tag));

                    // Dequeue the currently finished task and request the next.

                    if (queue.Count > 0)
                    {
                        queue.Dequeue();
                    }
                    _isBusy = false;
                    await Next(cts.Token);
                }
            }
            else
            {
                _isRunning = false;
            }
        }