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