How To Create A Shared Album On Google Photos
1. Introduction
What you will build
In this codelab, you'll build a field trip app, Field Trippa, that enables users to share photos.
Learn how to use the Google Photos Library API to back a media sharing experience in your own application.
The app for this codelab was built using Flutter, Google's UI toolkit for building beautiful, natively compiled applications for mobile, web, and desktop from a single codebase. Learn more at https://flutter.dev.
What you'll learn
- How to use the Google Photos Library API to upload media and share albums
- How to use Google Sign-In in Flutter
- How to make Google API calls from Flutter
What you'll need
- Flutter development environment
- Two Google user accounts set up on different emulators or devices that have access to Google Photos, so you can test sharing between users
- An Android device, emulator or physical iOS device - the iOS simulator is not supported due to missing camera hardware
Overview over the Field Trip Gallery App - "Field Trippa"
In this codelab you will build an app to share photos for an excursion or field trip, built using the Google Photos Library API.
The user logs in using Google Sign-In and authorizes the application to use the Google Photos Library API.
Then, the user can create a trip
for uploading photos with a description. Each trip
can be shared with other members of the application, who can also contribute photos.
Under the hood, each trip
is stored as a shared album inside Google Photos. The app handles sharing and uploading to this album, but you can also share the album with others who do not have the app directly through a URL to Google Photos.
What would you like to learn from this codelab?
2. Download the Code
Download the source code for this codelab:
To clone the GitHub repository from the command line, use the following command:
git clone https://github.com/flutter/codelabs flutter-codelabs
The sample code is cloned into a flutter-codelabs
directory that contains the code for a collection of codelabs. The code for this codelab is in flutter-codelabs/photos-sharing
. You can also browse the code on GitHub.
The directory structure under flutter-codelabs/photos-sharing
contains the initial and the final steps. The starter code is in initial
, so locating the matching files is as easy as:
cd flutter-codelabs/photos-sharing/initial
If you want to skip forward, or see what something should look like after a step, look in the final
directory that contains the finished code for this codelab.
Open the initial code:
Open the directory flutter-codelabs/photos-sharing/initial
in your preferred Flutter IDE, for example VSCode or Android Studio with the Dart and Flutter plugins installed.
3. Run the App
Follow these steps to get your development environment set up, if you haven't developed with Flutter before.
To run the "Field Trippa" app click the "run" button in your development IDE, or use the following command from the root directory of the source code:
flutter run
You should see the "Connect with Google Photos" screen:
4. Set up the Google Photos Library API
The Google Photos Library API requires you to authenticate your users using OAuth 2.0. Users sign into the application and authorize it to interact with the API on their behalf.
You can find some additional troubleshooting tips at the end of this step.
Create a new Firebase project and register your app
Go to the Firebase console and select "+ Add Project". Enter a project name and select "Create Project" to continue. Do not follow any other steps in the Firebase console. Instead, return to this codelab and continue to the "Android" or "iOS" parts below to configure the application.
Android only: If you are running the app on Android, register an Android app:
Click the Android icon to open the Android app registration screen.
For package, enter: com.google.codelab.photos.sharing
Retrieve the signing certificate SHA-1 from your machine:
On Windows run the following command:
keytool -alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystore -list -v -storepass android
On Mac or Linux, run the following command:
keytool -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v -storepass android
Click "register app" to continue.
Download the google-service.json
file to your computer and move it into the directory "android/app/
". (Tip: In Android Studio, you can drag the downloaded file directly into the correct location in the project side panel.)
This file contains the project configuration for the Firebase and Google Developers project you have just set up.
(See the documentation for the package google_sign_in for details.)
You don't have to complete any other steps in the Firebase console. The Firebase SDK has already been added to the application.
iOS only: If you are running the app on iOS, register an iOS app in Firebase:
Click the iOS icon to open the iOS app registration screen.
For iOS bundle ID, enter: com.google.codelab.photos.sharing
Click "next" to continue.
Download the GoogleService-Info.plist
file to your computer.
Open the Flutter project in Xcode
Right click on Runner directory, select "Add Files to Runner" and select the GoogleService-Info.plist
file you have downloaded to add it to the Runner module.
Edit the source code of the file ios/Runner/Info.plist
and add the value of the property REVERSED_CLIENT_ID
from the file GoogleService-Info.plist
. Replace the entry at the bottom of the file:
ios/Runner/Info.plist
<!-- Google Sign-in Section --> <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleTypeRole</key> <string>Editor</string> <key>CFBundleURLSchemes</key> <array> <string>COPY_REVERSED_CLIENT_ID_HERE</string> </array> </dict> </array> <!-- End of the Google Sign-in Section -->
(See the documentation for the package google_sign_in for more details.)
Enable the Google Photos Library API
Open the API screen in the Google Developers console and enable the "Google Photos Library API". (You may have to select the Firebase project at the top of the screen first if the "enable" button is disabled.)
Open the OAuth consent screen configuration in the Google Developers console to add the Google Photos Library API scopes and your email address. (This configuration is required for the OAuth verification review for any scopes used by the Google Photos Library API.) You do not have to submit for verification, but you need to complete the form and save your response. This will enable the scopes for development and testing.
- Enter the "Application Name", for example
Field Trippa Codelab
- Select a "Support email address"
- Select "Add scope", then "manually add paste scopes" to enter the following scopes:
https://www.googleapis.com/auth/photoslibrary https://www.googleapis.com/auth/photoslibrary.sharing
- Select "Save"
- There is no need to submit for verification to continue with this codelab. This is only required when launching your application, but not for personal testing.
Run the app and sign in
Google Sign-In has already been implemented using the google_sign_in flutter package. This package requires the google-services.json
or GoogleService-Info.plist
files that you have already copied into the project.
Run the application again and select "Connect to Google Photos". You'll be prompted to select a user account and accept the authentication scopes.
If everything has been set up successfully, you'll see an empty list on the next screen.
Troubleshooting sign in
If you are having trouble signing into the application, here are a few things you can check:
Check that the device has Internet connectivity.
If you receive the error PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null)
, make sure that you have followed all steps in the section Enable the Google Photos Library API. You must add the Google Photos Library API scopes, enter a support email address and select save.
If you receive the error PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 12500: , null)
, make sure that you have added a support email address in the Firebase console. Open Firebase console and navigate to the project settings by selecting the gear icon next to your project title. Select an email address under support email on the general settings screen.
Check the signing certificate SHA-1 that is configured in the Firebase console. Does it match the output from the keytool command from the first step? Does it match the output from the command ./gradlew signingReport
when run in the android/
project? You may need to also include the signing certificate SHA-256 in the console.
Check the package name and iOS bundle ID that are configured in the Firebase console. This should be set to com.google.codelab.photos.sharing
Check the location of the configuration files you have downloaded from the Firebase console. For Android, the file should be copied to android/app/google-service.json
. For iOS it should be added to the Runner module.
You may need to enable Google as a sign-in provider for your Firebase project. Open the Firebase console and navigate to Authentication and Sign-in method. Ensure that Google is enabled.
5. Create an album
Before you implement the first API call to the Google Photos Library API, let's walk through the data architecture that the "Field Trippa" app uses.
App Architecture
- Each screen is implemented as a separate page:
- The
PhotosLibraryApiModel
describes the data model of the application and abstracts the Google Photos Library API calls away. - The HTTPS REST calls to the Library API are implemented in the
PhotosLibraryApiClient
. Each call provided by this class takes a*Request
object where you specify parameters and options for a call. - The Library API requires user authentication via OAuth2. The access token required to be included in all API calls is set directly by the google_sign_in package on the
PhotosLibraryApiClient
.
Implement the create albums API call
Each trip is stored as an album in Google Photos. When you select the "CREATE A TRIP ALBUM" button, you should prompt the user for the name of the trip and create a new album with this name as its title.
In create_trip_page.dart
, write the logic that makes a request to the Library API to create the album. Implement the _createTrip(...)
method at the end of the file to call the PhotosLibraryApiModel
with the name of the trip the user entered.
lib/pages/create_trip_page.dart
Future<void> _createTrip(BuildContext context) async { // Display the loading indicator. setState(() => _isLoading = true); await ScopedModel.of<PhotosLibraryApiModel>(context) .createAlbum(tripNameFormController.text); // Hide the loading indicator. setState(() => _isLoading = false); Navigator.pop(context); }
Implement the call to the Library API that creates the album. In the API model, implement the createAlbum(...)
method that takes the title of the album as a parameter. It makes a call to the PhotosLibraryApiClient
where the actual REST call is made.
lib/model/photos_library_api_model.dart
Future<Album?> createAlbum(String title) async { final album = await client!.createAlbum(CreateAlbumRequest.fromTitle(title)); updateAlbums(); return album; }
Implement the REST call to create the album in photos_library_api_client.dart
. Remember that the CreateAlbumRequest
already contains the title
property- required for this call.
The following encodes it as JSON and adds the authentication headers to authorize the request. Finally, return the album created by the API.
lib/photos_library_api/photos_library_api_client.dart
Future<Album> createAlbum(CreateAlbumRequest request) async { final response = await http.post( Uri.parse('https://photoslibrary.googleapis.com/v1/albums'), body: jsonEncode(request), headers: await _authHeaders, ); printError(response); return Album.fromJson(jsonDecode(response.body)); }
Try it out!
Deploy the app and select "+ Create Trip".
6. Only show your app's albums
You may have noticed that the trips list shows other albums from Google Photos that were not created by your app. (If you do not have any other albums in Google Photos and want to see this behaviour, open the Google Photos app and create an album. However, this is not required to continue in this codelab.)
Remember that each trip is stored as an album in Google Photos. However, it does not make sense to show any other albums from Google Photos that were created through other means - Field Trippa should only show trips that the app has created.
You can use the API to restrict the list of trips that are displayed to show only those created by the app.
Modify the method listAlbums()
method (NOT listSharedAlbums()
!) in photos_library_api_client.dart
. This method makes the REST call to retrieve a list of albums. Add the parameter excludeNonAppCreatedData=true
that restricts the returned data to exclude albums that were not created by this app.
lib/photos_library_api/photos_library_api_client.dart
Future<ListAlbumsResponse> listAlbums() async { final response = await http.get( Uri.parse('https://photoslibrary.googleapis.com/v1/albums?' 'pageSize=50&excludeNonAppCreatedData=true'), headers: await _authHeaders); ... }
Try it out!
The first page now only shows trips that were created by the app.
7. Upload Photos
The next step is to upload photos to a trip. The data is stored in your user's Google Photos account, so you don't have to worry about storage or processing the data yourself.
Taking a photo in Flutter
First, implement the method _getImage(...)
in the contribute photo dialog. This method is called when the user clicks the "+ADD PHOTO" button.
The following code uses the image_picker
package to take a photo, update the UI and call the API model to upload the image. (You'll implement this in the next step.) The _getImage(...)
call stores an upload token needed later to create the photo in Google Photos.
lib/components/contribute_photo_dialog.dart
Future _getImage(BuildContext context) async { // Use the image_picker package to prompt the user for a photo from their // device. final pickedImage = await (_imagePicker.getImage( source: ImageSource.camera, )); if (pickedImage == null) { // No image selected. return; } final pickedFile = File(pickedImage.path); // Store the image that was selected. setState(() { _image = pickedFile; _isUploading = true; }); // Make a request to upload the image to Google Photos once it was selected. final uploadToken = await ScopedModel.of<PhotosLibraryApiModel>(context) .uploadMediaItem(pickedFile); setState(() { // Once the upload process has completed, store the upload token. // This token is used together with the description to create the media // item later. _uploadToken = uploadToken; _isUploading = false; }); }
Implement Library API call to upload the image to get an upload token
Uploading photos and videos to the Library API is done in two steps:
- Upload the media bytes to receive an upload token
- Create a media item in the user's library from the upload token
Implement the REST request to upload media. You need to set some headers to specify the type of upload request and the filename. In the file photos_library_api_client.dart
implement the method uploadMediaItem(...)
where the file is uploaded, returning the upload token that the HTTP call returns:
lib/photos_library_api/photos_library_api_client.dart
Future<String> uploadMediaItem(File image) async { // Get the filename of the image final filename = path.basename(image.path); // Set up the headers required for this request. final headers = <String, String>{}; headers.addAll(await _authHeaders); headers['Content-type'] = 'application/octet-stream'; headers['X-Goog-Upload-Protocol'] = 'raw'; headers['X-Goog-Upload-File-Name'] = filename; // Make the HTTP request to upload the image. The file is sent in the body. final response = await http.post( Uri.parse('https://photoslibrary.googleapis.com/v1/uploads'), body: image.readAsBytesSync(), headers: await _authHeaders, ); printError(response); return response.body; }
Next, implement the creation of a media item in the user's library from the upload token.
Creating a media item requires the upload token, an optional description (for example, the caption of the photo or video) and the optional identifier of an album. Field Trippa always adds the uploaded photo directly to a trip album.
Implement the call to the photos_library_api_client
that calls mediaItems.batchCreate
with the upload token, description, and album ID. In the API model, implement the method createMediaItem(...)
that calls the Library API. This method returns a media item.
(The photos_library_client
for this call is already implemented.)
lib/model/photos_library_api_model.dart
Future<BatchCreateMediaItemsResponse?> createMediaItem( String uploadToken, String? albumId, String? description) async { // Construct the request with the token, albumId and description. final request = BatchCreateMediaItemsRequest.inAlbum(uploadToken, albumId, description); // Make the API call to create the media item. The response contains a // media item. final response = await client!.batchCreateMediaItems(request); // Print and return the response. print(response.newMediaItemResults?[0].toJson()); return response; }
Try it out!
Open the app and select a trip. Click contribute and select a photo that you have taken previously. Enter a description and select upload. The image should appear in the trip after a few seconds.
Open the album in the Google Photos app - you'll see the new image in the album of this trip.
8. Share albums with non-app users
So far you have implemented the functionality to create a trip and upload photos with a description into it. In the backend, each trip is stored as an album in Google Photos.
Next, you will share a trip with others who are not using your application.
Each trip is backed by an album in Google Photos, therefore you can 'share' an album via a URL and make it available to anyone who has this URL.
Albums are shared from the trip page when a share button at the top of the album is pressed.
Implement the asynchronous call _shareAlbum(...)
that calls to the model to share the album and then reloads the displayed album. By reloading the album, the shareInfo
property is propagated which contains the shareableUrl
that you'll show the user in a dialog later.
lib/pages/trip_page.dart
Future<void> _shareAlbum(BuildContext context) async { String? id = album.id; if (id == null) { // Album is missing an ID. const snackBar = SnackBar( duration: Duration(seconds: 3), content: Text('Could not share album. Try reopening this page.'), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); return; } // Show the loading indicator setState(() => _inSharingApiCall = true); const snackBar = SnackBar( duration: Duration(seconds: 3), content: Text('Sharing Album...'), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); // Share the album and update the local model await ScopedModel.of<PhotosLibraryApiModel>(context).shareAlbum(id); final updatedAlbum = await ScopedModel.of<PhotosLibraryApiModel>(context).getAlbum(id); print('Album has been shared.'); setState(() { album = updatedAlbum; // Hide the loading indicator _inSharingApiCall = false; }); }
Implement the method _showShareableUrl(...)
that is called when the user clicks the "SHARE WITH ANYONE" button at the top of the page. First, check if the album has already been shared and call the method _showUrlDialog(...)
once it has been shared.
lib/pages/trip_page.dart
Future<void> _showShareableUrl(BuildContext context) async { if (album.shareInfo == null || album.shareInfo!.shareableUrl == null) { print('Not shared, sharing album first.'); // Album is not shared yet, share it first, then display dialog await _shareAlbum(context); _showUrlDialog(context); } else { // Album is already shared, display dialog with URL _showUrlDialog(context); } }
Implement the method _showUrlDialog(...)
that shows the shareableUrl
in a dialog.
lib/pages/trip_page.dart
void _showUrlDialog(BuildContext context) { print('This is the shareableUrl:\n${album.shareInfo!.shareableUrl}'); _showShareDialog( context, 'Share this URL with anyone. ' 'Anyone with this URL can access all items.', album.shareInfo!.shareableUrl!); }
Try it out!
The app only lists trips that are not shared yet on the main screen. Don't worry, we'll implement that in the next step. For now, you can simply create a new trip if you navigate away from the screen.
Open the app and select a trip. Select "SHARE WITH ANYONE" at the top of the screen and open the returned URL in your browser. (Tip: the URL is also printed to the log, so you can easily copy it on your computer. In Android Studio, the log is displayed in the "Run" tab.)
9. Share albums inside your app
In Google Photos, albums can be shared via a URL that anyone with access to the URL can access. Through the Library API you can also share albums via share tokens. A share token is a string that is used inside your application to join users to a shared album via the API.
The process for sharing an album by your application via the Library API looks like this:
- User A logs into your application and authorizes the Library API
- Create the album
- Share the album using the identifier of the album
- Transfer the share token to another User
The joining process is similar:
- User B logs into your application and authorizes the Library API
- Retrive the share token for the album the user should join
- Join the album using the share token
Shared albums are shown inside Google Photos on the "sharing" tab.
In the previous step you already implemented the method _shareAlbum(...)
that shares an album. The shareInfo
property also contains the "share token" that will be shown on screen.
On the trip page, implement the method _showShareToken(...)
that is called when the user presses the "SHARE WITH FIELD TRIPPA" button on screen.
lib/pages/trip_page.dart
Future<void> _showShareToken(BuildContext context) async { if (album.shareInfo == null) { print('Not shared, sharing album first.'); // Album is not shared yet, share it first, then display dialog await _shareAlbum(context); _showTokenDialog(context); } else { // Album is already shared, display dialog with token _showTokenDialog(context); } }
Next, implement the display of the "share token" in the method _showTokenDialog(...)
. The token is part of the shareInfo
property of an album.
lib/pages/trip_page.dart
void _showTokenDialog(BuildContext context) { print('This is the shareToken:\n${album.shareInfo!.shareToken}'); _showShareDialog( context, 'Use this token to share', album.shareInfo!.shareToken!); }
The application currently only lists albums that are owned by the user, but not shared albums.
Only albums that the user has created or explicitly added to their Google Photos library are shown on the "Albums" screen inside the Google Photos app. Only these albums are returned when calling albums.list in the Library API. However, in our app the user can join other user's shared albums, which are only returned in the call to list shared albums. You need to change the way the list of trips (albums) are retrieved from the Library API to include both owned and shared albums.
Albums are loaded and cached in the API Model. Change the implementation of updateAlbums()
in the model to load albums and shared albums, before storing them as one list.
This implementation uses multiple Futures to list the albums asynchronously before combining them into the list of cached albums. Delete the old implementation and comment out the new code.
lib/model/photos_library_api_model.dart
void updateAlbums() async { // Reset the flag before loading new albums hasAlbums = false; // Clear all albums _albums.clear(); // Skip if not signed in if (!isLoggedIn()) { return; } // Add albums from the user's Google Photos account // var ownedAlbums = await _loadAlbums(); // if (ownedAlbums != null) { // _albums.addAll(ownedAlbums); // } // Load albums from owned and shared albums final list = await Future.wait([_loadSharedAlbums(), _loadAlbums()]); _albums.addAll(list.expand((a) => a ?? [])); notifyListeners(); hasAlbums = true; }
You can join users of your application to an album by using the share token. This is done through a simple text dialog in this codelab.
Implement the _joinTrip
method on the join trip page that calls the API model with the share token the user has entered. First, display the loading indicator, then make the call to join the shared album with the input from the text form, before hiding the loading indicator and returning back to the previous screen.
lib/pages/join_trip_page.dart
Future<void> _joinTrip(BuildContext context) async { // Show loading indicator setState(() => _isLoading = true); // Call the API to join an album with the entered share token await ScopedModel.of<PhotosLibraryApiModel>(context) .joinSharedAlbum(shareTokenFormController.text); // Hide loading indicator setState(() => _isLoading = false); // Return to the previous screen Navigator.pop(context); }
Try it out!
You need a second device or emulator with a different user account to try out this part of the codelab.
Create and share a trip under one user, then select the "SHARE IN FIELD TRIPPA" option to retrieve the share token. Copy this share token to the other device or emulator and enter it via the "JOIN A TRIP ALBUM" option on the home page. (Tip: The clipboard between your emulators and your host computer is shared.)
Real world implementation tips
When you implement sharing in a real world application (and not a codelab), you should think carefully about how you can use share tokens to join users to albums. Consider storing them in your secure backend and using your relationships between users to create and join albums.
For example - a soccer club meet up application could keep track of attendees to particular scheduled events and only join the attendees to the album after prompting them.
Before making any changes in your user's Google Photos account, it is important to give your users notice and ask for consent. Review the Google Photos Library API UX guidelines for more information.
10. Summary
What you have built
- Implemented sharing functionality into your application, backed by Google Photos
- Create your own photo and video sharing experiences on top of the Google Photos Library API, without having to worry about infrastructure or storage
- Using the sharing functionality that is part of the API in interesting and novel ways to share content directly to your users.
- Used some key parts of the Library API:
- Created new albums and uploaded new photos
- Listed shared albums, limited to albums created by your application
Where to go next
See the developer documentation for the Google Photos APIs at https://developers.google.com/photos to find out more about sharing media and other parts of the Library API. For example smart content filters powered by machine learning to help you find the right photos and videos.
When you are getting ready to launch your integration, join the Google Photos partner program.
Don't forget to review the UX guidelines and technical best practices. To help you get started, client libraries are also available for some languages.
How To Create A Shared Album On Google Photos
Source: https://codelabs.developers.google.com/codelabs/google-photos-sharing/
Posted by: ramirezwharleas.blogspot.com
0 Response to "How To Create A Shared Album On Google Photos"
Post a Comment