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