OperationsService.java 33 KB

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