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