X-Git-Url: http://git.linex4red.de/pub/Android/ownCloud.git/blobdiff_plain/83ad608faadfcfc5a0ceee9d6c460702b3ff3f11..HEAD:/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 67cbc599..513a639f 100644 --- a/src/com/owncloud/android/files/services/FileDownloader.java +++ b/src/com/owncloud/android/files/services/FileDownloader.java @@ -1,4 +1,6 @@ -/* ownCloud Android client application +/** + * ownCloud Android client application + * * Copyright (C) 2012 Bartek Przybylski * Copyright (C) 2012-2015 ownCloud Inc. * @@ -19,13 +21,11 @@ package com.owncloud.android.files.services; import java.io.File; -import java.io.IOException; import java.util.AbstractList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Vector; -import java.util.concurrent.ConcurrentMap; import com.owncloud.android.R; import com.owncloud.android.authentication.AccountUtils; @@ -51,7 +51,8 @@ import com.owncloud.android.ui.preview.PreviewImageFragment; import com.owncloud.android.utils.ErrorMessageAdapter; import android.accounts.Account; -import android.accounts.AccountsException; +import android.accounts.AccountManager; +import android.accounts.OnAccountsUpdateListener; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; @@ -66,7 +67,8 @@ import android.os.Process; import android.support.v4.app.NotificationCompat; import android.util.Pair; -public class FileDownloader extends Service implements OnDatatransferProgressListener { +public class FileDownloader extends Service + implements OnDatatransferProgressListener, OnAccountsUpdateListener { public static final String EXTRA_ACCOUNT = "ACCOUNT"; public static final String EXTRA_FILE = "FILE"; @@ -113,11 +115,16 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis super.onCreate(); Log_OC.d(TAG, "Creating service"); mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); - HandlerThread thread = new HandlerThread("FileDownloaderThread", Process.THREAD_PRIORITY_BACKGROUND); + HandlerThread thread = new HandlerThread("FileDownloaderThread", + Process.THREAD_PRIORITY_BACKGROUND); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper, this); mBinder = new FileDownloaderBinder(); + + // add AccountsUpdatedListener + AccountManager am = AccountManager.get(getApplicationContext()); + am.addOnAccountsUpdatedListener(this, null, false); } @@ -132,13 +139,18 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis mServiceLooper.quit(); mServiceLooper = null; mNotificationManager = null; + + // remove AccountsUpdatedListener + AccountManager am = AccountManager.get(getApplicationContext()); + am.removeOnAccountsUpdatedListener(this); + super.onDestroy(); } /** * Entry point to add one or several files to the queue of downloads. - *

+ * * New downloads are added calling to startService(), resulting in a call to this method. * This ensures the service will keep on working although the caller activity goes away. */ @@ -154,12 +166,6 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis } else { final Account account = intent.getParcelableExtra(EXTRA_ACCOUNT); final OCFile file = intent.getParcelableExtra(EXTRA_FILE); - - /*Log_OC.v( - "NOW " + TAG + ", thread " + Thread.currentThread().getName(), - "Received request to download file" - );*/ - AbstractList requestedDownloads = new Vector(); try { DownloadFileOperation newDownload = new DownloadFileOperation(account, file); @@ -168,22 +174,11 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis Pair putResult = mPendingDownloads.putIfAbsent( account, file.getRemotePath(), newDownload ); - String downloadKey = putResult.first; - requestedDownloads.add(downloadKey); - /*Log_OC.v( - "NOW " + TAG + ", thread " + Thread.currentThread().getName(), - "Download on " + file.getRemotePath() + " added to queue" - );*/ - - // Store file on db with state 'downloading' - /* - TODO - check if helps with UI responsiveness, letting only folders use FileDownloaderBinder to check - FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver()); - file.setDownloading(true); - storageManager.saveFile(file); - */ - - sendBroadcastNewDownload(newDownload, putResult.second); + if (putResult != null) { + String downloadKey = putResult.first; + requestedDownloads.add(downloadKey); + sendBroadcastNewDownload(newDownload, putResult.second); + } // else, file already in the queue of downloads; don't repeat the request } catch (IllegalArgumentException e) { Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage()); @@ -224,6 +219,16 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis return false; // not accepting rebinding (default behaviour) } + @Override + public void onAccountsUpdated(Account[] accounts) { + //review the current download and cancel it if its account doesn't exist + if (mCurrentDownload != null && + !AccountUtils.exists(mCurrentDownload.getAccount(), getApplicationContext())) { + mCurrentDownload.cancel(); + } + // The rest of downloads are cancelled when they try to start + } + /** * Binder to let client components to perform operations on the queue of downloads. @@ -233,7 +238,8 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis public class FileDownloaderBinder extends Binder implements OnDatatransferProgressListener { /** - * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder} + * Map of listeners that will be reported about progress of downloads from a + * {@link FileDownloaderBinder} * instance. */ private Map mBoundListeners = @@ -247,34 +253,23 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis * @param file A file in the queue of pending downloads */ public void cancel(Account account, OCFile file) { - /*Log_OC.v( - "NOW " + TAG + ", thread " + Thread.currentThread().getName(), - "Received request to cancel download of " + file.getRemotePath() - ); - Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(), - "Removing download of " + file.getRemotePath());*/ - Pair removeResult = - mPendingDownloads.remove(account, file.getRemotePath()); + Pair removeResult = mPendingDownloads.remove(account, file.getRemotePath()); DownloadFileOperation download = removeResult.first; if (download != null) { - /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(), - "Canceling returned download of " + file.getRemotePath());*/ download.cancel(); } else { if (mCurrentDownload != null && mCurrentAccount != null && mCurrentDownload.getRemotePath().startsWith(file.getRemotePath()) && account.name.equals(mCurrentAccount.name)) { - /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(), - "Canceling current sync as descendant: " + mCurrentDownload.getRemotePath());*/ mCurrentDownload.cancel(); } } } /** - * Cancels a pending or current upload for an account + * Cancels all the downloads for an account * - * @param account Owncloud accountName where the remote file will be stored. + * @param account ownCloud account. */ public void cancel(Account account) { Log_OC.d(TAG, "Account= " + account.name); @@ -295,9 +290,9 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis /** - * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or - * waiting to download. - *

+ * Returns True when the file described by 'file' in the ownCloud account 'account' + * is downloading or waiting to download. + * * If 'file' is a directory, returns 'true' if any of its descendant files is downloading or * waiting to download. * @@ -321,7 +316,6 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis OnDatatransferProgressListener listener, Account account, OCFile file ) { if (account == null || file == null || listener == null) return; - //String targetKey = buildKey(account, file.getRemotePath()); mBoundListeners.put(file.getFileId(), listener); } @@ -329,15 +323,14 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis /** * Removes a listener interested in the progress of the download for a concrete file. * - * @param listener Object to notify about progress of transfer. - * @param account ownCloud account holding the file of interest. - * @param file {@link OCFile} of interest for listener. + * @param listener Object to notify about progress of transfer. + * @param account ownCloud account holding the file of interest. + * @param file {@link OCFile} of interest for listener. */ public void removeDatatransferProgressListener( OnDatatransferProgressListener listener, Account account, OCFile file ) { if (account == null || file == null || listener == null) return; - //String targetKey = buildKey(account, file.getRemotePath()); Long fileId = file.getFileId(); if (mBoundListeners.get(fileId) == listener) { mBoundListeners.remove(fileId); @@ -345,24 +338,14 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis } @Override - public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, - String fileName) { - //String key = buildKey(mCurrentDownload.getAccount(), mCurrentDownload.getFile().getRemotePath()); - OnDatatransferProgressListener boundListener = mBoundListeners.get(mCurrentDownload.getFile().getFileId()); + public void onTransferProgress(long progressRate, long totalTransferredSoFar, + long totalToTransfer, String fileName) { + OnDatatransferProgressListener boundListener = + mBoundListeners.get(mCurrentDownload.getFile().getFileId()); if (boundListener != null) { - boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, fileName); - } - } - - /** - * Review downloads and cancel it if its account doesn't exist - */ - public void checkAccountOfCurrentDownload() { - if (mCurrentDownload != null && - !AccountUtils.exists(mCurrentDownload.getAccount(), getApplicationContext())) { - mCurrentDownload.cancel(); + boundListener.onTransferProgress(progressRate, totalTransferredSoFar, + totalToTransfer, fileName); } - // The rest of downloads are cancelled when they try to start } } @@ -370,11 +353,12 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis /** * 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 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 + // 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) { @@ -408,20 +392,20 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis */ private void downloadFile(String downloadKey) { - /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(), - "Getting download of " + downloadKey);*/ mCurrentDownload = mPendingDownloads.get(downloadKey); if (mCurrentDownload != null) { // Detect if the account exists if (AccountUtils.exists(mCurrentDownload.getAccount(), getApplicationContext())) { Log_OC.d(TAG, "Account " + mCurrentDownload.getAccount().name + " exists"); + notifyDownloadStart(mCurrentDownload); RemoteOperationResult downloadResult = null; try { /// prepare client object to send the request to the ownCloud server - if (mCurrentAccount == null || !mCurrentAccount.equals(mCurrentDownload.getAccount())) { + if (mCurrentAccount == null || + !mCurrentAccount.equals(mCurrentDownload.getAccount())) { mCurrentAccount = mCurrentDownload.getAccount(); mStorageManager = new FileDataStorageManager( mCurrentAccount, @@ -429,42 +413,38 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis ); } // else, reuse storage manager from previous operation - // always get client from client manager, to get fresh credentials in case of update + // always get client from client manager, to get fresh credentials in case + // of update OwnCloudAccount ocAccount = new OwnCloudAccount(mCurrentAccount, this); mDownloadClient = OwnCloudClientManagerFactory.getDefaultSingleton(). getClientFor(ocAccount, this); /// perform the download - /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(), - "Executing download of " + mCurrentDownload.getRemotePath());*/ downloadResult = mCurrentDownload.execute(mDownloadClient); if (downloadResult.isSuccess()) { saveDownloadedFile(); } - } catch (AccountsException e) { - Log_OC.e(TAG, "Error while trying to get authorization for " + mCurrentAccount.name, e); - downloadResult = new RemoteOperationResult(e); - } catch (IOException e) { - Log_OC.e(TAG, "Error while trying to get authorization for " + mCurrentAccount.name, e); + } catch (Exception e) { + Log_OC.e(TAG, "Error downloading", e); downloadResult = new RemoteOperationResult(e); } finally { - /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(), - "Removing payload " + mCurrentDownload.getRemotePath());*/ - Pair removeResult = - mPendingDownloads.removePayload(mCurrentAccount, mCurrentDownload.getRemotePath()); + mPendingDownloads.removePayload(mCurrentAccount, + mCurrentDownload.getRemotePath()); /// notify result notifyDownloadResult(mCurrentDownload, downloadResult); sendBroadcastDownloadFinished(mCurrentDownload, downloadResult, removeResult.second); } + } else { // Cancel the transfer - Log_OC.d(TAG, "Account " + mCurrentDownload.getAccount().toString() + " doesn't exist"); + Log_OC.d(TAG, "Account " + mCurrentDownload.getAccount().toString() + + " doesn't exist"); cancelDownloadsForAccount(mCurrentDownload.getAccount()); } @@ -474,6 +454,8 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis /** * Updates the OC File after a successful download. + * + * TODO move to DownloadFileOperation */ private void saveDownloadedFile() { OCFile file = mStorageManager.getFileById(mCurrentDownload.getFile().getFileId()); @@ -483,26 +465,17 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis file.setNeedsUpdateThumbnail(true); file.setModificationTimestamp(mCurrentDownload.getModificationTimestamp()); file.setModificationTimestampAtLastSyncForData(mCurrentDownload.getModificationTimestamp()); - // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available + file.setEtag(mCurrentDownload.getEtag()); file.setMimetype(mCurrentDownload.getMimeType()); file.setStoragePath(mCurrentDownload.getSavePath()); file.setFileLength((new File(mCurrentDownload.getSavePath()).length())); file.setRemoteId(mCurrentDownload.getFile().getRemoteId()); mStorageManager.saveFile(file); mStorageManager.triggerMediaScan(file.getStoragePath()); + mStorageManager.saveConflict(file, null); } /** - * Update the OC File after a unsuccessful download - */ - private void updateUnsuccessfulDownloadedFile() { - OCFile file = mStorageManager.getFileById(mCurrentDownload.getFile().getFileId()); - file.setDownloading(false); - mStorageManager.saveFile(file); - } - - - /** * Creates a status notification to show the download progress * * @param download Download operation starting. @@ -546,7 +519,8 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis * Callback method to update the progress bar in the status notification. */ @Override - public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filePath) { + public void onTransferProgress(long progressRate, long totalTransferredSoFar, + long totalToTransfer, String filePath) { int percent = (int) (100.0 * ((double) totalTransferredSoFar) / ((double) totalToTransfer)); if (percent != mLastPercent) { mNotificationBuilder.setProgress(100, percent, totalToTransfer < 0); @@ -565,7 +539,8 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis * @param downloadResult Result of the download operation. * @param download Finished download operation */ - private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) { + private void notifyDownloadResult(DownloadFileOperation download, + RemoteOperationResult downloadResult) { mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker); if (!downloadResult.isCancelled()) { int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker : @@ -589,16 +564,19 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis // let the user update credentials with one click Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class); - updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, download.getAccount()); + updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, + download.getAccount()); updateAccountCredentials.putExtra( - AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN + AuthenticatorActivity.EXTRA_ACTION, + AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN ); updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND); mNotificationBuilder .setContentIntent(PendingIntent.getActivity( - this, (int) System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT)); + this, (int) System.currentTimeMillis(), updateAccountCredentials, + PendingIntent.FLAG_ONE_SHOT)); } else { // TODO put something smart in showDetailsIntent @@ -609,7 +587,8 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis } mNotificationBuilder.setContentText( - ErrorMessageAdapter.getErrorCauseMessage(downloadResult, download, getResources()) + ErrorMessageAdapter.getErrorCauseMessage(downloadResult, download, + getResources()) ); mNotificationManager.notify(tickerId, mNotificationBuilder.build()); @@ -627,7 +606,8 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis /** - * Sends a broadcast when a download finishes 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 @@ -637,6 +617,7 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis DownloadFileOperation download, RemoteOperationResult downloadResult, String unlinkedFromRemotePath) { + Intent end = new Intent(getDownloadFinishMessage()); end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult.isSuccess()); end.putExtra(ACCOUNT_NAME, download.getAccount().name); @@ -655,7 +636,8 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis * @param download Added download operation * @param linkedToRemotePath Path in the downloads tree where the download was linked to */ - private void sendBroadcastNewDownload(DownloadFileOperation download, String linkedToRemotePath) { + private void sendBroadcastNewDownload(DownloadFileOperation download, + String linkedToRemotePath) { Intent added = new Intent(getDownloadAddedMessage()); added.putExtra(ACCOUNT_NAME, download.getAccount().name); added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath()); @@ -667,26 +649,10 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis /** * Remove downloads of an account * - * @param account + * @param account Downloads account to remove */ private void cancelDownloadsForAccount(Account account) { // Cancel pending downloads - ConcurrentMap downloadsAccount = mPendingDownloads.get(account); - Iterator it = downloadsAccount.keySet().iterator(); - Log_OC.d(TAG, "Number of pending downloads= " + downloadsAccount.size()); - DownloadFileOperation download; - while (it.hasNext()) { - String key = it.next(); - Log_OC.d(TAG, "download CANCELLED " + key); - if (key.startsWith(account.name)) { - synchronized (mPendingDownloads) { - download = mPendingDownloads.get(key); - if (download != null) { - String remotePath = download.getRemotePath(); - mPendingDownloads.remove(account, remotePath); - } - } - } - } + mPendingDownloads.remove(account); } }