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