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