예제 #1
0
        /// <summary>
        /// This method is called by the JavaScript on the home page to activate the data robot
        /// </summary>
        /// <param name="driveId"></param>
        /// <returns></returns>
        public async Task <IHttpActionResult> ActivateRobot(string driveId)
        {
            // Make sure we still have a user signed in before we do anything (we'll need this to get auth tokens for MS Graph)
            var signedInUserId = AuthHelper.GetUserId();

            if (string.IsNullOrEmpty(signedInUserId))
            {
                return(Ok(new DataRobotSetup {
                    Success = false, Error = "User needs to sign in."
                }));
            }

            // Setup a Microsoft Graph client for calls to the graph
            var client = GetGraphClient();

            // Configure the document library with the custom columns, if they don't already exist.
            try
            {
                await ProvisionDocumentLibraryAsync(driveId, client);
            }
            catch (Exception ex)
            {
                return(Ok(new DataRobotSetup {
                    Success = false, Error = $"Unable to provision the selected document library: {ex.Message}"
                }));
            }

            // Check to see if this user already has a subscription, so we avoid duplicate subscriptions (this sample only allows a user to hook up the data robot to a single document library)
            var storedState  = StoredSubscriptionState.FindUser(signedInUserId, AzureTableContext.Default.SyncStateTable);
            var subscription = await CreateOrRefreshSubscriptionAsync(driveId, client, signedInUserId, storedState?.SubscriptionId);

            var results = new DataRobotSetup {
                SubscriptionId = subscription.Id
            };

            if (storedState == null)
            {
                storedState = StoredSubscriptionState.CreateNew(subscription.Id, driveId);
                storedState.SignInUserId = signedInUserId;
            }

            // Catch up our delta link so we only start working on files modified starting now
            var latestDeltaResponse = await client.Drives[driveId].Root.Delta("latest").Request().GetAsync();

            storedState.LastDeltaToken = latestDeltaResponse.AdditionalData["@odata.deltaLink"] as string;

            // Once we have a subscription, then we need to store that information into our Azure Table
            storedState.Insert(AzureTableContext.Default.SyncStateTable);

            results.Success            = true;
            results.ExpirationDateTime = subscription.ExpirationDateTime;

            return(Ok(results));
        }
        public async Task <IHttpActionResult> ActivateRobot()
        {
            // Setup a Microsoft Graph client for calls to the graph
            string             graphBaseUrl = SettingsHelper.MicrosoftGraphBaseUrl;
            GraphServiceClient client       = new GraphServiceClient(new DelegateAuthenticationProvider(async(req) =>
            {
                // Get a fresh auth token
                var authToken = await AuthHelper.GetUserAccessTokenSilentAsync(graphBaseUrl);
                req.Headers.TryAddWithoutValidation("Authorization", $"Bearer {authToken.AccessToken}");
            }));

            // Get an access token and signedInUserId
            AuthTokens tokens = null;

            try
            {
                tokens = await AuthHelper.GetUserAccessTokenSilentAsync(graphBaseUrl);
            }
            catch (Exception ex)
            {
                return(Ok(new DataRobotSetup {
                    Success = false, Error = ex.Message
                }));
            }

            // Check to see if this user is already wired up, so we avoid duplicate subscriptions
            var robotSubscription = StoredSubscriptionState.FindUser(tokens.SignInUserId, AzureTableContext.Default.SyncStateTable);

            var notificationSubscription = new Subscription()
            {
                ChangeType         = "updated",
                NotificationUrl    = SettingsHelper.NotificationUrl,
                Resource           = "/me/drive/root",
                ExpirationDateTime = DateTime.UtcNow.AddDays(3),
                ClientState        = "SecretClientState"
            };

            Subscription createdSubscription = null;

            if (null != robotSubscription)
            {
                // See if our existing subscription can be extended to today + 3 days
                try
                {
                    createdSubscription = await client.Subscriptions[robotSubscription.SubscriptionId].Request().UpdateAsync(notificationSubscription);
                }
                catch { }
            }

            if (null == createdSubscription)
            {
                // No existing subscription or we failed to update the existing subscription, so create a new one
                createdSubscription = await client.Subscriptions.Request().AddAsync(notificationSubscription);
            }

            var results = new DataRobotSetup()
            {
                SubscriptionId = createdSubscription.Id
            };

            if (robotSubscription == null)
            {
                robotSubscription = StoredSubscriptionState.CreateNew(createdSubscription.Id);
                robotSubscription.SignInUserId = tokens.SignInUserId;
            }

            // Get the latest delta URL
            var latestDeltaResponse = await client.Me.Drive.Root.Delta("latest").Request().GetAsync();

            robotSubscription.LastDeltaToken = latestDeltaResponse.AdditionalData["@odata.deltaLink"] as string;

            // Once we have a subscription, then we need to store that information into our Azure Table
            robotSubscription.Insert(AzureTableContext.Default.SyncStateTable);

            results.Success            = true;
            results.ExpirationDateTime = createdSubscription.ExpirationDateTime;

            return(Ok(results));
        }