public async Task <List <MediaItem> > GetAllMediaItemsAsync() { List <MediaItem> items = new List <MediaItem>(); using (var photoService = new PhotosLibraryService(new BaseClientService.Initializer() { HttpClientInitializer = _credential, ApplicationName = _applicationName })) { string nextPageToken = string.Empty; do { var searchRequest = photoService.MediaItems.Search(new SearchMediaItemsRequest() { PageSize = 100, PageToken = nextPageToken }); var result = await searchRequest.ExecuteAsync(); items.AddRange(result.MediaItems); nextPageToken = result.NextPageToken; }while (nextPageToken != null); } return(items); }
public MyImage(ILogger logger, PhotosLibraryService photoService, FileInfo imgFile) { this._logger = logger; this.service = photoService; this.mediaFile = imgFile; this.UploadStatus = UploadStatusEnum.NotStarted; }
private static (PhotosLibraryService, string) PrepareService() { UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = ClientId, ClientSecret = ClientSecret }, new[] { PhotosLibraryService .Scope.Photoslibrary, PhotosLibraryService.Scope .PhotoslibrarySharing }, "user", CancellationToken.None, new FileDataStore("BlogUploader.PhotosLibraryService")) .Result; // UserCredential credential = // Util.Cache(() => // { // // }, nameof(credential)); var serv = new PhotosLibraryService(new BaseClientService.Initializer { HttpClientInitializer = credential }); return (serv, credential.Token.AccessToken); }
public MyAlbum(ILogger logger, PhotosLibraryService service, string albumTitle, DirectoryInfo dirInfo) { this._logger = logger; this.service = service; this.albumTitle = albumTitle; this.dirInfo = dirInfo; this.UploadStatus = UploadStatus.NotStarted; }
/// <summary> /// Upload photo to Google Photos. /// API guide for media upload: /// https://developers.google.com/photos/library/guides/upload-media /// /// The implementation is inspired by this post due to limitations in the Google Photos API missing a method for content upload, /// but instead of System.Net.HttpClient it has been rewritten to use Google Photo's HTTP Client as it the has the Bearer Token already handled. /// https://stackoverflow.com/questions/51576778/upload-photos-to-google-photos-api-error-500 /// </summary> /// <param name="photo"></param> /// <returns>UploadToken from Google Photos. Null is returned if upload was not succesful.</returns> private string UploadMediaFile(PhotosLibraryService photoService) { string newUploadToken = null; try { using (var fileStream = mediaFile.OpenRead()) { //Create byte array to store the image for transfer byte[] pixels = new byte[fileStream.Length]; //Read image into the pixels byte array fileStream.Read(pixels, 0, (int)fileStream.Length); //Set http headers per Google Photos API requirement //https://developers.google.com/photos/library/guides/upload-media var httpContent = new ByteArrayContent(pixels); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); httpContent.Headers.Add("X-Goog-Upload-File-Name", NameASCII); httpContent.Headers.Add("X-Goog-Upload-Protocol", "raw"); //Object to store response HttpResponseMessage mediaResponse = null; try { //Send HTTP Post request mediaResponse = photoService.HttpClient.PostAsync(PhotosLibraryPasebath, httpContent).Result; } catch (Exception ex) { _logger.LogError(ex, "Exception occured during file posting. Inner Exception: {0}", ex.InnerException.ToString()); } if (mediaResponse is null) { _logger.LogDebug("mediaResponse is null"); } else if (mediaResponse.IsSuccessStatusCode) { newUploadToken = mediaResponse.Content.ReadAsStringAsync().Result; } else { _logger.LogWarning("Upload Media Response. Status Code: {0}. Reason Phrase: {1}", mediaResponse.StatusCode, mediaResponse.ReasonPhrase); } } } catch (Exception e) { _logger.LogError(e, "Upload of Image stream failed"); throw; } //Returning the new UploadToken, or if none will return null. return(newUploadToken); }
public static void Initialize() { service = ServiceHandler.GetPhotosLibraryService(); if (service is null) { throw new Exception("Initialize of Google Photos API Authentication failed"); } }
public AlbumViewModel(PhotosLibraryService service, Album albumSelected = null) { Title = albumSelected?.Name; AlbumSelected = albumSelected; this.service = service; LoadItemsCommand = new Command(async() => await ExecuteLoadMediaItemsCommand()); AddItemsCommand = new Command(async() => await ExecuteAddMediaItemsCommand()); MediaItemsCollection = new ObservableCollection <PhotoItem>(); }
public bool Initialize() { service = authenticationService.GetPhotosLibraryService(); driveService = authenticationService.GetDriveService(); if (service is null || driveService is null) { logger.LogCritical("Initialize of Google Photos API Authentication failed"); return(false); } return(true); }
public static bool Initialize(ILogger logger) { _logger = logger; service = ServiceHandler.GetPhotosLibraryService(); if (service is null) { _logger.LogCritical("Initialize of Google Photos API Authentication failed"); return(false); } return(true); }
public MyImage(ILogger logger, PhotosLibraryService photoService, FileInfo imgFile) { this._logger = logger; this.service = photoService; this.mediaFile = imgFile; this.UploadStatus = UploadStatus.NotStarted; this.ImageMediaType = GetMediaType(); if (IsPhoto) { using (var fileStream = mediaFile.OpenRead()) { imageInfo = Image.Identify(fileStream); } } }
public static PhotosLibraryService GetPhotosLibraryService() { if (credential == null) { Authenticate(); } // Create Google Photos API service. var service = new PhotosLibraryService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); return(service); }
private static void UploadPhotos(string postPath, PhotosLibraryService photosService, string accessToken, string postPathName, string[] imageFilenames) { var albums = photosService.Albums.List().Execute(); if (albums.Albums.Any(a => a.Title == postPathName && a.MediaItemsCount == imageFilenames.Length)) { "Found existing album with same photo count, skipping".Dump(); return; } var albumRq = new CreateAlbumRequest {Album = new Album {Title = postPathName}}; var response = photosService.Albums.Create(albumRq).Execute().Dump("Created album"); var photosRq = new BatchCreateMediaItemsRequest { AlbumId = response.Id, NewMediaItems = new List<NewMediaItem>() }; var shareRq = new ShareAlbumRequest { SharedAlbumOptions = new SharedAlbumOptions {IsCollaborative = false, IsCommentable = false} }; var shareResp = photosService.Albums.Share(shareRq, photosRq.AlbumId).Execute().Dump(); shareResp.Dump("Shared album"); foreach (var imageFilename in imageFilenames) { var imagePath = Path.Combine(Path.GetDirectoryName(postPath), imageFilename); var uploadId = UploadImage(imagePath, accessToken); photosRq.NewMediaItems.Add(new NewMediaItem { SimpleMediaItem = new SimpleMediaItem {UploadToken = uploadId} }); } var addedPhoto = photosService.MediaItems.BatchCreate(photosRq).Execute().Dump("Uploaded photos"); }
private static void ProcessOnePost(string postPath, PhotosLibraryService photosService, string accessToken) { var postPathName = Path.GetFileNameWithoutExtension(postPath); var imageFilenames = GetImagesInFile(postPath); if (imageFilenames.Any()) { imageFilenames.Length.Dump("Found images to process "); if (_uploadPhotos) { "Starting upload of the photos".Dump(); UploadPhotos(postPath, photosService, accessToken, postPathName, imageFilenames); } if (_getFinalUrls) { var finalUrls = GetFinalUrls(postPathName); if (changePostUrls) { var i = 0; if (imageFilenames.Length != finalUrls.Length) { throw new Exception("Image count mismatch"); } var postText = File.ReadAllText(postPath); foreach (var imageFilename in imageFilenames) { postText = postText.Replace(imageFilename, finalUrls[i]); i++; } File.WriteAllText(postPath, postText); } } } }
/// <summary> /// Upload photo to Google Photos. /// API guide for media upload: /// https://developers.google.com/photos/library/guides/upload-media /// /// The implementation is inspired by this post due to limitations in the Google Photos API missing a method for content upload, /// but instead of System.Net.HttpClient it has been rewritten to use Google Photo's HTTP Client as it the has the Bearer Token already handled. /// https://stackoverflow.com/questions/51576778/upload-photos-to-google-photos-api-error-500 /// </summary> /// <param name="photo"></param> /// <returns></returns> private string UploadMediaFile(PhotosLibraryService photoService) { string newUploadToken = null; try { using (var fileStream = mediaFile.OpenRead()) { //Create byte array to store the image for transfer byte[] pixels = new byte[fileStream.Length]; //Read image into the pixels byte array fileStream.Read(pixels, 0, (int)fileStream.Length); var httpContent = new ByteArrayContent(pixels); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); httpContent.Headers.Add("X-Goog-Upload-File-Name", NameASCII); httpContent.Headers.Add("X-Goog-Upload-Protocol", "raw"); HttpResponseMessage mediaResponse = photoService.HttpClient.PostAsync("https://photoslibrary.googleapis.com/v1/uploads", httpContent).Result; if (mediaResponse.IsSuccessStatusCode) { newUploadToken = mediaResponse.Content.ReadAsStringAsync().Result; } } } catch (Exception e) { _logger.LogError(e, "Upload of Image stream failed"); throw; } photoService.HttpClient.DefaultRequestHeaders.Clear(); return(newUploadToken); }
public static void ListAlbums(PhotosLibraryService service) { Console.WriteLine(); Console.WriteLine("Fetching albums..."); Google.Apis.PhotosLibrary.v1.AlbumsResource.ListRequest request = service.Albums.List(); // List events. Google.Apis.PhotosLibrary.v1.Data.ListAlbumsResponse response = request.Execute(); Console.WriteLine("Albums:"); if (response.Albums != null && response.Albums.Count > 0) { bool morePages = true; while (response.Albums != null && response.Albums.Count > 0 && morePages) { foreach (var album in response.Albums) { string title = album.Title; Console.WriteLine($"> {title}"); } if (response.NextPageToken != null) { request.PageToken = response.NextPageToken; response = request.Execute(); } else { morePages = false; } } } else { Console.WriteLine("No albums found."); } }
public static void ListAlbums(PhotosLibraryService service, ILogger logger) { logger.LogInformation(""); logger.LogInformation("Fetching albums..."); Google.Apis.PhotosLibrary.v1.AlbumsResource.ListRequest request = service.Albums.List(); // List events. Google.Apis.PhotosLibrary.v1.Data.ListAlbumsResponse response = request.Execute(); logger.LogInformation("Albums:"); if (response.Albums != null && response.Albums.Count > 0) { while (response.Albums != null && response.Albums.Count > 0) { foreach (var albumresponse in response.Albums) { string title = albumresponse.Title; logger.LogInformation($"> {title}"); } if (response.NextPageToken != null) { request.PageToken = response.NextPageToken; response = request.Execute(); } else { break; } } } else { logger.LogInformation("No albums found."); } }
public MyImage(PhotosLibraryService photoService, Album album, FileInfo imgFile) { this.service = photoService; this.album = album; this.imgFile = imgFile; }
//Not in viewmodel cos Navigation available only for content page and we need to create Browser view to show //in authentication process private async Task Run() { var folders = Environment.SpecialFolder.ApplicationData; viewModel.IsBusy = true; viewModel.PhotoCollection.Clear(); this.Appearing -= StartLoad; try { //var responcePage = new ResponcePage(); //var unused = Navigation.PushModalAsync(responcePage); var browser = new EmbeddedBrowser("Login to google"); browser.Cancelled += (s, evt) => { Navigation.PopModalAsync(); }; var unused = Navigation.PushModalAsync(browser); var currdir = DependencyService.Get <ICurrentDir>().GetCurrent(); // var currdir = "/opt/usr/apps/org.tizen.example.TizenXamlApp1.TV/res/"; using (var stream = new FileStream(currdir + "client_secrets.json", FileMode.Open, FileAccess.Read)){ credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { PhotosLibraryService.Scope.Photoslibrary }, "user", CancellationToken.None, codeReceiver : new TizenLocalServerCodeReceiver { EmbeddedBrowser = browser }); } unused = Navigation.PopModalAsync(); } catch (Exception e) { Console.WriteLine(e); throw; } // Create the service. service = new PhotosLibraryService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "PhotosViewerTizen", }); var request = service.SharedAlbums.List(); request.PageSize = 50; try { var bookshelves = await request.ExecuteAsync(); var she = bookshelves.SharedAlbums; foreach (var album in she) { if (album != null && album.Title != null) { string test = album.Title; await viewModel.AddOne(album); } } } catch (Exception e) { Console.WriteLine(e); throw; } finally { viewModel.IsBusy = false; TopLabel.Text = "My Albums"; this.Appearing += StartLoad; } }
public MyAlbum(PhotosLibraryService service, string albumTitle, DirectoryInfo dirInfo) { this.service = service; this.albumTitle = albumTitle; this.dirInfo = dirInfo; }