OperationsService.java 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author masensio
  5. * @author David A. Velasco
  6. * @author Andy Scherzinger
  7. * @author TSI-mc
  8. * Copyright (C) 2015 ownCloud Inc.
  9. * Copyright (C) 2018 Andy Scherzinger
  10. * Copyright (C) 2021 TSI-mc
  11. *
  12. * This program is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License version 2,
  14. * as published by the Free Software Foundation.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. */
  24. package com.owncloud.android.services;
  25. import android.accounts.Account;
  26. import android.accounts.AccountsException;
  27. import android.app.Service;
  28. import android.content.Intent;
  29. import android.net.Uri;
  30. import android.os.Binder;
  31. import android.os.Handler;
  32. import android.os.HandlerThread;
  33. import android.os.IBinder;
  34. import android.os.Looper;
  35. import android.os.Message;
  36. import android.os.Process;
  37. import android.text.TextUtils;
  38. import android.util.Pair;
  39. import com.nextcloud.client.account.User;
  40. import com.nextcloud.client.account.UserAccountManager;
  41. import com.nextcloud.java.util.Optional;
  42. import com.owncloud.android.MainApp;
  43. import com.owncloud.android.datamodel.FileDataStorageManager;
  44. import com.owncloud.android.datamodel.OCFile;
  45. import com.owncloud.android.lib.common.OwnCloudAccount;
  46. import com.owncloud.android.lib.common.OwnCloudClient;
  47. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  48. import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
  49. import com.owncloud.android.lib.common.operations.RemoteOperation;
  50. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  51. import com.owncloud.android.lib.common.utils.Log_OC;
  52. import com.owncloud.android.lib.resources.files.RestoreFileVersionRemoteOperation;
  53. import com.owncloud.android.lib.resources.files.model.FileVersion;
  54. import com.owncloud.android.lib.resources.shares.ShareType;
  55. import com.owncloud.android.lib.resources.users.GetUserInfoRemoteOperation;
  56. import com.owncloud.android.operations.CheckCurrentCredentialsOperation;
  57. import com.owncloud.android.operations.CopyFileOperation;
  58. import com.owncloud.android.operations.CreateFolderOperation;
  59. import com.owncloud.android.operations.CreateShareViaLinkOperation;
  60. import com.owncloud.android.operations.CreateShareWithShareeOperation;
  61. import com.owncloud.android.operations.GetServerInfoOperation;
  62. import com.owncloud.android.operations.MoveFileOperation;
  63. import com.owncloud.android.operations.RemoveFileOperation;
  64. import com.owncloud.android.operations.RenameFileOperation;
  65. import com.owncloud.android.operations.SynchronizeFileOperation;
  66. import com.owncloud.android.operations.SynchronizeFolderOperation;
  67. import com.owncloud.android.operations.UnshareOperation;
  68. import com.owncloud.android.operations.UpdateNoteForShareOperation;
  69. import com.owncloud.android.operations.UpdateShareInfoOperation;
  70. import com.owncloud.android.operations.UpdateSharePermissionsOperation;
  71. import com.owncloud.android.operations.UpdateShareViaLinkOperation;
  72. import java.io.IOException;
  73. import java.util.Iterator;
  74. import java.util.concurrent.ConcurrentHashMap;
  75. import java.util.concurrent.ConcurrentLinkedQueue;
  76. import java.util.concurrent.ConcurrentMap;
  77. import javax.inject.Inject;
  78. import androidx.annotation.NonNull;
  79. import androidx.annotation.Nullable;
  80. import dagger.android.AndroidInjection;
  81. public class OperationsService extends Service {
  82. private static final String TAG = OperationsService.class.getSimpleName();
  83. public static final String EXTRA_ACCOUNT = "ACCOUNT";
  84. public static final String EXTRA_SERVER_URL = "SERVER_URL";
  85. public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
  86. public static final String EXTRA_NEWNAME = "NEWNAME";
  87. public static final String EXTRA_REMOVE_ONLY_LOCAL = "REMOVE_LOCAL_COPY";
  88. public static final String EXTRA_SYNC_FILE_CONTENTS = "SYNC_FILE_CONTENTS";
  89. public static final String EXTRA_NEW_PARENT_PATH = "NEW_PARENT_PATH";
  90. public static final String EXTRA_FILE = "FILE";
  91. public static final String EXTRA_FILE_VERSION = "FILE_VERSION";
  92. public static final String EXTRA_SHARE_PASSWORD = "SHARE_PASSWORD";
  93. public static final String EXTRA_SHARE_TYPE = "SHARE_TYPE";
  94. public static final String EXTRA_SHARE_WITH = "SHARE_WITH";
  95. public static final String EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS = "SHARE_EXPIRATION_YEAR";
  96. public static final String EXTRA_SHARE_PERMISSIONS = "SHARE_PERMISSIONS";
  97. public static final String EXTRA_SHARE_PUBLIC_LABEL = "SHARE_PUBLIC_LABEL";
  98. public static final String EXTRA_SHARE_HIDE_FILE_DOWNLOAD = "HIDE_FILE_DOWNLOAD";
  99. public static final String EXTRA_SHARE_ID = "SHARE_ID";
  100. public static final String EXTRA_SHARE_NOTE = "SHARE_NOTE";
  101. public static final String EXTRA_IN_BACKGROUND = "IN_BACKGROUND";
  102. public static final String ACTION_CREATE_SHARE_VIA_LINK = "CREATE_SHARE_VIA_LINK";
  103. public static final String ACTION_CREATE_SHARE_WITH_SHAREE = "CREATE_SHARE_WITH_SHAREE";
  104. public static final String ACTION_UNSHARE = "UNSHARE";
  105. public static final String ACTION_UPDATE_PUBLIC_SHARE = "UPDATE_PUBLIC_SHARE";
  106. public static final String ACTION_UPDATE_USER_SHARE = "UPDATE_USER_SHARE";
  107. public static final String ACTION_UPDATE_SHARE_NOTE = "UPDATE_SHARE_NOTE";
  108. public static final String ACTION_UPDATE_SHARE_INFO = "UPDATE_SHARE_INFO";
  109. public static final String ACTION_GET_SERVER_INFO = "GET_SERVER_INFO";
  110. public static final String ACTION_GET_USER_NAME = "GET_USER_NAME";
  111. public static final String ACTION_RENAME = "RENAME";
  112. public static final String ACTION_REMOVE = "REMOVE";
  113. public static final String ACTION_CREATE_FOLDER = "CREATE_FOLDER";
  114. public static final String ACTION_SYNC_FILE = "SYNC_FILE";
  115. public static final String ACTION_SYNC_FOLDER = "SYNC_FOLDER";
  116. public static final String ACTION_MOVE_FILE = "MOVE_FILE";
  117. public static final String ACTION_COPY_FILE = "COPY_FILE";
  118. public static final String ACTION_CHECK_CURRENT_CREDENTIALS = "CHECK_CURRENT_CREDENTIALS";
  119. public static final String ACTION_RESTORE_VERSION = "RESTORE_VERSION";
  120. private ServiceHandler mOperationsHandler;
  121. private OperationsServiceBinder mOperationsBinder;
  122. private SyncFolderHandler mSyncFolderHandler;
  123. private ConcurrentMap<Integer, Pair<RemoteOperation, RemoteOperationResult>>
  124. mUndispatchedFinishedOperations = new ConcurrentHashMap<>();
  125. @Inject UserAccountManager accountManager;
  126. private static class Target {
  127. public Uri mServerUrl;
  128. public Account mAccount;
  129. public Target(Account account, Uri serverUrl) {
  130. mAccount = account;
  131. mServerUrl = serverUrl;
  132. }
  133. }
  134. /**
  135. * Service initialization
  136. */
  137. @Override
  138. public void onCreate() {
  139. super.onCreate();
  140. AndroidInjection.inject(this);
  141. Log_OC.d(TAG, "Creating service");
  142. // First worker thread for most of operations
  143. HandlerThread thread = new HandlerThread("Operations thread",
  144. Process.THREAD_PRIORITY_BACKGROUND);
  145. thread.start();
  146. mOperationsHandler = new ServiceHandler(thread.getLooper(), this);
  147. mOperationsBinder = new OperationsServiceBinder(mOperationsHandler);
  148. // Separated worker thread for download of folders (WIP)
  149. thread = new HandlerThread("Syncfolder thread", Process.THREAD_PRIORITY_BACKGROUND);
  150. thread.start();
  151. mSyncFolderHandler = new SyncFolderHandler(thread.getLooper(), this);
  152. }
  153. /**
  154. * Entry point to add a new operation to the queue of operations.
  155. * <p/>
  156. * New operations are added calling to startService(), resulting in a call to this method. This ensures the service
  157. * will keep on working although the caller activity goes away.
  158. */
  159. @Override
  160. public int onStartCommand(Intent intent, int flags, int startId) {
  161. Log_OC.d(TAG, "Starting command with id " + startId);
  162. // WIP: for the moment, only SYNC_FOLDER is expected here;
  163. // the rest of the operations are requested through the Binder
  164. if (intent != null && ACTION_SYNC_FOLDER.equals(intent.getAction())) {
  165. if (!intent.hasExtra(EXTRA_ACCOUNT) || !intent.hasExtra(EXTRA_REMOTE_PATH)) {
  166. Log_OC.e(TAG, "Not enough information provided in intent");
  167. return START_NOT_STICKY;
  168. }
  169. Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
  170. String remotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);
  171. Pair<Account, String> itemSyncKey = new Pair<>(account, remotePath);
  172. Pair<Target, RemoteOperation> itemToQueue = newOperation(intent);
  173. if (itemToQueue != null) {
  174. mSyncFolderHandler.add(account,
  175. remotePath,
  176. (SynchronizeFolderOperation) itemToQueue.second);
  177. Message msg = mSyncFolderHandler.obtainMessage();
  178. msg.arg1 = startId;
  179. msg.obj = itemSyncKey;
  180. mSyncFolderHandler.sendMessage(msg);
  181. }
  182. } else {
  183. Message msg = mOperationsHandler.obtainMessage();
  184. msg.arg1 = startId;
  185. mOperationsHandler.sendMessage(msg);
  186. }
  187. return START_NOT_STICKY;
  188. }
  189. @Override
  190. public void onDestroy() {
  191. Log_OC.v(TAG, "Destroying service");
  192. // Saving cookies
  193. OwnCloudClientManagerFactory.getDefaultSingleton()
  194. .saveAllClients(this, MainApp.getAccountType(getApplicationContext()));
  195. mUndispatchedFinishedOperations.clear();
  196. mOperationsBinder = null;
  197. mOperationsHandler.getLooper().quit();
  198. mOperationsHandler = null;
  199. mSyncFolderHandler.getLooper().quit();
  200. mSyncFolderHandler = null;
  201. super.onDestroy();
  202. }
  203. /**
  204. * Provides a binder object that clients can use to perform actions on the queue of operations, except the addition
  205. * of new operations.
  206. */
  207. @Override
  208. public IBinder onBind(Intent intent) {
  209. return mOperationsBinder;
  210. }
  211. /**
  212. * Called when ALL the bound clients were unbound.
  213. */
  214. @Override
  215. public boolean onUnbind(Intent intent) {
  216. mOperationsBinder.clearListeners();
  217. return false; // not accepting rebinding (default behaviour)
  218. }
  219. /**
  220. * Binder to let client components to perform actions on the queue of operations.
  221. * <p/>
  222. * It provides by itself the available operations.
  223. */
  224. public class OperationsServiceBinder extends Binder /* implements OnRemoteOperationListener */ {
  225. /**
  226. * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder}
  227. * instance
  228. */
  229. private final ConcurrentMap<OnRemoteOperationListener, Handler> mBoundListeners = new ConcurrentHashMap<>();
  230. private ServiceHandler mServiceHandler;
  231. public OperationsServiceBinder(ServiceHandler serviceHandler) {
  232. mServiceHandler = serviceHandler;
  233. }
  234. /**
  235. * Cancels a pending or current synchronization.
  236. *
  237. * @param account ownCloud account where the remote folder is stored.
  238. * @param file A folder in the queue of pending synchronizations
  239. */
  240. public void cancel(Account account, OCFile file) {
  241. mSyncFolderHandler.cancel(account, file);
  242. }
  243. public void clearListeners() {
  244. mBoundListeners.clear();
  245. }
  246. /**
  247. * Adds a listener interested in being reported about the end of operations.
  248. *
  249. * @param listener Object to notify about the end of operations.
  250. * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
  251. */
  252. public void addOperationListener(OnRemoteOperationListener listener,
  253. Handler callbackHandler) {
  254. synchronized (mBoundListeners) {
  255. mBoundListeners.put(listener, callbackHandler);
  256. }
  257. }
  258. /**
  259. * Removes a listener from the list of objects interested in the being reported about the end of operations.
  260. *
  261. * @param listener Object to notify about progress of transfer.
  262. */
  263. public void removeOperationListener(OnRemoteOperationListener listener) {
  264. synchronized (mBoundListeners) {
  265. mBoundListeners.remove(listener);
  266. }
  267. }
  268. /**
  269. * TODO - IMPORTANT: update implementation when more operations are moved into the service
  270. *
  271. * @return 'True' when an operation that enforces the user to wait for completion is in process.
  272. */
  273. public boolean isPerformingBlockingOperation() {
  274. return !mServiceHandler.mPendingOperations.isEmpty();
  275. }
  276. /**
  277. * Creates and adds to the queue a new operation, as described by operationIntent.
  278. * <p>
  279. * Calls startService to make the operation is processed by the ServiceHandler.
  280. *
  281. * @param operationIntent Intent describing a new operation to queue and execute.
  282. * @return Identifier of the operation created, or null if failed.
  283. */
  284. public long queueNewOperation(Intent operationIntent) {
  285. Pair<Target, RemoteOperation> itemToQueue = newOperation(operationIntent);
  286. if (itemToQueue != null) {
  287. mServiceHandler.mPendingOperations.add(itemToQueue);
  288. startService(new Intent(OperationsService.this, OperationsService.class));
  289. return itemToQueue.second.hashCode();
  290. } else {
  291. return Long.MAX_VALUE;
  292. }
  293. }
  294. public boolean dispatchResultIfFinished(int operationId,
  295. OnRemoteOperationListener listener) {
  296. Pair<RemoteOperation, RemoteOperationResult> undispatched =
  297. mUndispatchedFinishedOperations.remove(operationId);
  298. if (undispatched != null) {
  299. listener.onRemoteOperationFinish(undispatched.first, undispatched.second);
  300. return true;
  301. } else {
  302. return !mServiceHandler.mPendingOperations.isEmpty();
  303. }
  304. }
  305. /**
  306. * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to
  307. * download.
  308. * <p>
  309. * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to
  310. * download.
  311. *
  312. * @param user user where the remote file is stored.
  313. * @param file File to check if something is synchronizing / downloading / uploading inside.
  314. */
  315. public boolean isSynchronizing(User user, OCFile file) {
  316. return mSyncFolderHandler.isSynchronizing(user, file.getRemotePath());
  317. }
  318. }
  319. /**
  320. * Operations worker. Performs the pending operations in the order they were requested.
  321. * <p>
  322. * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
  323. */
  324. private static class ServiceHandler extends Handler {
  325. // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
  326. OperationsService mService;
  327. private ConcurrentLinkedQueue<Pair<Target, RemoteOperation>> mPendingOperations =
  328. new ConcurrentLinkedQueue<>();
  329. private RemoteOperation mCurrentOperation;
  330. private Target mLastTarget;
  331. private OwnCloudClient mOwnCloudClient;
  332. public ServiceHandler(Looper looper, OperationsService service) {
  333. super(looper);
  334. if (service == null) {
  335. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  336. }
  337. mService = service;
  338. }
  339. @Override
  340. public void handleMessage(Message msg) {
  341. nextOperation();
  342. Log_OC.d(TAG, "Stopping after command with id " + msg.arg1);
  343. mService.stopSelf(msg.arg1);
  344. }
  345. /**
  346. * Performs the next operation in the queue
  347. */
  348. private void nextOperation() {
  349. //Log_OC.e(TAG, "nextOperation init" );
  350. Pair<Target, RemoteOperation> next;
  351. synchronized (mPendingOperations) {
  352. next = mPendingOperations.peek();
  353. }
  354. if (next != null) {
  355. mCurrentOperation = next.second;
  356. RemoteOperationResult result;
  357. try {
  358. /// prepare client object to send the request to the ownCloud server
  359. if (mLastTarget == null || !mLastTarget.equals(next.first)) {
  360. mLastTarget = next.first;
  361. OwnCloudAccount ocAccount;
  362. if (mLastTarget.mAccount != null) {
  363. ocAccount = new OwnCloudAccount(mLastTarget.mAccount, mService);
  364. } else {
  365. ocAccount = new OwnCloudAccount(mLastTarget.mServerUrl, null);
  366. }
  367. mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  368. getClientFor(ocAccount, mService);
  369. }
  370. /// perform the operation
  371. result = mCurrentOperation.execute(mOwnCloudClient);
  372. } catch (AccountsException e) {
  373. if (mLastTarget.mAccount == null) {
  374. Log_OC.e(TAG, "Error while trying to get authorization for a NULL account",
  375. e);
  376. } else {
  377. Log_OC.e(TAG, "Error while trying to get authorization for " +
  378. mLastTarget.mAccount.name, e);
  379. }
  380. result = new RemoteOperationResult(e);
  381. } catch (IOException e) {
  382. if (mLastTarget.mAccount == null) {
  383. Log_OC.e(TAG, "Error while trying to get authorization for a NULL account",
  384. e);
  385. } else {
  386. Log_OC.e(TAG, "Error while trying to get authorization for " +
  387. mLastTarget.mAccount.name, e);
  388. }
  389. result = new RemoteOperationResult(e);
  390. } catch (Exception e) {
  391. if (mLastTarget.mAccount == null) {
  392. Log_OC.e(TAG, "Unexpected error for a NULL account", e);
  393. } else {
  394. Log_OC.e(TAG, "Unexpected error for " + mLastTarget.mAccount.name, e);
  395. }
  396. result = new RemoteOperationResult(e);
  397. } finally {
  398. synchronized (mPendingOperations) {
  399. mPendingOperations.poll();
  400. }
  401. }
  402. //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
  403. mService.dispatchResultToOperationListeners(mCurrentOperation, result);
  404. }
  405. }
  406. }
  407. /**
  408. * Creates a new operation, as described by operationIntent.
  409. * <p>
  410. * TODO - move to ServiceHandler (probably)
  411. *
  412. * @param operationIntent Intent describing a new operation to queue and execute.
  413. * @return Pair with the new operation object and the information about its target server.
  414. */
  415. private Pair<Target, RemoteOperation> newOperation(Intent operationIntent) {
  416. RemoteOperation operation = null;
  417. Target target = null;
  418. try {
  419. if (!operationIntent.hasExtra(EXTRA_ACCOUNT) &&
  420. !operationIntent.hasExtra(EXTRA_SERVER_URL)) {
  421. Log_OC.e(TAG, "Not enough information provided in intent");
  422. } else {
  423. Account account = operationIntent.getParcelableExtra(EXTRA_ACCOUNT);
  424. User user = toUser(account);
  425. String serverUrl = operationIntent.getStringExtra(EXTRA_SERVER_URL);
  426. target = new Target(account, (serverUrl == null) ? null : Uri.parse(serverUrl));
  427. String action = operationIntent.getAction();
  428. String remotePath;
  429. String password;
  430. ShareType shareType;
  431. String newParentPath;
  432. long shareId;
  433. FileDataStorageManager fileDataStorageManager = new FileDataStorageManager(user,
  434. getContentResolver());
  435. switch (action) {
  436. case ACTION_CREATE_SHARE_VIA_LINK:
  437. remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  438. password = operationIntent.getStringExtra(EXTRA_SHARE_PASSWORD);
  439. if (!TextUtils.isEmpty(remotePath)) {
  440. operation = new CreateShareViaLinkOperation(remotePath, password, fileDataStorageManager);
  441. }
  442. break;
  443. case ACTION_UPDATE_PUBLIC_SHARE:
  444. shareId = operationIntent.getLongExtra(EXTRA_SHARE_ID, -1);
  445. if (shareId > 0) {
  446. UpdateShareViaLinkOperation updateLinkOperation =
  447. new UpdateShareViaLinkOperation(shareId, fileDataStorageManager);
  448. password = operationIntent.getStringExtra(EXTRA_SHARE_PASSWORD);
  449. updateLinkOperation.setPassword(password);
  450. long expirationDate = operationIntent.getLongExtra(EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS, 0);
  451. updateLinkOperation.setExpirationDateInMillis(expirationDate);
  452. boolean hideFileDownload = operationIntent.getBooleanExtra(EXTRA_SHARE_HIDE_FILE_DOWNLOAD,
  453. false);
  454. updateLinkOperation.setHideFileDownload(hideFileDownload);
  455. // if (operationIntent.hasExtra(EXTRA_SHARE_PUBLIC_UPLOAD)) {
  456. // updateLinkOperation.setPublicUpload(true);
  457. // }
  458. if (operationIntent.hasExtra(EXTRA_SHARE_PUBLIC_LABEL)) {
  459. updateLinkOperation.setLabel(operationIntent.getStringExtra(EXTRA_SHARE_PUBLIC_LABEL));
  460. }
  461. operation = updateLinkOperation;
  462. }
  463. break;
  464. case ACTION_UPDATE_USER_SHARE:
  465. shareId = operationIntent.getLongExtra(EXTRA_SHARE_ID, -1);
  466. if (shareId > 0) {
  467. UpdateSharePermissionsOperation updateShare =
  468. new UpdateSharePermissionsOperation(shareId, fileDataStorageManager);
  469. int permissions = operationIntent.getIntExtra(EXTRA_SHARE_PERMISSIONS, -1);
  470. updateShare.setPermissions(permissions);
  471. long expirationDateInMillis = operationIntent
  472. .getLongExtra(EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS, 0L);
  473. updateShare.setExpirationDateInMillis(expirationDateInMillis);
  474. password = operationIntent.getStringExtra(EXTRA_SHARE_PASSWORD);
  475. updateShare.setPassword(password);
  476. operation = updateShare;
  477. }
  478. break;
  479. case ACTION_UPDATE_SHARE_NOTE:
  480. shareId = operationIntent.getLongExtra(EXTRA_SHARE_ID, -1);
  481. String note = operationIntent.getStringExtra(EXTRA_SHARE_NOTE);
  482. if (shareId > 0) {
  483. operation = new UpdateNoteForShareOperation(shareId, note, fileDataStorageManager);
  484. }
  485. break;
  486. case ACTION_CREATE_SHARE_WITH_SHAREE:
  487. remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  488. String shareeName = operationIntent.getStringExtra(EXTRA_SHARE_WITH);
  489. shareType = (ShareType) operationIntent.getSerializableExtra(EXTRA_SHARE_TYPE);
  490. int permissions = operationIntent.getIntExtra(EXTRA_SHARE_PERMISSIONS, -1);
  491. String noteMessage = operationIntent.getStringExtra(EXTRA_SHARE_NOTE);
  492. String sharePassword = operationIntent.getStringExtra(EXTRA_SHARE_PASSWORD);
  493. long expirationDateInMillis = operationIntent
  494. .getLongExtra(EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS, 0L);
  495. boolean hideFileDownload = operationIntent.getBooleanExtra(EXTRA_SHARE_HIDE_FILE_DOWNLOAD,
  496. false);
  497. if (!TextUtils.isEmpty(remotePath)) {
  498. CreateShareWithShareeOperation createShareWithShareeOperation =
  499. new CreateShareWithShareeOperation(remotePath,
  500. shareeName,
  501. shareType,
  502. permissions,
  503. noteMessage,
  504. sharePassword,
  505. expirationDateInMillis,
  506. hideFileDownload,
  507. fileDataStorageManager);
  508. if (operationIntent.hasExtra(EXTRA_SHARE_PUBLIC_LABEL)) {
  509. createShareWithShareeOperation.setLabel(operationIntent.getStringExtra(EXTRA_SHARE_PUBLIC_LABEL));
  510. }
  511. operation = createShareWithShareeOperation;
  512. }
  513. break;
  514. case ACTION_UPDATE_SHARE_INFO:
  515. shareId = operationIntent.getLongExtra(EXTRA_SHARE_ID, -1);
  516. if (shareId > 0) {
  517. UpdateShareInfoOperation updateShare = new UpdateShareInfoOperation(shareId,
  518. fileDataStorageManager);
  519. int permissionsToChange = operationIntent.getIntExtra(EXTRA_SHARE_PERMISSIONS, -1);
  520. updateShare.setPermissions(permissionsToChange);
  521. long expirationDateInMills = operationIntent
  522. .getLongExtra(EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS, 0L);
  523. updateShare.setExpirationDateInMillis(expirationDateInMills);
  524. password = operationIntent.getStringExtra(EXTRA_SHARE_PASSWORD);
  525. updateShare.setPassword(password);
  526. boolean fileDownloadHide = operationIntent.getBooleanExtra(EXTRA_SHARE_HIDE_FILE_DOWNLOAD
  527. , false);
  528. updateShare.setHideFileDownload(fileDownloadHide);
  529. if (operationIntent.hasExtra(EXTRA_SHARE_PUBLIC_LABEL)) {
  530. updateShare.setLabel(operationIntent.getStringExtra(EXTRA_SHARE_PUBLIC_LABEL));
  531. }
  532. operation = updateShare;
  533. }
  534. break;
  535. case ACTION_UNSHARE:
  536. remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  537. shareId = operationIntent.getLongExtra(EXTRA_SHARE_ID, -1);
  538. if (shareId > 0) {
  539. operation = new UnshareOperation(remotePath, shareId, fileDataStorageManager);
  540. }
  541. break;
  542. case ACTION_GET_SERVER_INFO:
  543. operation = new GetServerInfoOperation(serverUrl, this);
  544. break;
  545. case ACTION_GET_USER_NAME:
  546. operation = new GetUserInfoRemoteOperation();
  547. break;
  548. case ACTION_RENAME:
  549. remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  550. String newName = operationIntent.getStringExtra(EXTRA_NEWNAME);
  551. operation = new RenameFileOperation(remotePath, newName, fileDataStorageManager, getApplicationContext());
  552. break;
  553. case ACTION_REMOVE:
  554. // Remove file or folder
  555. OCFile file = operationIntent.getParcelableExtra(EXTRA_FILE);
  556. boolean onlyLocalCopy = operationIntent.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL, false);
  557. boolean inBackground = operationIntent.getBooleanExtra(EXTRA_IN_BACKGROUND, false);
  558. operation = new RemoveFileOperation(file,
  559. onlyLocalCopy,
  560. account,
  561. inBackground,
  562. getApplicationContext(),
  563. fileDataStorageManager);
  564. break;
  565. case ACTION_CREATE_FOLDER:
  566. remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  567. operation = new CreateFolderOperation(remotePath,
  568. user,
  569. getApplicationContext(),
  570. fileDataStorageManager);
  571. break;
  572. case ACTION_SYNC_FILE:
  573. remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  574. boolean syncFileContents = operationIntent.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS, true);
  575. operation = new SynchronizeFileOperation(remotePath,
  576. user,
  577. syncFileContents,
  578. getApplicationContext(),
  579. fileDataStorageManager);
  580. break;
  581. case ACTION_SYNC_FOLDER:
  582. remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  583. operation = new SynchronizeFolderOperation(
  584. this, // TODO remove this dependency from construction time
  585. remotePath,
  586. user,
  587. System.currentTimeMillis(), // TODO remove this dependency from construction time
  588. fileDataStorageManager
  589. );
  590. break;
  591. case ACTION_MOVE_FILE:
  592. remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  593. newParentPath = operationIntent.getStringExtra(EXTRA_NEW_PARENT_PATH);
  594. operation = new MoveFileOperation(remotePath, newParentPath, fileDataStorageManager);
  595. break;
  596. case ACTION_COPY_FILE:
  597. remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  598. newParentPath = operationIntent.getStringExtra(EXTRA_NEW_PARENT_PATH);
  599. operation = new CopyFileOperation(remotePath, newParentPath, fileDataStorageManager);
  600. break;
  601. case ACTION_CHECK_CURRENT_CREDENTIALS:
  602. operation = new CheckCurrentCredentialsOperation(user, fileDataStorageManager);
  603. break;
  604. case ACTION_RESTORE_VERSION:
  605. FileVersion fileVersion = operationIntent.getParcelableExtra(EXTRA_FILE_VERSION);
  606. operation = new RestoreFileVersionRemoteOperation(fileVersion.getRemoteId(),
  607. fileVersion.getFileName());
  608. break;
  609. default:
  610. // do nothing
  611. break;
  612. }
  613. }
  614. } catch (IllegalArgumentException e) {
  615. Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
  616. operation = null;
  617. }
  618. if (operation != null) {
  619. return new Pair<>(target, operation);
  620. } else {
  621. return null;
  622. }
  623. }
  624. /**
  625. * This is a temporary compatibility helper to convert legacy {@link Account} instance to new {@link User} model.
  626. *
  627. * @param account Account instance
  628. * @return User model that corresponds to Account
  629. */
  630. @NonNull
  631. private User toUser(@Nullable Account account) {
  632. String accountName = account != null ? account.name : "";
  633. Optional<User> optionalUser = accountManager.getUser(accountName);
  634. if (optionalUser.isPresent()) {
  635. return optionalUser.get();
  636. } else {
  637. return accountManager.getAnonymousUser();
  638. }
  639. }
  640. /**
  641. * Notifies the currently subscribed listeners about the end of an operation.
  642. *
  643. * @param operation Finished operation.
  644. * @param result Result of the operation.
  645. */
  646. protected void dispatchResultToOperationListeners(
  647. final RemoteOperation operation, final RemoteOperationResult result
  648. ) {
  649. int count = 0;
  650. Iterator<OnRemoteOperationListener> listeners = mOperationsBinder.mBoundListeners.keySet().iterator();
  651. while (listeners.hasNext()) {
  652. final OnRemoteOperationListener listener = listeners.next();
  653. final Handler handler = mOperationsBinder.mBoundListeners.get(listener);
  654. if (handler != null) {
  655. handler.post(() -> listener.onRemoteOperationFinish(operation, result));
  656. count += 1;
  657. }
  658. }
  659. if (count == 0) {
  660. Pair<RemoteOperation, RemoteOperationResult> undispatched = new Pair<>(operation, result);
  661. mUndispatchedFinishedOperations.put(operation.hashCode(), undispatched);
  662. }
  663. Log_OC.d(TAG, "Called " + count + " listeners");
  664. }
  665. }