Fixed lack of synchronization on local changes for kept-in-sync files
[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.operations.DownloadFileOperation;
40 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
41 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
42 import com.owncloud.android.lib.resources.files.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.ErrorMessageAdapter;
48 import com.owncloud.android.utils.Log_OC;
49 import com.owncloud.android.utils.NotificationBuilderWithProgressBar;
50
51 import android.accounts.Account;
52 import android.accounts.AccountsException;
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.support.v4.app.NotificationCompat;
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 NotificationCompat.Builder mNotificationBuilder;
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 mNotificationBuilder =
408 NotificationBuilderWithProgressBar.newNotificationBuilderWithProgressBar(this);
409 mNotificationBuilder
410 .setSmallIcon(R.drawable.notification_icon)
411 .setTicker(getString(R.string.downloader_download_in_progress_ticker))
412 .setContentTitle(getString(R.string.downloader_download_in_progress_ticker))
413 .setOngoing(true)
414 .setProgress(100, 0, download.getSize() < 0)
415 .setContentText(
416 String.format(getString(R.string.downloader_download_in_progress_content), 0,
417 new File(download.getSavePath()).getName())
418 );
419
420 /// includes a pending intent in the notification showing the details view of the file
421 Intent showDetailsIntent = null;
422 if (PreviewImageFragment.canBePreviewed(download.getFile())) {
423 showDetailsIntent = new Intent(this, PreviewImageActivity.class);
424 } else {
425 showDetailsIntent = new Intent(this, FileDisplayActivity.class);
426 }
427 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, download.getFile());
428 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, download.getAccount());
429 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
430
431 mNotificationBuilder.setContentIntent(PendingIntent.getActivity(
432 this, (int) System.currentTimeMillis(), showDetailsIntent, 0
433 ));
434
435 mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotificationBuilder.build());
436 }
437
438
439 /**
440 * Callback method to update the progress bar in the status notification.
441 */
442 @Override
443 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filePath) {
444 int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
445 if (percent != mLastPercent) {
446 mNotificationBuilder.setProgress(100, percent, totalToTransfer < 0);
447 String fileName = filePath.substring(filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1);
448 String text = String.format(getString(R.string.downloader_download_in_progress_content), percent, fileName);
449 mNotificationBuilder.setContentText(text);
450 mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotificationBuilder.build());
451 }
452 mLastPercent = percent;
453 }
454
455
456 /**
457 * Updates the status notification with the result of a download operation.
458 *
459 * @param downloadResult Result of the download operation.
460 * @param download Finished download operation
461 */
462 private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) {
463 mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);
464 if (!downloadResult.isCancelled()) {
465 int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker :
466 R.string.downloader_download_failed_ticker;
467
468 boolean needsToUpdateCredentials = (downloadResult.getCode() == ResultCode.UNAUTHORIZED ||
469 (downloadResult.isIdPRedirection()
470 && mDownloadClient.getCredentials() == null));
471 tickerId = (needsToUpdateCredentials) ?
472 R.string.downloader_download_failed_credentials_error : tickerId;
473
474 mNotificationBuilder
475 .setTicker(getString(tickerId))
476 .setContentTitle(getString(tickerId))
477 .setAutoCancel(true)
478 .setOngoing(false)
479 .setProgress(0, 0, false);
480
481 if (needsToUpdateCredentials) {
482
483 // let the user update credentials with one click
484 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
485 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, download.getAccount());
486 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
487 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
488 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
489 updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
490 mNotificationBuilder
491 .setContentIntent(PendingIntent.getActivity(
492 this, (int) System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT));
493
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 mNotificationBuilder
513 .setContentIntent(PendingIntent.getActivity(
514 this, (int) System.currentTimeMillis(), showDetailsIntent, 0));
515 }
516
517 mNotificationBuilder.setContentText(ErrorMessageAdapter.getErrorCauseMessage(downloadResult, download, getResources()));
518
519 mNotificationManager.notify(tickerId, mNotificationBuilder.build());
520 }
521 }
522
523
524 /**
525 * Sends a broadcast when a download finishes in order to the interested activities can update their view
526 *
527 * @param download Finished download operation
528 * @param downloadResult Result of the download operation
529 */
530 private void sendBroadcastDownloadFinished(DownloadFileOperation download, RemoteOperationResult downloadResult) {
531 Intent end = new Intent(getDownloadFinishMessage());
532 end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult.isSuccess());
533 end.putExtra(ACCOUNT_NAME, download.getAccount().name);
534 end.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
535 end.putExtra(EXTRA_FILE_PATH, download.getSavePath());
536 sendStickyBroadcast(end);
537 }
538
539
540 /**
541 * Sends a broadcast when a new download is added to the queue.
542 *
543 * @param download Added download operation
544 */
545 private void sendBroadcastNewDownload(DownloadFileOperation download) {
546 Intent added = new Intent(getDownloadAddedMessage());
547 added.putExtra(ACCOUNT_NAME, download.getAccount().name);
548 added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
549 added.putExtra(EXTRA_FILE_PATH, download.getSavePath());
550 sendStickyBroadcast(added);
551 }
552
553 }