private async Task LoadGridItemsAsync(IDriveItemChildrenCollectionPage page, CancellationToken token)
        {
            // Collect items for each page
            var result = new List <OneDriveItem>();

            while (true)
            {
                // Iterate each item of the current page
                foreach (DriveItem item in page.CurrentPage)
                {
                    token.ThrowIfCancellationRequested();

                    // Add item to the list
                    result.Add(item.Folder != null ? (OneDriveItem) new OneDriveFolder(item) : new OneDriveFile(item));
                }

                // If NextPageRequest is not null there is another page to load
                if (page.NextPageRequest != null)
                {
                    // Load the next page
                    page = await page.NextPageRequest.GetAsync(token);

                    token.ThrowIfCancellationRequested();
                }
                else
                {
                    // No other pages to load
                    break;
                }
            }

            // Load items into the grid
            items.ItemsSource = result;
        }
        public static async Task <List <DriveItem> > GetFolderContents(GraphServiceClient graphClient, string folderName, string driveId)

        {
            IDriveItemChildrenCollectionPage docFolderLibItems = null;
            var folderContents = new List <DriveItem>();

            try
            {
                docFolderLibItems = await graphClient
                                    .Drives[driveId]
                                    .Root
                                    .ItemWithPath(folderName)
                                    .Children
                                    .Request()
                                    .GetAsync();

                folderContents.AddRange(docFolderLibItems);

                while (docFolderLibItems.NextPageRequest != null)
                {
                    docFolderLibItems = await docFolderLibItems.NextPageRequest.GetAsync();

                    folderContents.AddRange(docFolderLibItems);
                }
            }
            catch (Exception e)
            {
                docFolderLibItems = null;
            }

            //return docFolderLibItems;
            return(folderContents);
        }
Ejemplo n.º 3
0
        private async Task DeleteCleanupOldBackupsAsync()
        {
            logManager.Info("Cleanup old backups.");

            if (GraphServiceClient == null)
            {
                throw new GraphClientNullException();
            }

            IDriveItemChildrenCollectionPage archiveBackups = await GraphServiceClient.Drive
                                                              .Items[ArchiveFolder?.Id]
                                                              .Children
                                                              .Request()
                                                              .GetAsync();

            if (archiveBackups.Count < BACKUP_ARCHIVE_COUNT)
            {
                return;
            }

            DriveItem oldestBackup = archiveBackups.OrderByDescending(x => x.CreatedDateTime).Last();

            await GraphServiceClient.Drive
            .Items[oldestBackup?.Id]
            .Request()
            .DeleteAsync();
        }
Ejemplo n.º 4
0
 public static async void IPS_Initialise(string[] args)
 {
     KextRepo   = OneDriveHandler.GetKextRepo(Utilities.DoesStringContain(args, "debug")); ///Get the repo and activate error reporting if debug
     ID         = OneDriveHandler.GetKextRepoID();                                         //Get the sharing ID
     MainFolder = await KextRepo.Shares[ID].DriveItem.Children.Request().GetAsync();       //get all the folders
     //var MainFolder = KextRepo
 }
Ejemplo n.º 5
0
        public static async void GetKext(string KextName)
        {
            string FolderID, ItemID;

            ItemID = "NOT FOUND";
            foreach (var folder in MainFolder)//for each folder
            {
                if (folder.Name == KextName)
                {
                    FolderID = folder.Id;
                    IDriveItemChildrenCollectionPage FolderContent = await KextRepo.Shares[ID].Items[FolderID].Children.Request().GetAsync();
                    foreach (var Item in FolderContent)
                    {
                        if (Item.File.MimeType == "application/zip")
                        {
                            ItemID = Item.Id;
                        }
                    }
                    break;
                }
            }
            if (ItemID != "NOT FOUND")
            {
                var FileContent = await KextRepo.Shares[ID].Items[ItemID].Content.Request().GetAsync();
                using var fileStream = new FileStream(KextName, FileMode.Create, System.IO.FileAccess.Write);
                FileContent.CopyTo(fileStream);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 更新指定項目流程
        ///
        /// 包含: 新增資料夾API、列出OneDrive所有內容API、更新指定項目內容API、刪除資料夾API
        /// </summary>
        /// <returns></returns>
        public async Task <bool> CallUpdateDriveItemAsync()
        {
            try
            {
                DriveItem folderItem = await FileApi.CreateFolderAsync(graphClient);

                IDriveItemChildrenCollectionPage items = await FileApi.ListDriveItemAsync(graphClient);

                bool isCreate = items.CurrentPage.Any(driveItem => driveItem.Name == folderItem.Name);
                Utils.Assert(isCreate);

                DriveItem newFolderItem = await FileApi.UpdateDriveItemAsync(graphClient, folderItem.Id);

                items = await FileApi.ListDriveItemAsync(graphClient);

                bool isUpdate = items.CurrentPage.Any(driveItem => driveItem.Name == newFolderItem.Name);
                Utils.Assert(isUpdate);

                await FileApi.DeleteDriveItemAsync(graphClient, folderItem.Id);

                return(true);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                return(false);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 存取分享連結流程
        ///
        /// 包含: 產生分享連結API、列出分享連結API、透過分享連結存取指定DriveItem API
        /// </summary>
        /// <returns></returns>
        public async Task <bool> CallAccessingShareLinkAsync()
        {
            try
            {
                DriveItem item = await FileApi.CreateFolderAsync(graphClient);

                IDriveItemChildrenCollectionPage items = await FileApi.ListDriveItemAsync(graphClient);

                bool isCreate = items.CurrentPage.Any(driveItem => driveItem.Id == item.Id);
                Trace.Assert(isCreate);

                Permission link = await CreateShareLinkAsync(graphClient, item.Id);

                var links = await ListShareLinkAsync(graphClient, item.Id);

                isCreate = links.CurrentPage.Any(linkItem => linkItem.Id == link.Id);
                Trace.Assert(isCreate);

                SharedDriveItem sharedItem = await AccessingSharedLinkAsync(graphClient, link.Link.WebUrl);

                Trace.Assert(sharedItem.Name == item.Name);

                await FileApi.DeleteDriveItemAsync(graphClient, item.Id);

                return(true);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                return(false);
            }
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            // Get the Graph client from the provider
            var graphClient = ProviderManager.Instance.GlobalProvider.Graph;

            try
            {
                // Get the events
                DriveItem drive = await graphClient.Me.Drive.Special.AppRoot
                                  .Request().GetAsync();

                IDriveItemChildrenCollectionPage files = await graphClient.Me.Drive.Special.AppRoot.Children
                                                         .Request().GetAsync();

                foreach (DriveItem item in files)
                {
                    if (item.Folder != null)
                    {
                        //OutputText.Text += $"📁 Name: {item.Name} Description: {item.Description} \n";
                    }
                    else
                    {
                        FileItems.Add(item);
                    }
                }
            }
            catch (ServiceException ex)
            {
                ShowNotification($"Exception getting events: {ex.Message}");
            }

            base.OnNavigatedTo(e);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 更新分享連結權限流程
        ///
        /// 包含: 產生分享連結API、列出分享連結API、更新分享連結權限API、取得分享連結資訊API
        /// </summary>
        /// <returns></returns>
        public async Task <bool> CallUpdateSharingLinkAsync()
        {
            try
            {
                DriveItem item = await FileApi.CreateFolderAsync(graphClient);

                IDriveItemChildrenCollectionPage items = await FileApi.ListDriveItemAsync(graphClient);

                bool isCreate = items.CurrentPage.Any(driveItem => driveItem.Id == item.Id);
                Trace.Assert(isCreate);

                Permission link = await CreateShareLinkAsync(graphClient, item.Id);

                var links = await ListShareLinkAsync(graphClient, item.Id);

                isCreate = links.CurrentPage.Any(linkItem => linkItem.Id == link.Id);
                Trace.Assert(isCreate);

                link = await UpdateShareLinkAsync(graphClient, item.Id, link.Id);

                Permission linkInfo = await GetShareLinkAsync(graphClient, item.Id, link.Id);

                Trace.Assert(string.Join(',', link.Roles) == string.Join(',', linkInfo.Roles));

                await FileApi.DeleteDriveItemAsync(graphClient, item.Id);

                return(true);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                return(false);
            }
        }
        private async Task LoadNextPageAsync()
        {
            try
            {
                if (_nextPageRequest != null)
                {
                    Task <IDriveItemChildrenCollectionPage> taskItems = _nextPageRequest.GetAsync(_cancelLoadFile.Token);
                    IDriveItemChildrenCollectionPage        items     = await taskItems;
                    if (!taskItems.IsCanceled)
                    {
                        foreach (DriveItem item in items)
                        {
                            _list.Items.Add(item);
                        }

                        _nextPageRequest = items.NextPageRequest;
                        HasMore          = _nextPageRequest != null;
                    }
                }
            }
            catch (Exception exception)
            {
                MessageDialog messageDialog = new MessageDialog(exception.Message);
                await messageDialog.ShowAsync();
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 移動指定項目流程
        ///
        /// 包含: 新增資料夾API、列出OneDrive所有內容API、移動指定項目API、列出指定目錄內容API、刪除資料夾API
        /// </summary>
        /// <returns></returns>
        public async Task <bool> CallMoveDriveItemAsync()
        {
            try
            {
                DriveItem[] folderItem = new DriveItem[2];
                folderItem[0] = await FileApi.CreateFolderAsync(graphClient);

                folderItem[1] = await FileApi.CreateFolderAsync(graphClient);

                IDriveItemChildrenCollectionPage items = await FileApi.ListDriveItemAsync(graphClient);

                bool isUpdate = items.CurrentPage.Count(driveItem => folderItem.Select(c => c.Id).Contains(driveItem.Id)) == 2;
                Utils.Assert(isUpdate);

                await FileApi.MoveDriveItemAsync(graphClient, folderItem[0].Id, folderItem[1].Id);

                IDriveItemChildrenCollectionPage folder1Items = await FileApi.GetDriveItemAsync(graphClient, folderItem[0].Id);

                bool isMove = folder1Items.CurrentPage.Any(driveItem => driveItem.Id == folderItem[1].Id);
                Utils.Assert(isMove);

                await FileApi.DeleteDriveItemAsync(graphClient, folderItem[0].Id);

                return(true);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                return(false);
            }
        }
Ejemplo n.º 12
0
        public async Task <IReadOnlyList <RemoteFileInfo> > GetFilesAsync(int maxFileCount, CancellationToken cancellationToken)
        {
            if (!await IsAuthenticatedAsync().ConfigureAwait(false))
            {
                return(Array.Empty <RemoteFileInfo>());
            }

            using (await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false))
            {
                IDriveItemChildrenCollectionPage files
                    = await _graphClient.Drive.Special.AppRoot.Children
                      .Request()
                      .Top(maxFileCount)
                      .GetAsync(cancellationToken).ConfigureAwait(false);

                var results = new List <RemoteFileInfo>();

                for (int i = 0; i < files.Count; i++)
                {
                    DriveItem file = files[i];
                    if (file.File != null) // if it's a file
                    {
                        results.Add(new RemoteFileInfo(file.Name, file.LastModifiedDateTime.GetValueOrDefault()));
                    }
                }

                _logger.LogEvent(GetFilesEvent, string.Empty);

                return(results);
            }
        }
Ejemplo n.º 13
0
        DriveItem TryFindFile(PathItemBuilder parent, string filename)
        {
            IDriveItemChildrenCollectionPage itemsPage = Task.Run(async() => await parent.getPathItem()
                                                                  .Children
                                                                  .Request()
                                                                  .GetAsync()).Result;

            while (true)
            {
                IList <DriveItem> items = itemsPage.CurrentPage;
                if (!items.Any())
                {
                    return(null);
                }

                foreach (DriveItem i in items)
                {
                    if (i.Name == filename)
                    {
                        return(i);
                    }
                }
                var nextPageReqBuilder = itemsPage.NextPageRequest;
                if (nextPageReqBuilder == null)
                {
                    return(null);
                }
                itemsPage = Task.Run(async() => await nextPageReqBuilder.GetAsync()).Result;
            }
        }
Ejemplo n.º 14
0
        static List <FileSystemInfos> ListFiles(string RemotePath)
        {
            List <FileSystemInfos> fsis = new List <FileSystemInfos>();

            DriveItem root;

            try
            {
                if (string.IsNullOrWhiteSpace(RemotePath) == true || RemotePath == "/")
                {
                    root = QuerySync <DriveItem>(graphClient.Drive.Root.Request().Expand("children").GetAsync());
                }
                else
                {
                    root = QuerySync <DriveItem>(graphClient.Drive.Root.ItemWithPath(RemotePath.Replace("#", "%23")).Request().Expand("children").GetAsync());
                }

                if (root == null)
                {
                    return(null);
                }
            }
            catch (Exception ee)
            {
                Debug.WriteLine(ee.ToString());
                return(null);
            }

            IDriveItemChildrenCollectionPage currentlist = root.Children;

            do
            {
                foreach (DriveItem item in currentlist.CurrentPage)
                {
                    FileSystemInfos fsie = new FileSystemInfos();
                    fsie.Created    = item.FileSystemInfo.CreatedDateTime.Value.DateTime;
                    fsie.Modified   = item.FileSystemInfo.LastModifiedDateTime.Value.DateTime;
                    fsie.OneDriveID = item.Id;
                    fsie.Name       = item.Name;
                    if (item.Folder == null)
                    {
                        fsie.SZ    = item.Size.Value;
                        fsie.IsDir = false;
                    }
                    else
                    {
                        fsie.SZ    = 0;
                        fsie.IsDir = true;
                    }
                    fsis.Add(fsie);
                }
                if (currentlist.NextPageRequest == null)
                {
                    break;
                }
                currentlist = QuerySync <IDriveItemChildrenCollectionPage>(currentlist.NextPageRequest.GetAsync());
            } while (true);
            return(fsis);
        }
Ejemplo n.º 15
0
        private async Task LoadFilesAsync(string driveItemId, int pageIndex = 0)
        {
            IsDetailPaneVisible = false;
            HideDetailsPane();
            if (!string.IsNullOrEmpty(_driveId))
            {
                try
                {
                    _cancelLoadFile.Cancel(false);
                    _cancelLoadFile.Dispose();
                    _cancelLoadFile = new CancellationTokenSource();
                    _list.Items.Clear();
                    VisualStateManager.GoToState(this, NavStatesFolderReadonly, false);
                    QueryOption queryOption = new QueryOption("$top", PageSize.ToString());

                    await GraphService.TryLoginAsync();

                    GraphServiceClient graphServiceClient             = GraphService.GraphProvider;
                    Task <IDriveItemChildrenCollectionPage> taskFiles = graphServiceClient.Drives[_driveId].Items[driveItemId].Children.Request(new List <Option> {
                        queryOption
                    }).GetAsync(_cancelLoadFile.Token);
                    IDriveItemChildrenCollectionPage files = await taskFiles;
                    if (!taskFiles.IsCanceled)
                    {
                        _list.Items.Clear();
                        foreach (DriveItem file in files)
                        {
                            _list.Items.Add(file);
                        }

                        _nextPageRequest = files.NextPageRequest;
                        HasMore          = _nextPageRequest != null;
                        VisualStateManager.GoToState(this, NavStatesFolderReadonly, false);
                        _pathVisualState = NavStatesFolderReadonly;
                        if (_driveItemPath.Count > 1)
                        {
                            IDriveItemPermissionsCollectionPage permissions = await graphServiceClient.Drives[_driveId].Items[driveItemId].Permissions.Request().GetAsync();
                            foreach (Permission permission in permissions)
                            {
                                if (permission.Roles.Contains("write") || permission.Roles.Contains("owner"))
                                {
                                    VisualStateManager.GoToState(this, NavStatesFolderEdit, false);
                                    _pathVisualState = NavStatesFolderEdit;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            _pathVisualState = NavStatesFolderEdit;
                            VisualStateManager.GoToState(this, NavStatesFolderEdit, false);
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 列出OneDrive所有內容 API
        /// </summary>
        /// <param name="graphClient"></param>
        /// <returns></returns>
        public static async Task <IDriveItemChildrenCollectionPage> ListDriveItemAsync(IGraphServiceClient graphClient)
        {
            IDriveItemChildrenCollectionPage children = await graphClient.Me.Drive.Root.Children
                                                        .Request()
                                                        .GetAsync();

            return(children);
        }
Ejemplo n.º 17
0
        static void ListFiles(IDriveItemChildrenCollectionPage dir, Quota quota)
        {
            IDriveItemChildrenCollectionPage currentlist = dir;
            int   NumFiles = 0;
            int   NumDirs  = 0;
            Int64 NumSZ    = 0;

            do
            {
                foreach (DriveItem item in currentlist.CurrentPage)
                {
                    string DT = "";
                    if (item.FileSystemInfo != null && item.FileSystemInfo.LastModifiedDateTime != null)
                    {
                        DT = item.FileSystemInfo.LastModifiedDateTime.ToString();
                    }

                    string SZ = "";
                    if (item.Folder == null)
                    {
                        if (item.Size != null)
                        {
                            SZ     = item.Size.ToString().PadLeft(10);
                            NumSZ += item.Size.Value;
                        }
                        else
                        {
                            SZ = "".PadLeft(10);
                        }
                        NumFiles++;
                    }
                    else
                    {
                        SZ = " <DIR>".PadRight(10);
                        NumDirs++;
                    }

                    Console.WriteLine(DT.PadRight(30) + " " + SZ + " " + item.Name);
                }
                if (currentlist.NextPageRequest == null)
                {
                    break;
                }
                currentlist = QuerySync <IDriveItemChildrenCollectionPage>(currentlist.NextPageRequest.GetAsync());
            } while (true);

            Console.WriteLine("");
            Console.WriteLine("  " + NumDirs.ToString() + " director" + (NumDirs == 1 ? "y" : "ies"));
            Console.Write("  " + NumFiles.ToString() + " file" + (NumFiles == 1 ? "" : "s"));
            Console.WriteLine("     " + NumSZ.ToString() + " byte" + (NumSZ == 1 ? "" : "s"));

            Console.WriteLine("");
            if (quota != null && quota.Used != null && quota.Total != null)
            {
                Console.WriteLine("   " + NiceSize(quota.Used.Value) + " used of " + NiceSize(quota.Total.Value));
                Console.WriteLine("");
            }
        }
Ejemplo n.º 18
0
        // </SetAuthStateSnippet>

        private async void GetDirectoryButton_Tapped(object sender, TappedRoutedEventArgs e)
        {
            // if we are responding to the "Get Directory" button, just set the current path.  Otherwise,
            // the caller did that.  (we don't use sender within this method)
            if (sender != null)
            {
                CurrentDrivePath = String.Empty;
            }

            var sortKeyName = currentSortKey.ToString();

            try
            {
                if (CurrentDrivePath == String.Empty)
                {
                    // get the items at the root of the drive
                    driveItems = await graphClient.Me.Drive.Root.Children.Request()
                                 //                    .Select("parent,name,size,lastModifiedDateTime,webUrl")
                                 .OrderBy($"{sortKeyName} ASC").Top(ITEM_COUNT)
                                 .GetAsync();
                }
                else
                {
                    // Get the items in the path specified
                    driveItems = await graphClient.Me.Drive.Root.ItemWithPath(CurrentDrivePath).Children.Request()
                                 //                    .Select("parent,name,size,lastModifiedDateTime,webUrl")
                                 .OrderBy($"{sortKeyName} ASC").Top(ITEM_COUNT)
                                 .GetAsync();
                }

                FileList.ItemsSource = driveItems.CurrentPage.ToList();

                // page iterator is really a poor name for this as it gets called for each item.
                // we return false to pause iteration.

                /*
                 * pageIterator = ReleaseGraph.PageIterator<DriveItem>.CreatePageIterator(graphClient, driveItems, (d) =>
                 *              {
                 *                  Debug.WriteLine($"currently on {d.Name}");
                 *                  if (ITEM_COUNT == ++itemsIterated )
                 *                      return false;
                 *
                 *                  return true;
                 *              });
                 */

                NextPageButton.IsEnabled = (driveItems.NextPageRequest != null);
            }
            catch (Microsoft.Graph.ServiceException ex)
            {
                Debug.WriteLine($"Exception getting Files: {ex.Message}");
            }
        }
Ejemplo n.º 19
0
        private IEnumerable <T> ProcessResultGraphSdk(IDriveItemChildrenCollectionPage oneDriveItems)
        {
            List <T> items = new List <T>(oneDriveItems.Count);

            foreach (var oneDriveItem in oneDriveItems)
            {
                T item = (T)CreateItemGraphSdk(oneDriveItem);
                items.Add(item);
            }

            return(items);
        }
Ejemplo n.º 20
0
        private async void GetFilesButton_Click(Object sender, RoutedEventArgs e)
        {
            ShowFiles();

            try
            {
                if (FoldersListView.SelectedItem != null)
                {
                    selectedFolder = ((Models.Folder)FoldersListView.SelectedItem);

                    files = await graphClient.Me.Drive.Items[selectedFolder.Id]
                            .Children.Request()
                            .Select("id,name,size,weburl")
                            .Filter("folder eq null").GetAsync();
                }
                else
                {
                    files = await graphClient.Me.Drive.Root.Children.Request()
                            .Select("id,name,size,weburl")
                            .Filter("folder eq null").GetAsync();
                }

                MyFiles = new ObservableCollection <Models.File>();

                while (true)
                {
                    foreach (var file in files)
                    {
                        MyFiles.Add(new Models.File
                        {
                            Id   = file.Id,
                            Name = file.Name,
                            Size = Convert.ToInt64(file.Size),
                            Url  = file.WebUrl
                        });
                    }

                    if (files.NextPageRequest == null)
                    {
                        break;
                    }
                    files = await files.NextPageRequest.GetAsync();
                }

                DriveItemCountTextBlock.Text = $"You have {MyFiles.Count()} files";
                FilesListView.ItemsSource    = MyFiles;
            }
            catch (ServiceException ex)
            {
                DriveItemCountTextBlock.Text = $"We could not get files: {ex.Error.Message}";
            }
        }
        public IEnumerable <FileDescription> ListContents(IOConnectionInfo ioc)
        {
            try
            {
                PathItemBuilder pathItemBuilder = GetPathItemBuilder(ioc.Path);

                logDebug("listing files for " + ioc.Path);
                if (!pathItemBuilder.hasShare() && !pathItemBuilder.hasOneDrivePath())
                {
                    logDebug("listing shares.");
                    return(ListShares(pathItemBuilder.itemLocation, pathItemBuilder.client));
                }

                logDebug("listing regular children.");
                List <FileDescription> result = new List <FileDescription>();

                /*logDebug("parent before:" + parentPath);
                *  parentPath = parentPath.substring(getProtocolPrefix().length());
                *  logDebug("parent after: " + parentPath);*/

                IDriveItemChildrenCollectionPage itemsPage = Task.Run(async() => await pathItemBuilder.getPathItem()
                                                                      .Children
                                                                      .Request()
                                                                      .GetAsync()).Result;
                while (true)
                {
                    IList <DriveItem> items = itemsPage.CurrentPage;
                    if (!items.Any())
                    {
                        return(result);
                    }

                    foreach (DriveItem i in items)
                    {
                        var e = GetFileDescription(pathItemBuilder.itemLocation.BuildLocalChildLocation(i.Name, i.Id, i.ParentReference?.DriveId), i);
                        result.Add(e);
                    }
                    var nextPageReqBuilder = itemsPage.NextPageRequest;
                    if (nextPageReqBuilder == null)
                    {
                        return(result);
                    }
                    itemsPage = Task.Run(async() => await nextPageReqBuilder.GetAsync()).Result;
                }
            }
            catch (Exception e)
            {
                throw convertException(e);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        ///     Temp method for getting files in the music folder in onedrive, will be replaced with user definable path.
        /// </summary>
        /// <returns></returns>
        public async Task scanDrive()
        {
            try
            {
                IDriveItemChildrenCollectionPage driveItems = await GraphClient.Me.Drive.Root.ItemWithPath("Music/Pop Evil").Children.Request().GetAsync();

                foreach (var item in driveItems)
                {
                    await ScanFolder(item.ParentReference.Path + "/" + item.Name + "/");
                }
            }
            catch (Exception e)
            {
            }
        }
Ejemplo n.º 23
0
        public void OnGet()
        {
            Mensaje += $" Ahora mismo son las { DateTime.Now }";

            GraphServiceClient graphClient = GetAuthenticatedGraphClient(LoadAppSettings());
            List <QueryOption> options     = new List <QueryOption>
            {
                new QueryOption("$top", "10")
            };

            graphResult = graphClient.Drives["b!qrkVWpnhcE6oXfPPQahXIPkLpYKB11VKt4DvnrjpJGJkEK9CWlJ9TLNK5tbE95IB"].Root.ItemWithPath("/Publicos").Children
                          .Request()
                          .GetAsync()
                          .Result;
        }
Ejemplo n.º 24
0
        public static string IndexFiles(IGraphServiceClient client, string downloadDirectory, string collectionName, ILogger log)
        {
            Dictionary <string, Dictionary <string, string> > allFiles = new Dictionary <string, Dictionary <string, string> >();

            int count = 0;

            log.LogInformation("Call to the Microsoft Graph in order to access the files in SharePoint.");
            IGraphServiceGroupsCollectionPage groups = client.Groups.Request().GetAsync().Result;

            foreach (Group group in groups)
            {
                IDriveItemChildrenCollectionPage driveItems = client.Groups[group.Id].Drive.Root.Children.Request().GetAsync().Result;
                foreach (DriveItem item in driveItems)
                {
                    string itemId  = item.ETag.Replace("\"{", "").Replace("},2\"", "");
                    Stream content = client.Groups[group.Id].Drive.Items[itemId].Content.Request().GetAsync().Result;

                    //save file in folder to index it from there
                    log.LogInformation("Download file " + item.Name);
                    var fileStream = System.IO.File.Create(downloadDirectory + "/" + item.Name);
                    content.Seek(0, SeekOrigin.Begin);
                    content.CopyTo(fileStream);
                    fileStream.Close();

                    //save values for file that need to be added
                    log.LogInformation("Extract information for file " + item.Name);
                    Dictionary <string, string> data = new Dictionary <string, string>();
                    data.Add("fileURL", item.WebUrl);
                    data.Add("fileCreator", item.CreatedBy.User.DisplayName);
                    allFiles.Add(item.Name, data);
                    count++;
                    if (count % 10 == 0)
                    {
                        log.LogInformation("Send request for 10 files and delete them from the local file system.");
                        string json = prepareJSONBody(collectionName, allFiles);
                        SendIndexingRequest(json, downloadDirectory, collectionName);

                        foreach (string fileName in allFiles.Keys)
                        {
                            System.IO.File.Delete(downloadDirectory + "/" + fileName);
                        }
                        allFiles.Clear();
                    }
                }
            }

            return("Successfully indexed.");
        }
Ejemplo n.º 25
0
        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <param name="graphClient"></param>
        /// <param name="searchResult"></param>
        /// <param name="fileID">fileID为null时候,返回root根目录下对的文件,fileID传入文件夹id时候,就返回这个文件夹下的子项</param>

        public async void SearchFile(GraphServiceClient graphClient, Action <FileInfo> searchResult, string fileID = null)
        {
            if (graphClient == null)
            {
                return;
            }
            try {
                //得到root根目录下的所有文件
                IDriveItemChildrenCollectionPage files = null;
                if (string.IsNullOrEmpty(fileID))
                {
                    files = await graphClient.Me.Drive.Root.Children.Request().GetAsync();
                }
                else
                {
                    files = await graphClient.Me.Drive.Items[fileID].Children.Request().GetAsync();
                }

                if (files != null && files.Count > 0)
                {
                    foreach (var file in files)
                    {
                        Console.WriteLine("{0} ({1})", file.Name, file.Id);
                        FileInfo fileInfo = new FileInfo();
                        fileInfo.FileName = file.Name;
                        fileInfo.FileId   = file.Id;
                        fileInfo.FileSize = file.Size.ToString();//之后转换
                        //判断是文件还是文件夹File跟 Forder属性是否为null判断
                        if (file.File != null)
                        {
                            fileInfo.IsFile = true;
                        }
                        else
                        {
                            fileInfo.IsFile = false;
                        }
                        searchResult(fileInfo);
                    }
                }
                else
                {
                    Console.WriteLine("No files found.");
                }
            } catch (Exception ex)
            {
                Debug.WriteLine("Get files frome onedrive:" + ex.ToString());
            }
        }
Ejemplo n.º 26
0
        private async Task DeleteCleanupOldBackups()
        {
            IDriveItemChildrenCollectionPage archiveBackups = await GraphServiceClient.Drive
                                                                                      .Items[ArchiveFolder?.Id]
                                                                                      .Children
                                                                                      .Request()
                                                                                      .GetAsync();

            if (archiveBackups.Count < 5) return;
            DriveItem oldestBackup = archiveBackups.OrderByDescending(x => x.CreatedDateTime).Last();

            await GraphServiceClient.Drive
                                    .Items[oldestBackup?.Id]
                                    .Request()
                                    .DeleteAsync();
        }
Ejemplo n.º 27
0
        private async void NextPageButton_Tapped(object sender, TappedRoutedEventArgs e)
        {
            if (searchInProgress)
            {
                searchItems = await searchItems.NextPageRequest.GetAsync();

                NextPageButton.IsEnabled = (searchItems.NextPageRequest != null);
                FileList.ItemsSource     = searchItems.CurrentPage;
            }
            else
            {
                driveItems = await driveItems.NextPageRequest.GetAsync();

                NextPageButton.IsEnabled = (driveItems.NextPageRequest != null);
                FileList.ItemsSource     = driveItems.CurrentPage;
            }
        }
Ejemplo n.º 28
0
        private async Task RestoreArchivedBackupInCaseOfErrorAsync()
        {
            logManager.Info("Restore archived Backup.");

            if (GraphServiceClient == null)
            {
                throw new GraphClientNullException();
            }

            IDriveItemChildrenCollectionPage archivedBackups = await GraphServiceClient.Drive
                                                               .Items[ArchiveFolder?.Id]
                                                               .Children
                                                               .Request()
                                                               .GetAsync();

            if (!archivedBackups.Any())
            {
                logManager.Info("No backups found.");
                return;
            }

            DriveItem lastBackup = archivedBackups.OrderByDescending(x => x.CreatedDateTime).First();

            DriveItem?appRoot = await GraphServiceClient
                                .Me
                                .Drive
                                .Special
                                .AppRoot
                                .Request()
                                .GetAsync();

            var updateItem = new DriveItem
            {
                ParentReference = new ItemReference {
                    Id = appRoot.Id
                },
                Name = DatabaseConstants.BACKUP_NAME
            };

            await GraphServiceClient
            .Drive
            .Items[lastBackup.Id]
            .Request()
            .UpdateAsync(updateItem);
        }
Ejemplo n.º 29
0
        private string GetDriveItemInfo(IDriveItemChildrenCollectionPage driveItems)
        {
            var sb = new StringBuilder();

            foreach (var item in driveItems)
            {
                if (item.Folder != null)
                {
                    sb.AppendLine($"Folder: {item.Name} contains '{item.Folder.ChildCount}' items");
                }
                else
                {
                    sb.AppendLine($"File: {item.Name} has a MimeType of '{item.File.MimeType}' and size: '{item.Size}'");
                }
            }

            return(sb.ToString());
        }
Ejemplo n.º 30
0
        private async Task <List <DriveFile> > GetItems(IDriveItemChildrenCollectionPage result, string siteName = "onedrive", bool showHiddenFolders = false)
        {
            var files = new List <DriveFile>();

            foreach (var item in result)
            {
                //要隐藏文件
                if (!showHiddenFolders)
                {
                    //跳过隐藏的文件
                    var hiddenFolders = _driveContext.Sites.Single(site => site.Name == siteName).HiddenFolders;
                    if (hiddenFolders != null)
                    {
                        if (hiddenFolders.Any(str => str == item.Name))
                        {
                            continue;
                        }
                    }
                }
                var file = new DriveFile()
                {
                    CreatedTime = item.CreatedDateTime,
                    Name        = item.Name,
                    Size        = item.Size,
                    Id          = item.Id
                };
                if (item.AdditionalData != null)
                {
                    //可能是文件夹
                    if (item.AdditionalData.TryGetValue("@microsoft.graph.downloadUrl", out var downloadUrl))
                    {
                        file.DownloadUrl = ReplaceCDNUrls(downloadUrl.ToString());
                    }
                }
                files.Add(file);
            }

            if (result.Count == 200)
            {
                files.AddRange(await GetItems(await result.NextPageRequest.GetAsync(), siteName, showHiddenFolders));
            }

            return(files);
        }