Beispiel #1
0
        public string GetDisplayName(IOConnectionInfo ioc)
        {
            try
            {
                var itemLocation = OneDrive2ItemLocation <OneDrive2PrefixContainerType> .FromString(ioc.Path);

                string result = ProtocolId + "://";
                if (!string.IsNullOrEmpty(itemLocation.User?.Id))
                {
                    result += itemLocation.User?.Name;
                    if (itemLocation.Share != null)
                    {
                        result += "/" + (itemLocation.Share?.Name ?? itemLocation.Share?.Id);

                        if (itemLocation.LocalPath.Any())
                        {
                            result += "/" + itemLocation.LocalPathString;
                        }
                    }
                }
                return(result);
            }
            catch (Exception e)
            {
                Kp2aLog.Log("Invalid OneDrive location " + ioc.Path +
                            ". Note that SprEnging expressions like {DB_PATH} are not supported with OneDrive!");
                return(ProtocolId + "://(invalid)");
            }
        }
Beispiel #2
0
        private FileDescription GetFileDescription(OneDrive2ItemLocation <OneDrive2PrefixContainerType> path, DriveItem i)
        {
            FileDescription e = new FileDescription();

            if (i.Size != null)
            {
                e.SizeInBytes = (long)i.Size;
            }
            else if ((i.RemoteItem != null) && (i.RemoteItem.Size != null))
            {
                e.SizeInBytes = (long)i.RemoteItem.Size;
            }

            e.DisplayName = i.Name;
            e.CanRead     = e.CanWrite = true;
            e.Path        = path.ToString();
            if (i.LastModifiedDateTime != null)
            {
                e.LastModified = i.LastModifiedDateTime.Value.LocalDateTime;
            }
            else if ((i.RemoteItem != null) && (i.RemoteItem.LastModifiedDateTime != null))
            {
                e.LastModified = i.RemoteItem.LastModifiedDateTime.Value.LocalDateTime;
            }
            e.IsDirectory = (i.Folder != null) || ((i.RemoteItem != null) && (i.RemoteItem.Folder != null));
            return(e);
        }
Beispiel #3
0
        private async Task <IGraphServiceClient> TryGetMsGraphClient(String path, bool tryConnect)
        {
            String userId = OneDrive2ItemLocation <OneDrive2PrefixContainerType> .FromString(path).User.Id;

            logDebug("TryGetMsGraphClient for " + userId);
            if (mClientByUser.ContainsKey(userId))
            {
                logDebug("TryGetMsGraphClient found user " + userId);
                GraphServiceClientWithState clientWithState = mClientByUser[userId];
                if (!(clientWithState.RequiresUserInteraction || (clientWithState.TokenExpiryDate < DateTime.Now) ||
                      (clientWithState.Client == null)))
                {
                    logDebug("TryGetMsGraphClient returning client");
                    return(clientWithState.Client);
                }
                else
                {
                    logDebug("not returning client because " + clientWithState.RequiresUserInteraction + " " +
                             (clientWithState.TokenExpiryDate < DateTime.Now) + " " + (clientWithState.Client == null));
                }
            }
            if (tryConnect)
            {
                logDebug("trying to connect...");
                if (await TryLoginSilent(path) != null)
                {
                    logDebug("trying to connect ok");
                    return(mClientByUser[userId].Client);
                }
                logDebug("trying to connect failed");
            }
            logDebug("TryGetMsGraphClient for " + userId + " returns null");
            return(null);
        }
Beispiel #4
0
        private async Task <string> TryLoginSilent(string iocPath)
        {
            IAccount account = null;

            try
            {
                if (IsConnected(iocPath))
                {
                    return(iocPath);
                }
                String userId = OneDrive2ItemLocation <OneDrive2PrefixContainerType> .FromString(iocPath).User?.Id;

                logDebug("needs acquire token");
                logDebug("trying silent login " + iocPath);

                account = Task.Run(async() => await _publicClientApp.GetAccountAsync(userId)).Result;
                logDebug("getting user ok.");
            }
            catch (Exception e)
            {
                logDebug(e.ToString());
            }
            if (account != null)
            {
                try
                {
                    logDebug("AcquireTokenSilent...");
                    AuthenticationResult authResult = await _publicClientApp.AcquireTokenSilent(Scopes, account)
                                                      .ExecuteAsync();

                    logDebug("AcquireTokenSilent ok.");
                    BuildClient(authResult);

                    /*User me = await graphClient.Me.Request().WithForceRefresh(true).GetAsync();
                     * logDebug("received name " + me.DisplayName);*/

                    return(BuildRootPathForUser(authResult));
                }
                catch (MsalUiRequiredException ex)
                {
                    GraphServiceClientWithState clientWithState = new GraphServiceClientWithState()
                    {
                        Client = null,
                        RequiresUserInteraction = true
                    };


                    mClientByUser[account.HomeAccountId.Identifier] = clientWithState;
                    logDebug("ui required");
                    return(null);
                }
                catch (Exception ex)
                {
                    logDebug("silent login failed: " + ex.ToString());
                    return(null);
                }
            }
            return(null);
        }
        private IGraphServiceClient tryGetMsGraphClient(String path)
        {
            String userId = OneDrive2ItemLocation <OneDrive2PrefixContainerType> .FromString(path).User.Id;

            if (mClientByUser.ContainsKey(userId))
            {
                return(mClientByUser[userId]);
            }
            return(null);
        }
Beispiel #6
0
            public OneDrive2ItemLocation <OneDrive2PrefixContainerType> BuildShare(string id, string name, string webUrl, string driveId)
            {
                OneDrive2ItemLocation <OneDrive2PrefixContainerType> copy = OneDrive2ItemLocation <OneDrive2PrefixContainerType> .FromString(this.ToString());

                copy.Share.Id     = id;
                copy.Share.Name   = name;
                copy.Share.WebUrl = webUrl;
                copy.DriveId      = driveId;

                return(copy);
            }
Beispiel #7
0
            public OneDrive2ItemLocation <OneDrive2PrefixContainerType> BuildLocalChildLocation(string name, string id, string parentReferenceDriveId)
            {
                //copy this:
                OneDrive2ItemLocation <OneDrive2PrefixContainerType> copy = OneDrive2ItemLocation <OneDrive2PrefixContainerType> .FromString(this.ToString());

                copy.LocalPath.Add(new Item {
                    Name = name, Id = id
                });
                copy.DriveId = parentReferenceDriveId;
                return(copy);
            }
Beispiel #8
0
            public static OneDrive2ItemLocation <OneDrive2PrefixContainerType> RootForUser(string accountUsername, string accountHomeAccountId)
            {
                OneDrive2ItemLocation <OneDrive2PrefixContainerType> loc = new OneDrive2ItemLocation <OneDrive2PrefixContainerType>
                {
                    User =
                    {
                        Id   = accountHomeAccountId,
                        Name = accountUsername
                    }
                };

                return(loc);
            }
Beispiel #9
0
        private async Task <List <FileDescription> > ListShares(OneDrive2ItemLocation <OneDrive2PrefixContainerType> parentPath, IGraphServiceClient client)
        {
            List <FileDescription> result = new List <FileDescription>();


            DriveItem root = await client.Me.Drive.Root.Request().GetAsync();

            FileDescription myEntry = GetFileDescription(parentPath.BuildShare("me", "me", "me", root.ParentReference?.DriveId), root);

            myEntry.DisplayName = MyOneDriveDisplayName;

            result.Add(myEntry);

            if (!CanListShares)
            {
                return(result);
            }



            IDriveSharedWithMeCollectionPage sharedWithMeCollectionPage = await client.Me.Drive.SharedWithMe().Request().GetAsync();

            while (true)
            {
                IList <DriveItem> sharedWithMeItems = sharedWithMeCollectionPage.CurrentPage;
                if (!sharedWithMeItems.Any())
                {
                    break;
                }

                foreach (DriveItem i in sharedWithMeItems)
                {
                    FileDescription sharedFileEntry = GetFileDescription(parentPath.BuildShare(i.Id, i.Name, i.WebUrl, i.ParentReference?.DriveId), i);
                    result.Add(sharedFileEntry);
                }
                var b = sharedWithMeCollectionPage.NextPageRequest;
                if (b == null)
                {
                    break;
                }
                sharedWithMeCollectionPage = await b.GetAsync();
            }
            return(result);
        }
        private PathItemBuilder GetPathItemBuilder(String path)
        {
            PathItemBuilder result = new PathItemBuilder(SpecialFolder);


            result.itemLocation = OneDrive2ItemLocation <OneDrive2PrefixContainerType> .FromString(path);

            if (string.IsNullOrEmpty(result.itemLocation.User?.Name))
            {
                throw new Exception("path does not contain user");
            }
            result.client = null;
            if (!mClientByUser.TryGetValue(result.itemLocation.User.Id, out result.client))
            {
                throw new Exception("failed to get client for " + result.itemLocation.User.Id);
            }

            return(result);
        }
Beispiel #11
0
        private async Task <IGraphServiceClient> TryGetMsGraphClient(String path, bool tryConnect)
        {
            String userId = OneDrive2ItemLocation <OneDrive2PrefixContainerType> .FromString(path).User.Id;

            if (mClientByUser.ContainsKey(userId))
            {
                GraphServiceClientWithState clientWithState = mClientByUser[userId];
                if (!(clientWithState.RequiresUserInteraction || (clientWithState.TokenExpiryDate < DateTime.Now) || (clientWithState.Client == null)))
                {
                    return(clientWithState.Client);
                }
            }
            if (tryConnect)
            {
                if (await TryLoginSilent(path) != null)
                {
                    return(mClientByUser[userId].Client);
                }
            }
            return(null);
        }
Beispiel #12
0
        private async Task <PathItemBuilder> GetPathItemBuilder(String path)
        {
            PathItemBuilder result = new PathItemBuilder(SpecialFolder);


            result.itemLocation = OneDrive2ItemLocation <OneDrive2PrefixContainerType> .FromString(path);

            if (string.IsNullOrEmpty(result.itemLocation.User?.Name))
            {
                throw new Exception("path does not contain user");
            }

            result.client = await TryGetMsGraphClient(path, true);

            if (result.client == null)
            {
                throw new Exception("Failed to connect or authenticate to OneDrive!");
            }


            return(result);
        }
Beispiel #13
0
 string BuildRootPathForUser(AuthenticationResult res)
 {
     return(OneDrive2ItemLocation <OneDrive2PrefixContainerType> .RootForUser(res.Account.Username, res.Account.HomeAccountId.Identifier).ToString());
 }
        public async void OnStart(IFileStorageSetupActivity activity)
        {
            if (activity.ProcessName.Equals(FileStorageSetupDefs.ProcessNameFileUsageSetup))
            {
                activity.State.PutString(FileStorageSetupDefs.ExtraPath, activity.Ioc.Path);
            }

            IAccount account = null;

            try
            {
                String userId = OneDrive2ItemLocation <OneDrive2PrefixContainerType> .FromString(activity.Ioc.Path).User?.Id;

                if (mClientByUser.ContainsKey(userId))
                {
                    finishActivityWithSuccess(activity);
                    return;
                }

                logDebug("needs acquire token");
                logDebug("trying silent login " + activity.Ioc.Path);

                account = Task.Run(async() => await _publicClientApp.GetAccountAsync(userId)).Result;
                logDebug("getting user ok.");
            }
            catch (Exception e)
            {
                logDebug(e.ToString());
            }
            if (account != null)
            {
                try
                {
                    logDebug("AcquireTokenSilent...");
                    AuthenticationResult authResult = await _publicClientApp.AcquireTokenSilent(Scopes, account)
                                                      .ExecuteAsync();

                    logDebug("AcquireTokenSilent ok.");
                    var graphClient = buildClient(authResult);

                    /*User me = await graphClient.Me.Request().WithForceRefresh(true).GetAsync();
                     * logDebug("received name " + me.DisplayName);*/

                    finishActivityWithSuccess(activity, authResult);
                    return;
                }
                catch (MsalUiRequiredException ex)
                {
                    logDebug("ui required");
                }
            }
            try
            {
                logDebug("try interactive");
                AuthenticationResult res = await _publicClientApp.AcquireTokenInteractive(Scopes)
                                           .WithParentActivityOrWindow((Activity)activity)
                                           .ExecuteAsync();

                logDebug("ok interactive");
                buildClient(res);
                finishActivityWithSuccess(activity, res);
            }
            catch (Exception e)
            {
                logDebug("authenticating not successful: " + e);
                Intent data = new Intent();
                data.PutExtra(FileStorageSetupDefs.ExtraErrorMessage, "authenticating not successful");
                ((Activity)activity).SetResult(Result.Canceled, data);
                ((Activity)activity).Finish();
            }
        }
Beispiel #15
0
        private string GetFilename(string path)
        {
            string localPath = "/" + OneDrive2ItemLocation <OneDrive2PrefixContainerType> .FromString(path).LocalPathString;

            return(localPath.Substring(localPath.LastIndexOf("/", StringComparison.Ordinal) + 1));
        }
Beispiel #16
0
 public string GetFileExtension(IOConnectionInfo ioc)
 {
     return(UrlUtil.GetExtension(OneDrive2ItemLocation <OneDrive2PrefixContainerType> .FromString(ioc.Path).LocalPathString));
 }
Beispiel #17
0
 public IOConnectionInfo GetParentPath(IOConnectionInfo ioc)
 {
     return(IOConnectionInfo.FromPath(OneDrive2ItemLocation <OneDrive2PrefixContainerType> .FromString(ioc.Path).Parent.ToString()));
 }
Beispiel #18
0
            public static OneDrive2ItemLocation <OneDrive2PrefixContainerType> FromString(string p)
            {
                if ((p == null) || (p == (new OneDrive2PrefixContainerType()).Onedrive2Prefix))
                {
                    return(new OneDrive2ItemLocation <OneDrive2PrefixContainerType>());
                }

                if (!p.StartsWith((new OneDrive2PrefixContainerType()).Onedrive2Prefix))
                {
                    throw new Exception("path not starting with prefix!");
                }
                if (!p.Contains("?"))
                {
                    throw new Exception("not found postfix");
                }
                var lengthParts = p.Split("?");

                p = lengthParts[0];
                if (int.Parse(lengthParts[1]) != p.Length)
                {
                    throw new Exception("Invalid length postfix in " + p);
                }

                p = p.Substring((new OneDrive2PrefixContainerType()).Onedrive2Prefix.Length);
                if (p == "")
                {
                    return(new OneDrive2ItemLocation <OneDrive2PrefixContainerType>());
                }
                OneDrive2ItemLocation <OneDrive2PrefixContainerType> result = new OneDrive2ItemLocation <OneDrive2PrefixContainerType>();
                var parts = p.Split("\\");

                if (parts.Length != 7)
                {
                    throw new Exception("Wrong number of parts in path " + p + " (" + parts.Length + ")");
                }
                result.User.Id      = Decode(parts[0]);
                result.User.Name    = Decode(parts[1]);
                result.Share.Id     = Decode(parts[2]);
                result.Share.Name   = Decode(parts[3]);
                result.Share.WebUrl = Decode(parts[4]);
                string localPath = Decode(parts[5]);

                if (localPath != "")
                {
                    var localPathParts = localPath.Split("/");
                    foreach (var lpp in localPathParts)
                    {
                        var lppsubParts = lpp.Split(":");
                        if (lppsubParts.Length != 2)
                        {
                            throw new Exception("Wrong number of subparts in in path " + p + ", " + lppsubParts);
                        }
                        result.LocalPath.Add(new Item {
                            Id = Decode(lppsubParts[0]), Name = Decode(lppsubParts[1])
                        });
                    }
                }
                result.DriveId = Decode(parts[6]);

                return(result);
            }