add licence header to 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 *
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.OCFile;
29 import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
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.ContentValues;
44 import android.content.Intent;
45 import android.net.Uri;
46 import android.os.Binder;
47 import android.os.Environment;
48 import android.os.Handler;
49 import android.os.HandlerThread;
50 import android.os.IBinder;
51 import android.os.Looper;
52 import android.os.Message;
53 import android.os.Process;
54 import android.util.Log;
55 import android.widget.RemoteViews;
56
57 import com.owncloud.android.R;
58 import eu.alefzero.webdav.WebdavClient;
59
60 public class FileDownloader extends Service implements OnDatatransferProgressListener {
61
62 public static final String EXTRA_ACCOUNT = "ACCOUNT";
63 public static final String EXTRA_FILE = "FILE";
64
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
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 public static final String getSavePath(String accountName) {
98 File sdCard = Environment.getExternalStorageDirectory();
99 return sdCard.getAbsolutePath() + "/owncloud/" + Uri.encode(accountName, "@");
100 // URL encoding is an 'easy fix' to overcome that NTFS and FAT32 don't allow ":" in file names, that can be in the accountName since 0.1.190B
101 }
102
103 public static final String getTemporalPath(String accountName) {
104 File sdCard = Environment.getExternalStorageDirectory();
105 return sdCard.getAbsolutePath() + "/owncloud/tmp/" + Uri.encode(accountName, "@");
106 // URL encoding is an 'easy fix' to overcome that NTFS and FAT32 don't allow ":" in file names, that can be in the accountName since 0.1.190B
107 }
108
109
110 /**
111 * Service initialization
112 */
113 @Override
114 public void onCreate() {
115 super.onCreate();
116 mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
117 HandlerThread thread = new HandlerThread("FileDownloaderThread",
118 Process.THREAD_PRIORITY_BACKGROUND);
119 thread.start();
120 mServiceLooper = thread.getLooper();
121 mServiceHandler = new ServiceHandler(mServiceLooper, this);
122 mBinder = new FileDownloaderBinder();
123 }
124
125
126 /**
127 * Entry point to add one or several files to the queue of downloads.
128 *
129 * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
130 * although the caller activity goes away.
131 */
132 @Override
133 public int onStartCommand(Intent intent, int flags, int startId) {
134 if ( !intent.hasExtra(EXTRA_ACCOUNT) ||
135 !intent.hasExtra(EXTRA_FILE)
136 /*!intent.hasExtra(EXTRA_FILE_PATH) ||
137 !intent.hasExtra(EXTRA_REMOTE_PATH)*/
138 ) {
139 Log.e(TAG, "Not enough information provided in intent");
140 return START_NOT_STICKY;
141 }
142 Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
143 OCFile file = intent.getParcelableExtra(EXTRA_FILE);
144
145 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)
146 String downloadKey = buildRemoteName(account, file);
147 try {
148 DownloadFileOperation newDownload = new DownloadFileOperation(account, file);
149 mPendingDownloads.putIfAbsent(downloadKey, newDownload);
150 newDownload.addDatatransferProgressListener(this);
151 requestedDownloads.add(downloadKey);
152
153 } catch (IllegalArgumentException e) {
154 Log.e(TAG, "Not enough information provided in intent: " + e.getMessage());
155 return START_NOT_STICKY;
156 }
157
158 if (requestedDownloads.size() > 0) {
159 Message msg = mServiceHandler.obtainMessage();
160 msg.arg1 = startId;
161 msg.obj = requestedDownloads;
162 mServiceHandler.sendMessage(msg);
163 }
164
165 return START_NOT_STICKY;
166 }
167
168
169 /**
170 * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
171 *
172 * Implemented to perform cancellation, pause and resume of existing downloads.
173 */
174 @Override
175 public IBinder onBind(Intent arg0) {
176 return mBinder;
177 }
178
179
180 /**
181 * Binder to let client components to perform operations on the queue of downloads.
182 *
183 * It provides by itself the available operations.
184 */
185 public class FileDownloaderBinder extends Binder {
186
187 /**
188 * Cancels a pending or current download of a remote file.
189 *
190 * @param account Owncloud account where the remote file is stored.
191 * @param file A file in the queue of pending downloads
192 */
193 public void cancel(Account account, OCFile file) {
194 DownloadFileOperation download = null;
195 synchronized (mPendingDownloads) {
196 download = mPendingDownloads.remove(buildRemoteName(account, file));
197 }
198 if (download != null) {
199 download.cancel();
200 }
201 }
202
203
204 /**
205 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download
206 *
207 * @param account Owncloud account where the remote file is stored.
208 * @param file A file that could be in the queue of downloads.
209 */
210 public boolean isDownloading(Account account, OCFile file) {
211 synchronized (mPendingDownloads) {
212 return (mPendingDownloads.containsKey(buildRemoteName(account, file)));
213 }
214 }
215 }
216
217
218 /**
219 * Download worker. Performs the pending downloads in the order they were requested.
220 *
221 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
222 */
223 private static class ServiceHandler extends Handler {
224 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
225 FileDownloader mService;
226 public ServiceHandler(Looper looper, FileDownloader service) {
227 super(looper);
228 if (service == null)
229 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
230 mService = service;
231 }
232
233 @Override
234 public void handleMessage(Message msg) {
235 @SuppressWarnings("unchecked")
236 AbstractList<String> requestedDownloads = (AbstractList<String>) msg.obj;
237 if (msg.obj != null) {
238 Iterator<String> it = requestedDownloads.iterator();
239 while (it.hasNext()) {
240 mService.downloadFile(it.next());
241 }
242 }
243 mService.stopSelf(msg.arg1);
244 }
245 }
246
247
248
249 /**
250 * Core download method: requests a file to download and stores it.
251 *
252 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
253 */
254 private void downloadFile(String downloadKey) {
255
256 synchronized(mPendingDownloads) {
257 mCurrentDownload = mPendingDownloads.get(downloadKey);
258 }
259
260 if (mCurrentDownload != null) {
261
262 notifyDownloadStart(mCurrentDownload);
263
264 /// prepare client object to send the request to the ownCloud server
265 if (mDownloadClient == null || !mLastAccount.equals(mCurrentDownload.getAccount())) {
266 mLastAccount = mCurrentDownload.getAccount();
267 mDownloadClient = OwnCloudClientUtils.createOwnCloudClient(mLastAccount, getApplicationContext());
268 }
269
270 /// perform the download
271 RemoteOperationResult downloadResult = null;
272 try {
273 downloadResult = mCurrentDownload.execute(mDownloadClient);
274 if (downloadResult.isSuccess()) {
275 ContentValues cv = new ContentValues();
276 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, mCurrentDownload.getSavePath());
277 getContentResolver().update(
278 ProviderTableMeta.CONTENT_URI,
279 cv,
280 ProviderTableMeta.FILE_NAME + "=? AND "
281 + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
282 new String[] {
283 mCurrentDownload.getSavePath().substring(mCurrentDownload.getSavePath().lastIndexOf('/') + 1),
284 mLastAccount.name });
285 }
286
287 } finally {
288 synchronized(mPendingDownloads) {
289 mPendingDownloads.remove(downloadKey);
290 }
291 }
292
293
294 /// notify result
295 notifyDownloadResult(mCurrentDownload, downloadResult);
296
297 sendFinalBroadcast(mCurrentDownload, downloadResult);
298 }
299 }
300
301
302 /**
303 * Creates a status notification to show the download progress
304 *
305 * @param download Download operation starting.
306 */
307 private void notifyDownloadStart(DownloadFileOperation download) {
308 /// create status notification with a progress bar
309 mLastPercent = 0;
310 mNotification = new Notification(R.drawable.icon, getString(R.string.downloader_download_in_progress_ticker), System.currentTimeMillis());
311 mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
312 mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
313 mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, download.getSize() < 0);
314 mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), 0, new File(download.getSavePath()).getName()));
315 mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
316
317 /// includes a pending intent in the notification showing the details view of the file
318 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
319 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, download.getFile());
320 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, download.getAccount());
321 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
322 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
323
324 mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotification);
325 }
326
327
328 /**
329 * Callback method to update the progress bar in the status notification.
330 */
331 @Override
332 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) {
333 int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
334 if (percent != mLastPercent) {
335 mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, totalToTransfer < 0);
336 String text = String.format(getString(R.string.downloader_download_in_progress_content), percent, fileName);
337 mNotification.contentView.setTextViewText(R.id.status_text, text);
338 mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotification);
339 }
340 mLastPercent = percent;
341 }
342
343
344 /**
345 * Callback method to update the progress bar in the status notification (old version)
346 */
347 @Override
348 public void onTransferProgress(long progressRate) {
349 // NOTHING TO DO HERE ANYMORE
350 }
351
352
353 /**
354 * Updates the status notification with the result of a download operation.
355 *
356 * @param downloadResult Result of the download operation.
357 * @param download Finished download operation
358 */
359 private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) {
360 mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);
361 if (!downloadResult.isCancelled()) {
362 int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker : R.string.downloader_download_failed_ticker;
363 int contentId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_content : R.string.downloader_download_failed_content;
364 Notification finalNotification = new Notification(R.drawable.icon, getString(tickerId), System.currentTimeMillis());
365 finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
366 // TODO put something smart in the contentIntent below
367 finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
368 finalNotification.setLatestEventInfo(getApplicationContext(), getString(tickerId), String.format(getString(contentId), new File(download.getSavePath()).getName()), finalNotification.contentIntent);
369 mNotificationManager.notify(tickerId, finalNotification);
370 }
371 }
372
373
374 /**
375 * Sends a broadcast in order to the interested activities can update their view
376 *
377 * @param download Finished download operation
378 * @param downloadResult Result of the download operation
379 */
380 private void sendFinalBroadcast(DownloadFileOperation download, RemoteOperationResult downloadResult) {
381 Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);
382 end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult.isSuccess());
383 end.putExtra(ACCOUNT_NAME, download.getAccount().name);
384 end.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
385 if (downloadResult.isSuccess()) {
386 end.putExtra(EXTRA_FILE_PATH, download.getSavePath());
387 }
388 sendBroadcast(end);
389 }
390
391 }