OperationsService.java 34 KB

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