123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371 |
- package com.owncloud.android.files.services;
- import android.accounts.Account;
- import android.accounts.AccountManager;
- import android.accounts.OnAccountsUpdateListener;
- import android.app.Notification;
- import android.app.NotificationManager;
- import android.app.PendingIntent;
- import android.app.Service;
- import android.content.Context;
- import android.content.Intent;
- import android.graphics.BitmapFactory;
- import android.os.Binder;
- import android.os.Build;
- 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.util.Pair;
- import com.nextcloud.client.account.User;
- import com.nextcloud.client.account.UserAccountManager;
- import com.nextcloud.client.device.BatteryStatus;
- import com.nextcloud.client.device.PowerManagementService;
- import com.nextcloud.client.network.Connectivity;
- import com.nextcloud.client.network.ConnectivityService;
- import com.owncloud.android.MainApp;
- import com.owncloud.android.R;
- 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.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.operations.UploadFileOperation;
- import com.owncloud.android.ui.activity.ConflictsResolveActivity;
- import com.owncloud.android.ui.activity.UploadListActivity;
- import com.owncloud.android.ui.notifications.NotificationUtils;
- import com.owncloud.android.utils.ErrorMessageAdapter;
- import com.owncloud.android.utils.ThemeUtils;
- import java.io.File;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import javax.annotation.Nullable;
- import javax.inject.Inject;
- import androidx.annotation.NonNull;
- import androidx.core.app.NotificationCompat;
- import dagger.android.AndroidInjection;
- 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";
- private static final int FOREGROUND_SERVICE_ID = 411;
- 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_NAME_COLLISION_POLICY = "KEY_NAME_COLLISION_POLICY";
-
- 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_ON_WIFI_ONLY = "KEY_ON_WIFI_ONLY";
-
- 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;
- public static final int LOCAL_BEHAVIOUR_DELETE = 3;
- private Notification mNotification;
- private Looper mServiceLooper;
- private ServiceHandler mServiceHandler;
- private IBinder mBinder;
- private OwnCloudClient mUploadClient;
- private Account mCurrentAccount;
- private FileDataStorageManager mStorageManager;
- @Inject UserAccountManager accountManager;
- @Inject UploadsStorageManager mUploadsStorageManager;
- @Inject ConnectivityService connectivityService;
- @Inject PowerManagementService powerManagementService;
- private IndexedForest<UploadFileOperation> mPendingUploads = new IndexedForest<>();
-
- private UploadFileOperation mCurrentUpload;
- private NotificationManager mNotificationManager;
- private NotificationCompat.Builder mNotificationBuilder;
- private int mLastPercent;
- @Override
- public void onRenameUpload() {
- mUploadsStorageManager.updateDatabaseUploadStart(mCurrentUpload);
- sendBroadcastUploadStarted(mCurrentUpload);
- }
-
- @Override
- public void onCreate() {
- super.onCreate();
- AndroidInjection.inject(this);
- 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();
- NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setContentTitle(
- getApplicationContext().getResources().getString(R.string.app_name))
- .setContentText(getApplicationContext().getResources().getString(R.string.foreground_service_upload))
- .setSmallIcon(R.drawable.notification_icon)
- .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.notification_icon))
- .setColor(ThemeUtils.primaryColor(getApplicationContext(), true));
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- builder.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_UPLOAD);
- }
- mNotification = builder.build();
-
- 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);
- }
-
- @SuppressWarnings("PMD.NullAssignment")
- @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);
- startForeground(FOREGROUND_SERVICE_ID, mNotification);
- if (intent == null) {
- Log_OC.e(TAG, "Intent is null");
- return Service.START_NOT_STICKY;
- }
- 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 (!accountManager.exists(account)) {
- return Service.START_NOT_STICKY;
- }
- boolean retry = intent.getBooleanExtra(KEY_RETRY, false);
- List<String> requestedUploads = new ArrayList<>();
- boolean onWifiOnly = intent.getBooleanExtra(KEY_WHILE_ON_WIFI_ONLY, false);
- boolean whileChargingOnly = intent.getBooleanExtra(KEY_WHILE_CHARGING_ONLY, false);
- 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;
- }
- Integer error = gatherAndStartNewUploads(intent, account, requestedUploads, onWifiOnly, whileChargingOnly);
- if (error != null) {
- return error;
- }
- } 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;
- }
- retryUploads(intent, account, requestedUploads);
- }
- if (requestedUploads.size() > 0) {
- Message msg = mServiceHandler.obtainMessage();
- msg.arg1 = startId;
- msg.obj = requestedUploads;
- mServiceHandler.sendMessage(msg);
- sendBroadcastUploadsAdded();
- }
- return Service.START_NOT_STICKY;
- }
-
- @Nullable
- private Integer gatherAndStartNewUploads(
- Intent intent,
- Account account,
- List<String> requestedUploads,
- boolean onWifiOnly,
- boolean whileChargingOnly
- ) {
- String[] localPaths = null;
- String[] remotePaths = null;
- String[] 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);
- }
- 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;
- }
- }
- }
-
- NameCollisionPolicy nameCollisionPolicy = (NameCollisionPolicy) intent.getSerializableExtra(KEY_NAME_COLLISION_POLICY);
- if (nameCollisionPolicy == null) {
- nameCollisionPolicy = NameCollisionPolicy.DEFAULT;
- }
- 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);
- try {
- for (OCFile file : files) {
- startNewUpload(
- account,
- requestedUploads,
- onWifiOnly,
- whileChargingOnly,
- nameCollisionPolicy,
- localAction,
- isCreateRemoteFolder,
- createdBy,
- file
- );
- }
- } 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;
- }
- return null;
- }
-
- private void startNewUpload(
- Account account,
- List<String> requestedUploads,
- boolean onWifiOnly,
- boolean whileChargingOnly,
- NameCollisionPolicy nameCollisionPolicy,
- int localAction,
- boolean isCreateRemoteFolder,
- int createdBy,
- OCFile file
- ) {
- OCUpload ocUpload = new OCUpload(file, account);
- ocUpload.setFileSize(file.getFileLength());
- ocUpload.setNameCollisionPolicy(nameCollisionPolicy);
- ocUpload.setCreateRemoteFolder(isCreateRemoteFolder);
- ocUpload.setCreatedBy(createdBy);
- ocUpload.setLocalAction(localAction);
- ocUpload.setUseWifiOnly(onWifiOnly);
- ocUpload.setWhileChargingOnly(whileChargingOnly);
- ocUpload.setUploadStatus(UploadStatus.UPLOAD_IN_PROGRESS);
- UploadFileOperation newUpload = new UploadFileOperation(
- mUploadsStorageManager,
- connectivityService,
- powerManagementService,
- account,
- file,
- ocUpload,
- nameCollisionPolicy,
- localAction,
- this,
- onWifiOnly,
- whileChargingOnly
- );
- 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,
- file.getRemotePath(),
- newUpload
- );
- if (putResult != null) {
- requestedUploads.add(putResult.first);
-
- long id = mUploadsStorageManager.storeUpload(ocUpload);
- newUpload.setOCUploadId(id);
- }
- }
-
- private void retryUploads(Intent intent, Account account, List<String> requestedUploads) {
- boolean onWifiOnly;
- boolean whileChargingOnly;
- OCUpload upload = intent.getParcelableExtra(KEY_RETRY_UPLOAD);
- onWifiOnly = upload.isUseWifiOnly();
- whileChargingOnly = upload.isWhileChargingOnly();
- UploadFileOperation newUpload = new UploadFileOperation(
- mUploadsStorageManager,
- connectivityService,
- powerManagementService,
- account,
- null,
- upload,
- upload.getNameCollisionPolicy(),
- upload.getLocalAction(),
- this,
- onWifiOnly,
- whileChargingOnly
- );
- 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);
- }
- }
-
- @Override
- public IBinder onBind(Intent intent) {
- return mBinder;
- }
-
- @Override
- public boolean onUnbind(Intent intent) {
- ((FileUploaderBinder) mBinder).clearListeners();
- return false;
- }
- @Override
- public void onAccountsUpdated(Account[] accounts) {
-
- if (mCurrentUpload != null && !accountManager.exists(mCurrentUpload.getAccount())) {
- mCurrentUpload.cancel(ResultCode.ACCOUNT_NOT_FOUND);
- }
-
- }
-
- public void uploadFile(String uploadKey) {
- mCurrentUpload = mPendingUploads.get(uploadKey);
- if (mCurrentUpload != null) {
-
- if (!accountManager.exists(mCurrentUpload.getAccount())) {
- 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.getDecryptedRemotePath());
- }
- mUploadsStorageManager.updateDatabaseUploadResult(uploadResult, mCurrentUpload);
-
- notifyUploadResult(mCurrentUpload, uploadResult);
- sendBroadcastUploadFinished(mCurrentUpload, uploadResult, removeResult.second);
- }
-
- final ThumbnailsCacheManager.ThumbnailGenerationTask task =
- new ThumbnailsCacheManager.ThumbnailGenerationTask(mStorageManager, mCurrentAccount);
- File file = new File(mCurrentUpload.getOriginalStoragePath());
- String remoteId = mCurrentUpload.getFile().getRemoteId();
- task.execute(new ThumbnailsCacheManager.ThumbnailGenerationTaskObject(file, remoteId));
- }
- }
-
- 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())
- );
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- mNotificationBuilder.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_UPLOAD);
- }
-
- Intent intent = UploadListActivity.createIntent(upload.getFile(),
- upload.getAccount(),
- Intent.FLAG_ACTIVITY_CLEAR_TOP,
- this);
- mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this,
- (int) System.currentTimeMillis(),
- intent,
- 0)
- );
- if (!upload.isInstantPicture() && !upload.isInstantVideo()) {
- if (mNotificationManager == null) {
- mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- }
- 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());
-
- if (mNotificationManager == null) {
- mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- }
- mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
-
- if (!uploadResult.isCancelled() &&
- !uploadResult.isSuccess() &&
- !ResultCode.LOCAL_FILE_NOT_FOUND.equals(uploadResult.getCode()) &&
- !uploadResult.getCode().equals(ResultCode.DELAYED_FOR_WIFI) &&
- !uploadResult.getCode().equals(ResultCode.DELAYED_FOR_CHARGING) &&
- !uploadResult.getCode().equals(ResultCode.DELAYED_IN_POWER_SAVE_MODE) &&
- !uploadResult.getCode().equals(ResultCode.LOCK_FAILED)) {
- int tickerId = R.string.uploader_upload_failed_ticker;
- String content;
-
- boolean needsToUpdateCredentials = uploadResult.getCode() == ResultCode.UNAUTHORIZED;
- if (needsToUpdateCredentials) {
- tickerId = R.string.uploader_upload_failed_credentials_error;
- } else if (uploadResult.getCode() == ResultCode.SYNC_CONFLICT) {
- tickerId = R.string.uploader_upload_failed_sync_conflict_error;
- }
- 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 {
- Intent intent;
- if (uploadResult.getCode().equals(ResultCode.SYNC_CONFLICT)) {
- intent = ConflictsResolveActivity.createIntent(upload.getFile(),
- upload.getAccount(),
- Intent.FLAG_ACTIVITY_CLEAR_TOP,
- this);
- } else {
- intent = UploadListActivity.createIntent(upload.getFile(),
- upload.getAccount(),
- Intent.FLAG_ACTIVITY_CLEAR_TOP,
- this);
- }
- mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this,
- (int) System.currentTimeMillis(),
- intent,
- 0)
- );
- }
- mNotificationBuilder.setContentText(content);
- mNotificationManager.notify(tickerId, mNotificationBuilder.build());
- }
- }
-
- private void sendBroadcastUploadsAdded() {
- Intent start = new Intent(getUploadsAddedMessage());
-
- start.setPackage(getPackageName());
- 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);
- start.setPackage(getPackageName());
- 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);
- }
- end.setPackage(getPackageName());
- sendStickyBroadcast(end);
- }
-
- private void cancelUploadsForAccount(Account account) {
- mPendingUploads.remove(account.name);
- mUploadsStorageManager.removeUploads(account.name);
- }
-
- public static void uploadNewFile(
- Context context,
- Account account,
- String localPath,
- String remotePath,
- int behaviour,
- String mimeType,
- boolean createRemoteFile,
- int createdBy,
- boolean requiresWifi,
- boolean requiresCharging,
- NameCollisionPolicy nameCollisionPolicy
- ) {
- uploadNewFile(
- context,
- account,
- new String[]{localPath},
- new String[]{remotePath},
- new String[]{mimeType},
- behaviour,
- createRemoteFile,
- createdBy,
- requiresWifi,
- requiresCharging,
- nameCollisionPolicy
- );
- }
-
- public static void uploadNewFile(
- Context context,
- Account account,
- String[] localPaths,
- String[] remotePaths,
- String[] mimeTypes,
- Integer behaviour,
- Boolean createRemoteFolder,
- int createdBy,
- boolean requiresWifi,
- boolean requiresCharging,
- NameCollisionPolicy nameCollisionPolicy
- ) {
- 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);
- intent.putExtra(FileUploader.KEY_WHILE_ON_WIFI_ONLY, requiresWifi);
- intent.putExtra(FileUploader.KEY_WHILE_CHARGING_ONLY, requiresCharging);
- intent.putExtra(FileUploader.KEY_NAME_COLLISION_POLICY, nameCollisionPolicy);
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- context.startForegroundService(intent);
- } else {
- context.startService(intent);
- }
- }
-
- public static void uploadUpdateFile(
- Context context,
- Account account,
- OCFile existingFile,
- Integer behaviour,
- NameCollisionPolicy nameCollisionPolicy
- ) {
- uploadUpdateFile(context, account, new OCFile[]{existingFile}, behaviour, nameCollisionPolicy);
- }
-
- public static void uploadUpdateFile(
- Context context,
- Account account,
- OCFile[] existingFiles,
- Integer behaviour,
- NameCollisionPolicy nameCollisionPolicy
- ) {
- 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_NAME_COLLISION_POLICY, nameCollisionPolicy);
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- context.startForegroundService(intent);
- } else {
- context.startService(intent);
- }
- }
-
- public static void retryUpload(@NonNull Context context, @NonNull Account account, @NonNull OCUpload upload) {
- 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);
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- context.startForegroundService(i);
- } else {
- context.startService(i);
- }
- }
-
- public static void retryFailedUploads(
- @NonNull final Context context,
- @Nullable final Account account,
- @NonNull final UploadsStorageManager uploadsStorageManager,
- @NonNull final ConnectivityService connectivityService,
- @NonNull final UserAccountManager accountManager,
- @NonNull final PowerManagementService powerManagementService,
- @Nullable final UploadResult uploadResult
- ) {
- OCUpload[] failedUploads = uploadsStorageManager.getFailedUploads();
- Account currentAccount = null;
- boolean resultMatch;
- boolean accountMatch;
- final Connectivity connectivity = connectivityService.getConnectivity();
- final boolean gotNetwork = connectivity.isConnected() && !connectivityService.isInternetWalled();
- final boolean gotWifi = connectivity.isWifi();
- final BatteryStatus batteryStatus = powerManagementService.getBattery();
- final boolean charging = batteryStatus.isCharging() || batteryStatus.isFull();
- final boolean isPowerSaving = powerManagementService.isPowerSavingEnabled();
- for (OCUpload failedUpload : failedUploads) {
- accountMatch = account == null || account.name.equals(failedUpload.getAccountName());
- resultMatch = uploadResult == null || uploadResult == failedUpload.getLastResult();
- if (accountMatch && resultMatch) {
- if (currentAccount == null || !currentAccount.name.equals(failedUpload.getAccountName())) {
- currentAccount = failedUpload.getAccount(accountManager);
- }
- if (!new File(failedUpload.getLocalPath()).exists()) {
- if (failedUpload.getLastResult() != UploadResult.FILE_NOT_FOUND) {
- failedUpload.setLastResult(UploadResult.FILE_NOT_FOUND);
- uploadsStorageManager.updateUpload(failedUpload);
- }
- } else {
- if (!isPowerSaving && gotNetwork && canUploadBeRetried(failedUpload, gotWifi, charging)) {
- retryUpload(context, currentAccount, failedUpload);
- }
- }
- }
- }
- }
- private static boolean canUploadBeRetried(OCUpload upload, boolean gotWifi, boolean isCharging) {
- File file = new File(upload.getLocalPath());
- boolean needsWifi = upload.isUseWifiOnly();
- boolean needsCharging = upload.isWhileChargingOnly();
- return file.exists() && (!needsWifi || gotWifi) && (!needsCharging || isCharging);
- }
- 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;
- }
-
- public enum NameCollisionPolicy {
- RENAME,
- OVERWRITE,
- CANCEL,
- ASK_USER;
- public static final NameCollisionPolicy DEFAULT = RENAME;
- public static NameCollisionPolicy deserialize(int ordinal) {
- NameCollisionPolicy[] values = NameCollisionPolicy.values();
- return ordinal >= 0 && ordinal < values.length ? values[ordinal] : DEFAULT;
- }
- public int serialize() {
- return this.ordinal();
- }
- }
-
- public class FileUploaderBinder extends Binder implements OnDatatransferProgressListener {
-
- private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<>();
-
- public void cancel(Account account, OCFile file) {
- cancel(account.name, file.getRemotePath(), null);
- }
-
- public void cancel(OCUpload storedUpload) {
- cancel(storedUpload.getAccountName(), storedUpload.getRemotePath(), null);
- }
-
- private void cancel(String accountName, String remotePath, @Nullable ResultCode resultCode) {
- 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) {
- upload.cancel(resultCode);
-
-
- if (resultCode != null) {
- mUploadsStorageManager.updateDatabaseUploadResult(new RemoteOperationResult(resultCode), upload);
- notifyUploadResult(upload, new RemoteOperationResult(resultCode));
- } else {
- 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(ResultCode.CANCELLED);
- }
- }
-
- 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,
- User user,
- OCFile file
- ) {
- if (user == null || file == null || listener == null) {
- return;
- }
- String targetKey = buildRemoteName(user.getAccountName(), 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,
- User user,
- OCFile file
- ) {
- if (user == null || file == null || listener == null) {
- return;
- }
- String targetKey = buildRemoteName(user.getAccountName(), 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);
- }
- Context context = MainApp.getAppContext();
- if (context != null) {
- ResultCode cancelReason = null;
- Connectivity connectivity = connectivityService.getConnectivity();
- if (mCurrentUpload.isWifiRequired() && !connectivity.isWifi()) {
- cancelReason = ResultCode.DELAYED_FOR_WIFI;
- } else if (mCurrentUpload.isChargingRequired() && !powerManagementService.getBattery().isCharging()) {
- cancelReason = ResultCode.DELAYED_FOR_CHARGING;
- } else if (!mCurrentUpload.isIgnoringPowerSaveMode() && powerManagementService.isPowerSavingEnabled()) {
- cancelReason = ResultCode.DELAYED_IN_POWER_SAVE_MODE;
- }
- if (cancelReason != null) {
- cancel(
- mCurrentUpload.getAccount().name,
- mCurrentUpload.getFile().getRemotePath(),
- cancelReason
- );
- }
- }
- }
-
- private String buildRemoteName(String accountName, String remotePath) {
- return accountName + remotePath;
- }
- }
-
- private static class ServiceHandler extends Handler {
-
-
- private 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")
- List<String> requestedUploads = (List<String>) msg.obj;
- if (msg.obj != null) {
- for (String requestedUpload : requestedUploads) {
- mService.uploadFile(requestedUpload);
- }
- }
- Log_OC.d(TAG, "Stopping command after id " + msg.arg1);
- mService.stopForeground(true);
- mService.stopSelf(msg.arg1);
- }
- }
- }
|