Merge branch 'fix_protocol_send_mail' into fix_logs_change_orientation
[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-2013 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 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.ConcurrentMap;
30
31 import com.owncloud.android.R;
32 import com.owncloud.android.authentication.AuthenticatorActivity;
33 import com.owncloud.android.datamodel.FileDataStorageManager;
34 import com.owncloud.android.datamodel.OCFile;
35
36 import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
37 import com.owncloud.android.lib.common.OwnCloudAccount;
38 import com.owncloud.android.lib.common.OwnCloudClient;
39 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
40 import com.owncloud.android.notifications.NotificationBuilderWithProgressBar;
41 import com.owncloud.android.notifications.NotificationDelayer;
42 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
43 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
44 import com.owncloud.android.lib.common.utils.Log_OC;
45 import com.owncloud.android.lib.resources.files.FileUtils;
46 import com.owncloud.android.operations.DownloadFileOperation;
47 import com.owncloud.android.ui.activity.FileActivity;
48 import com.owncloud.android.ui.activity.FileDisplayActivity;
49 import com.owncloud.android.ui.preview.PreviewImageActivity;
50 import com.owncloud.android.ui.preview.PreviewImageFragment;
51 import com.owncloud.android.utils.ErrorMessageAdapter;
52
53 import android.accounts.Account;
54 import android.accounts.AccountsException;
55 import android.app.NotificationManager;
56 import android.app.PendingIntent;
57 import android.app.Service;
58 import android.content.Intent;
59 import android.os.Binder;
60 import android.os.Handler;
61 import android.os.HandlerThread;
62 import android.os.IBinder;
63 import android.os.Looper;
64 import android.os.Message;
65 import android.os.Process;
66 import android.support.v4.app.NotificationCompat;
67
68 public class FileDownloader extends Service implements OnDatatransferProgressListener {
69
70 public static final String EXTRA_ACCOUNT = "ACCOUNT";
71 public static final String EXTRA_FILE = "FILE";
72
73 private static final String DOWNLOAD_ADDED_MESSAGE = "DOWNLOAD_ADDED";
74 private static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";
75 public static final String EXTRA_DOWNLOAD_RESULT = "RESULT";
76 public static final String EXTRA_FILE_PATH = "FILE_PATH";
77 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
78 public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
79
80 private static final String TAG = "FileDownloader";
81
82 private Looper mServiceLooper;
83 private ServiceHandler mServiceHandler;
84 private IBinder mBinder;
85 private OwnCloudClient mDownloadClient = null;
86 private Account mLastAccount = null;
87 private FileDataStorageManager mStorageManager;
88
89 private ConcurrentMap<String, DownloadFileOperation> mPendingDownloads = new ConcurrentHashMap<String, DownloadFileOperation>();
90 private DownloadFileOperation mCurrentDownload = null;
91
92 private NotificationManager mNotificationManager;
93 private NotificationCompat.Builder mNotificationBuilder;
94 private int mLastPercent;
95
96
97 public static String getDownloadAddedMessage() {
98 return FileDownloader.class.getName().toString() + DOWNLOAD_ADDED_MESSAGE;
99 }
100
101 public static String getDownloadFinishMessage() {
102 return FileDownloader.class.getName().toString() + DOWNLOAD_FINISH_MESSAGE;
103 }
104
105 /**
106 * Builds a key for mPendingDownloads from the account and file to download
107 *
108 * @param account Account where the file to download is stored
109 * @param file File to download
110 */
111 private String buildRemoteName(Account account, OCFile file) {
112 return account.name + file.getRemotePath();
113 }
114
115
116 /**
117 * Service initialization
118 */
119 @Override
120 public void onCreate() {
121 super.onCreate();
122 mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
123 HandlerThread thread = new HandlerThread("FileDownloaderThread",
124 Process.THREAD_PRIORITY_BACKGROUND);
125 thread.start();
126 mServiceLooper = thread.getLooper();
127 mServiceHandler = new ServiceHandler(mServiceLooper, this);
128 mBinder = new FileDownloaderBinder();
129 }
130
131 /**
132 * Entry point to add one or several files to the queue of downloads.
133 *
134 * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
135 * although the caller activity goes away.
136 */
137 @Override
138 public int onStartCommand(Intent intent, int flags, int startId) {
139 if ( !intent.hasExtra(EXTRA_ACCOUNT) ||
140 !intent.hasExtra(EXTRA_FILE)
141 /*!intent.hasExtra(EXTRA_FILE_PATH) ||
142 !intent.hasExtra(EXTRA_REMOTE_PATH)*/
143 ) {
144 Log_OC.e(TAG, "Not enough information provided in intent");
145 return START_NOT_STICKY;
146 }
147 Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
148 OCFile file = intent.getParcelableExtra(EXTRA_FILE);
149
150 AbstractList<String> requestedDownloads = new Vector<String>(); // dvelasco: now this always contains just one element, but that can change in a near future (download of multiple selection)
151 String downloadKey = buildRemoteName(account, file);
152 try {
153 DownloadFileOperation newDownload = new DownloadFileOperation(account, file);
154 mPendingDownloads.putIfAbsent(downloadKey, newDownload);
155 newDownload.addDatatransferProgressListener(this);
156 newDownload.addDatatransferProgressListener((FileDownloaderBinder)mBinder);
157 requestedDownloads.add(downloadKey);
158 sendBroadcastNewDownload(newDownload);
159
160 } catch (IllegalArgumentException e) {
161 Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
162 return START_NOT_STICKY;
163 }
164
165 if (requestedDownloads.size() > 0) {
166 Message msg = mServiceHandler.obtainMessage();
167 msg.arg1 = startId;
168 msg.obj = requestedDownloads;
169 mServiceHandler.sendMessage(msg);
170 }
171
172 return START_NOT_STICKY;
173 }
174
175
176 /**
177 * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
178 *
179 * Implemented to perform cancellation, pause and resume of existing downloads.
180 */
181 @Override
182 public IBinder onBind(Intent arg0) {
183 return mBinder;
184 }
185
186
187 /**
188 * Called when ALL the bound clients were onbound.
189 */
190 @Override
191 public boolean onUnbind(Intent intent) {
192 ((FileDownloaderBinder)mBinder).clearListeners();
193 return false; // not accepting rebinding (default behaviour)
194 }
195
196
197 /**
198 * Binder to let client components to perform operations on the queue of downloads.
199 *
200 * It provides by itself the available operations.
201 */
202 public class FileDownloaderBinder extends Binder implements OnDatatransferProgressListener {
203
204 /**
205 * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder} instance
206 */
207 private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<String, OnDatatransferProgressListener>();
208
209
210 /**
211 * Cancels a pending or current download of a remote file.
212 *
213 * @param account Owncloud account where the remote file is stored.
214 * @param file A file in the queue of pending downloads
215 */
216 public void cancel(Account account, OCFile file) {
217 DownloadFileOperation download = null;
218 synchronized (mPendingDownloads) {
219 download = mPendingDownloads.remove(buildRemoteName(account, file));
220 }
221 if (download != null) {
222 download.cancel();
223 }
224 }
225
226
227 public void clearListeners() {
228 mBoundListeners.clear();
229 }
230
231
232 /**
233 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
234 *
235 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
236 *
237 * @param account Owncloud account where the remote file is stored.
238 * @param file A file that could be in the queue of downloads.
239 */
240 public boolean isDownloading(Account account, OCFile file) {
241 if (account == null || file == null) return false;
242 String targetKey = buildRemoteName(account, file);
243 synchronized (mPendingDownloads) {
244 if (file.isFolder()) {
245 // this can be slow if there are many downloads :(
246 Iterator<String> it = mPendingDownloads.keySet().iterator();
247 boolean found = false;
248 while (it.hasNext() && !found) {
249 found = it.next().startsWith(targetKey);
250 }
251 return found;
252 } else {
253 return (mPendingDownloads.containsKey(targetKey));
254 }
255 }
256 }
257
258
259 /**
260 * Adds a listener interested in the progress of the download for a concrete file.
261 *
262 * @param listener Object to notify about progress of transfer.
263 * @param account ownCloud account holding the file of interest.
264 * @param file {@link OCfile} of interest for listener.
265 */
266 public void addDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
267 if (account == null || file == null || listener == null) return;
268 String targetKey = buildRemoteName(account, file);
269 mBoundListeners.put(targetKey, listener);
270 }
271
272
273 /**
274 * Removes a listener interested in the progress of the download for a concrete file.
275 *
276 * @param listener Object to notify about progress of transfer.
277 * @param account ownCloud account holding the file of interest.
278 * @param file {@link OCfile} of interest for listener.
279 */
280 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
281 if (account == null || file == null || listener == null) return;
282 String targetKey = buildRemoteName(account, file);
283 if (mBoundListeners.get(targetKey) == listener) {
284 mBoundListeners.remove(targetKey);
285 }
286 }
287
288 @Override
289 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer,
290 String fileName) {
291 String key = buildRemoteName(mCurrentDownload.getAccount(), mCurrentDownload.getFile());
292 OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
293 if (boundListener != null) {
294 boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, fileName);
295 }
296 }
297
298 }
299
300
301 /**
302 * Download worker. Performs the pending downloads in the order they were requested.
303 *
304 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
305 */
306 private static class ServiceHandler extends Handler {
307 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
308 FileDownloader mService;
309 public ServiceHandler(Looper looper, FileDownloader service) {
310 super(looper);
311 if (service == null)
312 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
313 mService = service;
314 }
315
316 @Override
317 public void handleMessage(Message msg) {
318 @SuppressWarnings("unchecked")
319 AbstractList<String> requestedDownloads = (AbstractList<String>) msg.obj;
320 if (msg.obj != null) {
321 Iterator<String> it = requestedDownloads.iterator();
322 while (it.hasNext()) {
323 mService.downloadFile(it.next());
324 }
325 }
326 mService.stopSelf(msg.arg1);
327 }
328 }
329
330
331 /**
332 * Core download method: requests a file to download and stores it.
333 *
334 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
335 */
336 private void downloadFile(String downloadKey) {
337
338 synchronized(mPendingDownloads) {
339 mCurrentDownload = mPendingDownloads.get(downloadKey);
340 }
341
342 if (mCurrentDownload != null) {
343
344 notifyDownloadStart(mCurrentDownload);
345
346 RemoteOperationResult downloadResult = null;
347 try {
348 /// prepare client object to send the request to the ownCloud server
349 if (mDownloadClient == null || !mLastAccount.equals(mCurrentDownload.getAccount())) {
350 mLastAccount = mCurrentDownload.getAccount();
351 mStorageManager =
352 new FileDataStorageManager(mLastAccount, getContentResolver());
353 OwnCloudAccount ocAccount = new OwnCloudAccount(mLastAccount, this);
354 mDownloadClient = OwnCloudClientManagerFactory.getDefaultSingleton().
355 getClientFor(ocAccount, this);
356 }
357
358 /// perform the download
359 downloadResult = mCurrentDownload.execute(mDownloadClient);
360 if (downloadResult.isSuccess()) {
361 saveDownloadedFile();
362 }
363
364 } catch (AccountsException e) {
365 Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
366 downloadResult = new RemoteOperationResult(e);
367 } catch (IOException e) {
368 Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
369 downloadResult = new RemoteOperationResult(e);
370
371 } finally {
372 synchronized(mPendingDownloads) {
373 mPendingDownloads.remove(downloadKey);
374 }
375 }
376
377
378 /// notify result
379 notifyDownloadResult(mCurrentDownload, downloadResult);
380
381 sendBroadcastDownloadFinished(mCurrentDownload, downloadResult);
382 }
383 }
384
385
386 /**
387 * Updates the OC File after a successful download.
388 */
389 private void saveDownloadedFile() {
390 OCFile file = mStorageManager.getFileById(mCurrentDownload.getFile().getFileId());
391 long syncDate = System.currentTimeMillis();
392 file.setLastSyncDateForProperties(syncDate);
393 file.setLastSyncDateForData(syncDate);
394 file.setNeedsUpdateThumbnail(true);
395 file.setModificationTimestamp(mCurrentDownload.getModificationTimestamp());
396 file.setModificationTimestampAtLastSyncForData(mCurrentDownload.getModificationTimestamp());
397 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
398 file.setMimetype(mCurrentDownload.getMimeType());
399 file.setStoragePath(mCurrentDownload.getSavePath());
400 file.setFileLength((new File(mCurrentDownload.getSavePath()).length()));
401 file.setRemoteId(mCurrentDownload.getFile().getRemoteId());
402 mStorageManager.saveFile(file);
403 mStorageManager.triggerMediaScan(file.getStoragePath());
404 }
405
406
407 /**
408 * Creates a status notification to show the download progress
409 *
410 * @param download Download operation starting.
411 */
412 private void notifyDownloadStart(DownloadFileOperation download) {
413 /// create status notification with a progress bar
414 mLastPercent = 0;
415 mNotificationBuilder =
416 NotificationBuilderWithProgressBar.newNotificationBuilderWithProgressBar(this);
417 mNotificationBuilder
418 .setSmallIcon(R.drawable.notification_icon)
419 .setTicker(getString(R.string.downloader_download_in_progress_ticker))
420 .setContentTitle(getString(R.string.downloader_download_in_progress_ticker))
421 .setOngoing(true)
422 .setProgress(100, 0, download.getSize() < 0)
423 .setContentText(
424 String.format(getString(R.string.downloader_download_in_progress_content), 0,
425 new File(download.getSavePath()).getName())
426 );
427
428 /// includes a pending intent in the notification showing the details view of the file
429 Intent showDetailsIntent = null;
430 if (PreviewImageFragment.canBePreviewed(download.getFile())) {
431 showDetailsIntent = new Intent(this, PreviewImageActivity.class);
432 } else {
433 showDetailsIntent = new Intent(this, FileDisplayActivity.class);
434 }
435 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, download.getFile());
436 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, download.getAccount());
437 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
438
439 mNotificationBuilder.setContentIntent(PendingIntent.getActivity(
440 this, (int) System.currentTimeMillis(), showDetailsIntent, 0
441 ));
442
443 mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotificationBuilder.build());
444 }
445
446
447 /**
448 * Callback method to update the progress bar in the status notification.
449 */
450 @Override
451 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filePath) {
452 int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
453 if (percent != mLastPercent) {
454 mNotificationBuilder.setProgress(100, percent, totalToTransfer < 0);
455 String fileName = filePath.substring(filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1);
456 String text = String.format(getString(R.string.downloader_download_in_progress_content), percent, fileName);
457 mNotificationBuilder.setContentText(text);
458 mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotificationBuilder.build());
459 }
460 mLastPercent = percent;
461 }
462
463
464 /**
465 * Updates the status notification with the result of a download operation.
466 *
467 * @param downloadResult Result of the download operation.
468 * @param download Finished download operation
469 */
470 private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) {
471 mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);
472 if (!downloadResult.isCancelled()) {
473 int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker :
474 R.string.downloader_download_failed_ticker;
475
476 boolean needsToUpdateCredentials = (
477 downloadResult.getCode() == ResultCode.UNAUTHORIZED ||
478 downloadResult.isIdPRedirection()
479 );
480 tickerId = (needsToUpdateCredentials) ?
481 R.string.downloader_download_failed_credentials_error : tickerId;
482
483 mNotificationBuilder
484 .setTicker(getString(tickerId))
485 .setContentTitle(getString(tickerId))
486 .setAutoCancel(true)
487 .setOngoing(false)
488 .setProgress(0, 0, false);
489
490 if (needsToUpdateCredentials) {
491
492 // let the user update credentials with one click
493 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
494 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, download.getAccount());
495 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
496 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
497 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
498 updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
499 mNotificationBuilder
500 .setContentIntent(PendingIntent.getActivity(
501 this, (int) System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT));
502
503 mDownloadClient = null; // grant that future retries on the same account will get the fresh credentials
504
505 } else {
506 // TODO put something smart in showDetailsIntent
507 Intent showDetailsIntent = new Intent();
508 mNotificationBuilder
509 .setContentIntent(PendingIntent.getActivity(
510 this, (int) System.currentTimeMillis(), showDetailsIntent, 0));
511 }
512
513 mNotificationBuilder.setContentText(ErrorMessageAdapter.getErrorCauseMessage(downloadResult, download, getResources()));
514 mNotificationManager.notify(tickerId, mNotificationBuilder.build());
515
516 // Remove success notification
517 if (downloadResult.isSuccess()) {
518 // Sleep 2 seconds, so show the notification before remove it
519 NotificationDelayer.cancelWithDelay(
520 mNotificationManager,
521 R.string.downloader_download_succeeded_ticker,
522 2000);
523 }
524
525 }
526 }
527
528
529 /**
530 * Sends a broadcast when a download finishes in order to the interested activities can update their view
531 *
532 * @param download Finished download operation
533 * @param downloadResult Result of the download operation
534 */
535 private void sendBroadcastDownloadFinished(DownloadFileOperation download, RemoteOperationResult downloadResult) {
536 Intent end = new Intent(getDownloadFinishMessage());
537 end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult.isSuccess());
538 end.putExtra(ACCOUNT_NAME, download.getAccount().name);
539 end.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
540 end.putExtra(EXTRA_FILE_PATH, download.getSavePath());
541 sendStickyBroadcast(end);
542 }
543
544
545 /**
546 * Sends a broadcast when a new download is added to the queue.
547 *
548 * @param download Added download operation
549 */
550 private void sendBroadcastNewDownload(DownloadFileOperation download) {
551 Intent added = new Intent(getDownloadAddedMessage());
552 added.putExtra(ACCOUNT_NAME, download.getAccount().name);
553 added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
554 added.putExtra(EXTRA_FILE_PATH, download.getSavePath());
555 sendStickyBroadcast(added);
556 }
557
558 }