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