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