0dee6050d98a779ccc0ea02e08335738ec218f01
[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.oc_framework.network.webdav.OnDatatransferProgressListener;
37 import com.owncloud.android.oc_framework.network.webdav.OwnCloudClientFactory;
38 import com.owncloud.android.oc_framework.network.webdav.WebdavClient;
39 import com.owncloud.android.operations.DownloadFileOperation;
40 import com.owncloud.android.oc_framework.operations.RemoteOperationResult;
41 import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode;
42 import com.owncloud.android.ui.activity.FileActivity;
43 import com.owncloud.android.ui.activity.FileDisplayActivity;
44 import com.owncloud.android.ui.preview.PreviewImageActivity;
45 import com.owncloud.android.ui.preview.PreviewImageFragment;
46 import com.owncloud.android.utils.DisplayUtils;
47 import com.owncloud.android.utils.Log_OC;
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 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 private static final String DOWNLOAD_ADDED_MESSAGE = "DOWNLOAD_ADDED";
71 private 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 public static String getDownloadAddedMessage() {
95 return FileDownloader.class.getName().toString() + DOWNLOAD_ADDED_MESSAGE;
96 }
97
98 public static String getDownloadFinishMessage() {
99 return FileDownloader.class.getName().toString() + DOWNLOAD_FINISH_MESSAGE;
100 }
101
102 /**
103 * Builds a key for mPendingDownloads from the account and file to download
104 *
105 * @param account Account where the file to download is stored
106 * @param file File to download
107 */
108 private String buildRemoteName(Account account, OCFile file) {
109 return account.name + file.getRemotePath();
110 }
111
112
113 /**
114 * Service initialization
115 */
116 @Override
117 public void onCreate() {
118 super.onCreate();
119 mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
120 HandlerThread thread = new HandlerThread("FileDownloaderThread",
121 Process.THREAD_PRIORITY_BACKGROUND);
122 thread.start();
123 mServiceLooper = thread.getLooper();
124 mServiceHandler = new ServiceHandler(mServiceLooper, this);
125 mBinder = new FileDownloaderBinder();
126 }
127
128 /**
129 * Entry point to add one or several files to the queue of downloads.
130 *
131 * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
132 * although the caller activity goes away.
133 */
134 @Override
135 public int onStartCommand(Intent intent, int flags, int startId) {
136 if ( !intent.hasExtra(EXTRA_ACCOUNT) ||
137 !intent.hasExtra(EXTRA_FILE)
138 /*!intent.hasExtra(EXTRA_FILE_PATH) ||
139 !intent.hasExtra(EXTRA_REMOTE_PATH)*/
140 ) {
141 Log_OC.e(TAG, "Not enough information provided in intent");
142 return START_NOT_STICKY;
143 }
144 Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
145 OCFile file = intent.getParcelableExtra(EXTRA_FILE);
146
147 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)
148 String downloadKey = buildRemoteName(account, file);
149 try {
150 DownloadFileOperation newDownload = new DownloadFileOperation(account, file);
151 mPendingDownloads.putIfAbsent(downloadKey, newDownload);
152 newDownload.addDatatransferProgressListener(this);
153 newDownload.addDatatransferProgressListener((FileDownloaderBinder)mBinder);
154 requestedDownloads.add(downloadKey);
155 sendBroadcastNewDownload(newDownload);
156
157 } catch (IllegalArgumentException e) {
158 Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
159 return START_NOT_STICKY;
160 }
161
162 if (requestedDownloads.size() > 0) {
163 Message msg = mServiceHandler.obtainMessage();
164 msg.arg1 = startId;
165 msg.obj = requestedDownloads;
166 mServiceHandler.sendMessage(msg);
167 }
168
169 return START_NOT_STICKY;
170 }
171
172
173 /**
174 * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
175 *
176 * Implemented to perform cancellation, pause and resume of existing downloads.
177 */
178 @Override
179 public IBinder onBind(Intent arg0) {
180 return mBinder;
181 }
182
183
184 /**
185 * Called when ALL the bound clients were onbound.
186 */
187 @Override
188 public boolean onUnbind(Intent intent) {
189 ((FileDownloaderBinder)mBinder).clearListeners();
190 return false; // not accepting rebinding (default behaviour)
191 }
192
193
194 /**
195 * Binder to let client components to perform operations on the queue of downloads.
196 *
197 * It provides by itself the available operations.
198 */
199 public class FileDownloaderBinder extends Binder implements OnDatatransferProgressListener {
200
201 /**
202 * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder} instance
203 */
204 private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<String, OnDatatransferProgressListener>();
205
206
207 /**
208 * Cancels a pending or current download of a remote file.
209 *
210 * @param account Owncloud account where the remote file is stored.
211 * @param file A file in the queue of pending downloads
212 */
213 public void cancel(Account account, OCFile file) {
214 DownloadFileOperation download = null;
215 synchronized (mPendingDownloads) {
216 download = mPendingDownloads.remove(buildRemoteName(account, file));
217 }
218 if (download != null) {
219 download.cancel();
220 }
221 }
222
223
224 public void clearListeners() {
225 mBoundListeners.clear();
226 }
227
228
229 /**
230 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
231 *
232 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
233 *
234 * @param account Owncloud account where the remote file is stored.
235 * @param file A file that could be in the queue of downloads.
236 */
237 public boolean isDownloading(Account account, OCFile file) {
238 if (account == null || file == null) return false;
239 String targetKey = buildRemoteName(account, file);
240 synchronized (mPendingDownloads) {
241 if (file.isFolder()) {
242 // this can be slow if there are many downloads :(
243 Iterator<String> it = mPendingDownloads.keySet().iterator();
244 boolean found = false;
245 while (it.hasNext() && !found) {
246 found = it.next().startsWith(targetKey);
247 }
248 return found;
249 } else {
250 return (mPendingDownloads.containsKey(targetKey));
251 }
252 }
253 }
254
255
256 /**
257 * Adds a listener interested in the progress of the download for a concrete file.
258 *
259 * @param listener Object to notify about progress of transfer.
260 * @param account ownCloud account holding the file of interest.
261 * @param file {@link OCfile} of interest for listener.
262 */
263 public void addDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
264 if (account == null || file == null || listener == null) return;
265 String targetKey = buildRemoteName(account, file);
266 mBoundListeners.put(targetKey, listener);
267 }
268
269
270 /**
271 * Removes a listener interested in the progress of the download for a concrete file.
272 *
273 * @param listener Object to notify about progress of transfer.
274 * @param account ownCloud account holding the file of interest.
275 * @param file {@link OCfile} of interest for listener.
276 */
277 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
278 if (account == null || file == null || listener == null) return;
279 String targetKey = buildRemoteName(account, file);
280 if (mBoundListeners.get(targetKey) == listener) {
281 mBoundListeners.remove(targetKey);
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 = OwnCloudClientFactory.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(DisplayUtils.getSeasonalIconId(), 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, DisplayUtils.getSeasonalIconId());
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 * Updates the status notification with the result of a download operation.
447 *
448 * @param downloadResult Result of the download operation.
449 * @param download Finished download operation
450 */
451 private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) {
452 mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);
453 if (!downloadResult.isCancelled()) {
454 int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker : R.string.downloader_download_failed_ticker;
455 int contentId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_content : R.string.downloader_download_failed_content;
456 Notification finalNotification = new Notification(DisplayUtils.getSeasonalIconId(), getString(tickerId), System.currentTimeMillis());
457 finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
458 boolean needsToUpdateCredentials = (downloadResult.getCode() == ResultCode.UNAUTHORIZED ||
459 // (downloadResult.isTemporalRedirection() && downloadResult.isIdPRedirection()
460 (downloadResult.isIdPRedirection()
461 && mDownloadClient.getCredentials() == null));
462 //&& MainApp.getAuthTokenTypeSamlSessionCookie().equals(mDownloadClient.getAuthTokenType())));
463 if (needsToUpdateCredentials) {
464 // let the user update credentials with one click
465 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
466 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, download.getAccount());
467 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ENFORCED_UPDATE, true);
468 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_TOKEN);
469 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
470 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
471 updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
472 finalNotification.contentIntent = PendingIntent.getActivity(this, (int)System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT);
473 finalNotification.setLatestEventInfo( getApplicationContext(),
474 getString(tickerId),
475 String.format(getString(contentId), new File(download.getSavePath()).getName()),
476 finalNotification.contentIntent);
477 mDownloadClient = null; // grant that future retries on the same account will get the fresh credentials
478
479 } else {
480 Intent showDetailsIntent = null;
481 if (downloadResult.isSuccess()) {
482 if (PreviewImageFragment.canBePreviewed(download.getFile())) {
483 showDetailsIntent = new Intent(this, PreviewImageActivity.class);
484 } else {
485 showDetailsIntent = new Intent(this, FileDisplayActivity.class);
486 }
487 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, download.getFile());
488 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, download.getAccount());
489 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
490
491 } else {
492 // TODO put something smart in showDetailsIntent
493 showDetailsIntent = new Intent();
494 }
495 finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
496 finalNotification.setLatestEventInfo(getApplicationContext(), getString(tickerId), String.format(getString(contentId), new File(download.getSavePath()).getName()), finalNotification.contentIntent);
497 }
498 mNotificationManager.notify(tickerId, finalNotification);
499 }
500 }
501
502
503 /**
504 * Sends a broadcast when a download finishes in order to the interested activities can update their view
505 *
506 * @param download Finished download operation
507 * @param downloadResult Result of the download operation
508 */
509 private void sendBroadcastDownloadFinished(DownloadFileOperation download, RemoteOperationResult downloadResult) {
510 Intent end = new Intent(getDownloadFinishMessage());
511 end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult.isSuccess());
512 end.putExtra(ACCOUNT_NAME, download.getAccount().name);
513 end.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
514 end.putExtra(EXTRA_FILE_PATH, download.getSavePath());
515 sendStickyBroadcast(end);
516 }
517
518
519 /**
520 * Sends a broadcast when a new download is added to the queue.
521 *
522 * @param download Added download operation
523 */
524 private void sendBroadcastNewDownload(DownloadFileOperation download) {
525 Intent added = new Intent(getDownloadAddedMessage());
526 added.putExtra(ACCOUNT_NAME, download.getAccount().name);
527 added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
528 added.putExtra(EXTRA_FILE_PATH, download.getSavePath());
529 sendStickyBroadcast(added);
530 }
531
532 }