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