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