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