OperationsService.java 33 KB

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