OperationsService.java 33 KB

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