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