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