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