Rewritten queue of FileUploader based on IndexedForest
[pub/Android/ownCloud.git] / src / com / owncloud / android / files / services / FileDownloader.java
1 /**
2 * ownCloud Android client application
3 *
4 * Copyright (C) 2012 Bartek Przybylski
5 * Copyright (C) 2012-2015 ownCloud Inc.
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2,
9 * as published by the Free Software Foundation.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 *
19 */
20
21 package com.owncloud.android.files.services;
22
23 import java.io.File;
24 import java.io.IOException;
25 import java.util.AbstractList;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.Map;
29 import java.util.Vector;
30
31 import com.owncloud.android.MainApp;
32 import com.owncloud.android.R;
33 import com.owncloud.android.authentication.AccountUtils;
34 import com.owncloud.android.authentication.AuthenticatorActivity;
35 import com.owncloud.android.datamodel.FileDataStorageManager;
36 import com.owncloud.android.datamodel.OCFile;
37
38 import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
39 import com.owncloud.android.lib.common.OwnCloudAccount;
40 import com.owncloud.android.lib.common.OwnCloudClient;
41 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
42 import com.owncloud.android.notifications.NotificationBuilderWithProgressBar;
43 import com.owncloud.android.notifications.NotificationDelayer;
44 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
45 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
46 import com.owncloud.android.lib.common.utils.Log_OC;
47 import com.owncloud.android.lib.resources.files.FileUtils;
48 import com.owncloud.android.operations.DownloadFileOperation;
49 import com.owncloud.android.ui.activity.FileActivity;
50 import com.owncloud.android.ui.activity.FileDisplayActivity;
51 import com.owncloud.android.ui.preview.PreviewImageActivity;
52 import com.owncloud.android.ui.preview.PreviewImageFragment;
53 import com.owncloud.android.utils.ErrorMessageAdapter;
54
55 import android.accounts.Account;
56 import android.accounts.AccountManager;
57 import android.accounts.AccountsException;
58 import android.accounts.OnAccountsUpdateListener;
59 import android.app.NotificationManager;
60 import android.app.PendingIntent;
61 import android.app.Service;
62 import android.content.Intent;
63 import android.os.Binder;
64 import android.os.Handler;
65 import android.os.HandlerThread;
66 import android.os.IBinder;
67 import android.os.Looper;
68 import android.os.Message;
69 import android.os.Process;
70 import android.support.v4.app.NotificationCompat;
71 import android.util.Pair;
72
73 public class FileDownloader extends Service
74 implements OnDatatransferProgressListener, OnAccountsUpdateListener {
75
76 public static final String EXTRA_ACCOUNT = "ACCOUNT";
77 public static final String EXTRA_FILE = "FILE";
78
79 private static final String DOWNLOAD_ADDED_MESSAGE = "DOWNLOAD_ADDED";
80 private static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";
81 public static final String EXTRA_DOWNLOAD_RESULT = "RESULT";
82 public static final String EXTRA_FILE_PATH = "FILE_PATH";
83 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
84 public static final String EXTRA_LINKED_TO_PATH = "LINKED_TO";
85 public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
86
87 private static final String TAG = "FileDownloader";
88
89 private Looper mServiceLooper;
90 private ServiceHandler mServiceHandler;
91 private IBinder mBinder;
92 private OwnCloudClient mDownloadClient = null;
93 private Account mCurrentAccount = null;
94 private FileDataStorageManager mStorageManager;
95
96 private IndexedForest<DownloadFileOperation> mPendingDownloads = new IndexedForest<DownloadFileOperation>();
97
98 private DownloadFileOperation mCurrentDownload = null;
99
100 private NotificationManager mNotificationManager;
101 private NotificationCompat.Builder mNotificationBuilder;
102 private int mLastPercent;
103
104
105 public static String getDownloadAddedMessage() {
106 return FileDownloader.class.getName() + DOWNLOAD_ADDED_MESSAGE;
107 }
108
109 public static String getDownloadFinishMessage() {
110 return FileDownloader.class.getName() + DOWNLOAD_FINISH_MESSAGE;
111 }
112
113 /**
114 * Service initialization
115 */
116 @Override
117 public void onCreate() {
118 super.onCreate();
119 Log_OC.d(TAG, "Creating service");
120 mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
121 HandlerThread thread = new HandlerThread("FileDownloaderThread",
122 Process.THREAD_PRIORITY_BACKGROUND);
123 thread.start();
124 mServiceLooper = thread.getLooper();
125 mServiceHandler = new ServiceHandler(mServiceLooper, this);
126 mBinder = new FileDownloaderBinder();
127
128 // add AccountsUpdatedListener
129 AccountManager am = AccountManager.get(getApplicationContext());
130 am.addOnAccountsUpdatedListener(this, null, false);
131 }
132
133
134 /**
135 * Service clean up
136 */
137 @Override
138 public void onDestroy() {
139 Log_OC.v(TAG, "Destroying service");
140 mBinder = null;
141 mServiceHandler = null;
142 mServiceLooper.quit();
143 mServiceLooper = null;
144 mNotificationManager = null;
145
146 // remove AccountsUpdatedListener
147 AccountManager am = AccountManager.get(getApplicationContext());
148 am.removeOnAccountsUpdatedListener(this);
149
150 super.onDestroy();
151 }
152
153
154 /**
155 * Entry point to add one or several files to the queue of downloads.
156 * <p/>
157 * New downloads are added calling to startService(), resulting in a call to this method.
158 * This ensures the service will keep on working although the caller activity goes away.
159 */
160 @Override
161 public int onStartCommand(Intent intent, int flags, int startId) {
162 Log_OC.d(TAG, "Starting command with id " + startId);
163
164 if (!intent.hasExtra(EXTRA_ACCOUNT) ||
165 !intent.hasExtra(EXTRA_FILE)
166 ) {
167 Log_OC.e(TAG, "Not enough information provided in intent");
168 return START_NOT_STICKY;
169 } else {
170 final Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
171 final OCFile file = intent.getParcelableExtra(EXTRA_FILE);
172
173 /*Log_OC.v(
174 "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
175 "Received request to download file"
176 );*/
177
178 AbstractList<String> requestedDownloads = new Vector<String>();
179 try {
180 DownloadFileOperation newDownload = new DownloadFileOperation(account, file);
181 newDownload.addDatatransferProgressListener(this);
182 newDownload.addDatatransferProgressListener((FileDownloaderBinder) mBinder);
183 Pair<String, String> putResult = mPendingDownloads.putIfAbsent(
184 account, file.getRemotePath(), newDownload
185 );
186 String downloadKey = putResult.first;
187 requestedDownloads.add(downloadKey);
188 /*Log_OC.v(
189 "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
190 "Download on " + file.getRemotePath() + " added to queue"
191 );*/
192
193 // Store file on db with state 'downloading'
194 /*
195 TODO - check if helps with UI responsiveness,
196 letting only folders use FileDownloaderBinder to check
197 FileDataStorageManager storageManager =
198 new FileDataStorageManager(account, getContentResolver());
199 file.setDownloading(true);
200 storageManager.saveFile(file);
201 */
202
203 sendBroadcastNewDownload(newDownload, putResult.second);
204
205 } catch (IllegalArgumentException e) {
206 Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
207 return START_NOT_STICKY;
208 }
209
210 if (requestedDownloads.size() > 0) {
211 Message msg = mServiceHandler.obtainMessage();
212 msg.arg1 = startId;
213 msg.obj = requestedDownloads;
214 mServiceHandler.sendMessage(msg);
215 }
216 //}
217 }
218
219 return START_NOT_STICKY;
220 }
221
222
223 /**
224 * Provides a binder object that clients can use to perform operations on the queue of downloads,
225 * excepting the addition of new files.
226 * <p/>
227 * Implemented to perform cancellation, pause and resume of existing downloads.
228 */
229 @Override
230 public IBinder onBind(Intent arg0) {
231 return mBinder;
232 }
233
234
235 /**
236 * Called when ALL the bound clients were onbound.
237 */
238 @Override
239 public boolean onUnbind(Intent intent) {
240 ((FileDownloaderBinder) mBinder).clearListeners();
241 return false; // not accepting rebinding (default behaviour)
242 }
243
244 @Override
245 public void onAccountsUpdated(Account[] accounts) {
246 //review the current download and cancel it if its account doesn't exist
247 if (mCurrentDownload != null &&
248 !AccountUtils.exists(mCurrentDownload.getAccount(), getApplicationContext())) {
249 mCurrentDownload.cancel();
250 }
251 // The rest of downloads are cancelled when they try to start
252 }
253
254
255 /**
256 * Binder to let client components to perform operations on the queue of downloads.
257 * <p/>
258 * It provides by itself the available operations.
259 */
260 public class FileDownloaderBinder extends Binder implements OnDatatransferProgressListener {
261
262 /**
263 * Map of listeners that will be reported about progress of downloads from a
264 * {@link FileDownloaderBinder}
265 * instance.
266 */
267 private Map<Long, OnDatatransferProgressListener> mBoundListeners =
268 new HashMap<Long, OnDatatransferProgressListener>();
269
270
271 /**
272 * Cancels a pending or current download of a remote file.
273 *
274 * @param account ownCloud account where the remote file is stored.
275 * @param file A file in the queue of pending downloads
276 */
277 public void cancel(Account account, OCFile file) {
278 /*Log_OC.v(
279 "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
280 "Received request to cancel download of " + file.getRemotePath()
281 );
282 Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
283 "Removing download of " + file.getRemotePath());*/
284 Pair<DownloadFileOperation, String> removeResult =
285 mPendingDownloads.remove(account, file.getRemotePath());
286 DownloadFileOperation download = removeResult.first;
287 if (download != null) {
288 /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
289 "Canceling returned download of " + file.getRemotePath());*/
290 download.cancel();
291 } else {
292 if (mCurrentDownload != null && mCurrentAccount != null &&
293 mCurrentDownload.getRemotePath().startsWith(file.getRemotePath()) &&
294 account.name.equals(mCurrentAccount.name)) {
295 /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
296 "Canceling current sync as descendant: " + mCurrentDownload.getRemotePath());*/
297 mCurrentDownload.cancel();
298 }
299 }
300 }
301
302 /**
303 * Cancels a pending or current upload for an account
304 *
305 * @param account Owncloud accountName where the remote file will be stored.
306 */
307 public void cancel(Account account) {
308 Log_OC.d(TAG, "Account= " + account.name);
309
310 if (mCurrentDownload != null) {
311 Log_OC.d(TAG, "Current Download Account= " + mCurrentDownload.getAccount().name);
312 if (mCurrentDownload.getAccount().name.equals(account.name)) {
313 mCurrentDownload.cancel();
314 }
315 }
316 // Cancel pending downloads
317 cancelDownloadsForAccount(account);
318 }
319
320 public void clearListeners() {
321 mBoundListeners.clear();
322 }
323
324
325 /**
326 * Returns True when the file described by 'file' in the ownCloud account 'account'
327 * is downloading or waiting to download.
328 *
329 * If 'file' is a directory, returns 'true' if any of its descendant files is downloading or
330 * waiting to download.
331 *
332 * @param account ownCloud account where the remote file is stored.
333 * @param file A file that could be in the queue of downloads.
334 */
335 public boolean isDownloading(Account account, OCFile file) {
336 if (account == null || file == null) return false;
337 return (mPendingDownloads.contains(account, file.getRemotePath()));
338 }
339
340
341 /**
342 * Adds a listener interested in the progress of the download for a concrete file.
343 *
344 * @param listener Object to notify about progress of transfer.
345 * @param account ownCloud account holding the file of interest.
346 * @param file {@link OCFile} of interest for listener.
347 */
348 public void addDatatransferProgressListener(
349 OnDatatransferProgressListener listener, Account account, OCFile file
350 ) {
351 if (account == null || file == null || listener == null) return;
352 //String targetKey = buildKey(account, file.getRemotePath());
353 mBoundListeners.put(file.getFileId(), listener);
354 }
355
356
357 /**
358 * Removes a listener interested in the progress of the download for a concrete file.
359 *
360 * @param listener Object to notify about progress of transfer.
361 * @param account ownCloud account holding the file of interest.
362 * @param file {@link OCFile} of interest for listener.
363 */
364 public void removeDatatransferProgressListener(
365 OnDatatransferProgressListener listener, Account account, OCFile file
366 ) {
367 if (account == null || file == null || listener == null) return;
368 //String targetKey = buildKey(account, file.getRemotePath());
369 Long fileId = file.getFileId();
370 if (mBoundListeners.get(fileId) == listener) {
371 mBoundListeners.remove(fileId);
372 }
373 }
374
375 @Override
376 public void onTransferProgress(long progressRate, long totalTransferredSoFar,
377 long totalToTransfer, String fileName) {
378 //String key = buildKey(mCurrentDownload.getAccount(),
379 // mCurrentDownload.getFile().getRemotePath());
380 OnDatatransferProgressListener boundListener =
381 mBoundListeners.get(mCurrentDownload.getFile().getFileId());
382 if (boundListener != null) {
383 boundListener.onTransferProgress(progressRate, totalTransferredSoFar,
384 totalToTransfer, fileName);
385 }
386 }
387
388 /**
389 * Review downloads and cancel it if its account doesn't exist
390 */
391 public void checkAccountOfCurrentDownload() {
392 if (mCurrentDownload != null &&
393 !AccountUtils.exists(mCurrentDownload.getAccount(), getApplicationContext())) {
394 mCurrentDownload.cancel();
395 }
396 // The rest of downloads are cancelled when they try to start
397 }
398
399 }
400
401
402 /**
403 * Download worker. Performs the pending downloads in the order they were requested.
404 * <p/>
405 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
406 */
407 private static class ServiceHandler extends Handler {
408 // don't make it a final class, and don't remove the static ; lint will warn about a
409 // possible memory leak
410 FileDownloader mService;
411
412 public ServiceHandler(Looper looper, FileDownloader service) {
413 super(looper);
414 if (service == null)
415 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
416 mService = service;
417 }
418
419 @Override
420 public void handleMessage(Message msg) {
421 @SuppressWarnings("unchecked")
422 AbstractList<String> requestedDownloads = (AbstractList<String>) msg.obj;
423 if (msg.obj != null) {
424 Iterator<String> it = requestedDownloads.iterator();
425 while (it.hasNext()) {
426 String next = it.next();
427 mService.downloadFile(next);
428 }
429 }
430 Log_OC.d(TAG, "Stopping after command with id " + msg.arg1);
431 mService.stopSelf(msg.arg1);
432 }
433 }
434
435
436 /**
437 * Core download method: requests a file to download and stores it.
438 *
439 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
440 */
441 private void downloadFile(String downloadKey) {
442
443 mCurrentDownload = mPendingDownloads.get(downloadKey);
444
445 if (mCurrentDownload != null) {
446 // Detect if the account exists
447 if (AccountUtils.exists(mCurrentDownload.getAccount(), getApplicationContext())) {
448 Log_OC.d(TAG, "Account " + mCurrentDownload.getAccount().name + " exists");
449
450 notifyDownloadStart(mCurrentDownload);
451
452 RemoteOperationResult downloadResult = null;
453 try {
454 /// prepare client object to send the request to the ownCloud server
455 if (mCurrentAccount == null ||
456 !mCurrentAccount.equals(mCurrentDownload.getAccount())) {
457 mCurrentAccount = mCurrentDownload.getAccount();
458 mStorageManager = new FileDataStorageManager(
459 mCurrentAccount,
460 getContentResolver()
461 );
462 } // else, reuse storage manager from previous operation
463
464 // always get client from client manager, to get fresh credentials in case
465 // of update
466 OwnCloudAccount ocAccount = new OwnCloudAccount(mCurrentAccount, this);
467 mDownloadClient = OwnCloudClientManagerFactory.getDefaultSingleton().
468 getClientFor(ocAccount, this);
469
470
471 /// perform the download
472 downloadResult = mCurrentDownload.execute(mDownloadClient);
473 if (downloadResult.isSuccess()) {
474 saveDownloadedFile();
475 }
476
477 } catch (AccountsException e) {
478 Log_OC.e(TAG, "Error while trying to get authorization for "
479 + mCurrentAccount.name, e);
480 downloadResult = new RemoteOperationResult(e);
481 } catch (IOException e) {
482 Log_OC.e(TAG, "Error while trying to get authorization for "
483 + mCurrentAccount.name, e);
484 downloadResult = new RemoteOperationResult(e);
485
486 } finally {
487 Pair<DownloadFileOperation, String> removeResult =
488 mPendingDownloads.removePayload(mCurrentAccount,
489 mCurrentDownload.getRemotePath());
490
491 /// notify result
492 notifyDownloadResult(mCurrentDownload, downloadResult);
493
494 sendBroadcastDownloadFinished(mCurrentDownload, downloadResult, removeResult.second);
495 }
496
497 } else {
498 // Cancel the transfer
499 Log_OC.d(TAG, "Account " + mCurrentDownload.getAccount().toString() +
500 " doesn't exist");
501 cancelDownloadsForAccount(mCurrentDownload.getAccount());
502
503 }
504 }
505 }
506
507
508 /**
509 * Updates the OC File after a successful download.
510 */
511 private void saveDownloadedFile() {
512 OCFile file = mStorageManager.getFileById(mCurrentDownload.getFile().getFileId());
513 long syncDate = System.currentTimeMillis();
514 file.setLastSyncDateForProperties(syncDate);
515 file.setLastSyncDateForData(syncDate);
516 file.setNeedsUpdateThumbnail(true);
517 file.setModificationTimestamp(mCurrentDownload.getModificationTimestamp());
518 file.setModificationTimestampAtLastSyncForData(mCurrentDownload.getModificationTimestamp());
519 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
520 file.setMimetype(mCurrentDownload.getMimeType());
521 file.setStoragePath(mCurrentDownload.getSavePath());
522 file.setFileLength((new File(mCurrentDownload.getSavePath()).length()));
523 file.setRemoteId(mCurrentDownload.getFile().getRemoteId());
524 mStorageManager.saveFile(file);
525 mStorageManager.triggerMediaScan(file.getStoragePath());
526 }
527
528 /**
529 * Update the OC File after a unsuccessful download
530 */
531 private void updateUnsuccessfulDownloadedFile() {
532 OCFile file = mStorageManager.getFileById(mCurrentDownload.getFile().getFileId());
533 file.setDownloading(false);
534 mStorageManager.saveFile(file);
535 }
536
537
538 /**
539 * Creates a status notification to show the download progress
540 *
541 * @param download Download operation starting.
542 */
543 private void notifyDownloadStart(DownloadFileOperation download) {
544 /// create status notification with a progress bar
545 mLastPercent = 0;
546 mNotificationBuilder =
547 NotificationBuilderWithProgressBar.newNotificationBuilderWithProgressBar(this);
548 mNotificationBuilder
549 .setSmallIcon(R.drawable.notification_icon)
550 .setTicker(getString(R.string.downloader_download_in_progress_ticker))
551 .setContentTitle(getString(R.string.downloader_download_in_progress_ticker))
552 .setOngoing(true)
553 .setProgress(100, 0, download.getSize() < 0)
554 .setContentText(
555 String.format(getString(R.string.downloader_download_in_progress_content), 0,
556 new File(download.getSavePath()).getName())
557 );
558
559 /// includes a pending intent in the notification showing the details view of the file
560 Intent showDetailsIntent = null;
561 if (PreviewImageFragment.canBePreviewed(download.getFile())) {
562 showDetailsIntent = new Intent(this, PreviewImageActivity.class);
563 } else {
564 showDetailsIntent = new Intent(this, FileDisplayActivity.class);
565 }
566 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, download.getFile());
567 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, download.getAccount());
568 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
569
570 mNotificationBuilder.setContentIntent(PendingIntent.getActivity(
571 this, (int) System.currentTimeMillis(), showDetailsIntent, 0
572 ));
573
574 mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotificationBuilder.build());
575 }
576
577
578 /**
579 * Callback method to update the progress bar in the status notification.
580 */
581 @Override
582 public void onTransferProgress(long progressRate, long totalTransferredSoFar,
583 long totalToTransfer, String filePath) {
584 int percent = (int) (100.0 * ((double) totalTransferredSoFar) / ((double) totalToTransfer));
585 if (percent != mLastPercent) {
586 mNotificationBuilder.setProgress(100, percent, totalToTransfer < 0);
587 String fileName = filePath.substring(filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1);
588 String text = String.format(getString(R.string.downloader_download_in_progress_content), percent, fileName);
589 mNotificationBuilder.setContentText(text);
590 mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotificationBuilder.build());
591 }
592 mLastPercent = percent;
593 }
594
595
596 /**
597 * Updates the status notification with the result of a download operation.
598 *
599 * @param downloadResult Result of the download operation.
600 * @param download Finished download operation
601 */
602 private void notifyDownloadResult(DownloadFileOperation download,
603 RemoteOperationResult downloadResult) {
604 mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);
605 if (!downloadResult.isCancelled()) {
606 int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker :
607 R.string.downloader_download_failed_ticker;
608
609 boolean needsToUpdateCredentials = (
610 downloadResult.getCode() == ResultCode.UNAUTHORIZED ||
611 downloadResult.isIdPRedirection()
612 );
613 tickerId = (needsToUpdateCredentials) ?
614 R.string.downloader_download_failed_credentials_error : tickerId;
615
616 mNotificationBuilder
617 .setTicker(getString(tickerId))
618 .setContentTitle(getString(tickerId))
619 .setAutoCancel(true)
620 .setOngoing(false)
621 .setProgress(0, 0, false);
622
623 if (needsToUpdateCredentials) {
624
625 // let the user update credentials with one click
626 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
627 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT,
628 download.getAccount());
629 updateAccountCredentials.putExtra(
630 AuthenticatorActivity.EXTRA_ACTION,
631 AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN
632 );
633 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
634 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
635 updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
636 mNotificationBuilder
637 .setContentIntent(PendingIntent.getActivity(
638 this, (int) System.currentTimeMillis(), updateAccountCredentials,
639 PendingIntent.FLAG_ONE_SHOT));
640
641 } else {
642 // TODO put something smart in showDetailsIntent
643 Intent showDetailsIntent = new Intent();
644 mNotificationBuilder
645 .setContentIntent(PendingIntent.getActivity(
646 this, (int) System.currentTimeMillis(), showDetailsIntent, 0));
647 }
648
649 mNotificationBuilder.setContentText(
650 ErrorMessageAdapter.getErrorCauseMessage(downloadResult, download,
651 getResources())
652 );
653 mNotificationManager.notify(tickerId, mNotificationBuilder.build());
654
655 // Remove success notification
656 if (downloadResult.isSuccess()) {
657 // Sleep 2 seconds, so show the notification before remove it
658 NotificationDelayer.cancelWithDelay(
659 mNotificationManager,
660 R.string.downloader_download_succeeded_ticker,
661 2000);
662 }
663
664 }
665 }
666
667
668 /**
669 * Sends a broadcast when a download finishes in order to the interested activities can
670 * update their view
671 *
672 * @param download Finished download operation
673 * @param downloadResult Result of the download operation
674 * @param unlinkedFromRemotePath Path in the downloads tree where the download was unlinked from
675 */
676 private void sendBroadcastDownloadFinished(
677 DownloadFileOperation download,
678 RemoteOperationResult downloadResult,
679 String unlinkedFromRemotePath) {
680
681 Intent end = new Intent(getDownloadFinishMessage());
682 end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult.isSuccess());
683 end.putExtra(ACCOUNT_NAME, download.getAccount().name);
684 end.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
685 end.putExtra(EXTRA_FILE_PATH, download.getSavePath());
686 if (unlinkedFromRemotePath != null) {
687 end.putExtra(EXTRA_LINKED_TO_PATH, unlinkedFromRemotePath);
688 }
689 sendStickyBroadcast(end);
690 }
691
692
693 /**
694 * Sends a broadcast when a new download is added to the queue.
695 *
696 * @param download Added download operation
697 * @param linkedToRemotePath Path in the downloads tree where the download was linked to
698 */
699 private void sendBroadcastNewDownload(DownloadFileOperation download,
700 String linkedToRemotePath) {
701 Intent added = new Intent(getDownloadAddedMessage());
702 added.putExtra(ACCOUNT_NAME, download.getAccount().name);
703 added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
704 added.putExtra(EXTRA_FILE_PATH, download.getSavePath());
705 added.putExtra(EXTRA_LINKED_TO_PATH, linkedToRemotePath);
706 sendStickyBroadcast(added);
707 }
708
709 /**
710 * Remove downloads of an account
711 *
712 * @param account Downloads account to remove
713 */
714 private void cancelDownloadsForAccount(Account account) {
715 // Cancel pending downloads
716 mPendingDownloads.remove(account);
717 }
718 }