예제 #1
0
        static void Main(string[] args)
        {
            try
            {
                UserCredential credential;
                // Load client secrets.
                using (var stream =
                           new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
                {
                    /* The file token.json stores the user's access and refresh tokens, and is created
                     * automatically when the authorization flow completes for the first time. */
                    string credPath = "token.json";
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.FromStream(stream).Secrets,
                        Scopes,
                        "user",
                        CancellationToken.None,
                        new FileDataStore(credPath, true)).Result;
                    Console.WriteLine("Credential file saved to: " + credPath);
                }

                // Create Google Drive Activity API service.
                var service = new DriveActivityService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = ApplicationName
                });

                // Define parameters of request.
                QueryDriveActivityRequest requestData = new QueryDriveActivityRequest();
                requestData.PageSize = 10;
                ActivityResource.QueryRequest queryRequest = service.Activity.Query(requestData);

                // List activities.
                IList <DriveActivity> activities = queryRequest.Execute().Activities;
                Console.WriteLine("Recent activity:");
                if (activities == null || activities.Count == 0)
                {
                    Console.WriteLine("No activity.");
                    return;
                }
                foreach (var activity in activities)
                {
                    string        time    = GetTimeInfo(activity);
                    string        action  = GetActionInfo(activity.PrimaryActionDetail);
                    List <string> actors  = activity.Actors.Select(GetActorInfo).ToList();
                    List <string> targets = activity.Targets.Select(GetTargetInfo).ToList();
                    Console.WriteLine("{0}: {1}, {2}, {3}",
                                      time, Truncated(actors), action, Truncated(targets));
                }
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine(e.Message);
            }
예제 #2
0
        static void GdriveWorker()
        {
            UserCredential credential;

            using (var stream =
                       new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Drive Activity API service.
            var service = new DriveActivityService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // Define parameters of request.
            QueryDriveActivityRequest requestData = new QueryDriveActivityRequest();

            requestData.PageSize = 10;
            ActivityResource.QueryRequest queryRequest = service.Activity.Query(requestData);

            // List activities.
            IList <Google.Apis.DriveActivity.v2.Data.DriveActivity> activities = queryRequest.Execute().Activities;

            Console.WriteLine("Recent activity:");
            if (activities != null && activities.Count > 0)
            {
                foreach (var activity in activities)
                {
                    string        time    = getTimeInfo(activity);
                    string        action  = getActionInfo(activity.PrimaryActionDetail);
                    List <string> actors  = activity.Actors.Select(a => getActorInfo(a)).ToList();
                    List <string> targets = activity.Targets.Select(t => getTargetInfo(t)).ToList();
                    Console.WriteLine("{0}: {1}, {2}, {3}",
                                      time, truncated(actors), action, truncated(targets));
                }
            }
            else
            {
                Console.WriteLine("No activity.");
            }
        }
예제 #3
0
        /// <summary>Snippet for QueryDriveActivityAsync</summary>
        public async Task QueryDriveActivityRequestObjectAsync()
        {
            // Snippet: QueryDriveActivityAsync(QueryDriveActivityRequest, CallSettings)
            // Create client
            DriveActivityServiceClient driveActivityServiceClient = await DriveActivityServiceClient.CreateAsync();

            // Initialize request argument(s)
            QueryDriveActivityRequest request = new QueryDriveActivityRequest
            {
                ItemName = "",
                ConsolidationStrategy = new ConsolidationStrategy(),
                Filter = "",
            };
            // Make the request
            PagedAsyncEnumerable <QueryDriveActivityResponse, DriveActivity> response = driveActivityServiceClient.QueryDriveActivityAsync(request);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((DriveActivity item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((QueryDriveActivityResponse page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (DriveActivity item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <DriveActivity> singlePage = await response.ReadPageAsync(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (DriveActivity item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
        public DriveItem FindOrphanParent(string orphan_id)
        {
            QueryDriveActivityResponse response;
            QueryDriveActivityRequest  requestData = new QueryDriveActivityRequest();

            requestData.ItemName = orphan_id;
            requestData.PageSize = drive.PageSize;

            do
            {
                ActivityResource.QueryRequest queryRequest = service.Activity.Query(requestData);
                response = queryRequest.Execute();
                IList <Google.Apis.DriveActivity.v2.Data.DriveActivity> activities = response.Activities;

                if (activities != null && activities.Count > 0)
                {
                    foreach (var activity in activities)
                    {
                        try
                        {
                            // check that the item lost its parent without getting a new one --> orphan!
                            if (activity.PrimaryActionDetail.Move != null && activity.PrimaryActionDetail.Move.RemovedParents != null && activity.PrimaryActionDetail.Move.AddedParents == null)
                            {
                                DriveItem item = new DriveItem
                                {
                                    id           = activity.Targets[0].DriveItem.Name,
                                    title        = activity.Targets[0].DriveItem.Title,
                                    parent_id    = activity.PrimaryActionDetail.Move.RemovedParents[0].DriveItem.Name,
                                    parent_title = activity.PrimaryActionDetail.Move.RemovedParents[0].DriveItem.Title,
                                    isFile       = activity.Targets[0].DriveItem.DriveFile != null
                                };
                                return(item);
                            }
                        }
                        catch (Exception) { }
                    }
                }
                else
                {
                    break;
                }

                // set next request to get next page
                requestData.PageToken = response.NextPageToken;
            } while (response.NextPageToken != null && response.NextPageToken != "");
            throw new FileNotFoundException("No Activity found!");
        }
예제 #5
0
        /// <summary>Snippet for QueryDriveActivity</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void QueryDriveActivityRequestObject()
        {
            // Create client
            DriveActivityServiceClient driveActivityServiceClient = DriveActivityServiceClient.Create();
            // Initialize request argument(s)
            QueryDriveActivityRequest request = new QueryDriveActivityRequest
            {
                ItemName = "",
                ConsolidationStrategy = new ConsolidationStrategy(),
                Filter = "",
            };
            // Make the request
            PagedEnumerable <QueryDriveActivityResponse, DriveActivity> response = driveActivityServiceClient.QueryDriveActivity(request);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (DriveActivity item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (QueryDriveActivityResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (DriveActivity item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <DriveActivity> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (DriveActivity item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
        /// <summary>
        /// https://dzone.com/articles/working-with-the-google-drive-api-track-changes-in
        /// https://developers.google.com/drive/activity/v2/quickstart/dotnet
        /// </summary>
        /// <param name="subject"></param>
        /// <param name="ct"></param>
        /// <returns></returns>
        private async Task ObserveActivitiesAsync(Subject <IReadOnlyCollection <GoogleDriveActivity> > subject, CancellationToken ct)
        {
            var activityService = await GetDriveActivityServiceAsync().ConfigureAwait(false);

            string pageToken;

            do
            {
                var requestData = new QueryDriveActivityRequest {
                    PageSize = 10
                };
                var query    = activityService.Activity.Query(requestData);
                var response = await query.ExecuteAsync(ct).ConfigureAwait(false);

                var activities = response.Activities;
                if (activities == null || activities.Count == 0)
                {
                    Logger.Info("No activities");
                    subject.OnCompleted();
                    return;
                }

                var googleActivities = new List <GoogleDriveActivity>(activities.Count);
                foreach (var activity in activities)
                {
                    string        time        = GetTimeInfo(activity);
                    string        action      = GetActionInfo(activity.PrimaryActionDetail);
                    List <string> actors      = activity.Actors.Select(a => GetActorInfo(a)).ToList();
                    List <string> targetNames = activity.Targets.Select(t => GetTargetName(t)).ToList();
                    List <string> targetIds   = activity.Targets.Select(t => GetTargetId(t)).ToList();
                    var           ga          = new GoogleDriveActivity(Truncated(actors), action, Truncated(targetNames), Truncated(targetIds), null);
                    Logger.Info("New activity: " + ga);
                    googleActivities.Add(ga);
                }
                subject.OnNext(googleActivities);

                pageToken = response.NextPageToken;
            }while (pageToken != null && !ct.IsCancellationRequested);

            subject.OnCompleted();
        }
        public void GetSingleActivity(string item, bool getAllInfoInsideFolder = false)
        {
            QueryDriveActivityResponse response;
            QueryDriveActivityRequest  requestData = new QueryDriveActivityRequest();

            if (getAllInfoInsideFolder)
            {
                requestData.AncestorName = item; // gets all activity inside the folder
            }
            else
            {
                requestData.ItemName = item; // gets all activity from the item
            }

            requestData.PageSize = drive.PageSize;
            ActivityResource.QueryRequest queryRequest = service.Activity.Query(requestData);
            response = queryRequest.Execute();

            // List activities.
            IList <Google.Apis.DriveActivity.v2.Data.DriveActivity> activities = response.Activities;
        }