1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183 |
- package com.owncloud.android.files.services;
- import android.accounts.Account;
- import android.accounts.AccountManager;
- import android.accounts.OnAccountsUpdateListener;
- import android.app.NotificationManager;
- import android.app.PendingIntent;
- import android.app.Service;
- import android.content.Context;
- import android.content.Intent;
- import android.os.Binder;
- import android.os.Handler;
- import android.os.HandlerThread;
- import android.os.IBinder;
- import android.os.Looper;
- import android.os.Message;
- import android.os.Parcelable;
- import android.os.Process;
- import android.support.v4.app.NotificationCompat;
- import android.util.Pair;
- import com.owncloud.android.R;
- import com.owncloud.android.authentication.AccountUtils;
- import com.owncloud.android.authentication.AuthenticatorActivity;
- import com.owncloud.android.datamodel.FileDataStorageManager;
- import com.owncloud.android.datamodel.OCFile;
- import com.owncloud.android.datamodel.ThumbnailsCacheManager;
- import com.owncloud.android.datamodel.UploadsStorageManager;
- import com.owncloud.android.datamodel.UploadsStorageManager.UploadStatus;
- import com.owncloud.android.db.OCUpload;
- import com.owncloud.android.db.UploadResult;
- import com.owncloud.android.datamodel.ThumbnailsCacheManager;
- import com.owncloud.android.lib.common.OwnCloudAccount;
- import com.owncloud.android.lib.common.OwnCloudClient;
- import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
- import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
- import com.owncloud.android.lib.common.operations.RemoteOperationResult;
- import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
- import com.owncloud.android.lib.common.utils.Log_OC;
- import com.owncloud.android.lib.resources.files.FileUtils;
- import com.owncloud.android.lib.resources.status.OwnCloudVersion;
- import com.owncloud.android.ui.notifications.NotificationUtils;
- import com.owncloud.android.operations.UploadFileOperation;
- import com.owncloud.android.ui.activity.FileActivity;
- import com.owncloud.android.ui.activity.UploadListActivity;
- import com.owncloud.android.utils.ErrorMessageAdapter;
- import java.io.File;
- import java.util.AbstractList;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Vector;
- public class FileUploader extends Service
- implements OnDatatransferProgressListener, OnAccountsUpdateListener, UploadFileOperation.OnRenameListener {
- private static final String TAG = FileUploader.class.getSimpleName();
- private static final String UPLOADS_ADDED_MESSAGE = "UPLOADS_ADDED";
- private static final String UPLOAD_START_MESSAGE = "UPLOAD_START";
- private static final String UPLOAD_FINISH_MESSAGE = "UPLOAD_FINISH";
- public static final String EXTRA_UPLOAD_RESULT = "RESULT";
- public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
- public static final String EXTRA_OLD_REMOTE_PATH = "OLD_REMOTE_PATH";
- public static final String EXTRA_OLD_FILE_PATH = "OLD_FILE_PATH";
- public static final String EXTRA_LINKED_TO_PATH = "LINKED_TO";
- public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
- public static final String KEY_FILE = "FILE";
- public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
- public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
- public static final String KEY_MIME_TYPE = "MIME_TYPE";
-
- private static final String KEY_RETRY = "KEY_RETRY";
-
- private static final String KEY_RETRY_UPLOAD = "KEY_RETRY_UPLOAD";
-
- public static final String KEY_ACCOUNT = "ACCOUNT";
-
- public static final String KEY_FORCE_OVERWRITE = "KEY_FORCE_OVERWRITE";
-
- public static final String KEY_CREATE_REMOTE_FOLDER = "CREATE_REMOTE_FOLDER";
-
- public static final String KEY_CREATED_BY = "CREATED_BY";
-
- public static final String KEY_WHILE_CHARGING_ONLY = "KEY_WHILE_CHARGING_ONLY";
- public static final String KEY_LOCAL_BEHAVIOUR = "BEHAVIOUR";
- public static final int LOCAL_BEHAVIOUR_COPY = 0;
- public static final int LOCAL_BEHAVIOUR_MOVE = 1;
- public static final int LOCAL_BEHAVIOUR_FORGET = 2;
- private Looper mServiceLooper;
- private ServiceHandler mServiceHandler;
- private IBinder mBinder;
- private OwnCloudClient mUploadClient = null;
- private Account mCurrentAccount = null;
- private FileDataStorageManager mStorageManager;
-
- private UploadsStorageManager mUploadsStorageManager = null;
- private IndexedForest<UploadFileOperation> mPendingUploads = new IndexedForest<UploadFileOperation>();
-
- private UploadFileOperation mCurrentUpload = null;
- private NotificationManager mNotificationManager;
- private NotificationCompat.Builder mNotificationBuilder;
- private int mLastPercent;
- public static String getUploadsAddedMessage() {
- return FileUploader.class.getName() + UPLOADS_ADDED_MESSAGE;
- }
- public static String getUploadStartMessage() {
- return FileUploader.class.getName() + UPLOAD_START_MESSAGE;
- }
- public static String getUploadFinishMessage() {
- return FileUploader.class.getName() + UPLOAD_FINISH_MESSAGE;
- }
- @Override
- public void onRenameUpload() {
- mUploadsStorageManager.updateDatabaseUploadStart(mCurrentUpload);
- sendBroadcastUploadStarted(mCurrentUpload);
- }
-
- public static class UploadRequester {
-
- public void uploadNewFile(
- Context context,
- Account account,
- String[] localPaths,
- String[] remotePaths,
- String[] mimeTypes,
- Integer behaviour,
- Boolean createRemoteFolder,
- int createdBy
- ) {
- Intent intent = new Intent(context, FileUploader.class);
- intent.putExtra(FileUploader.KEY_ACCOUNT, account);
- intent.putExtra(FileUploader.KEY_LOCAL_FILE, localPaths);
- intent.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
- intent.putExtra(FileUploader.KEY_MIME_TYPE, mimeTypes);
- intent.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, behaviour);
- intent.putExtra(FileUploader.KEY_CREATE_REMOTE_FOLDER, createRemoteFolder);
- intent.putExtra(FileUploader.KEY_CREATED_BY, createdBy);
- context.startService(intent);
- }
-
- public void uploadNewFile(Context context, Account account, String localPath, String remotePath, int
- behaviour, String mimeType, boolean createRemoteFile, int createdBy) {
- uploadNewFile(
- context,
- account,
- new String[]{localPath},
- new String[]{remotePath},
- new String[]{mimeType},
- behaviour,
- createRemoteFile,
- createdBy
- );
- }
-
- public void uploadUpdate(Context context, Account account, OCFile[] existingFiles, Integer behaviour,
- Boolean forceOverwrite) {
- Intent intent = new Intent(context, FileUploader.class);
- intent.putExtra(FileUploader.KEY_ACCOUNT, account);
- intent.putExtra(FileUploader.KEY_FILE, existingFiles);
- intent.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, behaviour);
- intent.putExtra(FileUploader.KEY_FORCE_OVERWRITE, forceOverwrite);
- context.startService(intent);
- }
-
- public void uploadUpdate(Context context, Account account, OCFile existingFile, Integer behaviour,
- Boolean forceOverwrite) {
- uploadUpdate(context, account, new OCFile[]{existingFile}, behaviour, forceOverwrite);
- }
-
- public void retry (Context context, OCUpload upload) {
- if (upload != null && context != null) {
- Account account = AccountUtils.getOwnCloudAccountByName(
- context,
- upload.getAccountName()
- );
- retry(context, account, upload);
- } else {
- throw new IllegalArgumentException("Null parameter!");
- }
- }
-
- public void retryFailedUploads(Context context, Account account, UploadResult uploadResult) {
- UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(context.getContentResolver());
- OCUpload[] failedUploads = uploadsStorageManager.getFailedUploads();
- Account currentAccount = null;
- boolean resultMatch, accountMatch;
- for ( OCUpload failedUpload: failedUploads) {
- accountMatch = (account == null || account.name.equals(failedUpload.getAccountName()));
- resultMatch = (uploadResult == null || uploadResult.equals(failedUpload.getLastResult()));
- if (accountMatch && resultMatch) {
- if (currentAccount == null ||
- !currentAccount.name.equals(failedUpload.getAccountName())) {
- currentAccount = failedUpload.getAccount(context);
- }
- retry(context, currentAccount, failedUpload);
- }
- }
- }
-
- private void retry(Context context, Account account, OCUpload upload) {
- if (upload != null) {
- Intent i = new Intent(context, FileUploader.class);
- i.putExtra(FileUploader.KEY_RETRY, true);
- i.putExtra(FileUploader.KEY_ACCOUNT, account);
- i.putExtra(FileUploader.KEY_RETRY_UPLOAD, upload);
- context.startService(i);
- }
- }
- }
-
- @Override
- public void onCreate() {
- super.onCreate();
- Log_OC.d(TAG, "Creating service");
- mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- HandlerThread thread = new HandlerThread("FileUploaderThread",
- Process.THREAD_PRIORITY_BACKGROUND);
- thread.start();
- mServiceLooper = thread.getLooper();
- mServiceHandler = new ServiceHandler(mServiceLooper, this);
- mBinder = new FileUploaderBinder();
- mUploadsStorageManager = new UploadsStorageManager(getContentResolver());
- int failedCounter = mUploadsStorageManager.failInProgressUploads(
- UploadResult.SERVICE_INTERRUPTED
- );
- if (failedCounter > 0) {
- resurrection();
- }
-
- AccountManager am = AccountManager.get(getApplicationContext());
- am.addOnAccountsUpdatedListener(this, null, false);
- }
-
- private void resurrection() {
-
- mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
- }
-
- @Override
- public void onDestroy() {
- Log_OC.v(TAG, "Destroying service");
- mBinder = null;
- mServiceHandler = null;
- mServiceLooper.quit();
- mServiceLooper = null;
- mNotificationManager = null;
-
- AccountManager am = AccountManager.get(getApplicationContext());
- am.removeOnAccountsUpdatedListener(this);
- super.onDestroy();
- }
-
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- Log_OC.d(TAG, "Starting command with id " + startId);
- boolean retry = intent.getBooleanExtra(KEY_RETRY, false);
- AbstractList<String> requestedUploads = new Vector<String>();
- if (!intent.hasExtra(KEY_ACCOUNT)) {
- Log_OC.e(TAG, "Not enough information provided in intent");
- return Service.START_NOT_STICKY;
- }
- Account account = intent.getParcelableExtra(KEY_ACCOUNT);
- if (!AccountUtils.exists(account, getApplicationContext())) {
- return Service.START_NOT_STICKY;
- }
- OwnCloudVersion ocv = AccountUtils.getServerVersion(account);
- boolean chunked = ocv.isChunkedUploadSupported();
- if (!retry) {
- if (!(intent.hasExtra(KEY_LOCAL_FILE) ||
- intent.hasExtra(KEY_FILE))) {
- Log_OC.e(TAG, "Not enough information provided in intent");
- return Service.START_NOT_STICKY;
- }
- String[] localPaths = null, remotePaths = null, mimeTypes = null;
- OCFile[] files = null;
- if (intent.hasExtra(KEY_FILE)) {
- Parcelable[] files_temp = intent.getParcelableArrayExtra(KEY_FILE);
- files = new OCFile[files_temp.length];
- System.arraycopy(files_temp, 0, files, 0, files_temp.length);
- } else {
- localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
- remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
- mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
- }
- boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
- int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_FORGET);
- boolean isCreateRemoteFolder = intent.getBooleanExtra(KEY_CREATE_REMOTE_FOLDER, false);
- int createdBy = intent.getIntExtra(KEY_CREATED_BY, UploadFileOperation.CREATED_BY_USER);
- if (intent.hasExtra(KEY_FILE) && files == null) {
- Log_OC.e(TAG, "Incorrect array for OCFiles provided in upload intent");
- return Service.START_NOT_STICKY;
- } else if (!intent.hasExtra(KEY_FILE)) {
- if (localPaths == null) {
- Log_OC.e(TAG, "Incorrect array for local paths provided in upload intent");
- return Service.START_NOT_STICKY;
- }
- if (remotePaths == null) {
- Log_OC.e(TAG, "Incorrect array for remote paths provided in upload intent");
- return Service.START_NOT_STICKY;
- }
- if (localPaths.length != remotePaths.length) {
- Log_OC.e(TAG, "Different number of remote paths and local paths!");
- return Service.START_NOT_STICKY;
- }
- files = new OCFile[localPaths.length];
- for (int i = 0; i < localPaths.length; i++) {
- files[i] = UploadFileOperation.obtainNewOCFileToUpload(
- remotePaths[i],
- localPaths[i],
- ((mimeTypes != null) ? mimeTypes[i] : null)
- );
- if (files[i] == null) {
- Log_OC.e(TAG, "obtainNewOCFileToUpload() returned null for remotePaths[i]:" + remotePaths[i]
- + " and localPaths[i]:" + localPaths[i]);
- return Service.START_NOT_STICKY;
- }
- }
- }
-
- String uploadKey = null;
- UploadFileOperation newUpload = null;
- try {
- for (int i = 0; i < files.length; i++) {
- OCUpload ocUpload = new OCUpload(files[i], account);
- ocUpload.setFileSize(files[i].getFileLength());
- ocUpload.setForceOverwrite(forceOverwrite);
- ocUpload.setCreateRemoteFolder(isCreateRemoteFolder);
- ocUpload.setCreatedBy(createdBy);
- ocUpload.setLocalAction(localAction);
-
- ocUpload.setUploadStatus(UploadStatus.UPLOAD_IN_PROGRESS);
- newUpload = new UploadFileOperation(
- account,
- files[i],
- ocUpload,
- chunked,
- forceOverwrite,
- localAction,
- this
- );
- newUpload.setCreatedBy(createdBy);
- if (isCreateRemoteFolder) {
- newUpload.setRemoteFolderToBeCreated();
- }
- newUpload.addDatatransferProgressListener(this);
- newUpload.addDatatransferProgressListener((FileUploaderBinder) mBinder);
- newUpload.addRenameUploadListener(this);
- Pair<String, String> putResult = mPendingUploads.putIfAbsent(
- account.name,
- files[i].getRemotePath(),
- newUpload
- );
- if (putResult != null) {
- uploadKey = putResult.first;
- requestedUploads.add(uploadKey);
-
- long id = mUploadsStorageManager.storeUpload(ocUpload);
- newUpload.setOCUploadId(id);
- }
- }
- } catch (IllegalArgumentException e) {
- Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
- return START_NOT_STICKY;
- } catch (IllegalStateException e) {
- Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
- return START_NOT_STICKY;
- } catch (Exception e) {
- Log_OC.e(TAG, "Unexpected exception while processing upload intent", e);
- return START_NOT_STICKY;
- }
-
- } else {
- if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_RETRY_UPLOAD)) {
- Log_OC.e(TAG, "Not enough information provided in intent: no KEY_RETRY_UPLOAD_KEY");
- return START_NOT_STICKY;
- }
- OCUpload upload = intent.getParcelableExtra(KEY_RETRY_UPLOAD);
- UploadFileOperation newUpload = new UploadFileOperation(
- account,
- null,
- upload,
- chunked,
- upload.isForceOverwrite(),
- upload.getLocalAction(),
- this
- );
- newUpload.addDatatransferProgressListener(this);
- newUpload.addDatatransferProgressListener((FileUploaderBinder) mBinder);
- newUpload.addRenameUploadListener(this);
- Pair<String, String> putResult = mPendingUploads.putIfAbsent(
- account.name,
- upload.getRemotePath(),
- newUpload
- );
- if (putResult != null) {
- String uploadKey = putResult.first;
- requestedUploads.add(uploadKey);
-
- upload.setUploadStatus(UploadStatus.UPLOAD_IN_PROGRESS);
- mUploadsStorageManager.updateUpload(upload);
- }
- }
-
- if (requestedUploads.size() > 0) {
- Message msg = mServiceHandler.obtainMessage();
- msg.arg1 = startId;
- msg.obj = requestedUploads;
- mServiceHandler.sendMessage(msg);
- sendBroadcastUploadsAdded();
- }
- return Service.START_NOT_STICKY;
- }
-
- @Override
- public IBinder onBind(Intent arg0) {
- return mBinder;
- }
-
- @Override
- public boolean onUnbind(Intent intent) {
- ((FileUploaderBinder) mBinder).clearListeners();
- return false;
- }
- @Override
- public void onAccountsUpdated(Account[] accounts) {
-
- if (mCurrentUpload != null &&
- !AccountUtils.exists(mCurrentUpload.getAccount(), getApplicationContext())) {
- mCurrentUpload.cancel();
- }
-
- }
-
- public class FileUploaderBinder extends Binder implements OnDatatransferProgressListener {
-
- private Map<String, OnDatatransferProgressListener> mBoundListeners =
- new HashMap<String, OnDatatransferProgressListener>();
-
- public void cancel(Account account, OCFile file) {
- cancel(account.name, file.getRemotePath());
- }
-
- public void cancel(OCUpload storedUpload) {
- cancel(storedUpload.getAccountName(), storedUpload.getRemotePath());
- }
-
- private void cancel(String accountName, String remotePath) {
- Pair<UploadFileOperation, String> removeResult =
- mPendingUploads.remove(accountName, remotePath);
- UploadFileOperation upload = removeResult.first;
- if (upload == null &&
- mCurrentUpload != null && mCurrentAccount != null &&
- mCurrentUpload.getRemotePath().startsWith(remotePath) &&
- accountName.equals(mCurrentAccount.name)) {
- upload = mCurrentUpload;
- }
- if (upload != null) {
- boolean pending = !upload.isUploadInProgress();
- upload.cancel();
-
-
- mUploadsStorageManager.removeUpload(
- accountName,
- remotePath
- );
- }
- }
-
- public void cancel(Account account) {
- Log_OC.d(TAG, "Account= " + account.name);
- if (mCurrentUpload != null) {
- Log_OC.d(TAG, "Current Upload Account= " + mCurrentUpload.getAccount().name);
- if (mCurrentUpload.getAccount().name.equals(account.name)) {
- mCurrentUpload.cancel();
- }
- }
-
- cancelUploadsForAccount(account);
- }
- public void clearListeners() {
- mBoundListeners.clear();
- }
-
- public boolean isUploading(Account account, OCFile file) {
- if (account == null || file == null)
- return false;
- return (mPendingUploads.contains(account.name, file.getRemotePath()));
- }
- public boolean isUploadingNow(OCUpload upload) {
- return (
- upload != null &&
- mCurrentAccount != null &&
- mCurrentUpload != null &&
- upload.getAccountName().equals(mCurrentAccount.name) &&
- upload.getRemotePath().equals(mCurrentUpload.getRemotePath())
- );
- }
-
- public void addDatatransferProgressListener(
- OnDatatransferProgressListener listener,
- Account account,
- OCFile file
- ) {
- if (account == null || file == null || listener == null) return;
- String targetKey = buildRemoteName(account.name, file.getRemotePath());
- mBoundListeners.put(targetKey, listener);
- }
-
- public void addDatatransferProgressListener(
- OnDatatransferProgressListener listener,
- OCUpload ocUpload
- ) {
- if (ocUpload == null || listener == null) return;
- String targetKey = buildRemoteName(ocUpload.getAccountName(), ocUpload.getRemotePath());
- mBoundListeners.put(targetKey, listener);
- }
-
- public void removeDatatransferProgressListener(
- OnDatatransferProgressListener listener,
- Account account,
- OCFile file
- ) {
- if (account == null || file == null || listener == null) return;
- String targetKey = buildRemoteName(account.name, file.getRemotePath());
- if (mBoundListeners.get(targetKey) == listener) {
- mBoundListeners.remove(targetKey);
- }
- }
-
- public void removeDatatransferProgressListener(
- OnDatatransferProgressListener listener,
- OCUpload ocUpload
- ) {
- if (ocUpload == null || listener == null) return;
- String targetKey = buildRemoteName(ocUpload.getAccountName(), ocUpload.getRemotePath());
- if (mBoundListeners.get(targetKey) == listener) {
- mBoundListeners.remove(targetKey);
- }
- }
- @Override
- public void onTransferProgress(long progressRate, long totalTransferredSoFar,
- long totalToTransfer, String fileName) {
- String key = buildRemoteName(mCurrentUpload.getAccount().name, mCurrentUpload.getFile().getRemotePath());
- OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
- if (boundListener != null) {
- boundListener.onTransferProgress(progressRate, totalTransferredSoFar,
- totalToTransfer, fileName);
- }
- }
-
- private String buildRemoteName(String accountName, String remotePath) {
- return accountName + remotePath;
- }
- }
-
- private static class ServiceHandler extends Handler {
-
-
- FileUploader mService;
- public ServiceHandler(Looper looper, FileUploader service) {
- super(looper);
- if (service == null)
- throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
- mService = service;
- }
- @Override
- public void handleMessage(Message msg) {
- @SuppressWarnings("unchecked")
- AbstractList<String> requestedUploads = (AbstractList<String>) msg.obj;
- if (msg.obj != null) {
- Iterator<String> it = requestedUploads.iterator();
- while (it.hasNext()) {
- mService.uploadFile(it.next());
- }
- }
- Log_OC.d(TAG, "Stopping command after id " + msg.arg1);
- mService.stopSelf(msg.arg1);
- }
- }
-
- public void uploadFile(String uploadKey) {
- mCurrentUpload = mPendingUploads.get(uploadKey);
- if (mCurrentUpload != null) {
-
- if (!AccountUtils.exists(mCurrentUpload.getAccount(), this)) {
- Log_OC.w(TAG, "Account " + mCurrentUpload.getAccount().name +
- " does not exist anymore -> cancelling all its uploads");
- cancelUploadsForAccount(mCurrentUpload.getAccount());
- return;
- }
-
- mUploadsStorageManager.updateDatabaseUploadStart(mCurrentUpload);
- notifyUploadStart(mCurrentUpload);
- sendBroadcastUploadStarted(mCurrentUpload);
- RemoteOperationResult uploadResult = null;
- try {
-
- if (mCurrentAccount == null || !mCurrentAccount.equals(mCurrentUpload.getAccount())) {
- mCurrentAccount = mCurrentUpload.getAccount();
- mStorageManager = new FileDataStorageManager(
- mCurrentAccount,
- getContentResolver()
- );
- }
-
- OwnCloudAccount ocAccount = new OwnCloudAccount(
- mCurrentAccount,
- this
- );
- mUploadClient = OwnCloudClientManagerFactory.getDefaultSingleton().
- getClientFor(ocAccount, this);
-
- uploadResult = mCurrentUpload.execute(mUploadClient, mStorageManager);
- } catch (Exception e) {
- Log_OC.e(TAG, "Error uploading", e);
- uploadResult = new RemoteOperationResult(e);
- } finally {
- Pair<UploadFileOperation, String> removeResult;
- if (mCurrentUpload.wasRenamed()) {
- removeResult = mPendingUploads.removePayload(
- mCurrentAccount.name,
- mCurrentUpload.getOldFile().getRemotePath()
- );
-
- } else {
- removeResult = mPendingUploads.removePayload(
- mCurrentAccount.name,
- mCurrentUpload.getRemotePath()
- );
- }
- mUploadsStorageManager.updateDatabaseUploadResult(uploadResult, mCurrentUpload);
-
- notifyUploadResult(mCurrentUpload, uploadResult);
- sendBroadcastUploadFinished(mCurrentUpload, uploadResult, removeResult.second);
- }
- }
-
- final ThumbnailsCacheManager.ThumbnailGenerationTask task =
- new ThumbnailsCacheManager.ThumbnailGenerationTask(mStorageManager, mCurrentAccount);
- Object[] params = new Object[2];
- params[0] = new File(mCurrentUpload.getOriginalStoragePath());
- params[1] = mCurrentUpload.getFile().getRemoteId();
- task.execute(params);
- }
-
- private void notifyUploadStart(UploadFileOperation upload) {
-
- mLastPercent = 0;
- mNotificationBuilder =
- NotificationUtils.newNotificationBuilder(this);
- mNotificationBuilder
- .setOngoing(true)
- .setSmallIcon(R.drawable.notification_icon)
- .setTicker(getString(R.string.uploader_upload_in_progress_ticker))
- .setContentTitle(getString(R.string.uploader_upload_in_progress_ticker))
- .setProgress(100, 0, false)
- .setContentText(
- String.format(getString(R.string.uploader_upload_in_progress_content), 0, upload.getFileName())
- );
-
- Intent showUploadListIntent = new Intent(this, UploadListActivity.class);
- showUploadListIntent.putExtra(FileActivity.EXTRA_FILE, upload.getFile());
- showUploadListIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
- showUploadListIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
- showUploadListIntent, 0));
- if (!upload.isInstantPicture() && !upload.isInstantVideo()) {
- mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotificationBuilder.build());
- }
-
-
- }
-
- @Override
- 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 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());
- }
- mLastPercent = percent;
- }
-
- private void notifyUploadResult(UploadFileOperation upload,
- RemoteOperationResult uploadResult) {
- Log_OC.d(TAG, "NotifyUploadResult with resultCode: " + uploadResult.getCode());
-
- mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
-
- if (!uploadResult.isCancelled() &&
- !uploadResult.getCode().equals(ResultCode.DELAYED_FOR_WIFI)) {
- int tickerId = (uploadResult.isSuccess()) ? R.string.uploader_upload_succeeded_ticker :
- R.string.uploader_upload_failed_ticker;
- String content;
-
- boolean needsToUpdateCredentials = (ResultCode.UNAUTHORIZED.equals(uploadResult.getCode()));
- tickerId = (needsToUpdateCredentials) ?
- R.string.uploader_upload_failed_credentials_error : tickerId;
- mNotificationBuilder
- .setTicker(getString(tickerId))
- .setContentTitle(getString(tickerId))
- .setAutoCancel(true)
- .setOngoing(false)
- .setProgress(0, 0, false);
- content = ErrorMessageAdapter.getErrorCauseMessage(
- uploadResult, upload, getResources()
- );
- if (needsToUpdateCredentials) {
-
- Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
- updateAccountCredentials.putExtra(
- AuthenticatorActivity.EXTRA_ACCOUNT, upload.getAccount()
- );
- 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);
- mNotificationBuilder.setContentIntent(PendingIntent.getActivity(
- this,
- (int) System.currentTimeMillis(),
- updateAccountCredentials,
- PendingIntent.FLAG_ONE_SHOT
- ));
- } else {
- mNotificationBuilder.setContentText(content);
- }
- if (!uploadResult.isSuccess() && !needsToUpdateCredentials ) {
-
- Intent showUploadListIntent = new Intent(this, UploadListActivity.class);
- showUploadListIntent.putExtra(FileActivity.EXTRA_FILE, upload.getFile());
- showUploadListIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
- showUploadListIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
- showUploadListIntent, 0));
- }
- mNotificationBuilder.setContentText(content);
- mNotificationManager.notify(tickerId, mNotificationBuilder.build());
- if (uploadResult.isSuccess()) {
- mPendingUploads.remove(upload.getAccount().name, upload.getFile().getRemotePath());
-
- NotificationUtils.cancelWithDelay(
- mNotificationManager,
- R.string.uploader_upload_succeeded_ticker,
- 2000);
- }
- }
- }
-
- private void sendBroadcastUploadsAdded() {
- Intent start = new Intent(getUploadsAddedMessage());
-
- sendStickyBroadcast(start);
- }
-
- private void sendBroadcastUploadStarted(
- UploadFileOperation upload) {
- Intent start = new Intent(getUploadStartMessage());
- start.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath());
- start.putExtra(EXTRA_OLD_FILE_PATH, upload.getOriginalStoragePath());
- start.putExtra(ACCOUNT_NAME, upload.getAccount().name);
- sendStickyBroadcast(start);
- }
-
- private void sendBroadcastUploadFinished(
- UploadFileOperation upload,
- RemoteOperationResult uploadResult,
- String unlinkedFromRemotePath) {
- Intent end = new Intent(getUploadFinishMessage());
- end.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath());
-
-
-
-
- if (upload.wasRenamed()) {
- end.putExtra(EXTRA_OLD_REMOTE_PATH, upload.getOldFile().getRemotePath());
- }
- end.putExtra(EXTRA_OLD_FILE_PATH, upload.getOriginalStoragePath());
- end.putExtra(ACCOUNT_NAME, upload.getAccount().name);
- end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult.isSuccess());
- if (unlinkedFromRemotePath != null) {
- end.putExtra(EXTRA_LINKED_TO_PATH, unlinkedFromRemotePath);
- }
- sendStickyBroadcast(end);
- }
-
- private void cancelUploadsForAccount(Account account) {
- mPendingUploads.remove(account.name);
- mUploadsStorageManager.removeUploads(account.name);
- }
- }
|