Merge branch 'develop' into share_link__unshare_file
[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.lib.network.OnDatatransferProgressListener;
37 import com.owncloud.android.lib.network.OwnCloudClientFactory;
38 import com.owncloud.android.lib.network.OwnCloudClient;
39 import com.owncloud.android.operations.DownloadFileOperation;
40 import com.owncloud.android.lib.operations.common.RemoteOperationResult;
41 import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode;
42 import com.owncloud.android.lib.utils.FileUtils;
43 import com.owncloud.android.ui.activity.FileActivity;
44 import com.owncloud.android.ui.activity.FileDisplayActivity;
45 import com.owncloud.android.ui.preview.PreviewImageActivity;
46 import com.owncloud.android.ui.preview.PreviewImageFragment;
47 import com.owncloud.android.utils.DisplayUtils;
48 import com.owncloud.android.utils.Log_OC;
49
50 import android.accounts.Account;
51 import android.accounts.AccountsException;
52 import android.app.Notification;
53 import android.app.NotificationManager;
54 import android.app.PendingIntent;
55 import android.app.Service;
56 import android.content.Intent;
57 import android.os.Binder;
58 import android.os.Handler;
59 import android.os.HandlerThread;
60 import android.os.IBinder;
61 import android.os.Looper;
62 import android.os.Message;
63 import android.os.Process;
64 import android.widget.RemoteViews;
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 OwnCloudClient 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 @Override
287 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer,
288 String fileName) {
289 String key = buildRemoteName(mCurrentDownload.getAccount(), mCurrentDownload.getFile());
290 OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
291 if (boundListener != null) {
292 boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, fileName);
293 }
294 }
295
296 }
297
298
299 /**
300 * Download worker. Performs the pending downloads in the order they were requested.
301 *
302 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
303 */
304 private static class ServiceHandler extends Handler {
305 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
306 FileDownloader mService;
307 public ServiceHandler(Looper looper, FileDownloader service) {
308 super(looper);
309 if (service == null)
310 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
311 mService = service;
312 }
313
314 @Override
315 public void handleMessage(Message msg) {
316 @SuppressWarnings("unchecked")
317 AbstractList<String> requestedDownloads = (AbstractList<String>) msg.obj;
318 if (msg.obj != null) {
319 Iterator<String> it = requestedDownloads.iterator();
320 while (it.hasNext()) {
321 mService.downloadFile(it.next());
322 }
323 }
324 mService.stopSelf(msg.arg1);
325 }
326 }
327
328
329 /**
330 * Core download method: requests a file to download and stores it.
331 *
332 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
333 */
334 private void downloadFile(String downloadKey) {
335
336 synchronized(mPendingDownloads) {
337 mCurrentDownload = mPendingDownloads.get(downloadKey);
338 }
339
340 if (mCurrentDownload != null) {
341
342 notifyDownloadStart(mCurrentDownload);
343
344 RemoteOperationResult downloadResult = null;
345 try {
346 /// prepare client object to send the request to the ownCloud server
347 if (mDownloadClient == null || !mLastAccount.equals(mCurrentDownload.getAccount())) {
348 mLastAccount = mCurrentDownload.getAccount();
349 mStorageManager = new FileDataStorageManager(mLastAccount, getContentResolver());
350 mDownloadClient = OwnCloudClientFactory.createOwnCloudClient(mLastAccount, getApplicationContext());
351 }
352
353 /// perform the download
354 downloadResult = mCurrentDownload.execute(mDownloadClient);
355 if (downloadResult.isSuccess()) {
356 saveDownloadedFile();
357 }
358
359 } catch (AccountsException e) {
360 Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
361 downloadResult = new RemoteOperationResult(e);
362 } catch (IOException e) {
363 Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
364 downloadResult = new RemoteOperationResult(e);
365
366 } finally {
367 synchronized(mPendingDownloads) {
368 mPendingDownloads.remove(downloadKey);
369 }
370 }
371
372
373 /// notify result
374 notifyDownloadResult(mCurrentDownload, downloadResult);
375
376 sendBroadcastDownloadFinished(mCurrentDownload, downloadResult);
377 }
378 }
379
380
381 /**
382 * Updates the OC File after a successful download.
383 */
384 private void saveDownloadedFile() {
385 OCFile file = mStorageManager.getFileById(mCurrentDownload.getFile().getFileId());
386 long syncDate = System.currentTimeMillis();
387 file.setLastSyncDateForProperties(syncDate);
388 file.setLastSyncDateForData(syncDate);
389 file.setModificationTimestamp(mCurrentDownload.getModificationTimestamp());
390 file.setModificationTimestampAtLastSyncForData(mCurrentDownload.getModificationTimestamp());
391 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
392 file.setMimetype(mCurrentDownload.getMimeType());
393 file.setStoragePath(mCurrentDownload.getSavePath());
394 file.setFileLength((new File(mCurrentDownload.getSavePath()).length()));
395 mStorageManager.saveFile(file);
396 }
397
398
399 /**
400 * Creates a status notification to show the download progress
401 *
402 * @param download Download operation starting.
403 */
404 private void notifyDownloadStart(DownloadFileOperation download) {
405 /// create status notification with a progress bar
406 mLastPercent = 0;
407 mNotification = new Notification(DisplayUtils.getSeasonalIconId(), getString(R.string.downloader_download_in_progress_ticker), System.currentTimeMillis());
408 mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
409 mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
410 mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, download.getSize() < 0);
411 mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), 0, new File(download.getSavePath()).getName()));
412 mNotification.contentView.setImageViewResource(R.id.status_icon, DisplayUtils.getSeasonalIconId());
413
414 /// includes a pending intent in the notification showing the details view of the file
415 Intent showDetailsIntent = null;
416 if (PreviewImageFragment.canBePreviewed(download.getFile())) {
417 showDetailsIntent = new Intent(this, PreviewImageActivity.class);
418 } else {
419 showDetailsIntent = new Intent(this, FileDisplayActivity.class);
420 }
421 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, download.getFile());
422 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, download.getAccount());
423 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
424 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
425
426 mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotification);
427 }
428
429
430 /**
431 * Callback method to update the progress bar in the status notification.
432 */
433 @Override
434 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filePath) {
435 int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
436 if (percent != mLastPercent) {
437 mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, totalToTransfer < 0);
438 String fileName = filePath.substring(filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1);
439 String text = String.format(getString(R.string.downloader_download_in_progress_content), percent, fileName);
440 mNotification.contentView.setTextViewText(R.id.status_text, text);
441 mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotification);
442 }
443 mLastPercent = percent;
444 }
445
446
447 /**
448 * Updates the status notification with the result of a download operation.
449 *
450 * @param downloadResult Result of the download operation.
451 * @param download Finished download operation
452 */
453 private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) {
454 mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);
455 if (!downloadResult.isCancelled()) {
456 int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker : R.string.downloader_download_failed_ticker;
457 int contentId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_content : R.string.downloader_download_failed_content;
458 Notification finalNotification = new Notification(DisplayUtils.getSeasonalIconId(), getString(tickerId), System.currentTimeMillis());
459 finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
460 boolean needsToUpdateCredentials = (downloadResult.getCode() == ResultCode.UNAUTHORIZED ||
461 // (downloadResult.isTemporalRedirection() && downloadResult.isIdPRedirection()
462 (downloadResult.isIdPRedirection()
463 && mDownloadClient.getCredentials() == null));
464 //&& MainApp.getAuthTokenTypeSamlSessionCookie().equals(mDownloadClient.getAuthTokenType())));
465 if (needsToUpdateCredentials) {
466 // let the user update credentials with one click
467 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
468 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, download.getAccount());
469 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ENFORCED_UPDATE, true);
470 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_TOKEN);
471 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
472 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
473 updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
474 finalNotification.contentIntent = PendingIntent.getActivity(this, (int)System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT);
475 finalNotification.setLatestEventInfo( getApplicationContext(),
476 getString(tickerId),
477 String.format(getString(contentId), new File(download.getSavePath()).getName()),
478 finalNotification.contentIntent);
479 mDownloadClient = null; // grant that future retries on the same account will get the fresh credentials
480
481 } else {
482 Intent showDetailsIntent = null;
483 if (downloadResult.isSuccess()) {
484 if (PreviewImageFragment.canBePreviewed(download.getFile())) {
485 showDetailsIntent = new Intent(this, PreviewImageActivity.class);
486 } else {
487 showDetailsIntent = new Intent(this, FileDisplayActivity.class);
488 }
489 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, download.getFile());
490 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, download.getAccount());
491 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
492
493 } else {
494 // TODO put something smart in showDetailsIntent
495 showDetailsIntent = new Intent();
496 }
497 finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
498 finalNotification.setLatestEventInfo(getApplicationContext(), getString(tickerId), String.format(getString(contentId), new File(download.getSavePath()).getName()), finalNotification.contentIntent);
499 }
500 mNotificationManager.notify(tickerId, finalNotification);
501 }
502 }
503
504
505 /**
506 * Sends a broadcast when a download finishes in order to the interested activities can update their view
507 *
508 * @param download Finished download operation
509 * @param downloadResult Result of the download operation
510 */
511 private void sendBroadcastDownloadFinished(DownloadFileOperation download, RemoteOperationResult downloadResult) {
512 Intent end = new Intent(getDownloadFinishMessage());
513 end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult.isSuccess());
514 end.putExtra(ACCOUNT_NAME, download.getAccount().name);
515 end.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
516 end.putExtra(EXTRA_FILE_PATH, download.getSavePath());
517 sendStickyBroadcast(end);
518 }
519
520
521 /**
522 * Sends a broadcast when a new download is added to the queue.
523 *
524 * @param download Added download operation
525 */
526 private void sendBroadcastNewDownload(DownloadFileOperation download) {
527 Intent added = new Intent(getDownloadAddedMessage());
528 added.putExtra(ACCOUNT_NAME, download.getAccount().name);
529 added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
530 added.putExtra(EXTRA_FILE_PATH, download.getSavePath());
531 sendStickyBroadcast(added);
532 }
533
534 }