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