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