-Subproject commit 0dd68c1f65c31bd716b2de26e644c87c98e9b9c2
+Subproject commit fc07af23643b3c6a1b7df7c4c81b57482111d4a1
return getAppContext().getResources().getString(R.string.log_name);
}
+ // user agent
+ // TODO: decide if it use account_type or another string for user_agent
+ public static String getUserAgent() {
+ return getAppContext().getResources().getString(R.string.account_type);
+ }
}
import android.net.Uri;
import android.os.AsyncTask;
+import com.owncloud.android.MainApp;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.OwnCloudClientFactory;
import com.owncloud.android.lib.common.OwnCloudCredentials;
mContext,
SUCCESS_IF_ABSENT
);
- result = operation.execute(client);
+ result = operation.execute(client, MainApp.getUserAgent());
} else {
result = new RemoteOperationResult(RemoteOperationResult.ResultCode.UNKNOWN_ERROR);
import java.util.Map;
import java.util.Vector;
+import com.owncloud.android.MainApp;
import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.authentication.AuthenticatorActivity;
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);
// 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());
+ 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);
*/
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<Long, OnDatatransferProgressListener> mBoundListeners =
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());*/
+ "Canceling current sync as descendant: " + mCurrentDownload.getRemotePath());*/
mCurrentDownload.cancel();
}
}
/**
- * 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.
* <p/>
* If 'file' is a directory, returns 'true' if any of its descendant files is downloading or
* waiting to download.
}
@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) {
+ //String key = buildKey(mCurrentDownload.getAccount(),
+ // mCurrentDownload.getFile().getRemotePath());
+ OnDatatransferProgressListener boundListener =
+ mBoundListeners.get(mCurrentDownload.getFile().getFileId());
if (boundListener != null) {
- boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, fileName);
+ boundListener.onTransferProgress(progressRate, totalTransferredSoFar,
+ totalToTransfer, fileName);
}
}
* 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) {
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,
);
} // 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);
+ downloadResult = mCurrentDownload.execute(mDownloadClient,
+ MainApp.getUserAgent());
if (downloadResult.isSuccess()) {
saveDownloadedFile();
}
} catch (AccountsException e) {
- Log_OC.e(TAG, "Error while trying to get authorization for " + mCurrentAccount.name, 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);
+ Log_OC.e(TAG, "Error while trying to get authorization for "
+ + mCurrentAccount.name, e);
downloadResult = new RemoteOperationResult(e);
} finally {
"Removing payload " + mCurrentDownload.getRemotePath());*/
Pair<DownloadFileOperation, String> removeResult =
- mPendingDownloads.removePayload(mCurrentAccount, mCurrentDownload.getRemotePath());
+ mPendingDownloads.removePayload(mCurrentAccount,
+ mCurrentDownload.getRemotePath());
/// notify result
notifyDownloadResult(mCurrentDownload, downloadResult);
- 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");
+ Log_OC.d(TAG, "Account " + mCurrentDownload.getAccount().toString() +
+ " doesn't exist");
cancelDownloadsForAccount(mCurrentDownload.getAccount());
}
* 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);
* @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 :
// 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
}
mNotificationBuilder.setContentText(
- ErrorMessageAdapter.getErrorCauseMessage(downloadResult, download, getResources())
+ ErrorMessageAdapter.getErrorCauseMessage(downloadResult, download,
+ getResources())
);
mNotificationManager.notify(tickerId, mNotificationBuilder.build());
/**
- * 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
* @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());
import android.support.v4.app.NotificationCompat;
import android.webkit.MimeTypeMap;
+import com.owncloud.android.MainApp;
import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.authentication.AuthenticatorActivity;
super.onCreate();
Log_OC.d(TAG, "Creating service");
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- HandlerThread thread = new HandlerThread("FileUploaderThread", Process.THREAD_PRIORITY_BACKGROUND);
+ HandlerThread thread = new HandlerThread("FileUploaderThread",
+ Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper, this);
}
}
- FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());
+ FileDataStorageManager storageManager = new FileDataStorageManager(account,
+ getContentResolver());
boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
boolean isInstant = intent.getBooleanExtra(KEY_INSTANT_UPLOAD, false);
files = new OCFile[localPaths.length];
for (int i = 0; i < localPaths.length; i++) {
- files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i], ((mimeTypes != null) ? mimeTypes[i]
- : (String) null), storageManager);
+ files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i],
+ ((mimeTypes != null) ? mimeTypes[i] : (String) null), storageManager);
if (files[i] == null) {
// TODO @andomaex add failure Notification
return Service.START_NOT_STICKY;
try {
for (int i = 0; i < files.length; i++) {
uploadKey = buildRemoteName(account, files[i].getRemotePath());
- newUpload = new UploadFileOperation(account, files[i], chunked, isInstant, forceOverwrite, localAction,
+ newUpload = new UploadFileOperation(account, files[i], chunked, isInstant,
+ forceOverwrite, localAction,
getApplicationContext());
if (isInstant) {
newUpload.setRemoteFolderToBeCreated();
}
- mPendingUploads.putIfAbsent(uploadKey, newUpload); // Grants that the file only upload once time
+ // Grants that the file only upload once time
+ mPendingUploads.putIfAbsent(uploadKey, newUpload);
newUpload.addDatatransferProgressListener(this);
newUpload.addDatatransferProgressListener((FileUploaderBinder)mBinder);
public class FileUploaderBinder extends Binder implements OnDatatransferProgressListener {
/**
- * Map of listeners that will be reported about progress of uploads from a {@link FileUploaderBinder} instance
+ * Map of listeners that will be reported about progress of uploads from a
+ * {@link FileUploaderBinder} instance
*/
private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<String, OnDatatransferProgressListener>();
* Returns True when the file described by 'file' is being uploaded to
* the ownCloud account 'account' or waiting for it
*
- * If 'file' is a directory, returns 'true' if some of its descendant files is uploading or waiting to upload.
+ * If 'file' is a directory, returns 'true' if some of its descendant files
+ * is uploading or waiting to upload.
*
* @param account ownCloud account where the remote file will be stored.
* @param file A file that could be in the queue of pending uploads
* @param account ownCloud account holding the file of interest.
* @param file {@link OCFile} of interest for listener.
*/
- public void addDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
+ public void addDatatransferProgressListener (OnDatatransferProgressListener listener,
+ Account account, OCFile file) {
if (account == null || file == null || listener == null) return;
String targetKey = buildRemoteName(account, file);
mBoundListeners.put(targetKey, listener);
* @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) {
+ public void removeDatatransferProgressListener (OnDatatransferProgressListener listener,
+ Account account, OCFile file) {
if (account == null || file == null || listener == null) return;
String targetKey = buildRemoteName(account, file);
if (mBoundListeners.get(targetKey) == listener) {
@Override
- public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer,
- String fileName) {
+ public void onTransferProgress(long progressRate, long totalTransferredSoFar,
+ long totalToTransfer, String fileName) {
String key = buildRemoteName(mCurrentUpload.getAccount(), mCurrentUpload.getFile());
OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
if (boundListener != null) {
- boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, fileName);
+ boundListener.onTransferProgress(progressRate, totalTransferredSoFar,
+ totalToTransfer, fileName);
}
}
try {
/// prepare client object to send requests to the ownCloud server
- if (mUploadClient == null || !mLastAccount.equals(mCurrentUpload.getAccount())) {
+ if (mUploadClient == null ||
+ !mLastAccount.equals(mCurrentUpload.getAccount())) {
mLastAccount = mCurrentUpload.getAccount();
mStorageManager =
new FileDataStorageManager(mLastAccount, getContentResolver());
if (grantResult.isSuccess()) {
OCFile parent = mStorageManager.getFileByPath(remoteParentPath);
mCurrentUpload.getFile().setParentId(parent.getFileId());
- uploadResult = mCurrentUpload.execute(mUploadClient);
+ uploadResult = mCurrentUpload.execute(mUploadClient,
+ MainApp.getUserAgent());
if (uploadResult.isSuccess()) {
saveUploadedFile();
}
}
} catch (AccountsException e) {
- Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
+ Log_OC.e(TAG, "Error while trying to get autorization for " +
+ mLastAccount.name, e);
uploadResult = new RemoteOperationResult(e);
} catch (IOException e) {
- Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
+ Log_OC.e(TAG, "Error while trying to get autorization for " +
+ mLastAccount.name, e);
uploadResult = new RemoteOperationResult(e);
} finally {
Log_OC.i(TAG, "Remove CurrentUploadItem from pending upload Item Map.");
}
if (uploadResult.isException()) {
- // enforce the creation of a new client object for next uploads; this grant that a new socket will
- // be created in the future if the current exception is due to an abrupt lose of network connection
+ // enforce the creation of a new client object for next uploads;
+ // this grant that a new socket will be created in the future if
+ // the current exception is due to an abrupt lose of network connection
mUploadClient = null;
}
}
} else {
// Cancel the transfer
- Log_OC.d(TAG, "Account " + mCurrentUpload.getAccount().toString() + " doesn't exist");
+ Log_OC.d(TAG, "Account " + mCurrentUpload.getAccount().toString() +
+ " doesn't exist");
cancelUploadForAccount(mCurrentUpload.getAccount().name);
}
}
/**
- * Checks the existence of the folder where the current file will be uploaded both in the remote server
- * and in the local database.
+ * Checks the existence of the folder where the current file will be uploaded both
+ * in the remote server and in the local database.
*
- * If the upload is set to enforce the creation of the folder, the method tries to create it both remote
- * and locally.
+ * If the upload is set to enforce the creation of the folder, the method tries to
+ * create it both remote and locally.
*
* @param pathToGrant Full remote path whose existence will be granted.
- * @return An {@link OCFile} instance corresponding to the folder where the file will be uploaded.
+ * @return An {@link OCFile} instance corresponding to the folder where the file
+ * will be uploaded.
*/
private RemoteOperationResult grantFolderExistence(String pathToGrant) {
RemoteOperation operation = new ExistenceCheckRemoteOperation(pathToGrant, this, false);
- RemoteOperationResult result = operation.execute(mUploadClient);
+ RemoteOperationResult result = operation.execute(mUploadClient, MainApp.getUserAgent());
if (!result.isSuccess() && result.getCode() == ResultCode.FILE_NOT_FOUND &&
mCurrentUpload.isRemoteFolderToBeCreated()) {
SyncOperation syncOp = new CreateFolderOperation( pathToGrant, true);
// new PROPFIND to keep data consistent with server
// in theory, should return the same we already have
- ReadRemoteFileOperation operation = new ReadRemoteFileOperation(mCurrentUpload.getRemotePath());
- RemoteOperationResult result = operation.execute(mUploadClient);
+ ReadRemoteFileOperation operation =
+ new ReadRemoteFileOperation(mCurrentUpload.getRemotePath());
+ RemoteOperationResult result = operation.execute(mUploadClient, MainApp.getUserAgent());
if (result.isSuccess()) {
updateOCFile(file, (RemoteFile) result.getData().get(0));
file.setLastSyncDateForProperties(syncDate);
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
remotePath.substring(remotePath.lastIndexOf('.') + 1));
} catch (IndexOutOfBoundsException e) {
- Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " + remotePath);
+ Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " +
+ remotePath);
}
}
if (mimeType == null) {
* 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, false);
- String fileName = filePath.substring(filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1);
+ String fileName = filePath.substring(
+ filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1);
String text = String.format(getString(R.string.uploader_upload_in_progress_content), percent, fileName);
mNotificationBuilder.setContentText(text);
mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotificationBuilder.build());
* @param mimeType
* @return true if is needed to add the pdf file extension to the file
*/
- private boolean isPdfFileFromContentProviderWithoutExtension(String localPath, String mimeType) {
+ private boolean isPdfFileFromContentProviderWithoutExtension(String localPath,
+ String mimeType) {
return localPath.startsWith(UriUtils.URI_CONTENT_SCHEME) &&
mimeType.equals(MIME_TYPE_PDF) &&
!localPath.endsWith(FILE_EXTENSION_PDF);
package com.owncloud.android.operations;
+import com.owncloud.android.MainApp;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.resources.files.CreateRemoteFolderOperation;
/**
* Constructor
*
- * @param createFullPath 'True' means that all the ancestor folders should be created if don't exist yet.
+ * @param createFullPath 'True' means that all the ancestor folders should be created
+ * if don't exist yet.
*/
public CreateFolderOperation(String remotePath, boolean createFullPath) {
mRemotePath = remotePath;
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
- CreateRemoteFolderOperation operation = new CreateRemoteFolderOperation(mRemotePath, mCreateFullPath);
- RemoteOperationResult result = operation.execute(client);
+ CreateRemoteFolderOperation operation = new CreateRemoteFolderOperation(mRemotePath,
+ mCreateFullPath);
+ RemoteOperationResult result = operation.execute(client, MainApp.getUserAgent());
if (result.isSuccess()) {
saveFolderInDB();
}
- private void onCreateRemoteFolderOperationFinish(CreateRemoteFolderOperation operation, RemoteOperationResult result) {
+ private void onCreateRemoteFolderOperationFinish(CreateRemoteFolderOperation operation,
+ RemoteOperationResult result) {
if (result.isSuccess()) {
saveFolderInDB();
} else {
import android.content.Context;
import android.content.Intent;
+import com.owncloud.android.MainApp;
import com.owncloud.android.R;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile;
* @param context The context that the share is coming from.
* @param path Full path of the file/folder being shared. Mandatory argument
* @param shareType 0 = user, 1 = group, 3 = Public link. Mandatory argument
- * @param shareWith User/group ID with who the file should be shared. This is mandatory for shareType of 0 or 1
+ * @param shareWith User/group ID with who the file should be shared.
+ * This is mandatory for shareType of 0 or 1
* @param publicUpload If false (default) public cannot upload to a public shared folder.
- * If true public can upload to a shared folder. Only available for public link shares
- * @param password Password to protect a public link share. Only available for public link shares
+ * If true public can upload to a shared folder.
+ * Only available for public link shares
+ * @param password Password to protect a public link share.
+ * Only available for public link shares
* @param permissions 1 - Read only - Default for public shares
* 2 - Update
* 4 - Create
// Check if the share link already exists
operation = new GetRemoteSharesForFileOperation(mPath, false, false);
- RemoteOperationResult result = ((GetRemoteSharesForFileOperation)operation).execute(client);
+ RemoteOperationResult result =
+ ((GetRemoteSharesForFileOperation)operation).execute(client, MainApp.getUserAgent());
if (!result.isSuccess() || result.getData().size() <= 0) {
operation = new CreateRemoteShareOperation(mPath, mShareType, mShareWith, mPublicUpload,
mPassword, mPermissions);
- result = ((CreateRemoteShareOperation)operation).execute(client);
+ result = ((CreateRemoteShareOperation)operation).execute(client, MainApp.getUserAgent());
}
if (result.isSuccess()) {
import java.util.ArrayList;
+import com.owncloud.android.MainApp;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
import com.owncloud.android.lib.common.operations.RemoteOperation;
* Constructor
*
* @param context Android context of the caller.
- * @param webdavUrl
*/
public DetectAuthenticationMethodOperation(Context context) {
mContext = context;
client.setFollowRedirects(false);
// try to access the root folder, following redirections but not SAML SSO redirections
- result = operation.execute(client);
+ result = operation.execute(client, MainApp.getUserAgent());
String redirectedLocation = result.getRedirectedLocation();
while (redirectedLocation != null && redirectedLocation.length() > 0 &&
!result.isIdPRedirection()) {
client.setBaseUri(Uri.parse(result.getRedirectedLocation()));
- result = operation.execute(client);
+ result = operation.execute(client, MainApp.getUserAgent());
redirectedLocation = result.getRedirectedLocation();
}
ArrayList<Object> data = new ArrayList<Object>();
data.add(authMethod);
result.setData(data);
- return result; // same result instance, so that other errors can be handled by the caller transparently
+ return result; // same result instance, so that other errors
+ // can be handled by the caller transparently
}
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
+import com.owncloud.android.MainApp;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
import com.owncloud.android.lib.common.OwnCloudClient;
public DownloadFileOperation(Account account, OCFile file) {
if (account == null)
- throw new IllegalArgumentException("Illegal null account in DownloadFileOperation creation");
+ throw new IllegalArgumentException("Illegal null account in DownloadFileOperation " +
+ "creation");
if (file == null)
- throw new IllegalArgumentException("Illegal null file in DownloadFileOperation creation");
+ throw new IllegalArgumentException("Illegal null file in DownloadFileOperation " +
+ "creation");
mAccount = account;
mFile = file;
}
public String getSavePath() {
- String path = mFile.getStoragePath(); // re-downloads should be done over the original file
+ String path = mFile.getStoragePath(); // re-downloads should be done over the original file
if (path != null && path.length() > 0) {
return path;
}
try {
mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(
- mFile.getRemotePath().substring(mFile.getRemotePath().lastIndexOf('.') + 1));
+ mFile.getRemotePath().substring(
+ mFile.getRemotePath().lastIndexOf('.') + 1));
} catch (IndexOutOfBoundsException e) {
- Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " + mFile.getRemotePath());
+ Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " +
+ mFile.getRemotePath());
}
}
if (mimeType == null) {
}
public long getModificationTimestamp() {
- return (mModificationTimestamp > 0) ? mModificationTimestamp : mFile.getModificationTimestamp();
+ return (mModificationTimestamp > 0) ? mModificationTimestamp :
+ mFile.getModificationTimestamp();
}
@Override
while (listener.hasNext()) {
mDownloadOperation.addDatatransferProgressListener(listener.next());
}
- result = mDownloadOperation.execute(client);
+ result = mDownloadOperation.execute(client, MainApp.getUserAgent());
if (result.isSuccess()) {
mModificationTimestamp = mDownloadOperation.getModificationTimestamp();
newFile.getParentFile().mkdirs();
moved = tmpFile.renameTo(newFile);
if (!moved)
- result = new RemoteOperationResult(RemoteOperationResult.ResultCode.LOCAL_STORAGE_NOT_MOVED);
+ result = new RemoteOperationResult(
+ RemoteOperationResult.ResultCode.LOCAL_STORAGE_NOT_MOVED);
}
- Log_OC.i(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage());
+ Log_OC.i(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " +
+ result.getLogMessage());
return result;
}
import java.util.ArrayList;
+import com.owncloud.android.MainApp;
import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.operations.RemoteOperation;
// first: check the status of the server (including its version)
GetRemoteStatusOperation getStatus = new GetRemoteStatusOperation(mContext);
- RemoteOperationResult result = getStatus.execute(client);
+ RemoteOperationResult result = getStatus.execute(client, MainApp.getUserAgent());
if (result.isSuccess()) {
// second: get authentication method required by the server
Log_OC.d(TAG, "Trying empty authorization to detect authentication method");
DetectAuthenticationMethodOperation operation =
new DetectAuthenticationMethodOperation(mContext);
- return operation.execute(client);
+ return operation.execute(client, MainApp.getUserAgent());
}
import java.util.ArrayList;
+import com.owncloud.android.MainApp;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.resources.shares.OCShare;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
- GetRemoteSharesForFileOperation operation = new GetRemoteSharesForFileOperation(mPath, mReshares, mSubfiles);
- RemoteOperationResult result = operation.execute(client);
+ GetRemoteSharesForFileOperation operation = new GetRemoteSharesForFileOperation(mPath,
+ mReshares, mSubfiles);
+ RemoteOperationResult result = operation.execute(client, MainApp.getUserAgent());
if (result.isSuccess()) {
import java.util.ArrayList;
+import com.owncloud.android.MainApp;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.utils.Log_OC;
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
GetRemoteSharesOperation operation = new GetRemoteSharesOperation();
- RemoteOperationResult result = operation.execute(client);
+ RemoteOperationResult result = operation.execute(client, MainApp.getUserAgent());
if (result.isSuccess()) {
package com.owncloud.android.operations;
+import com.owncloud.android.MainApp;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
/**
* Constructor
*
- * @param path Remote path of the {@link OCFile} to move.
- * @param newParentPath Path to the folder where the file will be moved into.
+ * @param srcPath Remote path of the {@link OCFile} to move.
+ * @param targetParentPath Path to the folder where the file will be moved into.
* @param account OwnCloud account containing both the file and the target folder
*/
public MoveFileOperation(String srcPath, String targetParentPath, Account account) {
targetPath,
false
);
- result = operation.execute(client);
+ result = operation.execute(client, MainApp.getUserAgent());
/// 3. local move
if (result.isSuccess()) {
import android.util.Log;
//import android.support.v4.content.LocalBroadcastManager;
+import com.owncloud.android.MainApp;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile;
* @param syncFullAccount 'True' means that this operation is part of a full account
* synchronization.
* @param isShareSupported 'True' means that the server supports the sharing API.
- * @param ignoreEtag 'True' means that the content of the remote folder should
+ * @param ignoreETag 'True' means that the content of the remote folder should
* be fetched and updated even though the 'eTag' did not
* change.
* @param dataStorageManager Interface with the local database.
private void updateOCVersion(OwnCloudClient client) {
UpdateOCVersionOperation update = new UpdateOCVersionOperation(mAccount, mContext);
- RemoteOperationResult result = update.execute(client);
+ RemoteOperationResult result = update.execute(client, MainApp.getUserAgent());
if (result.isSuccess()) {
mIsShareSupported = update.getOCVersion().isSharedSupported();
}
// remote request
ReadRemoteFileOperation operation = new ReadRemoteFileOperation(remotePath);
- result = operation.execute(client);
+ result = operation.execute(client, MainApp.getUserAgent());
if (result.isSuccess()){
OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) {
String remotePath = mLocalFolder.getRemotePath();
ReadRemoteFolderOperation operation = new ReadRemoteFolderOperation(remotePath);
- RemoteOperationResult result = operation.execute(client);
+ RemoteOperationResult result = operation.execute(client, MainApp.getUserAgent());
Log_OC.d(TAG, "Synchronizing " + mAccount.name + remotePath);
if (result.isSuccess()) {
remoteFile.setFileLength(localFile.getFileLength());
// TODO move operations about size of folders to FileContentProvider
} else if (mRemoteFolderChanged && remoteFile.isImage() &&
- remoteFile.getModificationTimestamp() != localFile.getModificationTimestamp()) {
+ remoteFile.getModificationTimestamp() !=
+ localFile.getModificationTimestamp()) {
remoteFile.setNeedsUpdateThumbnail(true);
Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
}
// remote request
GetRemoteSharesForFileOperation operation =
new GetRemoteSharesForFileOperation(mLocalFolder.getRemotePath(), false, true);
- result = operation.execute(client);
+ result = operation.execute(client, MainApp.getUserAgent());
if (result.isSuccess()) {
// update local database
package com.owncloud.android.operations;
+import com.owncloud.android.MainApp;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
boolean localRemovalFailed = false;
if (!mOnlyLocalCopy) {
RemoveRemoteFileOperation operation = new RemoveRemoteFileOperation(mRemotePath);
- result = operation.execute(client);
+ result = operation.execute(client, MainApp.getUserAgent());
if (result.isSuccess() || result.getCode() == ResultCode.FILE_NOT_FOUND) {
localRemovalFailed = !(getStorageManager().removeFile(mFileToRemove, true, true));
}
import java.io.File;
import java.io.IOException;
+import com.owncloud.android.MainApp;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
/**
* Constructor
*
- * @param remotePath RemotePath of the OCFile instance describing the remote file or folder to rename
+ * @param remotePath RemotePath of the OCFile instance describing the remote file or
+ * folder to rename
* @param newName New name to set as the name of file.
*/
public RenameFileOperation(String remotePath, String newName) {
return new RemoteOperationResult(ResultCode.INVALID_LOCAL_FILE_NAME);
}
String parent = (new File(mFile.getRemotePath())).getParent();
- parent = (parent.endsWith(OCFile.PATH_SEPARATOR)) ? parent : parent + OCFile.PATH_SEPARATOR;
+ parent = (parent.endsWith(OCFile.PATH_SEPARATOR)) ? parent : parent +
+ OCFile.PATH_SEPARATOR;
mNewRemotePath = parent + mNewName;
if (mFile.isFolder()) {
mNewRemotePath += OCFile.PATH_SEPARATOR;
return new RemoteOperationResult(ResultCode.INVALID_OVERWRITE);
}
- RenameRemoteFileOperation operation = new RenameRemoteFileOperation(mFile.getFileName(), mFile.getRemotePath(),
+ RenameRemoteFileOperation operation = new RenameRemoteFileOperation(mFile.getFileName(),
+ mFile.getRemotePath(),
mNewName, mFile.isFolder());
- result = operation.execute(client);
+ result = operation.execute(client, MainApp.getUserAgent());
if (result.isSuccess()) {
if (mFile.isFolder()) {
}
} catch (IOException e) {
- Log_OC.e(TAG, "Rename " + mFile.getRemotePath() + " to " + ((mNewRemotePath==null) ? mNewName : mNewRemotePath) + ": " +
+ Log_OC.e(TAG, "Rename " + mFile.getRemotePath() + " to " + ((mNewRemotePath==null) ?
+ mNewName : mNewRemotePath) + ": " +
((result!= null) ? result.getLogMessage() : ""), e);
}
// notify to scan about new file
getStorageManager().triggerMediaScan(newPath);
}
- // else - NOTHING: the link to the local file is kept although the local name can't be updated
+ // else - NOTHING: the link to the local file is kept although the local name
+ // can't be updated
// TODO - study conditions when this could be a problem
}
/**
* Checks if the new name to set is valid in the file system
*
- * The only way to be sure is trying to create a file with that name. It's made in the temporal directory
- * for downloads, out of any account, and then removed.
+ * The only way to be sure is trying to create a file with that name. It's made in the
+ * temporal directory for downloads, out of any account, and then removed.
*
- * IMPORTANT: The test must be made in the same file system where files are download. The internal storage
- * could be formatted with a different file system.
+ * IMPORTANT: The test must be made in the same file system where files are download.
+ * The internal storage could be formatted with a different file system.
*
- * TODO move this method, and maybe FileDownload.get***Path(), to a class with utilities specific for the interactions with the file system
+ * TODO move this method, and maybe FileDownload.get***Path(), to a class with utilities
+ * specific for the interactions with the file system
*
- * @return 'True' if a temporal file named with the name to set could be created in the file system where
- * local files are stored.
+ * @return 'True' if a temporal file named with the name to set could be
+ * created in the file system where local files are stored.
* @throws IOException When the temporal folder can not be created.
*/
private boolean isValidNewName() throws IOException {
throw new IOException("Unexpected error: temporal directory could not be created");
}
try {
- testFile.createNewFile(); // return value is ignored; it could be 'false' because the file already existed, that doesn't invalidate the name
+ testFile.createNewFile(); // return value is ignored; it could be 'false' because
+ // the file already existed, that doesn't invalidate the name
} catch (IOException e) {
Log_OC.i(TAG, "Test for validity of name " + mNewName + " in the file system failed");
return false;
}
boolean result = (testFile.exists() && testFile.isFile());
- // cleaning ; result is ignored, since there is not much we could do in case of failure, but repeat and repeat...
+ // cleaning ; result is ignored, since there is not much we could do in case of failure,
+ // but repeat and repeat...
testFile.delete();
return result;
package com.owncloud.android.operations;
+import com.owncloud.android.MainApp;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.files.services.FileDownloader;
import com.owncloud.android.files.services.FileUploader;
/**
* Constructor for "full synchronization mode".
*
- * Uses remotePath to retrieve all the data both in local cache and in the remote OC server when the operation
- * is executed, instead of reusing {@link OCFile} instances.
+ * Uses remotePath to retrieve all the data both in local cache and in the remote OC server
+ * when the operation is executed, instead of reusing {@link OCFile} instances.
*
* Useful for direct synchronization of a single file.
*
/**
- * Constructor allowing to reuse {@link OCFile} instances just queried from local cache or from remote OC server.
+ * Constructor allowing to reuse {@link OCFile} instances just queried from local cache or
+ * from remote OC server.
*
- * Useful to include this operation as part of the synchronization of a folder (or a full account), avoiding the
- * repetition of fetch operations (both in local database or remote server).
+ * Useful to include this operation as part of the synchronization of a folder
+ * (or a full account), avoiding the repetition of fetch operations (both in local database
+ * or remote server).
*
- * At least one of localFile or serverFile MUST NOT BE NULL. If you don't have none of them, use the other
- * constructor.
+ * At least one of localFile or serverFile MUST NOT BE NULL. If you don't have none of them,
+ * use the other constructor.
*
* @param localFile Data of file (just) retrieved from local cache/database.
- * @param serverFile Data of file (just) retrieved from a remote server. If null, will be
- * retrieved from network by the operation when executed.
+ * @param serverFile Data of file (just) retrieved from a remote server. If null,
+ * will be retrieved from network by the operation when executed.
* @param account ownCloud account holding the file.
* @param syncFileContents When 'true', transference of data will be started by the
* operation if needed and no conflict is detected.
if (mLocalFile != null) {
mRemotePath = mLocalFile.getRemotePath();
if (mServerFile != null && !mServerFile.getRemotePath().equals(mRemotePath)) {
- throw new IllegalArgumentException("serverFile and localFile do not correspond to the same OC file");
+ throw new IllegalArgumentException("serverFile and localFile do not correspond" +
+ " to the same OC file");
}
} else if (mServerFile != null) {
mRemotePath = mServerFile.getRemotePath();
/**
* Temporal constructor.
*
- * Extends the previous one to allow constrained synchronizations where uploads are never performed - only
- * downloads or conflict detection.
+ * Extends the previous one to allow constrained synchronizations where uploads are never
+ * performed - only downloads or conflict detection.
*
- * Do not use unless you are involved in 'folder synchronization' or 'folder download' work in progress.
+ * Do not use unless you are involved in 'folder synchronization' or 'folder download' work
+ * in progress.
*
* TODO Remove when 'folder synchronization' replaces 'folder download'.
*
- * @param localFile Data of file (just) retrieved from local cache/database. MUSTN't be null.
- * @param serverFile Data of file (just) retrieved from a remote server. If null, will be
- * retrieved from network by the operation when executed.
+ * @param localFile Data of file (just) retrieved from local cache/database.
+ * MUSTN't be null.
+ * @param serverFile Data of file (just) retrieved from a remote server.
+ * If null, will be retrieved from network by the operation
+ * when executed.
* @param account ownCloud account holding the file.
* @param syncFileContents When 'true', transference of data will be started by the
* operation if needed and no conflict is detected.
- * @param allowUploads When 'false', uploads to the server are not done; only downloads or conflict
- * detection.
+ * @param allowUploads When 'false', uploads to the server are not done;
+ * only downloads or conflict detection.
* @param context Android context; needed to start transfers.
*/
public SynchronizeFileOperation(
if (mServerFile == null) {
ReadRemoteFileOperation operation = new ReadRemoteFileOperation(mRemotePath);
- result = operation.execute(client);
+ result = operation.execute(client, MainApp.getUserAgent());
if (result.isSuccess()){
mServerFile = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
mServerFile.setLastSyncDateForProperties(System.currentTimeMillis());
serverChanged = (!mServerFile.getEtag().equals(mLocalFile.getEtag()));
} else { */
serverChanged = (
- mServerFile.getModificationTimestamp() != mLocalFile.getModificationTimestampAtLastSyncForData()
+ mServerFile.getModificationTimestamp() !=
+ mLocalFile.getModificationTimestampAtLastSyncForData()
);
//}
boolean localChanged = (
} else if (localChanged) {
if (mSyncFileContents && mAllowUploads) {
requestForUpload(mLocalFile);
- // the local update of file properties will be done by the FileUploader service when the upload finishes
+ // the local update of file properties will be done by the FileUploader
+ // service when the upload finishes
} else {
- // NOTHING TO DO HERE: updating the properties of the file in the server without uploading the contents would be stupid;
- // So, an instance of SynchronizeFileOperation created with syncFileContents == false is completely useless when we suspect
+ // NOTHING TO DO HERE: updating the properties of the file in the server
+ // without uploading the contents would be stupid;
+ // So, an instance of SynchronizeFileOperation created with
+ // syncFileContents == false is completely useless when we suspect
// that an upload is necessary (for instance, in FileObserverService).
}
result = new RemoteOperationResult(ResultCode.OK);
mLocalFile.setRemoteId(mServerFile.getRemoteId());
if (mSyncFileContents) {
- requestForDownload(mLocalFile); // local, not server; we won't to keep the value of keepInSync!
- // the update of local data will be done later by the FileUploader service when the upload finishes
+ requestForDownload(mLocalFile); // local, not server; we won't to keep
+ // the value of keepInSync!
+ // the update of local data will be done later by the FileUploader
+ // service when the upload finishes
} else {
// TODO CHECK: is this really useful in some point in the code?
mServerFile.setKeepInSync(mLocalFile.keepInSync());
}
- Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", file " + mLocalFile.getRemotePath() + ": "
- + result.getLogMessage());
+ Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", file " + mLocalFile.getRemotePath() +
+ ": " + result.getLogMessage());
return result;
}
Intent i = new Intent(mContext, FileUploader.class);
i.putExtra(FileUploader.KEY_ACCOUNT, mAccount);
i.putExtra(FileUploader.KEY_FILE, file);
- /*i.putExtra(FileUploader.KEY_REMOTE_FILE, mRemotePath); // doing this we would lose the value of keepInSync in the road, and maybe it's not updated in the database when the FileUploader service gets it!
+ /*i.putExtra(FileUploader.KEY_REMOTE_FILE, mRemotePath);
+ // doing this we would lose the value of keepInSync in the road, and maybe
+ // it's not updated in the database when the FileUploader service gets it!
i.putExtra(FileUploader.KEY_LOCAL_FILE, localFile.getStoragePath());*/
i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
i.putExtra(FileUploader.KEY_FORCE_OVERWRITE, true);
import android.content.Intent;
import android.util.Log;
+import com.owncloud.android.MainApp;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.files.services.FileDownloader;
* @param account ownCloud account where the folder is located.
* @param currentSyncTime Time stamp for the synchronization process in progress.
*/
- public SynchronizeFolderOperation(Context context, String remotePath, Account account, long currentSyncTime){
+ public SynchronizeFolderOperation(Context context, String remotePath, Account account,
+ long currentSyncTime){
mRemotePath = remotePath;
mCurrentSyncTime = currentSyncTime;
mAccount = account;
}
- private RemoteOperationResult checkForChanges(OwnCloudClient client) throws OperationCancelledException {
+ private RemoteOperationResult checkForChanges(OwnCloudClient client)
+ throws OperationCancelledException {
Log_OC.d(TAG, "Checking changes in " + mAccount.name + mRemotePath);
mRemoteFolderChanged = true;
// remote request
ReadRemoteFileOperation operation = new ReadRemoteFileOperation(mRemotePath);
- result = operation.execute(client);
+ result = operation.execute(client, MainApp.getUserAgent());
if (result.isSuccess()){
OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
}
- private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) throws OperationCancelledException {
+ private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client)
+ throws OperationCancelledException {
if (mCancellationRequested.get()) {
throw new OperationCancelledException();
}
ReadRemoteFolderOperation operation = new ReadRemoteFolderOperation(mRemotePath);
- RemoteOperationResult result = operation.execute(client);
+ RemoteOperationResult result = operation.execute(client, MainApp.getUserAgent());
Log_OC.d(TAG, "Synchronizing " + mAccount.name + mRemotePath);
if (result.isSuccess()) {
storageManager.removeFolder(
mLocalFolder,
true,
- ( mLocalFolder.isDown() && // TODO: debug, I think this is always false for folders
+ ( mLocalFolder.isDown() && // TODO: debug, I think this is
+ // always false for folders
mLocalFolder.getStoragePath().startsWith(currentSavePath)
)
);
remoteFile.setFileLength(localFile.getFileLength());
// TODO move operations about size of folders to FileContentProvider
} else if (mRemoteFolderChanged && remoteFile.isImage() &&
- remoteFile.getModificationTimestamp() != localFile.getModificationTimestamp()) {
+ remoteFile.getModificationTimestamp() !=
+ localFile.getModificationTimestamp()) {
remoteFile.setNeedsUpdateThumbnail(true);
Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
}
* @param filesToSyncContents Synchronization operations to execute.
* @param client Interface to the remote ownCloud server.
*/
- private void startContentSynchronizations(List<SyncOperation> filesToSyncContents, OwnCloudClient client)
+ private void startContentSynchronizations(List<SyncOperation> filesToSyncContents,
+ OwnCloudClient client)
throws OperationCancelledException {
Log_OC.v(TAG, "Starting content synchronization... ");
/**
- * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile} object with the data read from the server.
+ * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile}
+ * object with the data read from the server.
*
* @param remote remote file read from the server (remote file or folder).
* @return New OCFile instance representing the remote resource described by we.
/**
* Scans the default location for saving local copies of files searching for
- * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile} received as
- * parameter.
+ * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile}
+ * received as parameter.
*
* @param file File to associate a possible 'lost' local file.
*/
import android.content.Context;
+import com.owncloud.android.MainApp;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.common.OwnCloudClient;
RemoteOperationResult result = null;
// Get Share for a file
- OCShare share = getStorageManager().getFirstShareByPathAndType(mRemotePath, ShareType.PUBLIC_LINK);
+ OCShare share = getStorageManager().getFirstShareByPathAndType(mRemotePath,
+ ShareType.PUBLIC_LINK);
if (share != null) {
- RemoveRemoteShareOperation operation = new RemoveRemoteShareOperation((int) share.getIdRemoteShared());
- result = operation.execute(client);
+ RemoveRemoteShareOperation operation =
+ new RemoveRemoteShareOperation((int) share.getIdRemoteShared());
+ result = operation.execute(client, MainApp.getUserAgent());
if (result.isSuccess() || result.getCode() == ResultCode.SHARE_NOT_FOUND) {
Log_OC.d(TAG, "Share id = " + share.getIdRemoteShared() + " deleted");
}
private boolean existsFile(OwnCloudClient client, String remotePath){
- ExistenceCheckRemoteOperation existsOperation = new ExistenceCheckRemoteOperation(remotePath, mContext, false);
- RemoteOperationResult result = existsOperation.execute(client);
+ ExistenceCheckRemoteOperation existsOperation =
+ new ExistenceCheckRemoteOperation(remotePath, mContext, false);
+ RemoteOperationResult result = existsOperation.execute(client, MainApp.getUserAgent());
return result.isSuccess();
}
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
-import java.util.concurrent.CancellationException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.httpclient.methods.PutMethod;
int localBehaviour,
Context context) {
if (account == null)
- throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation creation");
+ throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation " +
+ "creation");
if (file == null)
throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
if (file.getStoragePath() == null || file.getStoragePath().length() <= 0) {
mUploadOperation.addDatatransferProgressListener(listener.next());
}
if (!mCancellationRequested.get()) {
- result = mUploadOperation.execute(client);
+ result = mUploadOperation.execute(client, MainApp.getUserAgent());
/// move local temporal file or original file to its corresponding
// location in the ownCloud local folder
private boolean existsFile(OwnCloudClient client, String remotePath){
ExistenceCheckRemoteOperation existsOperation =
new ExistenceCheckRemoteOperation(remotePath, mContext, false);
- RemoteOperationResult result = existsOperation.execute(client);
+ RemoteOperationResult result = existsOperation.execute(client, MainApp.getUserAgent());
return result.isSuccess();
}
package com.owncloud.android.operations.common;
+import com.owncloud.android.MainApp;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
*
* Do not call this method from the main thread.
*
- * This method should be used whenever an ownCloud account is available, instead of {@link #execute(OwnCloudClient)}.
+ * This method should be used whenever an ownCloud account is available, instead of
+ * {@link #execute(OwnCloudClient, com.owncloud.android.datamodel.FileDataStorageManager)}.
*
- * @param account ownCloud account in remote ownCloud server to reach during the execution of the operation.
+ * @param storageManager
* @param context Android context for the component calling the method.
* @return Result of the operation.
*/
public RemoteOperationResult execute(FileDataStorageManager storageManager, Context context) {
if (storageManager == null) {
- throw new IllegalArgumentException("Trying to execute a sync operation with a NULL storage manager");
+ throw new IllegalArgumentException("Trying to execute a sync operation with a " +
+ "NULL storage manager");
}
if (storageManager.getAccount() == null) {
- throw new IllegalArgumentException("Trying to execute a sync operation with a storage manager for a NULL account");
+ throw new IllegalArgumentException("Trying to execute a sync operation with a " +
+ "storage manager for a NULL account");
}
mStorageManager = storageManager;
- return super.execute(mStorageManager.getAccount(), context);
+ return super.execute(mStorageManager.getAccount(), context, getUserAgent());
}
*
* Do not call this method from the main thread.
*
- * @param client Client object to reach an ownCloud server during the execution of the operation.
+ * @param client Client object to reach an ownCloud server during the execution of the o
+ * peration.
+ * @param storageManager
* @return Result of the operation.
*/
- public RemoteOperationResult execute(OwnCloudClient client, FileDataStorageManager storageManager) {
+ public RemoteOperationResult execute(OwnCloudClient client,
+ FileDataStorageManager storageManager) {
if (storageManager == null)
- throw new IllegalArgumentException("Trying to execute a sync operation with a NULL storage manager");
+ throw new IllegalArgumentException("Trying to execute a sync operation with a " +
+ "NULL storage manager");
mStorageManager = storageManager;
- return super.execute(client);
+ return super.execute(client, MainApp.getUserAgent());
}
/**
* Asynchronously executes the remote operation
*
- * This method should be used whenever an ownCloud account is available, instead of {@link #execute(OwnCloudClient)}.
+ * This method should be used whenever an ownCloud account is available, instead of
+ * {@link #execute(OwnCloudClient)}.
*
- * @param account ownCloud account in remote ownCloud server to reach during the execution of the operation.
+ * @param account ownCloud account in remote ownCloud server to reach during the
+ * execution of the operation.
* @param context Android context for the component calling the method.
* @param listener Listener to be notified about the execution of the operation.
- * @param listenerHandler Handler associated to the thread where the methods of the listener objects must be called.
+ * @param listenerHandler Handler associated to the thread where the methods of the listener
+ * objects must be called.
* @return Thread were the remote operation is executed.
*/
/*
- public Thread execute(FileDataStorageManager storageManager, Context context, OnRemoteOperationListener listener, Handler listenerHandler, Activity callerActivity) {
+ public Thread execute(FileDataStorageManager storageManager,
+ Context context, OnRemoteOperationListener listener, Handler listenerHandler, Activity callerActivity) {
if (storageManager == null) {
- throw new IllegalArgumentException("Trying to execute a sync operation with a NULL storage manager");
+ throw new IllegalArgumentException("Trying to execute a sync operation
+ with a NULL storage manager");
}
if (storageManager.getAccount() == null) {
- throw new IllegalArgumentException("Trying to execute a sync operation with a storage manager for a NULL account");
+ throw new IllegalArgumentException("Trying to execute a sync operation with a
+ storage manager for a NULL account");
}
mStorageManager = storageManager;
- return super.execute(storageManager.getAccount(), context, listener, listenerHandler, callerActivity);
+ return super.execute(storageManager.getAccount(), context, listener, listenerHandler,
+ callerActivity);
}
*/
/**
* Asynchronously executes the remote operation
*
- * @param client Client object to reach an ownCloud server during the execution of the operation.
+ * @param client Client object to reach an ownCloud server during the
+ * execution of the operation.
* @param listener Listener to be notified about the execution of the operation.
- * @param listenerHandler Handler associated to the thread where the methods of the listener objects must be called.
+ * @param listenerHandler Handler associated to the thread where the methods of
+ * the listener objects must be called.
* @return Thread were the remote operation is executed.
*/
- public Thread execute(OwnCloudClient client, FileDataStorageManager storageManager, OnRemoteOperationListener listener, Handler listenerHandler) {
+ public Thread execute(OwnCloudClient client, FileDataStorageManager storageManager,
+ OnRemoteOperationListener listener, Handler listenerHandler) {
if (storageManager == null) {
- throw new IllegalArgumentException("Trying to execute a sync operation with a NULL storage manager");
+ throw new IllegalArgumentException("Trying to execute a sync operation " +
+ "with a NULL storage manager");
}
mStorageManager = storageManager;
- return super.execute(client, listener, listenerHandler);
+ return super.execute(client, MainApp.getUserAgent(), listener, listenerHandler);
}
if (mCurrentOperation instanceof SyncOperation) {
result = ((SyncOperation)mCurrentOperation).execute(mOwnCloudClient, mStorageManager);
} else {
- result = mCurrentOperation.execute(mOwnCloudClient);
+ result = mCurrentOperation.execute(mOwnCloudClient, MainApp.getUserAgent());
}
} catch (AccountsException e) {
import org.apache.jackrabbit.webdav.DavException;
+import com.owncloud.android.MainApp;
import com.owncloud.android.R;
import com.owncloud.android.authentication.AuthenticatorActivity;
import com.owncloud.android.datamodel.FileDataStorageManager;
* Implementation of {@link AbstractThreadedSyncAdapter} responsible for synchronizing
* ownCloud files.
*
- * Performs a full synchronization of the account recieved in {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}.
+ * Performs a full synchronization of the account recieved in {@link #onPerformSync(Account, Bundle,
+ * String, ContentProviderClient, SyncResult)}.
*/
public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
private final static String TAG = FileSyncAdapter.class.getSimpleName();
- /** Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation */
+ /** Maximum number of failed folder synchronizations that are supported before finishing
+ * the synchronization operation */
private static final int MAX_FAILED_RESULTS = 3;
- public static final String EVENT_FULL_SYNC_START = FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_START";
- public static final String EVENT_FULL_SYNC_END = FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_END";
- public static final String EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED = FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED";
- //public static final String EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED = FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED";
+ public static final String EVENT_FULL_SYNC_START = FileSyncAdapter.class.getName() +
+ ".EVENT_FULL_SYNC_START";
+ public static final String EVENT_FULL_SYNC_END = FileSyncAdapter.class.getName() +
+ ".EVENT_FULL_SYNC_END";
+ public static final String EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED =
+ FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED";
+ //public static final String EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED =
+ // FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED";
- public static final String EXTRA_ACCOUNT_NAME = FileSyncAdapter.class.getName() + ".EXTRA_ACCOUNT_NAME";
- public static final String EXTRA_FOLDER_PATH = FileSyncAdapter.class.getName() + ".EXTRA_FOLDER_PATH";
+ public static final String EXTRA_ACCOUNT_NAME = FileSyncAdapter.class.getName() +
+ ".EXTRA_ACCOUNT_NAME";
+ public static final String EXTRA_FOLDER_PATH = FileSyncAdapter.class.getName() +
+ ".EXTRA_FOLDER_PATH";
public static final String EXTRA_RESULT = FileSyncAdapter.class.getName() + ".EXTRA_RESULT";
/** Flag made 'true' when a request to cancel the synchronization is received */
private boolean mCancellation;
- /** When 'true' the process was requested by the user through the user interface; when 'false', it was requested automatically by the system */
+ /** When 'true' the process was requested by the user through the user interface;
+ * when 'false', it was requested automatically by the system */
private boolean mIsManualSync;
/** Counter for failed operations in the synchronization process */
/** Counter of failed operations in synchronization of kept-in-sync files */
private int mFailsInFavouritesFound;
- /** Map of remote and local paths to files that where locally stored in a location out of the ownCloud folder and couldn't be copied automatically into it */
+ /** Map of remote and local paths to files that where locally stored in a location out
+ * of the ownCloud folder and couldn't be copied automatically into it */
private Map<String, String> mForgottenLocalFiles;
/** {@link SyncResult} instance to return to the system when the synchronization finish */
try {
this.initClientForCurrentAccount();
} catch (IOException e) {
- /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
+ /// the account is unknown for the Synchronization Manager, unreachable this context,
+ // or can not be authenticated; don't try this again
mSyncResult.tooManyRetries = true;
notifyFailedSynchronization();
return;
} catch (AccountsException e) {
- /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
+ /// the account is unknown for the Synchronization Manager, unreachable this context,
+ // or can not be authenticated; don't try this again
mSyncResult.tooManyRetries = true;
notifyFailedSynchronization();
return;
}
Log_OC.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");
- sendLocalBroadcast(EVENT_FULL_SYNC_START, null, null); // message to signal the start of the synchronization to the UI
+ sendLocalBroadcast(EVENT_FULL_SYNC_START, null, null); // message to signal the start
+ // of the synchronization to the UI
try {
updateOCVersion();
synchronizeFolder(getStorageManager().getFileByPath(OCFile.ROOT_PATH));
} else {
- Log_OC.d(TAG, "Leaving synchronization before synchronizing the root folder because cancelation request");
+ Log_OC.d(TAG, "Leaving synchronization before synchronizing the root folder " +
+ "because cancelation request");
}
} finally {
- // it's important making this although very unexpected errors occur; that's the reason for the finally
+ // it's important making this although very unexpected errors occur;
+ // that's the reason for the finally
if (mFailedResultsCounter > 0 && mIsManualSync) {
/// don't let the system synchronization manager retries MANUAL synchronizations
- // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
+ // (be careful: "MANUAL" currently includes the synchronization requested when
+ // a new account is created and when the user changes the current account)
mSyncResult.tooManyRetries = true;
/// notify the user about the failure of MANUAL synchronization
if (mForgottenLocalFiles.size() > 0) {
notifyForgottenLocalFiles();
}
- sendLocalBroadcast(EVENT_FULL_SYNC_END, null, mLastFailedResult); // message to signal the end to the UI
+ sendLocalBroadcast(EVENT_FULL_SYNC_END, null, mLastFailedResult); // message to signal
+ // the end to the UI
}
}
*/
private void updateOCVersion() {
UpdateOCVersionOperation update = new UpdateOCVersionOperation(getAccount(), getContext());
- RemoteOperationResult result = update.execute(getClient());
+ RemoteOperationResult result = update.execute(getClient(), MainApp.getUserAgent());
if (!result.isSuccess()) {
mLastFailedResult = result;
} else {
}
*/
// folder synchronization
- RefreshFolderOperation synchFolderOp = new RefreshFolderOperation( folder,
- mCurrentSyncTime,
- true,
- mIsShareSupported,
- false,
- getStorageManager(),
- getAccount(),
- getContext()
+ RefreshFolderOperation synchFolderOp = new RefreshFolderOperation( folder,
+ mCurrentSyncTime,
+ true,
+ mIsShareSupported,
+ false,
+ getStorageManager(),
+ getAccount(),
+ getContext()
);
- RemoteOperationResult result = synchFolderOp.execute(getClient());
+ RemoteOperationResult result = synchFolderOp.execute(getClient(), MainApp.getUserAgent());
// synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
if (result.isSuccess()) {
// synchronize children folders
List<OCFile> children = synchFolderOp.getChildren();
- fetchChildren(folder, children, synchFolderOp.getRemoteFolderChanged()); // beware of the 'hidden' recursion here!
+ // beware of the 'hidden' recursion here!
+ fetchChildren(folder, children, synchFolderOp.getRemoteFolderChanged());
}
} else {
}
/**
- * Checks if a failed result should terminate the synchronization process immediately, according to
- * OUR OWN POLICY
+ * Checks if a failed result should terminate the synchronization process immediately,
+ * according to OUR OWN POLICY
*
* @param failedResult Remote operation result to check.
- * @return 'True' if the result should immediately finish the synchronization
+ * @return 'True' if the result should immediately finish the
+ * synchronization
*/
private boolean isFinisher(RemoteOperationResult failedResult) {
if (failedResult != null) {
syncDown = (parentEtagChanged || etag == null || etag.length() == 0);
if(syncDown) { */
synchronizeFolder(newFile);
- //sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED, parent.getRemotePath(), null);
+ //sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED, parent.getRemotePath(),
+ // null);
//}
}
}
- if (mCancellation && i <files.size()) Log_OC.d(TAG, "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() + " due to cancelation request");
+ if (mCancellation && i <files.size()) Log_OC.d(TAG,
+ "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() +
+ " due to cancelation request");
}
/**
- * Sends a message to any application component interested in the progress of the synchronization.
+ * Sends a message to any application component interested in the progress of the
+ * synchronization.
*
* @param event Event in the process of synchronization to be notified.
* @param dirRemotePath Remote path of the folder target of the event occurred.
- * @param result Result of an individual {@ SynchronizeFolderOperation}, if completed; may be null.
+ * @param result Result of an individual {@ SynchronizeFolderOperation},
+ * if completed; may be null.
*/
- private void sendLocalBroadcast(String event, String dirRemotePath, RemoteOperationResult result) {
+ private void sendLocalBroadcast(String event, String dirRemotePath,
+ RemoteOperationResult result) {
Log_OC.d(TAG, "Send broadcast " + event);
Intent intent = new Intent(event);
intent.putExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME, getAccount().name);
// let the user update credentials with one click
Intent updateAccountCredentials = new Intent(getContext(), AuthenticatorActivity.class);
updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
- updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
+ updateAccountCredentials.putExtra(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);
.setTicker(i18n(R.string.sync_fail_ticker_unauthorized))
.setContentTitle(i18n(R.string.sync_fail_ticker_unauthorized))
.setContentIntent(PendingIntent.getActivity(
- getContext(), (int)System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT
+ getContext(), (int)System.currentTimeMillis(), updateAccountCredentials,
+ PendingIntent.FLAG_ONE_SHOT
))
.setContentText(i18n(R.string.sync_fail_content_unauthorized, getAccount().name));
} else {
/**
- * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
+ * Notifies the user about conflicts and strange fails when trying to synchronize the contents
+ * of kept-in-sync files.
*
* By now, we won't consider a failed synchronization.
*/
getContext(), (int) System.currentTimeMillis(), new Intent(), 0
))
.setContentTitle(i18n(R.string.sync_fail_in_favourites_ticker))
- .setContentText(i18n(R.string.sync_fail_in_favourites_content, mFailedResultsCounter + mConflictsFound, mConflictsFound));
+ .setContentText(i18n(R.string.sync_fail_in_favourites_content,
+ mFailedResultsCounter + mConflictsFound, mConflictsFound));
showNotification(R.string.sync_fail_in_favourites_ticker, notificationBuilder);
} else {
}
/**
- * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
- * copying them inside the ownCloud local directory was not possible.
+ * Notifies the user about local copies of files out of the ownCloud local directory that
+ * were 'forgotten' because copying them inside the ownCloud local directory was not possible.
*
- * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
- * synchronization problems if a local file is linked to more than one remote file.
+ * We don't want links to files out of the ownCloud local directory (foreign files) anymore.
+ * It's easy to have synchronization problems if a local file is linked to more than one
+ * remote file.
*
- * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
+ * We won't consider a synchronization as failed when foreign files can not be copied to
+ * the ownCloud local directory.
*/
private void notifyForgottenLocalFiles() {
NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
getContext(), (int) System.currentTimeMillis(), explanationIntent, 0
))
.setContentTitle(i18n(R.string.sync_foreign_files_forgotten_ticker))
- .setContentText(i18n(R.string.sync_foreign_files_forgotten_content, mForgottenLocalFiles.size(), i18n(R.string.app_name)));
+ .setContentText(i18n(R.string.sync_foreign_files_forgotten_content,
+ mForgottenLocalFiles.size(), i18n(R.string.app_name)));
showNotification(R.string.sync_foreign_files_forgotten_ticker, notificationBuilder);
}
if (file.isFolder()) {
return file;
} else if (getStorageManager() != null) {
- String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
+ String parentPath = file.getRemotePath().substring(0,
+ file.getRemotePath().lastIndexOf(file.getFileName()));
return getStorageManager().getFileByPath(parentPath);
}
}
getAccount(),
getApplicationContext()
);
- synchFolderOp.execute(getAccount(), this, null, null);
+ synchFolderOp.execute(getAccount(), MainApp.getAppContext(), this, null, null);
setSupportProgressBarIndeterminateVisibility(true);
*/
public void showUntrustedCertDialog(RemoteOperationResult result) {
// Show a dialog with the certificate info
- SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException)result.getException());
+ SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError(
+ (CertificateCombinedException)result.getException());
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
dialog.show(ft, DIALOG_UNTRUSTED_CERT);
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
+import com.owncloud.android.MainApp;
import com.owncloud.android.R;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.common.OwnCloudAccount;
getAccount(),
getApplicationContext()
);
- synchFolderOp.execute(getAccount(), this, null, null);
+ synchFolderOp.execute(getAccount(), this, MainApp.getUserAgent(), null, null);
setSupportProgressBarIndeterminateVisibility(true);