示例#1
0
        private async Task ProcessChangesToUserFolder(OneDriveUser user, SignalR.NotificationService notificationService)
        {
            var client = await SubscriptionController.GetOneDriveClientAsync(user);

            List <string> filesChanged = new List <string>();

            var knownFiles = user.FileNameAndETag;
            var request    = client.Drive.Special["approot"].Children.Request();

            while (request != null)
            {
                var items = await request.GetAsync();

                // Pull out the changes we're interested in

                foreach (var item in items)
                {
                    string etag;
                    if (knownFiles.TryGetValue(item.Name, out etag))
                    {
                        if (etag == item.ETag)
                        {
                            continue;
                        }
                    }
                    knownFiles[item.Name] = item.ETag;
                    filesChanged.Add(item.Name);
                }
                request = items.NextPageRequest;
            }

            notificationService.SendFileChangeNotification(filesChanged);
        }
示例#2
0
        public async Task<ActionResult> Redirect(string code, string state)
        {
            OAuthHelper helper;
            try {
                helper = OAuthHelper.HelperForService(state, this.RedirectUri);
            }
            catch (ArgumentException ex)
            {
                ViewBag.Message = ex.Message;
                return View("Error");
            }

            string discoveryResource = "https://api.office.com/discovery/";
            var token = await helper.RedeemAuthorizationCodeAsync(code, discoveryResource);
            if (null == token)
            {
                ViewBag.Message = "Invalid response from token service. Unable to login. Try again later.";
                return View("Error");
            }

            OneDriveUser user = new OneDriveUser(token, helper, discoveryResource);
            user.SetResponseCookie(whois.Response);

            return Redirect(Url.Action("Index", "Subscription"));
        }
示例#3
0
        public AppModel(string specialRedirectUri = null)
        {
            var pca = PublicClientApplicationBuilder.Create(App.MsalClientID)
                      .WithRedirectUri(specialRedirectUri ?? $"msal{App.MsalClientID}://auth")
                      .WithIosKeychainSecurityGroup("com.blenderfreaky.Pictua")
                      .WithParentActivityOrWindow(() => App.AuthParentWindow)
                      .Build();

            var logger = LoggerFactory.Create(options =>
                                              options.AddConsole());

            Client = Client.Create(FilePathConfig.Client, logger.CreateLogger <Client>());

            this.WhenAnyValue(x => x.IsSignedIn)
            .Where(x => x)
            .Subscribe(async _ =>
                       Server = await OneDriveServer.CreateAsync(OneDriveUser, FilePathConfig.Server, logger.CreateLogger <OneDriveServer>()).ConfigureAwait(false));

            Observable.Start(async() =>
            {
                OneDriveUser = OneDriveUser.Create(pca);

                await OneDriveUser.InitializeGraphClientAsync().ConfigureAwait(false);
                IsSignedIn = await OneDriveUser.SignInAsync(forceSilent: true).ConfigureAwait(false);
            });
        }
示例#4
0
        /// <summary>
        /// Use the discovery API to resolve the base URL for the OneDrive API
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        internal static async Task <string> LookupOneDriveUrl(OneDriveUser user)
        {
            if (user.ClientType == ClientType.Consumer)
            {
                return("https://api.onedrive.com/v1.0");
            }
            var accessToken = await user.GetAccessTokenAsync("https://api.office.com/discovery/");

            HttpClient         client  = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://api.office.com/discovery/v2.0/me/services");

            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
            request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            var response = await client.SendAsync(request);

            if (!response.IsSuccessStatusCode)
            {
                throw new InvalidOperationException("Unable to determine OneDrive URL: " + response.ReasonPhrase);
            }

            var services = JsonConvert.DeserializeObject <DiscoveryServiceResponse>(await response.Content.ReadAsStringAsync());

            var query = from s in services.Value
                        where s.Capability == "MyFiles" && s.ServiceApiVersion == "v2.0"
                        select s.ServiceEndpointUri;

            return(query.FirstOrDefault());
        }
        public ActionResult Index()
        {
            OneDriveUser user = OneDriveUser.UserForRequest(this.Request);

            ViewBag.ShowSignInButtons = (user == null);

            return(View());
        }
示例#6
0
        // Create webhook subscription
        public async Task <ActionResult> CreateSubscription()
        {
            #region Create OneDriveClient for current user
            OneDriveUser user = OneDriveUser.UserForRequest(this.Request);
            if (null == user)
            {
                return(Redirect(Url.Action("Index", "Home")));
            }
            var client = await GetOneDriveClientAsync(user);

            #endregion

            // Ensure the app folder is created first
            var appFolder = await client.Drive.Special["approot"].Request().GetAsync();

            // Create a subscription on the drive
            var notificationUrl = ConfigurationManager.AppSettings["ida:NotificationUrl"];

            Models.OneDriveSubscription subscription = new OneDriveSubscription
            {
                NotificationUrl = notificationUrl,
                ClientState     = "my client state"
            };
            FixPPESubscriptionBug(user, subscription);

            // Because the OneDrive SDK does not support OneDrive subscriptions natively yet,
            // we use BaseRequest to generate a request the SDK can understand. You could also use HttpClient
            var request = new BaseRequest(client.BaseUrl + "/drive/root/subscriptions", client)
            {
                Method      = "POST",
                ContentType = "application/json"
            };

            try
            {
                var subscriptionResponse = await request.SendAsync <Models.OneDriveSubscription>(subscription);

                if (null != subscriptionResponse)
                {
                    // Store the subscription ID so we can keep track of which subscriptions are tied to which users
                    user.SubscriptionId = subscriptionResponse.SubscriptionId;

                    Models.SubscriptionViewModel viewModel = new Models.SubscriptionViewModel {
                        Subscription = subscriptionResponse
                    };
                    return(View("Subscription", viewModel));
                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
            }

            return(View("Error"));
        }
示例#7
0
        public void OnedriveTest()
        {
            var user = new OneDriveUser(
                "token");

            user.RefreshAsync().GetAwaiter().GetResult();
            var files = user.GetFileRootAsync().GetAwaiter().GetResult();
            var root  = files.Root.GetChildrenAsync().GetAwaiter().GetResult();
            var sub   = root.First(v => v.Content.Type == FileType.FolderType).GetChildrenAsync().GetAwaiter().GetResult();

            Console.WriteLine(user.Username);
        }
示例#8
0
 private static void FixPPESubscriptionBug(OneDriveUser user, OneDriveSubscription subscription)
 {
     if (user.ClientType == ClientType.Business)
     {
         subscription.Scenarios = null;
     }
     else
     {
         subscription.SubscriptionExpirationDateTime = DateTime.Now.AddDays(3);
         subscription.ClientState = null;
     }
 }
示例#9
0
        /// <summary>
        /// Create a new instance of the OneDriveClient for the signed in user.
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        internal static async Task <OneDriveClient> GetOneDriveClientAsync(OneDriveUser user)
        {
            if (string.IsNullOrEmpty(user.OneDriveBaseUrl))
            {
                // Resolve the API URL for this user
                user.OneDriveBaseUrl = await LookupOneDriveUrl(user);
            }

            var client = new OneDriveClient(new AppConfig(), null, null, new OneDriveAccountServiceProvider(user), user.ClientType);
            await client.AuthenticateAsync();

            return(client);
        }
示例#10
0
        /// <summary>
        /// Delete the user's active subscription and then redirect to logout
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> DeleteSubscription()
        {
            OneDriveUser user = OneDriveUser.UserForRequest(this.Request);

            if (null == user)
            {
                return(Redirect(Url.Action("Index", "Home")));
            }

            if (!string.IsNullOrEmpty(user.SubscriptionId))
            {
                var client = await GetOneDriveClientAsync(user);

                // Because the OneDrive SDK does not support OneDrive subscriptions natively yet,
                // we use BaseRequest to generate a request the SDK can understand
                var request = new BaseRequest(client.BaseUrl + "/drive/root/subscriptions/" + user.SubscriptionId, client)
                {
                    Method = "DELETE"
                };

                try
                {
                    var response = await request.SendRequestAsync(null);

                    if (!response.IsSuccessStatusCode)
                    {
                        ViewBag.Message = response.ReasonPhrase;
                        return(View("Error"));
                    }
                    else
                    {
                        user.SubscriptionId = null;
                    }
                }
                catch (Exception ex)
                {
                    ViewBag.Message = ex.Message;
                    return(View("Error"));
                }
            }
            return(RedirectToAction("SignOut", "Account"));
        }
示例#11
0
 public ActionResult SignOut()
 {
     OneDriveUser.ClearResponseCookie(whois.Response);
     return Redirect(Url.Action("Index", "Home"));
 }