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