import com.owncloud.android.authentication.AuthenticatorActivity;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.authentication.AuthenticatorActivity;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
public static final String EXTRA_ACCOUNT = "ACCOUNT";
public static final String EXTRA_FILE = "FILE";
private static final String DOWNLOAD_ADDED_MESSAGE = "DOWNLOAD_ADDED";
private static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";
public static final String EXTRA_ACCOUNT = "ACCOUNT";
public static final String EXTRA_FILE = "FILE";
private static final String DOWNLOAD_ADDED_MESSAGE = "DOWNLOAD_ADDED";
private static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";
public static final String EXTRA_FILE_PATH = "FILE_PATH";
public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
public static final String EXTRA_LINKED_TO_PATH = "LINKED_TO";
public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
public static final String EXTRA_FILE_PATH = "FILE_PATH";
public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
public static final String EXTRA_LINKED_TO_PATH = "LINKED_TO";
public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
private OwnCloudClient mDownloadClient = null;
private Account mCurrentAccount = null;
private FileDataStorageManager mStorageManager;
private OwnCloudClient mDownloadClient = null;
private Account mCurrentAccount = null;
private FileDataStorageManager mStorageManager;
private IndexedForest<DownloadFileOperation> mPendingDownloads = new IndexedForest<DownloadFileOperation>();
private DownloadFileOperation mCurrentDownload = null;
private IndexedForest<DownloadFileOperation> mPendingDownloads = new IndexedForest<DownloadFileOperation>();
private DownloadFileOperation mCurrentDownload = null;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mNotificationBuilder;
private int mLastPercent;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mNotificationBuilder;
private int mLastPercent;
public static String getDownloadAddedMessage() {
return FileDownloader.class.getName() + DOWNLOAD_ADDED_MESSAGE;
}
public static String getDownloadAddedMessage() {
return FileDownloader.class.getName() + DOWNLOAD_ADDED_MESSAGE;
}
public static String getDownloadFinishMessage() {
return FileDownloader.class.getName() + DOWNLOAD_FINISH_MESSAGE;
}
public static String getDownloadFinishMessage() {
return FileDownloader.class.getName() + DOWNLOAD_FINISH_MESSAGE;
}
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper, this);
mBinder = new FileDownloaderBinder();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper, this);
mBinder = new FileDownloaderBinder();
* 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.
*/
* 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.
*/
public int onStartCommand(Intent intent, int flags, int startId) {
Log_OC.d(TAG, "Starting command with id " + startId);
public int onStartCommand(Intent intent, int flags, int startId) {
Log_OC.d(TAG, "Starting command with id " + startId);
- AbstractList<String> requestedDownloads = new Vector<String>();
- try {
- DownloadFileOperation newDownload = new DownloadFileOperation(account, file);
- newDownload.addDatatransferProgressListener(this);
- newDownload.addDatatransferProgressListener((FileDownloaderBinder) mBinder);
- Pair<String, String> putResult = mPendingDownloads.putIfAbsent(
+ AbstractList<String> requestedDownloads = new Vector<String>();
+ try {
+ DownloadFileOperation newDownload = new DownloadFileOperation(account, file);
+ newDownload.addDatatransferProgressListener(this);
+ newDownload.addDatatransferProgressListener((FileDownloaderBinder) mBinder);
+ Pair<String, String> putResult = mPendingDownloads.putIfAbsent(
/*Log_OC.v(
"NOW " + TAG + ", thread " + Thread.currentThread().getName(),
"Download on " + file.getRemotePath() + " added to queue"
);*/
/*Log_OC.v(
"NOW " + TAG + ", thread " + Thread.currentThread().getName(),
"Download on " + file.getRemotePath() + " added to queue"
);*/
/*
TODO - check if helps with UI responsiveness, letting only folders use FileDownloaderBinder to check
FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());
/*
TODO - check if helps with UI responsiveness, letting only folders use FileDownloaderBinder to check
FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());
- } catch (IllegalArgumentException e) {
- Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
- return START_NOT_STICKY;
- }
+ } catch (IllegalArgumentException e) {
+ Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
+ return START_NOT_STICKY;
+ }
- if (requestedDownloads.size() > 0) {
- Message msg = mServiceHandler.obtainMessage();
- msg.arg1 = startId;
- msg.obj = requestedDownloads;
- mServiceHandler.sendMessage(msg);
- }
+ if (requestedDownloads.size() > 0) {
+ Message msg = mServiceHandler.obtainMessage();
+ msg.arg1 = startId;
+ msg.obj = requestedDownloads;
+ mServiceHandler.sendMessage(msg);
+ }
/**
* Provides a binder object that clients can use to perform operations on the queue of downloads,
* excepting the addition of new files.
/**
* Provides a binder object that clients can use to perform operations on the queue of downloads,
* excepting the addition of new files.
+ @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.
- *
- * It provides by itself the available operations.
+ * Binder to let client components to perform operations on the queue of downloads.
+ * <p/>
+ * It provides by itself the available operations.
- * @param account ownCloud account where the remote file is stored.
- * @param file A file in the queue of pending downloads
+ * @param account ownCloud account where the remote file is stored.
+ * @param file A file in the queue of pending downloads
);
Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
"Removing download of " + file.getRemotePath());*/
);
Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
"Removing download of " + file.getRemotePath());*/
- Pair<DownloadFileOperation, String> removeResult = mPendingDownloads.remove(account, file.getRemotePath());
+ Pair<DownloadFileOperation, String> removeResult =
+ mPendingDownloads.remove(account, file.getRemotePath());
DownloadFileOperation download = removeResult.first;
if (download != null) {
/*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
DownloadFileOperation download = removeResult.first;
if (download != null) {
/*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
+
+ /**
+ * Cancels a pending or current upload for an account
+ *
+ * @param account Owncloud accountName where the remote file will be stored.
+ */
+ public void cancel(Account account) {
+ Log_OC.d(TAG, "Account= " + account.name);
+
+ if (mCurrentDownload != null) {
+ Log_OC.d(TAG, "Current Download Account= " + mCurrentDownload.getAccount().name);
+ if (mCurrentDownload.getAccount().name.equals(account.name)) {
+ mCurrentDownload.cancel();
+ }
+ }
+ // Cancel pending downloads
+ cancelDownloadsForAccount(account);
+ }
+
- *
- * @param account ownCloud account where the remote file is stored.
- * @param file A file that could be in the queue of downloads.
+ *
+ * @param account ownCloud account where the remote file is stored.
+ * @param file A file that could be in the queue of downloads.
*/
public boolean isDownloading(Account account, OCFile file) {
if (account == null || file == null) return false;
return (mPendingDownloads.contains(account, file.getRemotePath()));
}
*/
public boolean isDownloading(Account account, OCFile file) {
if (account == null || file == null) return false;
return (mPendingDownloads.contains(account, file.getRemotePath()));
}
- *
- * @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.
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);
}
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);
}
- *
- * @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.
OnDatatransferProgressListener listener, Account account, OCFile file
) {
if (account == null || file == null || listener == null) return;
OnDatatransferProgressListener listener, Account account, OCFile file
) {
if (account == null || file == null || listener == null) return;
@Override
public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer,
@Override
public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer,
//String key = buildKey(mCurrentDownload.getAccount(), mCurrentDownload.getFile().getRemotePath());
OnDatatransferProgressListener boundListener = mBoundListeners.get(mCurrentDownload.getFile().getFileId());
if (boundListener != null) {
boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, fileName);
}
}
//String key = buildKey(mCurrentDownload.getAccount(), mCurrentDownload.getFile().getRemotePath());
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();
+ }
+ // The rest of downloads are cancelled when they try to start
+ }
+
-
-
- /**
- * 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()}.
+
+
+ /**
+ * Download worker. Performs the pending downloads in the order they were requested.
+ * <p/>
+ * 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
FileDownloader mService;
*/
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;
-
- notifyDownloadStart(mCurrentDownload);
+ // 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())) {
- mCurrentAccount = mCurrentDownload.getAccount();
- mStorageManager = new FileDataStorageManager(
- mCurrentAccount,
- getContentResolver()
- );
- } // else, reuse storage manager from previous operation
-
- // 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(),
+ RemoteOperationResult downloadResult = null;
+ try {
+ /// prepare client object to send the request to the ownCloud server
+ if (mCurrentAccount == null || !mCurrentAccount.equals(mCurrentDownload.getAccount())) {
+ mCurrentAccount = mCurrentDownload.getAccount();
+ mStorageManager = new FileDataStorageManager(
+ mCurrentAccount,
+ getContentResolver()
+ );
+ } // else, reuse storage manager from previous operation
+
+ // 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(),
- 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);
- downloadResult = new RemoteOperationResult(e);
-
- } finally {
+ 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);
+ downloadResult = new RemoteOperationResult(e);
+
+ } finally {
/*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
"Removing payload " + mCurrentDownload.getRemotePath());*/
/*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
"Removing payload " + mCurrentDownload.getRemotePath());*/
- Pair<DownloadFileOperation, String> removeResult =
- mPendingDownloads.removePayload(mCurrentAccount, mCurrentDownload.getRemotePath());
+ Pair<DownloadFileOperation, String> removeResult =
+ mPendingDownloads.removePayload(mCurrentAccount, mCurrentDownload.getRemotePath());
- sendBroadcastDownloadFinished(mCurrentDownload, downloadResult, removeResult.second);
- }
+ sendBroadcastDownloadFinished(mCurrentDownload, downloadResult, removeResult.second);
+ }
+ } else {
+ // Cancel the transfer
+ Log_OC.d(TAG, "Account " + mCurrentDownload.getAccount().toString() + " doesn't exist");
+ cancelDownloadsForAccount(mCurrentDownload.getAccount());
*/
private void notifyDownloadStart(DownloadFileOperation download) {
/// create status notification with a progress bar
mLastPercent = 0;
*/
private void notifyDownloadStart(DownloadFileOperation download) {
/// create status notification with a progress bar
mLastPercent = 0;
NotificationBuilderWithProgressBar.newNotificationBuilderWithProgressBar(this);
mNotificationBuilder
.setSmallIcon(R.drawable.notification_icon)
NotificationBuilderWithProgressBar.newNotificationBuilderWithProgressBar(this);
mNotificationBuilder
.setSmallIcon(R.drawable.notification_icon)
String.format(getString(R.string.downloader_download_in_progress_content), 0,
new File(download.getSavePath()).getName())
);
String.format(getString(R.string.downloader_download_in_progress_content), 0,
new File(download.getSavePath()).getName())
);
/// includes a pending intent in the notification showing the details view of the file
Intent showDetailsIntent = null;
if (PreviewImageFragment.canBePreviewed(download.getFile())) {
/// includes a pending intent in the notification showing the details view of the file
Intent showDetailsIntent = null;
if (PreviewImageFragment.canBePreviewed(download.getFile())) {
showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, download.getFile());
showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, download.getAccount());
showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, download.getFile());
showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, download.getAccount());
showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- this, (int) System.currentTimeMillis(), showDetailsIntent, 0
+ this, (int) System.currentTimeMillis(), showDetailsIntent, 0
- public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filePath)
- {
- int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
+ 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);
String fileName = filePath.substring(filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1);
if (percent != mLastPercent) {
mNotificationBuilder.setProgress(100, percent, totalToTransfer < 0);
String fileName = filePath.substring(filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1);
- *
- * @param downloadResult Result of the download operation.
- * @param download Finished download operation
+ *
+ * @param downloadResult Result of the download operation.
+ * @param download Finished download operation
*/
private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) {
mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);
if (!downloadResult.isCancelled()) {
*/
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 :
- R.string.downloader_download_failed_ticker;
-
+ int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker :
+ R.string.downloader_download_failed_ticker;
+
- .setTicker(getString(tickerId))
- .setContentTitle(getString(tickerId))
- .setAutoCancel(true)
- .setOngoing(false)
- .setProgress(0, 0, false);
-
+ .setTicker(getString(tickerId))
+ .setContentTitle(getString(tickerId))
+ .setAutoCancel(true)
+ .setOngoing(false)
+ .setProgress(0, 0, false);
+
// let the user update credentials with one click
Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, download.getAccount());
// let the user update credentials with one click
Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, download.getAccount());
updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
mNotificationBuilder
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));
-
+ .setContentIntent(PendingIntent.getActivity(
+ this, (int) System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT));
+
- .setContentIntent(PendingIntent.getActivity(
- this, (int) System.currentTimeMillis(), showDetailsIntent, 0));
+ .setContentIntent(PendingIntent.getActivity(
+ this, (int) System.currentTimeMillis(), showDetailsIntent, 0));
mNotificationBuilder.setContentText(
ErrorMessageAdapter.getErrorCauseMessage(downloadResult, download, getResources())
);
mNotificationManager.notify(tickerId, mNotificationBuilder.build());
mNotificationBuilder.setContentText(
ErrorMessageAdapter.getErrorCauseMessage(downloadResult, download, getResources())
);
mNotificationManager.notify(tickerId, mNotificationBuilder.build());
// Sleep 2 seconds, so show the notification before remove it
NotificationDelayer.cancelWithDelay(
// Sleep 2 seconds, so show the notification before remove it
NotificationDelayer.cancelWithDelay(
- *
- * @param download Finished download operation
- * @param downloadResult Result of the download operation
- * @param unlinkedFromRemotePath Path in the downloads tree where the download was unlinked from
+ *
+ * @param download Finished download operation
+ * @param downloadResult Result of the download operation
+ * @param unlinkedFromRemotePath Path in the downloads tree where the download was unlinked from
*/
private void sendBroadcastDownloadFinished(
DownloadFileOperation download,
*/
private void sendBroadcastDownloadFinished(
DownloadFileOperation download,
- *
- * @param download Added download operation
- * @param linkedToRemotePath Path in the downloads tree where the download was linked to
+ *
+ * @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) {
Intent added = new Intent(getDownloadAddedMessage());
*/
private void sendBroadcastNewDownload(DownloadFileOperation download, String linkedToRemotePath) {
Intent added = new Intent(getDownloadAddedMessage());
+ /**
+ * Remove downloads of an account
+ *
+ * @param account Downloads account to remove
+ */
+ private void cancelDownloadsForAccount(Account account) {
+ // Cancel pending downloads
+ mPendingDownloads.remove(account);
+ }