X-Git-Url: http://git.linex4red.de/pub/Android/ownCloud.git/blobdiff_plain/38512099c49a32406725086074ac4973220807c1..e4bc3bdadc47c01e88dd1de94a4666d3753ee90e:/src/com/owncloud/android/files/services/FileDownloader.java
diff --git a/src/com/owncloud/android/files/services/FileDownloader.java b/src/com/owncloud/android/files/services/FileDownloader.java
index 2e0c6863..f58e563c 100644
--- a/src/com/owncloud/android/files/services/FileDownloader.java
+++ b/src/com/owncloud/android/files/services/FileDownloader.java
@@ -1,3 +1,21 @@
+/* ownCloud Android client application
+ * Copyright (C) 2012 Bartek Przybylski
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ *
+ */
+
package com.owncloud.android.files.services;
import java.io.File;
@@ -7,23 +25,23 @@ import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
-import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
+import com.owncloud.android.datamodel.FileDataStorageManager;
+import com.owncloud.android.datamodel.OCFile;
import eu.alefzero.webdav.OnDatatransferProgressListener;
import com.owncloud.android.network.OwnCloudClientUtils;
import com.owncloud.android.operations.DownloadFileOperation;
import com.owncloud.android.operations.RemoteOperationResult;
+import com.owncloud.android.ui.activity.FileDetailActivity;
+import com.owncloud.android.ui.fragment.FileDetailFragment;
import android.accounts.Account;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
-import android.content.ContentValues;
import android.content.Intent;
-import android.net.Uri;
import android.os.Binder;
-import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
@@ -32,16 +50,20 @@ import android.os.Message;
import android.os.Process;
import android.util.Log;
import android.widget.RemoteViews;
+
import com.owncloud.android.R;
import eu.alefzero.webdav.WebdavClient;
public class FileDownloader extends Service implements OnDatatransferProgressListener {
+
+ public static final String EXTRA_ACCOUNT = "ACCOUNT";
+ public static final String EXTRA_FILE = "FILE";
+
+ public static final String DOWNLOAD_ADDED_MESSAGE = "DOWNLOAD_ADDED";
public static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";
public static final String EXTRA_DOWNLOAD_RESULT = "RESULT";
- public static final String EXTRA_ACCOUNT = "ACCOUNT";
public static final String EXTRA_FILE_PATH = "FILE_PATH";
public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
- public static final String EXTRA_FILE_SIZE = "FILE_SIZE";
public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
private static final String TAG = "FileDownloader";
@@ -51,53 +73,24 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
private IBinder mBinder;
private WebdavClient mDownloadClient = null;
private Account mLastAccount = null;
+ private FileDataStorageManager mStorageManager;
- //private AbstractList mAccounts = new Vector();
private ConcurrentMap mPendingDownloads = new ConcurrentHashMap();
private DownloadFileOperation mCurrentDownload = null;
- /*
- private Account mAccount;
- private String mFilePath;
- private String mRemotePath;
- private long mTotalDownloadSize;
- private long mCurrentDownloadSize;
- */
-
- private NotificationManager mNotificationMngr;
+ private NotificationManager mNotificationManager;
private Notification mNotification;
private int mLastPercent;
/**
- * Static map with the files being download and the path to the temporal file were are download
- */
- //private static Set mDownloadsInProgress = Collections.synchronizedSet(new HashSet());
-
- /**
- * Returns True when the file referred by 'remotePath' in the ownCloud account 'account' is downloading
- */
- /*public static boolean isDownloading(Account account, String remotePath) {
- return (mDownloadsInProgress.contains(buildRemoteName(account.name, remotePath)));
- }*/
-
- /**
- * Builds a key for mDownloadsInProgress from the accountName and remotePath
+ * Builds a key for mPendingDownloads from the account and file to download
+ *
+ * @param account Account where the file to download is stored
+ * @param file File to download
*/
- private static String buildRemoteName(String accountName, String remotePath) {
- return accountName + remotePath;
- }
-
- public static final String getSavePath(String accountName) {
- File sdCard = Environment.getExternalStorageDirectory();
- return sdCard.getAbsolutePath() + "/owncloud/" + Uri.encode(accountName, "@");
- // 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
- }
-
- public static final String getTemporalPath(String accountName) {
- File sdCard = Environment.getExternalStorageDirectory();
- return sdCard.getAbsolutePath() + "/owncloud/tmp/" + Uri.encode(accountName, "@");
- // 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
+ private String buildRemoteName(Account account, OCFile file) {
+ return account.name + file.getRemotePath();
}
@@ -107,12 +100,12 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
@Override
public void onCreate() {
super.onCreate();
- mNotificationMngr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- HandlerThread thread = new HandlerThread("FileDownladerThread",
+ mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
+ HandlerThread thread = new HandlerThread("FileDownloaderThread",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mServiceLooper = thread.getLooper();
- mServiceHandler = new ServiceHandler(mServiceLooper);
+ mServiceHandler = new ServiceHandler(mServiceLooper, this);
mBinder = new FileDownloaderBinder();
}
@@ -126,24 +119,24 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if ( !intent.hasExtra(EXTRA_ACCOUNT) ||
- !intent.hasExtra(EXTRA_FILE_PATH) ||
- !intent.hasExtra(EXTRA_REMOTE_PATH)
+ !intent.hasExtra(EXTRA_FILE)
+ /*!intent.hasExtra(EXTRA_FILE_PATH) ||
+ !intent.hasExtra(EXTRA_REMOTE_PATH)*/
) {
Log.e(TAG, "Not enough information provided in intent");
return START_NOT_STICKY;
}
Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
- String filePath = intent.getStringExtra(EXTRA_FILE_PATH);
- String remotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);
- long totalDownloadSize = intent.getLongExtra(EXTRA_FILE_SIZE, -1);
-
- AbstractList requestedDownloads = new Vector(); // dvelasco: now this will always contain just one element, but that can change in a near future
- String downloadKey = buildRemoteName(account.name, remotePath);
+ OCFile file = intent.getParcelableExtra(EXTRA_FILE);
+
+ AbstractList requestedDownloads = new Vector(); // dvelasco: now this always contains just one element, but that can change in a near future (download of multiple selection)
+ String downloadKey = buildRemoteName(account, file);
try {
- DownloadFileOperation newDownload = new DownloadFileOperation(account, filePath, remotePath, (String)null, totalDownloadSize, false);
+ DownloadFileOperation newDownload = new DownloadFileOperation(account, file);
mPendingDownloads.putIfAbsent(downloadKey, newDownload);
newDownload.addDatatransferProgressListener(this);
requestedDownloads.add(downloadKey);
+ sendBroadcastNewDownload(newDownload);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Not enough information provided in intent: " + e.getMessage());
@@ -183,39 +176,46 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
* Cancels a pending or current download of a remote file.
*
* @param account Owncloud account where the remote file is stored.
- * @param remotePath URL to the remote file in the queue of downloads.
+ * @param file A file in the queue of pending downloads
*/
- public void cancel(Account account, String remotePath) {
+ public void cancel(Account account, OCFile file) {
+ DownloadFileOperation download = null;
synchronized (mPendingDownloads) {
- DownloadFileOperation download = mPendingDownloads.remove(buildRemoteName(account.name, remotePath));
- if (download != null) {
- download.cancel();
- }
+ download = mPendingDownloads.remove(buildRemoteName(account, file));
+ }
+ if (download != null) {
+ download.cancel();
}
}
/**
- * Returns True when the file referred by 'remotePath' in the ownCloud account 'account' is downloading
+ * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download
*
* @param account Owncloud account where the remote file is stored.
- * @param remotePath URL to the remote file in the queue of downloads.
+ * @param file A file that could be in the queue of downloads.
*/
- public boolean isDownloading(Account account, String remotePath) {
+ public boolean isDownloading(Account account, OCFile file) {
synchronized (mPendingDownloads) {
- return (mPendingDownloads.containsKey(buildRemoteName(account.name, remotePath)));
+ return (mPendingDownloads.containsKey(buildRemoteName(account, file)));
}
}
}
+
/**
* Download worker. Performs the pending downloads in the order they were requested.
*
* Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
*/
- private final class ServiceHandler extends Handler {
- public ServiceHandler(Looper looper) {
+ private static class ServiceHandler extends Handler {
+ // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
+ FileDownloader mService;
+ public ServiceHandler(Looper looper, FileDownloader service) {
super(looper);
+ if (service == null)
+ throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
+ mService = service;
}
@Override
@@ -225,10 +225,10 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
if (msg.obj != null) {
Iterator it = requestedDownloads.iterator();
while (it.hasNext()) {
- downloadFile(it.next());
+ mService.downloadFile(it.next());
}
}
- stopSelf(msg.arg1);
+ mService.stopSelf(msg.arg1);
}
}
@@ -250,44 +250,77 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
notifyDownloadStart(mCurrentDownload);
/// prepare client object to send the request to the ownCloud server
- if (mDownloadClient == null || mLastAccount != mCurrentDownload.getAccount()) {
+ if (mDownloadClient == null || !mLastAccount.equals(mCurrentDownload.getAccount())) {
mLastAccount = mCurrentDownload.getAccount();
+ mStorageManager = new FileDataStorageManager(mLastAccount, getContentResolver());
mDownloadClient = OwnCloudClientUtils.createOwnCloudClient(mLastAccount, getApplicationContext());
}
/// perform the download
- //mDownloadsInProgress.add(buildRemoteName(mLastAccount.name, mCurrentDownload.getRemotePath()));
RemoteOperationResult downloadResult = null;
- File newLocalFile = null;
- //try {
+ try {
downloadResult = mCurrentDownload.execute(mDownloadClient);
if (downloadResult.isSuccess()) {
- ContentValues cv = new ContentValues();
- newLocalFile = new File(getSavePath(mCurrentDownload.getAccount().name) + mCurrentDownload.getLocalPath());
- cv.put(ProviderTableMeta.FILE_STORAGE_PATH, newLocalFile.getAbsolutePath());
- getContentResolver().update(
- ProviderTableMeta.CONTENT_URI,
- cv,
- ProviderTableMeta.FILE_NAME + "=? AND "
- + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
- new String[] {
- mCurrentDownload.getLocalPath().substring(mCurrentDownload.getLocalPath().lastIndexOf('/') + 1),
- mLastAccount.name });
+ saveDownloadedFile();
}
- /*} finally {
- mDownloadsInProgress.remove(buildRemoteName(mLastAccount.name, mCurrentDownload.getRemotePath()));
- }*/
-
- mPendingDownloads.remove(downloadKey);
+ } finally {
+ synchronized(mPendingDownloads) {
+ mPendingDownloads.remove(downloadKey);
+ }
+ }
+
/// notify result
notifyDownloadResult(mCurrentDownload, downloadResult);
- sendFinalBroadcast(mCurrentDownload, downloadResult, (downloadResult.isSuccess())? newLocalFile.getAbsolutePath():null);
+ sendBroadcastDownloadFinished(mCurrentDownload, downloadResult);
}
}
+
+ /**
+ * Updates the OC File after a successful download.
+ */
+ private void saveDownloadedFile() {
+ OCFile file = mCurrentDownload.getFile();
+ long syncDate = System.currentTimeMillis();
+ file.setLastSyncDateForProperties(syncDate);
+ file.setLastSyncDateForData(syncDate);
+ file.setModificationTimestamp(mCurrentDownload.getModificationTimestamp());
+ // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
+ file.setMimetype(mCurrentDownload.getMimeType());
+ file.setStoragePath(mCurrentDownload.getSavePath());
+ file.setFileLength((new File(mCurrentDownload.getSavePath()).length()));
+ mStorageManager.saveFile(file);
+ }
+
+
+ /**
+ * Creates a status notification to show the download progress
+ *
+ * @param download Download operation starting.
+ */
+ private void notifyDownloadStart(DownloadFileOperation download) {
+ /// create status notification with a progress bar
+ mLastPercent = 0;
+ mNotification = new Notification(R.drawable.icon, getString(R.string.downloader_download_in_progress_ticker), System.currentTimeMillis());
+ mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
+ mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
+ mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, download.getSize() < 0);
+ mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), 0, new File(download.getSavePath()).getName()));
+ mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
+
+ /// includes a pending intent in the notification showing the details view of the file
+ Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
+ showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, download.getFile());
+ showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, download.getAccount());
+ showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
+ mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
+
+ mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotification);
+ }
+
/**
* Callback method to update the progress bar in the status notification.
@@ -296,9 +329,10 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) {
int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
if (percent != mLastPercent) {
- mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, totalToTransfer == -1);
- mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), percent, fileName));
- mNotificationMngr.notify(R.string.downloader_download_in_progress_ticker, mNotification);
+ mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, totalToTransfer < 0);
+ String text = String.format(getString(R.string.downloader_download_in_progress_content), percent, fileName);
+ mNotification.contentView.setTextViewText(R.id.status_text, text);
+ mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotification);
}
mLastPercent = percent;
}
@@ -314,62 +348,53 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
/**
- * Creates a status notification to show the download progress
- *
- * @param download Download operation starting.
- */
- private void notifyDownloadStart(DownloadFileOperation download) {
- /// create status notification to show the download progress
- mLastPercent = 0;
- mNotification = new Notification(R.drawable.icon, getString(R.string.downloader_download_in_progress_ticker), System.currentTimeMillis());
- mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
- mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
- mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, download.getSize() == -1);
- mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), 0, new File(download.getLocalPath()).getName()));
- mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
- // TODO put something smart in the contentIntent below
- mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
- mNotificationMngr.notify(R.string.downloader_download_in_progress_ticker, mNotification);
- }
-
-
- /**
* Updates the status notification with the result of a download operation.
*
* @param downloadResult Result of the download operation.
* @param download Finished download operation
*/
private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) {
- mNotificationMngr.cancel(R.string.downloader_download_in_progress_ticker);
+ mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);
if (!downloadResult.isCancelled()) {
int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker : R.string.downloader_download_failed_ticker;
int contentId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_content : R.string.downloader_download_failed_content;
Notification finalNotification = new Notification(R.drawable.icon, getString(tickerId), System.currentTimeMillis());
finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
// TODO put something smart in the contentIntent below
- finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
- finalNotification.setLatestEventInfo(getApplicationContext(), getString(tickerId), String.format(getString(contentId), new File(download.getLocalPath()).getName()), finalNotification.contentIntent);
- mNotificationMngr.notify(tickerId, finalNotification);
+ finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
+ finalNotification.setLatestEventInfo(getApplicationContext(), getString(tickerId), String.format(getString(contentId), new File(download.getSavePath()).getName()), finalNotification.contentIntent);
+ mNotificationManager.notify(tickerId, finalNotification);
}
}
/**
- * Sends a broadcast in order to the interested activities can update their view
+ * Sends a broadcast when a download finishes in order to the interested activities can update their view
*
* @param download Finished download operation
* @param downloadResult Result of the download operation
- * @param newFilePath Absolute path to the downloaded file
*/
- private void sendFinalBroadcast(DownloadFileOperation download, RemoteOperationResult downloadResult, String newFilePath) {
+ private void sendBroadcastDownloadFinished(DownloadFileOperation download, RemoteOperationResult downloadResult) {
Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);
end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult.isSuccess());
end.putExtra(ACCOUNT_NAME, download.getAccount().name);
end.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
- if (downloadResult.isSuccess()) {
- end.putExtra(EXTRA_FILE_PATH, newFilePath);
- }
- sendBroadcast(end);
+ end.putExtra(EXTRA_FILE_PATH, download.getSavePath());
+ sendStickyBroadcast(end);
+ }
+
+
+ /**
+ * Sends a broadcast when a new download is added to the queue.
+ *
+ * @param download Added download operation
+ */
+ private void sendBroadcastNewDownload(DownloadFileOperation download) {
+ Intent added = new Intent(DOWNLOAD_ADDED_MESSAGE);
+ /*added.putExtra(ACCOUNT_NAME, download.getAccount().name);
+ added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());*/
+ added.putExtra(EXTRA_FILE_PATH, download.getSavePath());
+ sendStickyBroadcast(added);
}
}