Ejemplo n.º 1
0
        /// <summary>
        /// Download the primary mid sized thumbnail as a Sprite.
        /// </summary>
        /// <param name="drive">Target drive.</param>
        /// <param name="itemId">Source item id.</param>
        /// <returns>Thumbnail as Sprite or null if the item has no thumbnail.</returns>
        private async Task <Sprite> DownloadDriveItemThumbnail(IDriveRequestBuilder drive, string itemId)
        {
            var thumbnails = await drive.Items[itemId].Thumbnails.Request().GetAsync();

            if (!thumbnails.Any())
            {
                return(null);
            }

            var thumbnail = thumbnails.First();
            var content   = await drive.Items[itemId].Thumbnails[thumbnail.Id]["medium"].Content.Request().GetAsync();

            using (var reader = new MemoryStream())
            {
                await content.CopyToAsync(reader);

                var data    = reader.ToArray();
                var texture = new Texture2D(0, 0);
                texture.LoadImage(data);
                return(Sprite.Create(
                           texture,
                           new Rect(0, 0, texture.width, texture.height),
                           new Vector2(0.5f, 0.5f)));
            }
        }
        /// <summary>
        /// Uploads a new file into the folder id specificied
        /// </summary>
        /// <param name="folderId"></param>
        /// <returns></returns>
        public async Task UploadFileAsync(string folderId)
        {
            // Check if session is set
            if (AuthenticationService == null)
            {
                throw new InvalidOperationException($"No {nameof(AuthenticationService)} has been specified");
            }

            // Open the picker for file selection
            var picker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.Downloads,
            };

            // User can select any file
            picker.FileTypeFilter.Add("*");
            StorageFile storageFile = await picker.PickSingleFileAsync();

            // storageFile is null if no file has been selected
            if (storageFile != null)
            {
                // Create the graph request builder for the drive
                IDriveRequestBuilder driveRequest = AuthenticationService.GraphClient.Me.Drive;

                // If folder id is null, the request refers to the root folder
                IDriveItemRequestBuilder driveItemsRequest;
                if (folderId == null)
                {
                    driveItemsRequest = driveRequest.Root;
                }
                else
                {
                    driveItemsRequest = driveRequest.Items[folderId];
                }

                try
                {
                    // Create an upload session for a file with the same name of the user selected file
                    UploadSession session = await driveItemsRequest
                                            .ItemWithPath(storageFile.Name)
                                            .CreateUploadSession()
                                            .Request()
                                            .PostAsync();

                    // Add a new upload item at the beginning
                    var item = new OneDriveFileProgress(storageFile.Name);
                    _progressItems.Insert(0, item);

                    // Start the upload process
                    await item.UploadFileAsync(AuthenticationService, storageFile, session);
                }
                catch (Exception ex)
                {
                    Error?.Invoke(this, ex);
                }
            }
        }
Ejemplo n.º 3
0
        public async Task <Drive> GetUserDrive(User user, CancellationToken token)
        {
            IDriveRequestBuilder rb = client.Users[user.Id].Drive;

            try
            {
                return(await rb.Request().GetAsync(token));
            }
            catch (Exception ex)
            {
                HandleException(ex, null, messageOnlyExceptions, $"Get drive for user: {user.DisplayName}");
            }

            return(default(Drive));
        }
Ejemplo n.º 4
0
        public async Task <Drive> GetGroupDrive(Group group, CancellationToken token)
        {
            IDriveRequestBuilder rb = client.Groups[group.Id].Drive;

            try
            {
                return(await rb.Request().GetAsync(token));
            }
            catch (Exception ex)
            {
                HandleException(ex, null, messageOnlyExceptions, $"Get drive for group: {group.DisplayName}");
            }

            return(default(Drive));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 取得空間資訊,並初始化 Drive 物件
        /// </summary>
        private async Task <(CloudStorageResult result, long usedSpace, long totalSpace)> GetRootInfoAsync()
        {
            CloudStorageResult result = new CloudStorageResult();
            long usedSpace = 0, totalSpace = 0;

            try
            {
                myDriveBuilder = graphServiceClient.Me.Drive;
                Drive myDrive = await myDriveBuilder.Request().GetAsync();

                usedSpace     = myDrive.Quota.Used ?? 0;
                totalSpace    = myDrive.Quota.Total ?? 0;
                result.Status = Status.Success;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result, usedSpace, totalSpace);
        }
        private async Task LoadFolderAsync(string id = null)
        {
            // Cancel any previous operation
            _cancellationTokenSource?.Cancel();
            _cancellationTokenSource = new CancellationTokenSource();

            // Check if session is set
            if (AuthenticationService == null)
            {
                throw new InvalidOperationException($"No {nameof(AuthenticationService)} has been specified");
            }

            // Keep a local copy of the token because the source can change while executing this function
            var token = _cancellationTokenSource.Token;

            // Add an option to the REST API in order to get thumbnails for each file
            // https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_list_thumbnails
            var options = new[]
            {
                new QueryOption("$expand", "thumbnails"),
            };

            // Create the graph request builder for the drive
            IDriveRequestBuilder driveRequest = AuthenticationService.GraphClient.Me.Drive;

            // If folder id is null, the request refers to the root folder
            IDriveItemRequestBuilder driveItemsRequest;

            if (id == null)
            {
                driveItemsRequest = driveRequest.Root;
            }
            else
            {
                driveItemsRequest = driveRequest.Items[id];
            }

            // Raise the loading event
            FolderLoading?.Invoke(this, EventArgs.Empty);
            try
            {
                try
                {
                    // Make a API request loading 50 items per time
                    var page = await driveItemsRequest.Children.Request(options).Top(50).GetAsync(token);

                    token.ThrowIfCancellationRequested();

                    // Load each page
                    await LoadGridItemsAsync(page, token);

                    token.ThrowIfCancellationRequested();
                }
                finally
                {
                    // Raise the loaded event
                    FolderLoaded?.Invoke(this, EventArgs.Empty);
                }
            }
            catch (OperationCanceledException)
            { }
            catch (Exception ex)
            {
                // Raise the error event
                LoadingError?.Invoke(this, ex);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Search the drive by the given <see href="https://docs.microsoft.com/en-us/graph/query-parameters">OData Query</see> string.
        /// </summary>
        /// <param name="drive">Target drive to search at.</param>
        /// <param name="query">Search text query</param>
        /// <returns>Found DriveItems</returns>
        private async Task <List <DriveItem> > SearchDrive(IDriveRequestBuilder drive, string query)
        {
            var search = await drive.Search(query).Request().GetAsync();

            return(search.ToList());
        }