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