• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2022 Google LLC
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.google.android.libraries.mobiledatadownload;
17 
18 import com.google.android.libraries.mobiledatadownload.TaskScheduler.ConstraintOverrides;
19 import com.google.common.base.Optional;
20 import com.google.common.collect.ImmutableList;
21 import com.google.common.util.concurrent.Futures;
22 import com.google.common.util.concurrent.ListenableFuture;
23 import com.google.errorprone.annotations.CanIgnoreReturnValue;
24 import com.google.errorprone.annotations.CheckReturnValue;
25 import com.google.mobiledatadownload.ClientConfigProto.ClientFileGroup;
26 import com.google.mobiledatadownload.DownloadConfigProto.DataFileGroup;
27 import java.util.Map;
28 
29 /** The root object and entry point for the MobileDataDownload library. */
30 public interface MobileDataDownload {
31 
32   /**
33    * Adds for download the data file group in {@link AddFileGroupRequest}, after running validation
34    * on the group. This group will replace any previous version of this group once it is downloaded.
35    *
36    * <p>This api takes {@link AddFileGroupRequest} that contains data file group, and it can be used
37    * to set extra params such as account.
38    *
39    * <p>This doesn't start the download right away. The download starts later when the tasks
40    * scheduled via {@link #schedulePeriodicTasks} are run.
41    *
42    * <p>Calling this api with the exact same parameters multiple times is a no-op.
43    *
44    * @param addFileGroupRequest The request to add file group in MDD.
45    * @return ListenableFuture of true if the group was successfully added, or the group was already
46    *     present; ListenableFuture of false if the group is invalid or an I/O error occurs.
47    */
addFileGroup(AddFileGroupRequest addFileGroupRequest)48   ListenableFuture<Boolean> addFileGroup(AddFileGroupRequest addFileGroupRequest);
49 
50   /**
51    * Removes all versions of the data file group that matches {@link RemoveFileGroupRequest} from
52    * MDD. If no data file group matches, this call is a no-op.
53    *
54    * <p>This api takes {@link RemoveFileGroupRequest} that contains data file group, and it can be
55    * used to set extra params such as account.
56    *
57    * @param removeFileGroupRequest The request to remove file group from MDD.
58    * @return Listenable of true if the group was successfully removed, or no group matches;
59    *     Listenable of false if the matching group fails to be removed.
60    */
removeFileGroup(RemoveFileGroupRequest removeFileGroupRequest)61   ListenableFuture<Boolean> removeFileGroup(RemoveFileGroupRequest removeFileGroupRequest);
62 
63   /**
64    * Removes all versions of the data file groups that match {@link RemoveFileGroupsByFilterRequest}
65    * from MDD. If no data file group matches, this call is a no-op.
66    *
67    * <p>This api takes a {@link RemoveFileGroupsByFilterRequest} that contains optional filters for
68    * the group name, group source, associated account, etc.
69    *
70    * <p>A resolved future will only be returned if the removal completes successfully for all
71    * matching file groups. If any failures occur during this method, it will return a failed future
72    * with an {@link AggregateException} containing the failures that occurred.
73    *
74    * <p>NOTE: This only removes the metadata from MDD, not file content. Downloaded files that are
75    * no longer needed are deleted during MDD's daily maintenance task.
76    *
77    * @param removeFileGroupsByFilterRequest The request to remove file group from MDD.
78    * @return ListenableFuture that resolves with {@link RemoveFileGroupsByFilterResponse}, or fails
79    *     with {@link AggregateException}
80    */
removeFileGroupsByFilter( RemoveFileGroupsByFilterRequest removeFileGroupsByFilterRequest)81   ListenableFuture<RemoveFileGroupsByFilterResponse> removeFileGroupsByFilter(
82       RemoveFileGroupsByFilterRequest removeFileGroupsByFilterRequest);
83 
84   /**
85    * Gets the file group definition that was added to MDD. This API cannot be used to access files,
86    * but it can be accessed by populators to manipulate the existing file group state - eg, to
87    * rename a file group, or otherwise migrate from one format to another.
88    *
89    * @return DataFileGroup if downloaded file group is found, otherwise a failing LF.
90    */
readDataFileGroup( ReadDataFileGroupRequest readDataFileGroupRequest)91   default ListenableFuture<DataFileGroup> readDataFileGroup(
92       ReadDataFileGroupRequest readDataFileGroupRequest) {
93     throw new UnsupportedOperationException();
94   }
95 
96   /**
97    * Returns the latest downloaded data that we have for the given group name.
98    *
99    * <p>This api takes an instance of {@link GetFileGroupRequest} that contains group name, and it
100    * can be used to set extra params such as account.
101    *
102    * <p>This listenable future will return null if no group exists or has been downloaded for the
103    * given group name.
104    *
105    * <p>Note: getFileGroup returns a snapshot of the latest state, but it's possible for the state
106    * to change between a getFileGroup call and accessing the files if the ClientFileGroup gets
107    * cached. Caching the returned ClientFileGroup is therefore discouraged.
108    *
109    * @param getFileGroupRequest The request to get a single file group.
110    * @return The ListenableFuture of requested client file group for the given request.
111    */
getFileGroup(GetFileGroupRequest getFileGroupRequest)112   ListenableFuture<ClientFileGroup> getFileGroup(GetFileGroupRequest getFileGroupRequest);
113 
114   /**
115    * Returns all the data that we have for the given {@link GetFileGroupsByFilterRequest}.
116    *
117    * <p>This listenable future will return a list of file groups with their current download status.
118    *
119    * <p>Only present fields in {@link GetFileGroupsByFilterRequest} will be used to perform the
120    * filtering, i.e. when no account is specified in the filter, file groups won't be filtered based
121    * on account.
122    *
123    * <p>Note: getFileGroupsByFilter returns a snapshot of the latest state, but it's possible for
124    * the state to change between a getFileGroupsByFilter call and accessing the files if the
125    * ClientFileGroup gets cached. Caching the returned ClientFileGroup is therefore discouraged.
126    *
127    * @param getFileGroupsByFilterRequest The request to get multiple file groups after filtering.
128    * @return The ListenableFuture that will resolve to a list of the requested client file groups,
129    *     including pending and downloaded versions; this ListenableFuture will resolve to all client
130    *     file groups when {@code getFileGroupsByFilterRequest.includeAllGroups} is true.
131    */
getFileGroupsByFilter( GetFileGroupsByFilterRequest getFileGroupsByFilterRequest)132   ListenableFuture<ImmutableList<ClientFileGroup>> getFileGroupsByFilter(
133       GetFileGroupsByFilterRequest getFileGroupsByFilterRequest);
134 
135   /**
136    * Imports Inline Files into an Existing MDD File Group.
137    *
138    * <p>This api takes a {@link ImportFilesRequest} containing identifying information about an
139    * existing File Group, an optional list of {@link DataFile}s to import into the existing File
140    * Group, and a Map of file content to import into MDD.
141    *
142    * <p>The identifying information is used to identify a file group and its specific version. This
143    * prevents the caller from accidentally importing files into the wrong file group or the wrong
144    * version of the file group. An optional {@link Account} parameter can also be specified if the
145    * existing file group was associated with an account.
146    *
147    * <p>The given {@link DataFile} list allows updated files (still compatible with a given file
148    * group version) to be imported into MDD. This API wll merge the given DataFiles into the
149    * existing file group in the following manner:
150    *
151    * <ul>
152    *   <li>DataFiles included in the DataFile list but not the existing file group will be added as
153    *       new DataFiles
154    *   <li>DataFiles included in the DataFile list will replace DataFiles in the existing file group
155    *       if their file Ids match.
156    *   <li>DataFiles included in the existing file group but not the DataFile list will remain
157    *       untouched.
158    * </ul>
159    *
160    * <p>{@link ImportFilesRequest} also requires a Map of file sources that should be imported by
161    * MDD. The Map is keyed by the fileIds of DataFiles and contains the contents of the file to
162    * import within a {@link ByteString}. This Map must contains an entry for all {@link DataFile}s
163    * which require an inline file source. Only "Inline" {@link DataFile}s should be included in this
164    * map (see details below).
165    *
166    * <p>An inline {@link DataFile} is the same as a standard {@link DataFile}, but instead of an
167    * "https" url, the url should match the following format:
168    *
169    * <pre>{@code "inlinefile:<key>"}</pre>
170    *
171    * <p>Where {@code key} is a unique identifier of the file. In most cases, the checksum should be
172    * used as this key. If the checksum is not used, another unique identifier should be used to
173    * allow proper deduping of the file import within MDD.
174    *
175    * <p>Example inline file url:
176    *
177    * <pre>{@code inlinefile:sha1:9a4ea3ca81d3f1d631531cbc216a62d9b10509ee}</pre>
178    *
179    * <p>NOTE: Inline files can be specified by the given DataFile list in {@link
180    * ImportFilesRequest}, but can also be specified by a {@link DataFileGroup} added via {@link
181    * #addFileGroup}. A File Group that contains inline files will not be considered DOWNLOADED until
182    * all inline files are imported via this API.
183    *
184    * <p>Because this method performs an update to the stored File Group metadata, the given {@link
185    * ImportFilesRequest} must satisfy the following conditions:
186    *
187    * <ul>
188    *   <li>The requests identifying information must match an existing File Group
189    *   <li>All inline DataFiles must have file content specified in the request's Inline File Map
190    * </ul>
191    *
192    * <p>If either of these conditions is not met, this operation will return a failed
193    * ListenableFuture.
194    *
195    * <p>Finally, this API is a atomic operation. That is, <em>either all inline files will be
196    * imported successfully or none will be imported</em>. If there is a failure with importing a
197    * file, MDD will not update the file group (i.e. future calls to {@link #getFileGroup} will
198    * return the same {@link ClientFileGroup} as before this call).
199    *
200    * @param importFilesRequest Request containing required parameters to perform import files
201    *     operation.
202    * @return ListenableFuture that resolves when all inline files are successfully imported.
203    */
importFiles(ImportFilesRequest importFilesRequest)204   ListenableFuture<Void> importFiles(ImportFilesRequest importFilesRequest);
205 
206   /**
207    * Downloads a single file.
208    *
209    * <p>This api takes {@link SingleFileDownloadRequest}, which contains a download url of the file
210    * to download. the destination location on device must also be specified. See
211    * SingleFileDownloadRequest for full list of required/optional parameters.
212    *
213    * <p>The returned ListenableFuture will fail if there is an error during the download. The caller
214    * is responsible for calling downloadFile again to restart the download.
215    *
216    * <p>The caller can be notified of progress by providing a {@link SingleFileDownloadListener}.
217    * This listener will also provide callbacks for a completed download, failed download, or paused
218    * download due to connectivity loss.
219    *
220    * <p>The caller can specify constraints that should be used for the download by providing a
221    * {@link com.google.android.libraries.mobiledatadownload.downloader.DownloadConstraints}. This
222    * allows downloads to only start when on Wifi, for example. By default, no constraints are
223    * specified.
224    *
225    * @param singleFileDownloadRequest The request to download a file.
226    * @return ListenableFuture that resolves when file is downloaded.
227    */
228   @CheckReturnValue
downloadFile(SingleFileDownloadRequest singleFileDownloadRequest)229   ListenableFuture<Void> downloadFile(SingleFileDownloadRequest singleFileDownloadRequest);
230 
231   /**
232    * Downloads and returns the latest downloaded data that we have for the given group name.
233    *
234    * <p>This api takes {@link DownloadFileGroupRequest} that contains group name, and it can be used
235    * to set extra params such as account, download conditions, and download listener.
236    *
237    * <p>The group name must be added using {@link #addFileGroup} before downloading the file group.
238    *
239    * <p>The returned ListenableFuture will be resolved when the file group is downloaded. It can
240    * also be used to cancel the download.
241    *
242    * <p>The returned ListenableFuture would fail if there is any error during the download. Client
243    * is responsible to call the downloadFileGroup to resume the download.
244    *
245    * <p>Download progress is supported through the DownloadListener.
246    *
247    * <p>To download under any conditions, clients should use {@link
248    * Constants.NO_RESTRICTIONS_DOWNLOAD_CONDITIONS}
249    *
250    * @param downloadFileGroupRequest The request to download file group.
251    */
downloadFileGroup( DownloadFileGroupRequest downloadFileGroupRequest)252   ListenableFuture<ClientFileGroup> downloadFileGroup(
253       DownloadFileGroupRequest downloadFileGroupRequest);
254 
255   /**
256    * Downloads a file using a foreground service and notification.
257    *
258    * <p>This is similar to {@link #downloadFile}, but allows the download to continue running when
259    * the app enters the background.
260    *
261    * <p>The notification created for the download includes a cancel action. This will allow the
262    * download to be cancelled even when the app is in the background.
263    *
264    * <p>The cancel action in the notification menu requires the ForegroundService to be registered
265    * with the application (via the AndroidManifest.xml). This allows the cancellation intents to be
266    * properly picked up. To register the service, the following lines must be included in the app's
267    * {@code AndroidManifest.xml}:
268    *
269    * <pre>{@code
270    * <!-- Needed by foreground download service -->
271    * <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
272    *
273    * <!-- Service for MDD foreground downloads -->
274    * <service
275    *   android:name="com.google.android.libraries.mobiledatadownload.foreground.sting.ForegroundDownloadService"
276    *   android:exported="false" />
277    * }</pre>
278    *
279    * <p>NOTE: The above excerpt is for Framework and Sting apps. Dagger apps should use the same
280    * excerpt, but change the {@code android:name} property to:
281    *
282    * <pre>{@code
283    * android:name="com.google.android.libraries.mobiledatadownload.foreground.dagger.ForegroundDownloadService"
284    * }</pre>
285    */
286   @CheckReturnValue
downloadFileWithForegroundService( SingleFileDownloadRequest singleFileDownloadRequest)287   ListenableFuture<Void> downloadFileWithForegroundService(
288       SingleFileDownloadRequest singleFileDownloadRequest);
289 
290   /**
291    * Download a file group and show foreground download progress in a notification. User can cancel
292    * the download from the notification menu.
293    *
294    * <p>The cancel action in the notification menu requires the ForegroundService to be registered
295    * with the application (via the AndroidManifest.xml). This allows the cancellation intents to be
296    * properly picked up. To register the service, the following lines must be included in the app's
297    * {@code AndroidManifest.xml}:
298    *
299    * <pre>{@code
300    * <!-- Needed by foreground download service -->
301    * <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
302    *
303    * <!-- Service for MDD foreground downloads -->
304    * <service
305    *   android:name="com.google.android.libraries.mobiledatadownload.foreground.sting.ForegroundDownloadService"
306    *   android:exported="false" />
307    * }</pre>
308    *
309    * <p>NOTE: The above excerpt is for Framework and Sting apps. Dagger apps should use the same
310    * excerpt, but change the {@code android:name} property to:
311    *
312    * <pre>{@code
313    * android:name="com.google.android.libraries.mobiledatadownload.foreground.dagger.ForegroundDownloadService"
314    * }</pre>
315    */
downloadFileGroupWithForegroundService( DownloadFileGroupRequest downloadFileGroupRequest)316   ListenableFuture<ClientFileGroup> downloadFileGroupWithForegroundService(
317       DownloadFileGroupRequest downloadFileGroupRequest);
318 
319   /**
320    * Cancel an on-going foreground download.
321    *
322    * <p>Attempts to cancel an on-going foreground download using best effort. If download is unknown
323    * to MDD, this operation is a noop.
324    *
325    * <p>The key passed here must be created using {@link ForegroundDownloadKey}, and must match the
326    * properties used from the request. Depending on which API was used to start the download, this
327    * would be {@link DownloadFileGroupRequest} for {@link SingleFileDownloadRequest}.
328    *
329    * <p><b>NOTE:</b> In most cases, clients will not need to call this -- it is meant to allow the
330    * ForegroundDownloadService to cancel a download via the Cancel action registered to a
331    * notification.
332    *
333    * <p>Clients should prefer to cancel the future returned to them from the download call.
334    *
335    * @param downloadKey the key associated with the download
336    */
cancelForegroundDownload(String downloadKey)337   void cancelForegroundDownload(String downloadKey);
338 
339   /**
340    * Triggers the execution of MDD maintenance.
341    *
342    * <p>MDD needs to run maintenance task once a day. If you call {@link
343    * #schedulePeriodicBackgroundTasks} api, the maintenance will be called automatically. In case
344    * you don't want to schedule MDD tasks, you can call this maintenance method directly.
345    *
346    * <p>If you do need to call this api, make sure that this api is called exactly once every day.
347    *
348    * <p>The returned ListenableFuture would fail if the maintenance execution doesn't succeed.
349    */
maintenance()350   ListenableFuture<Void> maintenance();
351 
352   /**
353    * Perform garbage collection, which includes removing expired file groups and unreferenced files.
354    *
355    * <p>By default, this is run as part of {@link #maintenance} so doesn't need to be invoked
356    * directly by client code. If you disabled that behavior via {@link
357    * Flags#mddEnableGarbageCollection} then this method should be periodically called to clean up
358    * unused files.
359    */
collectGarbage()360   ListenableFuture<Void> collectGarbage();
361 
362   /**
363    * Schedule periodic tasks that will download and verify all file groups when the required
364    * conditions are met, using the given {@link TaskScheduler}.
365    *
366    * <p>If the host app doesn't provide a TaskScheduler, calling this API will be a no-op.
367    *
368    * @deprecated Use the {@link schedulePeriodicBackgroundTasks} instead.
369    */
370   @Deprecated
schedulePeriodicTasks()371   void schedulePeriodicTasks();
372 
373   /**
374    * Schedule periodic background tasks that will download and verify all file groups when the
375    * required conditions are met, using the given {@link TaskScheduler}.
376    *
377    * <p>If the host app doesn't provide a TaskScheduler, calling this API will be a no-op.
378    */
schedulePeriodicBackgroundTasks()379   ListenableFuture<Void> schedulePeriodicBackgroundTasks();
380 
381   /**
382    * Schedule periodic background tasks that will download and verify all file groups when the
383    * required conditions are met, using the given {@link TaskScheduler}.
384    *
385    * <p>If the host app doesn't provide a TaskScheduler, calling this API will be a no-op.
386    *
387    * @param constraintOverridesMap to allow clients to override constraints requirements.
388    *     <p><code>{@code
389    *  ConstraintOverrides wifiOverrides =
390    *     ConstraintOverrides.newBuilder()
391    *         .setRequiresCharging(false)
392    *         .setRequiresDeviceIdle(true)
393    *         .build();
394    * ConstraintOverrides cellularOverrides =
395    *     ConstraintOverrides.newBuilder()
396    *         .setRequiresCharging(true)
397    *         .setRequiresDeviceIdle(false)
398    *         .build();
399    *
400    *  Map<String, ConstraintOverrides> constraintOverridesMap = new HashMap<>();
401    *  constraintOverridesMap.put(TaskScheduler.WIFI_CHARGING_PERIODIC_TASK, wifiOverrides);
402    *  constraintOverridesMap.put(TaskScheduler.CELLULAR_CHARGING_PERIODIC_TASK, cellularOverrides);
403    *
404    *  mobileDataDownload.schedulePeriodicBackgroundTasks(Optional.of(constraintOverridesMap)).get();
405    * }</code>
406    */
schedulePeriodicBackgroundTasks( Optional<Map<String, ConstraintOverrides>> constraintOverridesMap)407   ListenableFuture<Void> schedulePeriodicBackgroundTasks(
408       Optional<Map<String, ConstraintOverrides>> constraintOverridesMap);
409 
410   /**
411    * Cancels previously-scheduled periodic background tasks using the given {@link TaskScheduler}.
412    * Cancelling is best-effort and only meant to be used in an emergency; most apps will never need
413    * to call it.
414    *
415    * <p>If the host app doesn't provide a TaskScheduler, calling this API is a no-op.
416    */
cancelPeriodicBackgroundTasks()417   default ListenableFuture<Void> cancelPeriodicBackgroundTasks() {
418     // TODO(b/223822302): remove default once all implementations have been updated to include it
419     return Futures.immediateVoidFuture();
420   }
421 
422   /**
423    * Handle a task scheduled via a task scheduling service.
424    *
425    * <p>This method should not be called on the main thread, as it does work on the thread it is
426    * called on.
427    *
428    * @return a listenable future which indicates when any async task scheduled is complete.
429    */
handleTask(String tag)430   ListenableFuture<Void> handleTask(String tag);
431 
432   /** Clear MDD metadata and its managed files. MDD will be reset to a clean state. */
clear()433   ListenableFuture<Void> clear();
434 
435   /**
436    * Return MDD debug info as a string. This could return some PII information so it's not
437    * recommended to be called in production build.
438    *
439    * <p>This debug info string could be very long. In order to print them in adb logcat, we have to
440    * split the string. See how it is done in our sample app: <internal>
441    */
getDebugInfoAsString()442   String getDebugInfoAsString();
443 
444   /**
445    * Reports usage of a file group back to MDD. This can be used to track errors with file group
446    * roll outs. Each usage of the file group should result in a single call of this method in order
447    * to allow for accurate metrics server side.
448    *
449    * @param usageEvent that will be logged.
450    * @return a listenable future which indicates that the UsageEvent has been logged.
451    */
452   @CanIgnoreReturnValue
reportUsage(UsageEvent usageEvent)453   ListenableFuture<Void> reportUsage(UsageEvent usageEvent);
454 }
455