OperationsService.java 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. /* ownCloud Android client application
  2. * Copyright (C) 2012-2014 ownCloud Inc.
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License version 2,
  6. * as published by the Free Software Foundation.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. *
  16. */
  17. package com.owncloud.android.services;
  18. import java.io.IOException;
  19. import java.util.Iterator;
  20. import java.util.concurrent.ConcurrentHashMap;
  21. import java.util.concurrent.ConcurrentLinkedQueue;
  22. import java.util.concurrent.ConcurrentMap;
  23. import com.owncloud.android.MainApp;
  24. import com.owncloud.android.R;
  25. import com.owncloud.android.datamodel.FileDataStorageManager;
  26. import com.owncloud.android.datamodel.OCFile;
  27. import com.owncloud.android.files.services.FileDownloader;
  28. import com.owncloud.android.lib.common.OwnCloudAccount;
  29. import com.owncloud.android.lib.common.OwnCloudClient;
  30. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  31. import com.owncloud.android.lib.common.OwnCloudCredentials;
  32. import com.owncloud.android.lib.common.OwnCloudCredentialsFactory;
  33. import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
  34. import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
  35. import com.owncloud.android.lib.common.operations.RemoteOperation;
  36. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  37. import com.owncloud.android.lib.common.utils.Log_OC;
  38. import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
  39. import com.owncloud.android.lib.resources.shares.ShareType;
  40. import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation;
  41. import com.owncloud.android.operations.common.SyncOperation;
  42. import com.owncloud.android.operations.CreateFolderOperation;
  43. import com.owncloud.android.operations.CreateShareOperation;
  44. import com.owncloud.android.operations.GetServerInfoOperation;
  45. import com.owncloud.android.operations.MoveFileOperation;
  46. import com.owncloud.android.operations.OAuth2GetAccessToken;
  47. import com.owncloud.android.operations.RemoveFileOperation;
  48. import com.owncloud.android.operations.RenameFileOperation;
  49. import com.owncloud.android.operations.SynchronizeFileOperation;
  50. import com.owncloud.android.operations.SynchronizeFolderOperation;
  51. import com.owncloud.android.operations.UnshareLinkOperation;
  52. import com.owncloud.android.utils.FileStorageUtils;
  53. import android.accounts.Account;
  54. import android.accounts.AccountsException;
  55. import android.accounts.AuthenticatorException;
  56. import android.accounts.OperationCanceledException;
  57. import android.app.Service;
  58. import android.content.Intent;
  59. import android.net.Uri;
  60. import android.os.Binder;
  61. import android.os.Handler;
  62. import android.os.HandlerThread;
  63. import android.os.IBinder;
  64. import android.os.Looper;
  65. import android.os.Message;
  66. import android.os.Process;
  67. import android.util.Pair;
  68. public class OperationsService extends Service {
  69. private static final String TAG = OperationsService.class.getSimpleName();
  70. public static final String EXTRA_ACCOUNT = "ACCOUNT";
  71. public static final String EXTRA_SERVER_URL = "SERVER_URL";
  72. public static final String EXTRA_OAUTH2_QUERY_PARAMETERS = "OAUTH2_QUERY_PARAMETERS";
  73. public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
  74. public static final String EXTRA_SEND_INTENT = "SEND_INTENT";
  75. public static final String EXTRA_NEWNAME = "NEWNAME";
  76. public static final String EXTRA_REMOVE_ONLY_LOCAL = "REMOVE_LOCAL_COPY";
  77. public static final String EXTRA_CREATE_FULL_PATH = "CREATE_FULL_PATH";
  78. public static final String EXTRA_SYNC_FILE_CONTENTS = "SYNC_FILE_CONTENTS";
  79. public static final String EXTRA_RESULT = "RESULT";
  80. public static final String EXTRA_NEW_PARENT_PATH = "NEW_PARENT_PATH";
  81. public static final String EXTRA_FILE = "FILE";
  82. // TODO review if ALL OF THEM are necessary
  83. public static final String EXTRA_SUCCESS_IF_ABSENT = "SUCCESS_IF_ABSENT";
  84. public static final String EXTRA_USERNAME = "USERNAME";
  85. public static final String EXTRA_PASSWORD = "PASSWORD";
  86. public static final String EXTRA_AUTH_TOKEN = "AUTH_TOKEN";
  87. public static final String EXTRA_COOKIE = "COOKIE";
  88. public static final String ACTION_CREATE_SHARE = "CREATE_SHARE";
  89. public static final String ACTION_UNSHARE = "UNSHARE";
  90. public static final String ACTION_GET_SERVER_INFO = "GET_SERVER_INFO";
  91. public static final String ACTION_OAUTH2_GET_ACCESS_TOKEN = "OAUTH2_GET_ACCESS_TOKEN";
  92. public static final String ACTION_EXISTENCE_CHECK = "EXISTENCE_CHECK";
  93. public static final String ACTION_GET_USER_NAME = "GET_USER_NAME";
  94. public static final String ACTION_RENAME = "RENAME";
  95. public static final String ACTION_REMOVE = "REMOVE";
  96. public static final String ACTION_CREATE_FOLDER = "CREATE_FOLDER";
  97. public static final String ACTION_SYNC_FILE = "SYNC_FILE";
  98. public static final String ACTION_SYNC_FOLDER = "SYNC_FOLDER"; // for the moment, just to download
  99. public static final String ACTION_CANCEL_SYNC_FOLDER = "CANCEL_SYNC_FOLDER"; // for the moment, just to download
  100. public static final String ACTION_MOVE_FILE = "MOVE_FILE";
  101. public static final String ACTION_OPERATION_ADDED = OperationsService.class.getName() + ".OPERATION_ADDED";
  102. public static final String ACTION_OPERATION_FINISHED = OperationsService.class.getName() + ".OPERATION_FINISHED";
  103. private ConcurrentMap<Integer, Pair<RemoteOperation, RemoteOperationResult>>
  104. mUndispatchedFinishedOperations =
  105. new ConcurrentHashMap<Integer, Pair<RemoteOperation, RemoteOperationResult>>();
  106. private static class Target {
  107. public Uri mServerUrl = null;
  108. public Account mAccount = null;
  109. public String mUsername = null;
  110. public String mPassword = null;
  111. public String mAuthToken = null;
  112. public String mCookie = null;
  113. public Target(Account account, Uri serverUrl, String username, String password, String authToken,
  114. String cookie) {
  115. mAccount = account;
  116. mServerUrl = serverUrl;
  117. mUsername = username;
  118. mPassword = password;
  119. mAuthToken = authToken;
  120. mCookie = cookie;
  121. }
  122. }
  123. private ServiceHandler mOperationsHandler;
  124. private OperationsServiceBinder mOperationsBinder;
  125. private SyncFolderHandler mSyncFolderHandler;
  126. /**
  127. * Service initialization
  128. */
  129. @Override
  130. public void onCreate() {
  131. super.onCreate();
  132. /// First worker thread for most of operations
  133. HandlerThread thread = new HandlerThread("Operations thread", Process.THREAD_PRIORITY_BACKGROUND);
  134. thread.start();
  135. mOperationsHandler = new ServiceHandler(thread.getLooper(), this);
  136. mOperationsBinder = new OperationsServiceBinder(mOperationsHandler);
  137. /// Separated worker thread for download of folders (WIP)
  138. thread = new HandlerThread("Syncfolder thread", Process.THREAD_PRIORITY_BACKGROUND);
  139. thread.start();
  140. mSyncFolderHandler = new SyncFolderHandler(thread.getLooper(), this);
  141. }
  142. /**
  143. * Entry point to add a new operation to the queue of operations.
  144. *
  145. * New operations are added calling to startService(), resulting in a call to this method.
  146. * This ensures the service will keep on working although the caller activity goes away.
  147. */
  148. @Override
  149. public int onStartCommand(Intent intent, int flags, int startId) {
  150. // WIP: for the moment, only SYNC_FOLDER and CANCEL_SYNC_FOLDER is expected here;
  151. // the rest of the operations are requested through the Binder
  152. if (ACTION_SYNC_FOLDER.equals(intent.getAction())) {
  153. if (!intent.hasExtra(EXTRA_ACCOUNT) || !intent.hasExtra(EXTRA_REMOTE_PATH)) {
  154. Log_OC.e(TAG, "Not enough information provided in intent");
  155. return START_NOT_STICKY;
  156. }
  157. Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
  158. String remotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);
  159. Pair<Account, String> itemSyncKey = new Pair<Account , String>(account, remotePath);
  160. Pair<Target, RemoteOperation> itemToQueue = newOperation(intent);
  161. if (itemToQueue != null) {
  162. mSyncFolderHandler.add(account, remotePath, (SynchronizeFolderOperation)itemToQueue.second);
  163. sendBroadcastNewSyncFolder(account, remotePath);
  164. Message msg = mSyncFolderHandler.obtainMessage();
  165. msg.arg1 = startId;
  166. msg.obj = itemSyncKey;
  167. mSyncFolderHandler.sendMessage(msg);
  168. }
  169. } else if (ACTION_CANCEL_SYNC_FOLDER.equals(intent.getAction())) {
  170. if (!intent.hasExtra(EXTRA_ACCOUNT) || !intent.hasExtra(EXTRA_FILE)) {
  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. OCFile file = intent.getParcelableExtra(EXTRA_FILE);
  176. // Cancel operation
  177. mSyncFolderHandler.cancel(account,file);
  178. } else {
  179. Message msg = mOperationsHandler.obtainMessage();
  180. msg.arg1 = startId;
  181. mOperationsHandler.sendMessage(msg);
  182. }
  183. return START_NOT_STICKY;
  184. }
  185. /**
  186. * TODO remove this method when "folder synchronization" replaces "folder download"; this is a fast and ugly
  187. * patch.
  188. */
  189. private void sendBroadcastNewSyncFolder(Account account, String remotePath) {
  190. Intent added = new Intent(FileDownloader.getDownloadAddedMessage());
  191. added.putExtra(FileDownloader.ACCOUNT_NAME, account.name);
  192. added.putExtra(FileDownloader.EXTRA_REMOTE_PATH, remotePath);
  193. added.putExtra(FileDownloader.EXTRA_FILE_PATH, FileStorageUtils.getSavePath(account.name) + remotePath);
  194. sendStickyBroadcast(added);
  195. }
  196. @Override
  197. public void onDestroy() {
  198. //Log_OC.wtf(TAG, "onDestroy init" );
  199. // Saving cookies
  200. try {
  201. OwnCloudClientManagerFactory.getDefaultSingleton().
  202. saveAllClients(this, MainApp.getAccountType());
  203. // TODO - get rid of these exceptions
  204. } catch (AccountNotFoundException e) {
  205. e.printStackTrace();
  206. } catch (AuthenticatorException e) {
  207. e.printStackTrace();
  208. } catch (OperationCanceledException e) {
  209. e.printStackTrace();
  210. } catch (IOException e) {
  211. e.printStackTrace();
  212. }
  213. //Log_OC.wtf(TAG, "Clear mUndispatchedFinisiedOperations" );
  214. mUndispatchedFinishedOperations.clear();
  215. //Log_OC.wtf(TAG, "onDestroy end" );
  216. super.onDestroy();
  217. }
  218. /**
  219. * Provides a binder object that clients can use to perform actions on the queue of operations,
  220. * except the addition of new operations.
  221. */
  222. @Override
  223. public IBinder onBind(Intent intent) {
  224. //Log_OC.wtf(TAG, "onBind" );
  225. return mOperationsBinder;
  226. }
  227. /**
  228. * Called when ALL the bound clients were unbound.
  229. */
  230. @Override
  231. public boolean onUnbind(Intent intent) {
  232. ((OperationsServiceBinder)mOperationsBinder).clearListeners();
  233. return false; // not accepting rebinding (default behaviour)
  234. }
  235. /**
  236. * Binder to let client components to perform actions on the queue of operations.
  237. *
  238. * It provides by itself the available operations.
  239. */
  240. public class OperationsServiceBinder extends Binder /* implements OnRemoteOperationListener */ {
  241. /**
  242. * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
  243. */
  244. private ConcurrentMap<OnRemoteOperationListener, Handler> mBoundListeners =
  245. new ConcurrentHashMap<OnRemoteOperationListener, Handler>();
  246. private ServiceHandler mServiceHandler = null;
  247. public OperationsServiceBinder(ServiceHandler serviceHandler) {
  248. mServiceHandler = serviceHandler;
  249. }
  250. /**
  251. * Cancels an operation
  252. *
  253. * TODO
  254. */
  255. public void cancel() {
  256. // TODO
  257. }
  258. public void clearListeners() {
  259. mBoundListeners.clear();
  260. }
  261. /**
  262. * Adds a listener interested in being reported about the end of operations.
  263. *
  264. * @param listener Object to notify about the end of operations.
  265. * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
  266. */
  267. public void addOperationListener (OnRemoteOperationListener listener, Handler callbackHandler) {
  268. synchronized (mBoundListeners) {
  269. mBoundListeners.put(listener, callbackHandler);
  270. }
  271. }
  272. /**
  273. * Removes a listener from the list of objects interested in the being reported about the end of operations.
  274. *
  275. * @param listener Object to notify about progress of transfer.
  276. */
  277. public void removeOperationListener (OnRemoteOperationListener listener) {
  278. synchronized (mBoundListeners) {
  279. mBoundListeners.remove(listener);
  280. }
  281. }
  282. /**
  283. * TODO - IMPORTANT: update implementation when more operations are moved into the service
  284. *
  285. * @return 'True' when an operation that enforces the user to wait for completion is in process.
  286. */
  287. public boolean isPerformingBlockingOperation() {
  288. return (!mServiceHandler.mPendingOperations.isEmpty());
  289. }
  290. /**
  291. * Creates and adds to the queue a new operation, as described by operationIntent.
  292. *
  293. * Calls startService to make the operation is processed by the ServiceHandler.
  294. *
  295. * @param operationIntent Intent describing a new operation to queue and execute.
  296. * @return Identifier of the operation created, or null if failed.
  297. */
  298. public long queueNewOperation(Intent operationIntent) {
  299. Pair<Target, RemoteOperation> itemToQueue = newOperation(operationIntent);
  300. if (itemToQueue != null) {
  301. mServiceHandler.mPendingOperations.add(itemToQueue);
  302. startService(new Intent(OperationsService.this, OperationsService.class));
  303. return itemToQueue.second.hashCode();
  304. } else {
  305. return Long.MAX_VALUE;
  306. }
  307. }
  308. public boolean dispatchResultIfFinished(int operationId, OnRemoteOperationListener listener) {
  309. Pair<RemoteOperation, RemoteOperationResult> undispatched =
  310. mUndispatchedFinishedOperations.remove(operationId);
  311. if (undispatched != null) {
  312. listener.onRemoteOperationFinish(undispatched.first, undispatched.second);
  313. return true;
  314. //Log_OC.wtf(TAG, "Sending callback later");
  315. } else {
  316. if (!mServiceHandler.mPendingOperations.isEmpty()) {
  317. return true;
  318. } else {
  319. return false;
  320. }
  321. //Log_OC.wtf(TAG, "Not finished yet");
  322. }
  323. }
  324. /**
  325. * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
  326. *
  327. * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
  328. *
  329. * @param account ownCloud account where the remote file is stored.
  330. * @param file A file that could be affected
  331. */
  332. public boolean isSynchronizing(Account account, String remotePath) {
  333. return mSyncFolderHandler.isSynchronizing(account, remotePath);
  334. }
  335. }
  336. /**
  337. * SyncFolder worker. Performs the pending operations in the order they were requested.
  338. *
  339. * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
  340. */
  341. private static class SyncFolderHandler extends Handler {
  342. // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
  343. OperationsService mService;
  344. private ConcurrentMap<String,SynchronizeFolderOperation> mPendingOperations =
  345. new ConcurrentHashMap<String,SynchronizeFolderOperation>();
  346. private OwnCloudClient mOwnCloudClient = null;
  347. private FileDataStorageManager mStorageManager;
  348. private SynchronizeFolderOperation mCurrentSyncOperation;
  349. public SyncFolderHandler(Looper looper, OperationsService service) {
  350. super(looper);
  351. if (service == null) {
  352. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  353. }
  354. mService = service;
  355. }
  356. public boolean isSynchronizing(Account account, String remotePath) {
  357. if (account == null || remotePath == null) return false;
  358. String targetKey = buildRemoteName(account, remotePath);
  359. synchronized (mPendingOperations) {
  360. return (mPendingOperations.containsKey(targetKey));
  361. }
  362. }
  363. @Override
  364. public void handleMessage(Message msg) {
  365. Pair<Account, String> itemSyncKey = (Pair<Account, String>) msg.obj;
  366. doOperation(itemSyncKey.first, itemSyncKey.second);
  367. mService.stopSelf(msg.arg1);
  368. }
  369. /**
  370. * Performs the next operation in the queue
  371. */
  372. private void doOperation(Account account, String remotePath) {
  373. String syncKey = buildRemoteName(account,remotePath);
  374. synchronized(mPendingOperations) {
  375. mCurrentSyncOperation = mPendingOperations.get(syncKey);
  376. }
  377. if (mCurrentSyncOperation != null) {
  378. try {
  379. OwnCloudAccount ocAccount = new OwnCloudAccount(account, mService);
  380. mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  381. getClientFor(ocAccount, mService);
  382. mStorageManager = new FileDataStorageManager(
  383. account,
  384. mService.getContentResolver()
  385. );
  386. mCurrentSyncOperation.execute(mOwnCloudClient, mStorageManager);
  387. } catch (AccountsException e) {
  388. Log_OC.e(TAG, "Error while trying to get autorization", e);
  389. } catch (IOException e) {
  390. Log_OC.e(TAG, "Error while trying to get autorization", e);
  391. } finally {
  392. synchronized(mPendingOperations) {
  393. mPendingOperations.remove(syncKey);
  394. }
  395. }
  396. }
  397. }
  398. public void add(Account account, String remotePath, SynchronizeFolderOperation syncFolderOperation){
  399. String syncKey = buildRemoteName(account,remotePath);
  400. mPendingOperations.putIfAbsent(syncKey,syncFolderOperation);
  401. }
  402. /**
  403. * Cancels a pending or current sync operation.
  404. *
  405. * @param account Owncloud account where the remote file is stored.
  406. * @param file File
  407. */
  408. public void cancel(Account account, OCFile file) {
  409. SynchronizeFolderOperation syncOperation = null;
  410. synchronized (mPendingOperations) {
  411. syncOperation = mPendingOperations.remove(buildRemoteName(account, file.getRemotePath()));
  412. }
  413. if (syncOperation != null) {
  414. syncOperation.cancel();
  415. }
  416. Intent intent = new Intent( MainApp.getAppContext(), FileDownloader.class);
  417. intent.setAction(FileDownloader.ACTION_CANCEL_FILE_DOWNLOAD);
  418. intent.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  419. intent.putExtra(FileDownloader.EXTRA_FILE, file);
  420. MainApp.getAppContext().startService(intent);
  421. }
  422. /**
  423. * Builds a key from the account and file to download
  424. *
  425. * @param account Account where the file to download is stored
  426. * @param path File path
  427. */
  428. private String buildRemoteName(Account account, String path) {
  429. return account.name + path;
  430. }
  431. }
  432. /**
  433. * Operations worker. Performs the pending operations in the order they were requested.
  434. *
  435. * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
  436. */
  437. private static class ServiceHandler extends Handler {
  438. // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
  439. OperationsService mService;
  440. private ConcurrentLinkedQueue<Pair<Target, RemoteOperation>> mPendingOperations =
  441. new ConcurrentLinkedQueue<Pair<Target, RemoteOperation>>();
  442. private RemoteOperation mCurrentOperation = null;
  443. private Target mLastTarget = null;
  444. private OwnCloudClient mOwnCloudClient = null;
  445. private FileDataStorageManager mStorageManager;
  446. public ServiceHandler(Looper looper, OperationsService service) {
  447. super(looper);
  448. if (service == null) {
  449. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  450. }
  451. mService = service;
  452. }
  453. @Override
  454. public void handleMessage(Message msg) {
  455. nextOperation();
  456. mService.stopSelf(msg.arg1);
  457. }
  458. /**
  459. * Performs the next operation in the queue
  460. */
  461. private void nextOperation() {
  462. //Log_OC.wtf(TAG, "nextOperation init" );
  463. Pair<Target, RemoteOperation> next = null;
  464. synchronized(mPendingOperations) {
  465. next = mPendingOperations.peek();
  466. }
  467. if (next != null) {
  468. mCurrentOperation = next.second;
  469. RemoteOperationResult result = null;
  470. try {
  471. /// prepare client object to send the request to the ownCloud server
  472. if (mLastTarget == null || !mLastTarget.equals(next.first)) {
  473. mLastTarget = next.first;
  474. if (mLastTarget.mAccount != null) {
  475. OwnCloudAccount ocAccount = new OwnCloudAccount(mLastTarget.mAccount, mService);
  476. mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  477. getClientFor(ocAccount, mService);
  478. mStorageManager = new FileDataStorageManager(
  479. mLastTarget.mAccount,
  480. mService.getContentResolver()
  481. );
  482. } else {
  483. OwnCloudCredentials credentials = null;
  484. if (mLastTarget.mUsername != null &&
  485. mLastTarget.mUsername.length() > 0) {
  486. credentials = OwnCloudCredentialsFactory.newBasicCredentials(
  487. mLastTarget.mUsername,
  488. mLastTarget.mPassword); // basic
  489. } else if (mLastTarget.mAuthToken != null &&
  490. mLastTarget.mAuthToken.length() > 0) {
  491. credentials = OwnCloudCredentialsFactory.newBearerCredentials(
  492. mLastTarget.mAuthToken); // bearer token
  493. } else if (mLastTarget.mCookie != null &&
  494. mLastTarget.mCookie.length() > 0) {
  495. credentials = OwnCloudCredentialsFactory.newSamlSsoCredentials(
  496. mLastTarget.mCookie); // SAML SSO
  497. }
  498. OwnCloudAccount ocAccount = new OwnCloudAccount(
  499. mLastTarget.mServerUrl, credentials);
  500. mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  501. getClientFor(ocAccount, mService);
  502. mStorageManager = null;
  503. }
  504. }
  505. /// perform the operation
  506. if (mCurrentOperation instanceof SyncOperation) {
  507. result = ((SyncOperation)mCurrentOperation).execute(mOwnCloudClient, mStorageManager);
  508. } else {
  509. result = mCurrentOperation.execute(mOwnCloudClient);
  510. }
  511. } catch (AccountsException e) {
  512. if (mLastTarget.mAccount == null) {
  513. Log_OC.e(TAG, "Error while trying to get authorization for a NULL account", e);
  514. } else {
  515. Log_OC.e(TAG, "Error while trying to get authorization for " + mLastTarget.mAccount.name, e);
  516. }
  517. result = new RemoteOperationResult(e);
  518. } catch (IOException e) {
  519. if (mLastTarget.mAccount == null) {
  520. Log_OC.e(TAG, "Error while trying to get authorization for a NULL account", e);
  521. } else {
  522. Log_OC.e(TAG, "Error while trying to get authorization for " + mLastTarget.mAccount.name, e);
  523. }
  524. result = new RemoteOperationResult(e);
  525. } catch (Exception e) {
  526. if (mLastTarget.mAccount == null) {
  527. Log_OC.e(TAG, "Unexpected error for a NULL account", e);
  528. } else {
  529. Log_OC.e(TAG, "Unexpected error for " + mLastTarget.mAccount.name, e);
  530. }
  531. result = new RemoteOperationResult(e);
  532. } finally {
  533. synchronized(mPendingOperations) {
  534. mPendingOperations.poll();
  535. }
  536. }
  537. //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
  538. mService.dispatchResultToOperationListeners(mLastTarget, mCurrentOperation, result);
  539. }
  540. }
  541. }
  542. /**
  543. * Creates a new operation, as described by operationIntent.
  544. *
  545. * TODO - move to ServiceHandler (probably)
  546. *
  547. * @param operationIntent Intent describing a new operation to queue and execute.
  548. * @return Pair with the new operation object and the information about its target server.
  549. */
  550. private Pair<Target , RemoteOperation> newOperation(Intent operationIntent) {
  551. RemoteOperation operation = null;
  552. Target target = null;
  553. try {
  554. if (!operationIntent.hasExtra(EXTRA_ACCOUNT) &&
  555. !operationIntent.hasExtra(EXTRA_SERVER_URL)) {
  556. Log_OC.e(TAG, "Not enough information provided in intent");
  557. } else {
  558. Account account = operationIntent.getParcelableExtra(EXTRA_ACCOUNT);
  559. String serverUrl = operationIntent.getStringExtra(EXTRA_SERVER_URL);
  560. String username = operationIntent.getStringExtra(EXTRA_USERNAME);
  561. String password = operationIntent.getStringExtra(EXTRA_PASSWORD);
  562. String authToken = operationIntent.getStringExtra(EXTRA_AUTH_TOKEN);
  563. String cookie = operationIntent.getStringExtra(EXTRA_COOKIE);
  564. target = new Target(
  565. account,
  566. (serverUrl == null) ? null : Uri.parse(serverUrl),
  567. username,
  568. password,
  569. authToken,
  570. cookie
  571. );
  572. String action = operationIntent.getAction();
  573. if (action.equals(ACTION_CREATE_SHARE)) { // Create Share
  574. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  575. Intent sendIntent = operationIntent.getParcelableExtra(EXTRA_SEND_INTENT);
  576. if (remotePath.length() > 0) {
  577. operation = new CreateShareOperation(remotePath, ShareType.PUBLIC_LINK,
  578. "", false, "", 1, sendIntent);
  579. }
  580. } else if (action.equals(ACTION_UNSHARE)) { // Unshare file
  581. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  582. if (remotePath.length() > 0) {
  583. operation = new UnshareLinkOperation(
  584. remotePath,
  585. OperationsService.this);
  586. }
  587. } else if (action.equals(ACTION_GET_SERVER_INFO)) {
  588. // check OC server and get basic information from it
  589. operation = new GetServerInfoOperation(serverUrl, OperationsService.this);
  590. } else if (action.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN)) {
  591. /// GET ACCESS TOKEN to the OAuth server
  592. String oauth2QueryParameters =
  593. operationIntent.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS);
  594. operation = new OAuth2GetAccessToken(
  595. getString(R.string.oauth2_client_id),
  596. getString(R.string.oauth2_redirect_uri),
  597. getString(R.string.oauth2_grant_type),
  598. oauth2QueryParameters);
  599. } else if (action.equals(ACTION_EXISTENCE_CHECK)) {
  600. // Existence Check
  601. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  602. boolean successIfAbsent = operationIntent.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT, false);
  603. operation = new ExistenceCheckRemoteOperation(remotePath, OperationsService.this, successIfAbsent);
  604. } else if (action.equals(ACTION_GET_USER_NAME)) {
  605. // Get User Name
  606. operation = new GetRemoteUserNameOperation();
  607. } else if (action.equals(ACTION_RENAME)) {
  608. // Rename file or folder
  609. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  610. String newName = operationIntent.getStringExtra(EXTRA_NEWNAME);
  611. operation = new RenameFileOperation(remotePath, newName);
  612. } else if (action.equals(ACTION_REMOVE)) {
  613. // Remove file or folder
  614. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  615. boolean onlyLocalCopy = operationIntent.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL, false);
  616. operation = new RemoveFileOperation(remotePath, onlyLocalCopy);
  617. } else if (action.equals(ACTION_CREATE_FOLDER)) {
  618. // Create Folder
  619. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  620. boolean createFullPath = operationIntent.getBooleanExtra(EXTRA_CREATE_FULL_PATH, true);
  621. operation = new CreateFolderOperation(remotePath, createFullPath);
  622. } else if (action.equals(ACTION_SYNC_FILE)) {
  623. // Sync file
  624. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  625. boolean syncFileContents = operationIntent.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS, true);
  626. operation = new SynchronizeFileOperation(
  627. remotePath, account, syncFileContents, getApplicationContext()
  628. );
  629. } else if (action.equals(ACTION_SYNC_FOLDER)) {
  630. // Sync file
  631. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  632. operation = new SynchronizeFolderOperation(
  633. this, // TODO remove this dependency from construction time
  634. remotePath,
  635. account,
  636. System.currentTimeMillis() // TODO remove this dependency from construction time
  637. );
  638. } else if (action.equals(ACTION_MOVE_FILE)) {
  639. // Move file/folder
  640. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  641. String newParentPath = operationIntent.getStringExtra(EXTRA_NEW_PARENT_PATH);
  642. operation = new MoveFileOperation(remotePath,newParentPath,account);
  643. }
  644. }
  645. } catch (IllegalArgumentException e) {
  646. Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
  647. operation = null;
  648. }
  649. if (operation != null) {
  650. return new Pair<Target , RemoteOperation>(target, operation);
  651. } else {
  652. return null;
  653. }
  654. }
  655. /**
  656. * Sends a broadcast when a new operation is added to the queue.
  657. *
  658. * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
  659. *
  660. * @param target Account or URL pointing to an OC server.
  661. * @param operation Added operation.
  662. */
  663. private void sendBroadcastNewOperation(Target target, RemoteOperation operation) {
  664. Intent intent = new Intent(ACTION_OPERATION_ADDED);
  665. if (target.mAccount != null) {
  666. intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
  667. } else {
  668. intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
  669. }
  670. //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
  671. //lbm.sendBroadcast(intent);
  672. sendStickyBroadcast(intent);
  673. }
  674. // TODO - maybe add a notification for real start of operations
  675. /**
  676. * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
  677. *
  678. * Local broadcasts are only delivered to activities in the same process.
  679. *
  680. * @param target Account or URL pointing to an OC server.
  681. * @param operation Finished operation.
  682. * @param result Result of the operation.
  683. */
  684. private void sendBroadcastOperationFinished(Target target, RemoteOperation operation, RemoteOperationResult result) {
  685. Intent intent = new Intent(ACTION_OPERATION_FINISHED);
  686. intent.putExtra(EXTRA_RESULT, result);
  687. if (target.mAccount != null) {
  688. intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
  689. } else {
  690. intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
  691. }
  692. //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
  693. //lbm.sendBroadcast(intent);
  694. sendStickyBroadcast(intent);
  695. }
  696. /**
  697. * Notifies the currently subscribed listeners about the end of an operation.
  698. *
  699. * @param target Account or URL pointing to an OC server.
  700. * @param operation Finished operation.
  701. * @param result Result of the operation.
  702. */
  703. private void dispatchResultToOperationListeners(
  704. Target target, final RemoteOperation operation, final RemoteOperationResult result) {
  705. int count = 0;
  706. Iterator<OnRemoteOperationListener> listeners = mOperationsBinder.mBoundListeners.keySet().iterator();
  707. while (listeners.hasNext()) {
  708. final OnRemoteOperationListener listener = listeners.next();
  709. final Handler handler = mOperationsBinder.mBoundListeners.get(listener);
  710. if (handler != null) {
  711. handler.post(new Runnable() {
  712. @Override
  713. public void run() {
  714. listener.onRemoteOperationFinish(operation, result);
  715. }
  716. });
  717. count += 1;
  718. }
  719. }
  720. if (count == 0) {
  721. //mOperationResults.put(operation.hashCode(), result);
  722. Pair<RemoteOperation, RemoteOperationResult> undispatched =
  723. new Pair<RemoteOperation, RemoteOperationResult>(operation, result);
  724. mUndispatchedFinishedOperations.put(operation.hashCode(), undispatched);
  725. }
  726. Log_OC.d(TAG, "Called " + count + " listeners");
  727. }
  728. }