X-Git-Url: http://git.linex4red.de/pub/Android/ownCloud.git/blobdiff_plain/16b5c6b9ad29bee58dec8aa301b21a2992d63d00..9ae0e1746ad60925dc18e19d2f63f5780ec75872:/src/eu/alefzero/owncloud/files/services/FileDownloader.java diff --git a/src/eu/alefzero/owncloud/files/services/FileDownloader.java b/src/eu/alefzero/owncloud/files/services/FileDownloader.java index 734359ed..b0dd2b26 100644 --- a/src/eu/alefzero/owncloud/files/services/FileDownloader.java +++ b/src/eu/alefzero/owncloud/files/services/FileDownloader.java @@ -1,7 +1,9 @@ package eu.alefzero.owncloud.files.services; import java.io.File; -import java.io.IOException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; import android.accounts.Account; import android.accounts.AccountManager; @@ -21,23 +23,21 @@ import android.os.Message; import android.os.Process; import android.util.Log; import android.widget.RemoteViews; -import eu.alefzero.owncloud.AccountUtils; import eu.alefzero.owncloud.R; -import eu.alefzero.owncloud.R.drawable; import eu.alefzero.owncloud.authenticator.AccountAuthenticator; import eu.alefzero.owncloud.db.ProviderMeta.ProviderTableMeta; import eu.alefzero.owncloud.files.interfaces.OnDatatransferProgressListener; -import eu.alefzero.owncloud.ui.activity.FileDisplayActivity; -import eu.alefzero.owncloud.utils.OwnCloudVersion; import eu.alefzero.webdav.WebdavClient; public class FileDownloader extends Service implements OnDatatransferProgressListener { public static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH"; - public static final String BAD_DOWNLOAD_MESSAGE = "BAD_DOWNLOAD"; + 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"; private NotificationManager mNotificationMngr; @@ -48,9 +48,29 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis private String mRemotePath; private int mLastPercent; private long mTotalDownloadSize; - private long mCurrentDownlodSize; + private long mCurrentDownloadSize; private Notification mNotification; + + /** + * Static map with the files being download and the path to the temporal file were are download + */ + private static Map mDownloadsInProgress = Collections.synchronizedMap(new HashMap()); + + /** + * 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.get(buildRemoteName(account.name, remotePath)) != null); + } + + /** + * Builds a key for mDownloadsInProgress from the accountName and remotePath + */ + private static String buildRemoteName(String accountName, String remotePath) { + return accountName + remotePath; + } + private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); @@ -62,6 +82,18 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis stopSelf(msg.arg1); } } + + 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 + } @Override public void onCreate() { @@ -81,104 +113,140 @@ 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)) { + if ( !intent.hasExtra(EXTRA_ACCOUNT) || + !intent.hasExtra(EXTRA_FILE_PATH) || + !intent.hasExtra(EXTRA_REMOTE_PATH) + ) { Log.e(TAG, "Not enough information provided in intent"); - return START_STICKY; + return START_NOT_STICKY; } mAccount = intent.getParcelableExtra(EXTRA_ACCOUNT); mFilePath = intent.getStringExtra(EXTRA_FILE_PATH); mRemotePath = intent.getStringExtra(EXTRA_REMOTE_PATH); + mTotalDownloadSize = intent.getLongExtra(EXTRA_FILE_SIZE, -1); + mCurrentDownloadSize = mLastPercent = 0; + Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; mServiceHandler.sendMessage(msg); - mCurrentDownlodSize = mLastPercent = 0; - mTotalDownloadSize = intent.getLongExtra(EXTRA_FILE_SIZE, -1); return START_NOT_STICKY; } - void downloadFile() { - AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE); - String oc_base_url = am.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL); - OwnCloudVersion ocv = new OwnCloudVersion(am - .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION)); - String webdav_path = AccountUtils.getWebdavPath(ocv); - Uri oc_url = Uri.parse(oc_base_url+webdav_path); + /** + * Core download method: requests the file to download and stores it. + */ + private void downloadFile() { + boolean downloadResult = false; - WebdavClient wdc = new WebdavClient(Uri.parse(oc_base_url + webdav_path)); - + /// prepare client object to send the request to the ownCloud server + AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE); + WebdavClient wdc = new WebdavClient(mAccount, getApplicationContext()); String username = mAccount.name.split("@")[0]; - String password = ""; + String password = null; try { password = am.blockingGetAuthToken(mAccount, AccountAuthenticator.AUTH_TOKEN_TYPE, true); } catch (Exception e) { - e.printStackTrace(); + Log.e(TAG, "Access to account credentials failed", e); + sendFinalBroadcast(downloadResult, null); return; } - wdc.setCredentials(username, password); wdc.allowSelfsignedCertificates(); wdc.setDataTransferProgressListener(this); - mNotification = new Notification(R.drawable.icon, "Downloading file", System.currentTimeMillis()); - + + /// download will be in a temporal file + File tmpFile = new File(getTemporalPath(mAccount.name) + mFilePath); + + /// create status notification to show the download progress + 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, mTotalDownloadSize == -1); + mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), 0, tmpFile.getName())); mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon); - // dvelasco ; contentIntent MUST be assigned to avoid app crashes in versions previous to Android 4.x ; - // BUT an empty Intent is not a very elegant solution; something smart should happen when a user 'clicks' on a download in the notification bar + // 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); - mNotificationMngr.notify(1, mNotification); - File sdCard = Environment.getExternalStorageDirectory(); - File file = new File(sdCard.getAbsolutePath() + "/owncloud/" + mAccount.name + mFilePath); + /// perform the download + tmpFile.getParentFile().mkdirs(); + mDownloadsInProgress.put(buildRemoteName(mAccount.name, mRemotePath), tmpFile.getAbsolutePath()); + File newFile = null; try { - file.getParentFile().mkdirs(); - file.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); + if (wdc.downloadFile(mRemotePath, tmpFile)) { + newFile = new File(getSavePath(mAccount.name) + mFilePath); + newFile.getParentFile().mkdirs(); + boolean moved = tmpFile.renameTo(newFile); + + if (moved) { + ContentValues cv = new ContentValues(); + cv.put(ProviderTableMeta.FILE_STORAGE_PATH, newFile.getAbsolutePath()); + getContentResolver().update( + ProviderTableMeta.CONTENT_URI, + cv, + ProviderTableMeta.FILE_NAME + "=? AND " + + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?", + new String[] { + mFilePath.substring(mFilePath.lastIndexOf('/') + 1), + mAccount.name }); + downloadResult = true; + } + } + } finally { + mDownloadsInProgress.remove(buildRemoteName(mAccount.name, mRemotePath)); } - Log.e(TAG, file.getAbsolutePath() + " " + oc_url.toString()); - Log.e(TAG, mFilePath+""); - String message; - if (wdc.downloadFile(mRemotePath, file)) { - ContentValues cv = new ContentValues(); - cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getAbsolutePath()); - getContentResolver().update( - ProviderTableMeta.CONTENT_URI, - cv, - ProviderTableMeta.FILE_NAME + "=? AND " - + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?", - new String[] { - mFilePath.substring(mFilePath.lastIndexOf('/') + 1), - mAccount.name }); - message = DOWNLOAD_FINISH_MESSAGE; - } else { - message = BAD_DOWNLOAD_MESSAGE; - } - mNotificationMngr.cancel(1); - Intent end = new Intent(message); - end.putExtra(EXTRA_FILE_PATH, file.getAbsolutePath()); - sendBroadcast(end); + /// notify result + mNotificationMngr.cancel(R.string.downloader_download_in_progress_ticker); + int tickerId = (downloadResult) ? R.string.downloader_download_succeeded_ticker : R.string.downloader_download_failed_ticker; + int contentId = (downloadResult) ? 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), tmpFile.getName()), finalNotification.contentIntent); + mNotificationMngr.notify(tickerId, finalNotification); + + sendFinalBroadcast(downloadResult, (downloadResult)?newFile.getAbsolutePath():null); } + /** + * Callback method to update the progress bar in the status notification. + */ @Override public void transferProgress(long progressRate) { - mCurrentDownlodSize += progressRate; - int percent = (int)(100.0*((double)mCurrentDownlodSize)/((double)mTotalDownloadSize)); + mCurrentDownloadSize += progressRate; + int percent = (int)(100.0*((double)mCurrentDownloadSize)/((double)mTotalDownloadSize)); if (percent != mLastPercent) { - mNotification.contentView.setProgressBar(R.id.status_progress, 100, (int)(100*mCurrentDownlodSize/mTotalDownloadSize), mTotalDownloadSize == -1); - mNotification.contentView.setTextViewText(R.id.status_text, percent+"%"); - mNotificationMngr.notify(1, mNotification); + mNotification.contentView.setProgressBar(R.id.status_progress, 100, (int)(100*mCurrentDownloadSize/mTotalDownloadSize), mTotalDownloadSize == -1); + mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), percent, new File(mFilePath).getName())); + mNotificationMngr.notify(R.string.downloader_download_in_progress_ticker, mNotification); } mLastPercent = percent; } + + + /** + * Sends a broadcast in order to the interested activities can update their view + * + * @param downloadResult 'True' if the download was successful + * @param newFilePath Absolute path to the download file + */ + private void sendFinalBroadcast(boolean downloadResult, String newFilePath) { + Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE); + end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult); + end.putExtra(ACCOUNT_NAME, mAccount.name); + end.putExtra(EXTRA_REMOTE_PATH, mRemotePath); + if (downloadResult) { + end.putExtra(EXTRA_FILE_PATH, newFilePath); + } + sendBroadcast(end); + } }