summaryrefslogtreecommitdiff
path: root/java/com/google/android/libraries/mobiledatadownload/lite/DownloaderImpl.java
blob: 75bafd3a2eef4a8decc55eada41d9985a8e33f83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
/*
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.android.libraries.mobiledatadownload.lite;

import static com.google.common.util.concurrent.Futures.immediateFailedFuture;
import static com.google.common.util.concurrent.Futures.immediateVoidFuture;

import android.content.Context;
import androidx.annotation.VisibleForTesting;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import com.google.android.libraries.mobiledatadownload.DownloadException;
import com.google.android.libraries.mobiledatadownload.DownloadException.DownloadResultCode;
import com.google.android.libraries.mobiledatadownload.downloader.FileDownloader;
import com.google.android.libraries.mobiledatadownload.foreground.ForegroundDownloadKey;
import com.google.android.libraries.mobiledatadownload.foreground.NotificationUtil;
import com.google.android.libraries.mobiledatadownload.internal.logging.LogUtil;
import com.google.android.libraries.mobiledatadownload.internal.util.DownloadFutureMap;
import com.google.android.libraries.mobiledatadownload.tracing.PropagatedFluentFuture;
import com.google.android.libraries.mobiledatadownload.tracing.PropagatedFutures;
import com.google.common.base.Optional;
import com.google.common.base.Supplier;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableFutureTask;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.concurrent.Executor;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

final class DownloaderImpl implements Downloader {
  private static final String TAG = "DownloaderImp";

  private final Context context;
  private final Optional<Class<?>> foregroundDownloadServiceClassOptional;
  // This executor will execute tasks sequentially.
  private final Executor sequentialControlExecutor;
  private final Optional<SingleFileDownloadProgressMonitor> downloadMonitorOptional;
  private final Supplier<FileDownloader> fileDownloaderSupplier;

  @VisibleForTesting final DownloadFutureMap<Void> downloadFutureMap;
  @VisibleForTesting final DownloadFutureMap<Void> foregroundDownloadFutureMap;

  DownloaderImpl(
      Context context,
      Optional<Class<?>> foregroundDownloadServiceClassOptional,
      Executor sequentialControlExecutor,
      Optional<SingleFileDownloadProgressMonitor> downloadMonitorOptional,
      Supplier<FileDownloader> fileDownloaderSupplier) {
    this.context = context;
    this.sequentialControlExecutor = sequentialControlExecutor;
    this.foregroundDownloadServiceClassOptional = foregroundDownloadServiceClassOptional;
    this.downloadMonitorOptional = downloadMonitorOptional;
    this.fileDownloaderSupplier = fileDownloaderSupplier;
    this.downloadFutureMap = DownloadFutureMap.create(sequentialControlExecutor);
    this.foregroundDownloadFutureMap =
        DownloadFutureMap.create(
            sequentialControlExecutor,
            createCallbacksForForegroundService(context, foregroundDownloadServiceClassOptional));
  }

  @Override
  public ListenableFuture<Void> download(DownloadRequest downloadRequest) {
    LogUtil.d("%s: download for Uri = %s", TAG, downloadRequest.destinationFileUri().toString());
    ForegroundDownloadKey foregroundDownloadKey =
        ForegroundDownloadKey.ofSingleFile(downloadRequest.destinationFileUri());

    return PropagatedFutures.transformAsync(
        getInProgressDownloadFuture(foregroundDownloadKey.toString()),
        (Optional<ListenableFuture<Void>> existingDownloadFuture) -> {
          // if there is the same on-going request, return that one.
          if (existingDownloadFuture.isPresent()) {
            return existingDownloadFuture.get();
          }

          // Register listener with monitor if present
          if (downloadRequest.listenerOptional().isPresent()) {
            if (downloadMonitorOptional.isPresent()) {
              downloadMonitorOptional
                  .get()
                  .addDownloadListener(
                      downloadRequest.destinationFileUri(),
                      downloadRequest.listenerOptional().get());
            } else {
              LogUtil.w(
                  "%s: download request included DownloadListener, but DownloadMonitor is not"
                      + " present! DownloadListener will only be invoked for complete/failure.",
                  TAG);
            }
          }

          // Create a ListenableFutureTask to delay starting the downloadFuture until we can add the
          // future to our map.
          ListenableFutureTask<Void> startTask = ListenableFutureTask.create(() -> null);
          ListenableFuture<Void> downloadFuture =
              PropagatedFutures.transformAsync(
                  startTask, unused -> startDownload(downloadRequest), sequentialControlExecutor);

          PropagatedFutures.addCallback(
              downloadFuture,
              new FutureCallback<Void>() {
                @Override
                public void onSuccess(Void result) {
                  // Currently the MobStore monitor does not support onSuccess so we have to add
                  // callback to the download future here.

                  // Remove download listener and remove download future from map after listener
                  // completes
                  if (downloadRequest.listenerOptional().isPresent()) {
                    PropagatedFutures.addCallback(
                        downloadRequest.listenerOptional().get().onComplete(),
                        new FutureCallback<Void>() {
                          @Override
                          public void onSuccess(@NullableDecl Void result) {
                            if (downloadMonitorOptional.isPresent()) {
                              downloadMonitorOptional
                                  .get()
                                  .removeDownloadListener(downloadRequest.destinationFileUri());
                            }
                            ListenableFuture<Void> unused =
                                downloadFutureMap.remove(foregroundDownloadKey.toString());
                          }

                          @Override
                          public void onFailure(Throwable t) {
                            LogUtil.e(t, "%s: Failed to run client onComplete", TAG);
                            if (downloadMonitorOptional.isPresent()) {
                              downloadMonitorOptional
                                  .get()
                                  .removeDownloadListener(downloadRequest.destinationFileUri());
                            }
                            ListenableFuture<Void> unused =
                                downloadFutureMap.remove(foregroundDownloadKey.toString());
                          }
                        },
                        sequentialControlExecutor);
                  } else {
                    ListenableFuture<Void> unused =
                        downloadFutureMap.remove(foregroundDownloadKey.toString());
                  }
                }

                @Override
                public void onFailure(Throwable t) {
                  LogUtil.e(t, "%s: Download Future failed", TAG);

                  // Currently the MobStore monitor does not support onFailure so we have to add
                  // callback to the download future here.
                  if (downloadRequest.listenerOptional().isPresent()) {
                    downloadRequest.listenerOptional().get().onFailure(t);
                    if (downloadMonitorOptional.isPresent()) {
                      downloadMonitorOptional
                          .get()
                          .removeDownloadListener(downloadRequest.destinationFileUri());
                    }
                  }
                  ListenableFuture<Void> unused =
                      downloadFutureMap.remove(foregroundDownloadKey.toString());
                }
              },
              MoreExecutors.directExecutor());

          return PropagatedFutures.transformAsync(
              downloadFutureMap.add(foregroundDownloadKey.toString(), downloadFuture),
              unused -> {
                // Now that the download future is added, start the task and return the future
                startTask.run();
                return downloadFuture;
              },
              sequentialControlExecutor);
        },
        sequentialControlExecutor);
  }

  private ListenableFuture<Void> startDownload(DownloadRequest downloadRequest) {
    // Translate from MDDLite DownloadRequest to MDDDownloader DownloadRequest.
    com.google.android.libraries.mobiledatadownload.downloader.DownloadRequest
        fileDownloaderRequest =
            com.google.android.libraries.mobiledatadownload.downloader.DownloadRequest.newBuilder()
                .setFileUri(downloadRequest.destinationFileUri())
                .setDownloadConstraints(downloadRequest.downloadConstraints())
                .setUrlToDownload(downloadRequest.urlToDownload())
                .setExtraHttpHeaders(downloadRequest.extraHttpHeaders())
                .setTrafficTag(downloadRequest.trafficTag())
                .build();
    try {
      return fileDownloaderSupplier.get().startDownloading(fileDownloaderRequest);
    } catch (RuntimeException e) {
      // Catch any unchecked exceptions that prevented the download from starting.
      return immediateFailedFuture(
          DownloadException.builder()
              .setDownloadResultCode(DownloadResultCode.UNKNOWN_ERROR)
              .setCause(e)
              .build());
    }
  }

  @Override
  public ListenableFuture<Void> downloadWithForegroundService(DownloadRequest downloadRequest) {
    LogUtil.d(
        "%s: downloadWithForegroundService for Uri = %s",
        TAG, downloadRequest.destinationFileUri().toString());
    if (!downloadMonitorOptional.isPresent()) {
      return immediateFailedFuture(
          new IllegalStateException(
              "downloadWithForegroundService: DownloadMonitor is not provided!"));
    }
    if (!foregroundDownloadServiceClassOptional.isPresent()) {
      return immediateFailedFuture(
          new IllegalStateException(
              "downloadWithForegroundService: ForegroundDownloadService is not provided!"));
    }

    ForegroundDownloadKey foregroundDownloadKey =
        ForegroundDownloadKey.ofSingleFile(downloadRequest.destinationFileUri());

    return PropagatedFutures.transformAsync(
        getInProgressDownloadFuture(foregroundDownloadKey.toString()),
        (Optional<ListenableFuture<Void>> existingDownloadFuture) -> {
          // if there is the same on-going request, return that one.
          if (existingDownloadFuture.isPresent()) {
            return existingDownloadFuture.get();
          }

          // It's OK to recreate the NotificationChannel since it can also be used to restore a
          // deleted channel and to update an existing channel's name, description, group, and/or
          // importance.
          NotificationUtil.createNotificationChannel(context);

          DownloadListener downloadListenerWithNotification =
              createDownloadListenerWithNotification(downloadRequest);

          // The downloadMonitor will trigger the DownloadListener.
          downloadMonitorOptional
              .get()
              .addDownloadListener(
                  downloadRequest.destinationFileUri(), downloadListenerWithNotification);

          // Create a ListenableFutureTask to delay starting the downloadFuture until we can add the
          // future to our map.
          ListenableFutureTask<Void> startTask = ListenableFutureTask.create(() -> null);
          ListenableFuture<Void> downloadFuture =
              PropagatedFutures.transformAsync(
                  startTask, unused -> startDownload(downloadRequest), sequentialControlExecutor);

          PropagatedFutures.addCallback(
              downloadFuture,
              new FutureCallback<Void>() {
                @Override
                public void onSuccess(Void result) {
                  // Currently the MobStore monitor does not support onSuccess so we have to add
                  // callback to the download future here.

                  PropagatedFutures.addCallback(
                      downloadListenerWithNotification.onComplete(),
                      new FutureCallback<Void>() {
                        @Override
                        public void onSuccess(@NullableDecl Void result) {}

                        @Override
                        public void onFailure(Throwable t) {
                          LogUtil.e(t, "%s: Failed to run client onComplete", TAG);
                        }
                      },
                      sequentialControlExecutor);
                }

                @Override
                public void onFailure(Throwable t) {
                  // Currently the MobStore monitor does not support onFailure so we have to add
                  // callback to the download future here.
                  LogUtil.e(t, "%s: Download Future failed", TAG);
                  downloadListenerWithNotification.onFailure(t);
                }
              },
              MoreExecutors.directExecutor());

          return PropagatedFutures.transformAsync(
              foregroundDownloadFutureMap.add(foregroundDownloadKey.toString(), downloadFuture),
              unused -> {
                // Now that the download future is added, start the task and return the future
                startTask.run();
                return downloadFuture;
              },
              sequentialControlExecutor);
        },
        sequentialControlExecutor);
  }

  // Assertion: foregroundDownloadService and downloadMonitor are present
  private DownloadListener createDownloadListenerWithNotification(DownloadRequest downloadRequest) {
    String networkPausedMessage =
        downloadRequest.downloadConstraints().requireUnmeteredNetwork()
            ? NotificationUtil.getDownloadPausedWifiMessage(context)
            : NotificationUtil.getDownloadPausedMessage(context);

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
    NotificationCompat.Builder notification =
        NotificationUtil.createNotificationBuilder(
            context,
            downloadRequest.fileSizeBytes(),
            downloadRequest.notificationContentTitle(),
            downloadRequest.notificationContentTextOptional().or(downloadRequest.urlToDownload()));

    ForegroundDownloadKey foregroundDownloadKey =
        ForegroundDownloadKey.ofSingleFile(downloadRequest.destinationFileUri());

    int notificationKey = NotificationUtil.notificationKeyForKey(foregroundDownloadKey.toString());

    // Attach the Cancel action to the notification.
    NotificationUtil.createCancelAction(
        context,
        foregroundDownloadServiceClassOptional.get(),
        foregroundDownloadKey.toString(),
        notification,
        notificationKey);
    notificationManager.notify(notificationKey, notification.build());

    return new DownloadListener() {
      @Override
      public void onProgress(long currentSize) {
        // TODO(b/229123693): return this future once DownloadListener has an async api.
        ListenableFuture<?> unused =
            PropagatedFutures.transformAsync(
                foregroundDownloadFutureMap.containsKey(foregroundDownloadKey.toString()),
                futureInProgress -> {
                  if (futureInProgress) {
                    notification
                        .setCategory(NotificationCompat.CATEGORY_PROGRESS)
                        .setContentText(
                            downloadRequest
                                .notificationContentTextOptional()
                                .or(downloadRequest.urlToDownload()))
                        .setSmallIcon(android.R.drawable.stat_sys_download)
                        .setProgress(
                            downloadRequest.fileSizeBytes(),
                            (int) currentSize,
                            /* indeterminate= */ downloadRequest.fileSizeBytes() <= 0);
                    notificationManager.notify(notificationKey, notification.build());
                  }
                  if (downloadRequest.listenerOptional().isPresent()) {
                    downloadRequest.listenerOptional().get().onProgress(currentSize);
                  }
                  return immediateVoidFuture();
                },
                sequentialControlExecutor);
      }

      @Override
      public void onPausedForConnectivity() {
        // TODO(b/229123693): return this future once DownloadListener has an async api.
        ListenableFuture<?> unused =
            PropagatedFutures.transformAsync(
                foregroundDownloadFutureMap.containsKey(foregroundDownloadKey.toString()),
                futureInProgress -> {
                  if (futureInProgress) {
                    notification
                        .setCategory(NotificationCompat.CATEGORY_STATUS)
                        .setContentText(networkPausedMessage)
                        .setSmallIcon(android.R.drawable.stat_sys_download)
                        .setOngoing(true)
                        // hide progress bar.
                        .setProgress(0, 0, false);
                    notificationManager.notify(notificationKey, notification.build());
                  }
                  if (downloadRequest.listenerOptional().isPresent()) {
                    downloadRequest.listenerOptional().get().onPausedForConnectivity();
                  }
                  return immediateVoidFuture();
                },
                sequentialControlExecutor);
      }

      @Override
      public ListenableFuture<Void> onComplete() {
        // We want to keep the Foreground Download Service alive until client's onComplete finishes.
        ListenableFuture<Void> clientOnCompleteFuture =
            downloadRequest.listenerOptional().isPresent()
                ? downloadRequest.listenerOptional().get().onComplete()
                : immediateVoidFuture();

        // Logic to shutdown Foreground Download Service after the client's provided onComplete
        // finished
        return PropagatedFluentFuture.from(clientOnCompleteFuture)
            .transformAsync(
                unused -> {
                  // onComplete succeeded, show a success message
                  notification.mActions.clear();

                  if (downloadRequest.showDownloadedNotification()) {
                    notification
                        .setCategory(NotificationCompat.CATEGORY_STATUS)
                        .setContentText(NotificationUtil.getDownloadSuccessMessage(context))
                        .setOngoing(false)
                        .setSmallIcon(android.R.drawable.stat_sys_download_done)
                        // hide progress bar.
                        .setProgress(0, 0, false);

                    notificationManager.notify(notificationKey, notification.build());
                  } else {
                    NotificationUtil.cancelNotificationForKey(
                        context, foregroundDownloadKey.toString());
                  }
                  return immediateVoidFuture();
                },
                sequentialControlExecutor)
            .catchingAsync(
                Exception.class,
                e -> {
                  LogUtil.w(
                      e,
                      "%s: Delegate onComplete failed for uri: %s, showing failure notification.",
                      TAG,
                      downloadRequest.destinationFileUri());
                  notification.mActions.clear();

                  if (downloadRequest.showDownloadedNotification()) {
                    notification
                        .setCategory(NotificationCompat.CATEGORY_STATUS)
                        .setContentText(NotificationUtil.getDownloadFailedMessage(context))
                        .setOngoing(false)
                        .setSmallIcon(android.R.drawable.stat_sys_warning)
                        // hide progress bar.
                        .setProgress(0, 0, false);

                    notificationManager.notify(notificationKey, notification.build());
                  } else {
                    NotificationUtil.cancelNotificationForKey(
                        context, foregroundDownloadKey.toString());
                  }

                  return immediateVoidFuture();
                },
                sequentialControlExecutor)
            .transformAsync(
                unused -> {
                  // After success or failure notification is shown, clean up
                  downloadMonitorOptional
                      .get()
                      .removeDownloadListener(downloadRequest.destinationFileUri());

                  return foregroundDownloadFutureMap.remove(foregroundDownloadKey.toString());
                },
                sequentialControlExecutor);
      }

      @Override
      public void onFailure(Throwable t) {
        // TODO(b/229123693): return this future once DownloadListener has an async api.
        ListenableFuture<?> unused =
            PropagatedFutures.submitAsync(
                () -> {
                  // Clear the notification action.
                  notification.mActions.clear();

                  // Show download failed in notification.
                  notification
                      .setCategory(NotificationCompat.CATEGORY_STATUS)
                      .setContentText(NotificationUtil.getDownloadFailedMessage(context))
                      .setOngoing(false)
                      .setSmallIcon(android.R.drawable.stat_sys_warning)
                      // hide progress bar.
                      .setProgress(0, 0, false);

                  notificationManager.notify(notificationKey, notification.build());

                  if (downloadRequest.listenerOptional().isPresent()) {
                    downloadRequest.listenerOptional().get().onFailure(t);
                  }
                  downloadMonitorOptional
                      .get()
                      .removeDownloadListener(downloadRequest.destinationFileUri());

                  return foregroundDownloadFutureMap.remove(foregroundDownloadKey.toString());
                },
                sequentialControlExecutor);
      }
    };
  }

  @Override
  public void cancelForegroundDownload(String downloadKey) {
    LogUtil.d("%s: CancelForegroundDownload for Uri = %s", TAG, downloadKey);
    ListenableFuture<?> unused =
        PropagatedFutures.transformAsync(
            getInProgressDownloadFuture(downloadKey),
            downloadFuture -> {
              if (downloadFuture.isPresent()) {
                LogUtil.v(
                    "%s: CancelForegroundDownload future found for key = %s, cancelling...",
                    TAG, downloadKey);
                downloadFuture.get().cancel(false);
              }
              return immediateVoidFuture();
            },
            sequentialControlExecutor);
  }

  private ListenableFuture<Optional<ListenableFuture<Void>>> getInProgressDownloadFuture(
      String key) {
    return PropagatedFutures.transformAsync(
        foregroundDownloadFutureMap.containsKey(key),
        isInForeground ->
            isInForeground ? foregroundDownloadFutureMap.get(key) : downloadFutureMap.get(key),
        sequentialControlExecutor);
  }

  private static DownloadFutureMap.StateChangeCallbacks createCallbacksForForegroundService(
      Context context, Optional<Class<?>> foregroundDownloadServiceClassOptional) {
    return new DownloadFutureMap.StateChangeCallbacks() {
      @Override
      public void onAdd(String key, int newSize) {
        // Only start foreground service if this is the first future we are adding.
        if (newSize == 1 && foregroundDownloadServiceClassOptional.isPresent()) {
          NotificationUtil.startForegroundDownloadService(
              context, foregroundDownloadServiceClassOptional.get(), key);
        }
      }

      @Override
      public void onRemove(String key, int newSize) {
        // Only stop foreground service if there are no more futures remaining.
        if (newSize == 0 && foregroundDownloadServiceClassOptional.isPresent()) {
          NotificationUtil.stopForegroundDownloadService(
              context, foregroundDownloadServiceClassOptional.get(), key);
        }
      }
    };
  }
}