OperationsService.java 41 KB

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