1 /* ownCloud Android client application 
   2  *   Copyright (C) 2012-2014 ownCloud Inc. 
   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. 
   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. 
  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/>. 
  18 package com
.owncloud
.android
.services
; 
  20 import java
.io
.IOException
; 
  21 import java
.util
.Iterator
; 
  22 import java
.util
.concurrent
.ConcurrentHashMap
; 
  23 import java
.util
.concurrent
.ConcurrentLinkedQueue
; 
  24 import java
.util
.concurrent
.ConcurrentMap
; 
  26 import com
.owncloud
.android
.MainApp
; 
  27 import com
.owncloud
.android
.R
; 
  28 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
; 
  29 import com
.owncloud
.android
.datamodel
.OCFile
; 
  30 import com
.owncloud
.android
.files
.services
.FileDownloader
; 
  31 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
; 
  32 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
; 
  33 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
; 
  34 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
; 
  35 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentialsFactory
; 
  36 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
; 
  37 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
; 
  38 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
; 
  39 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
; 
  40 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
; 
  41 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
; 
  42 import com
.owncloud
.android
.lib
.resources
.shares
.ShareType
; 
  43 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
; 
  44 import com
.owncloud
.android
.operations
.common
.SyncOperation
; 
  45 import com
.owncloud
.android
.operations
.CreateFolderOperation
; 
  46 import com
.owncloud
.android
.operations
.CreateShareOperation
; 
  47 import com
.owncloud
.android
.operations
.GetServerInfoOperation
; 
  48 import com
.owncloud
.android
.operations
.MoveFileOperation
; 
  49 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
; 
  50 import com
.owncloud
.android
.operations
.RemoveFileOperation
; 
  51 import com
.owncloud
.android
.operations
.RenameFileOperation
; 
  52 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
; 
  53 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
; 
  54 import com
.owncloud
.android
.operations
.UnshareLinkOperation
; 
  56 import android
.accounts
.Account
; 
  57 import android
.accounts
.AccountsException
; 
  58 import android
.accounts
.AuthenticatorException
; 
  59 import android
.accounts
.OperationCanceledException
; 
  60 import android
.app
.Service
; 
  61 import android
.content
.Intent
; 
  62 import android
.net
.Uri
; 
  63 import android
.os
.Binder
; 
  64 import android
.os
.Handler
; 
  65 import android
.os
.HandlerThread
; 
  66 import android
.os
.IBinder
; 
  67 import android
.os
.Looper
; 
  68 import android
.os
.Message
; 
  69 import android
.os
.Process
; 
  70 import android
.util
.Pair
; 
  72 public class OperationsService 
extends Service 
{ 
  74     private static final String TAG 
= OperationsService
.class.getSimpleName(); 
  76     public static final String EXTRA_ACCOUNT 
= "ACCOUNT"; 
  77     public static final String EXTRA_SERVER_URL 
= "SERVER_URL"; 
  78     public static final String EXTRA_OAUTH2_QUERY_PARAMETERS 
= "OAUTH2_QUERY_PARAMETERS"; 
  79     public static final String EXTRA_REMOTE_PATH 
= "REMOTE_PATH"; 
  80     public static final String EXTRA_SEND_INTENT 
= "SEND_INTENT"; 
  81     public static final String EXTRA_NEWNAME 
= "NEWNAME"; 
  82     public static final String EXTRA_REMOVE_ONLY_LOCAL 
= "REMOVE_LOCAL_COPY"; 
  83     public static final String EXTRA_CREATE_FULL_PATH 
= "CREATE_FULL_PATH"; 
  84     public static final String EXTRA_SYNC_FILE_CONTENTS 
= "SYNC_FILE_CONTENTS"; 
  85     public static final String EXTRA_RESULT 
= "RESULT"; 
  86     public static final String EXTRA_NEW_PARENT_PATH 
= "NEW_PARENT_PATH"; 
  87     public static final String EXTRA_FILE 
= "FILE"; 
  89     // TODO review if ALL OF THEM are necessary 
  90     public static final String EXTRA_SUCCESS_IF_ABSENT 
= "SUCCESS_IF_ABSENT"; 
  91     public static final String EXTRA_USERNAME 
= "USERNAME"; 
  92     public static final String EXTRA_PASSWORD 
= "PASSWORD"; 
  93     public static final String EXTRA_AUTH_TOKEN 
= "AUTH_TOKEN"; 
  94     public static final String EXTRA_COOKIE 
= "COOKIE"; 
  96     public static final String ACTION_CREATE_SHARE 
= "CREATE_SHARE"; 
  97     public static final String ACTION_UNSHARE 
= "UNSHARE"; 
  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_EXISTENCE_CHECK 
= "EXISTENCE_CHECK"; 
 101     public static final String ACTION_GET_USER_NAME 
= "GET_USER_NAME"; 
 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";  // for the moment, just to download 
 107     public static final String ACTION_CANCEL_SYNC_FOLDER 
= "CANCEL_SYNC_FOLDER";  // for the moment, just to download 
 108     public static final String ACTION_MOVE_FILE 
= "MOVE_FILE"; 
 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"; 
 114     private ConcurrentMap
<Integer
, Pair
<RemoteOperation
, RemoteOperationResult
>>  
 115         mUndispatchedFinishedOperations 
= 
 116             new ConcurrentHashMap
<Integer
, Pair
<RemoteOperation
, RemoteOperationResult
>>(); 
 118     private static class Target 
{ 
 119         public Uri mServerUrl 
= null
; 
 120         public Account mAccount 
= null
; 
 121         public String mUsername 
= null
; 
 122         public String mPassword 
= null
; 
 123         public String mAuthToken 
= null
; 
 124         public String mCookie 
= null
; 
 126         public Target(Account account
, Uri serverUrl
, String username
, String password
, String authToken
, 
 129             mServerUrl 
= serverUrl
; 
 130             mUsername 
= username
; 
 131             mPassword 
= password
; 
 132             mAuthToken 
= authToken
; 
 137     private ServiceHandler mOperationsHandler
; 
 138     private OperationsServiceBinder mOperationsBinder
; 
 140     private SyncFolderHandler mSyncFolderHandler
; 
 143      * Service initialization 
 146     public void onCreate() { 
 148         /// First worker thread for most of operations  
 149         HandlerThread thread 
= new HandlerThread("Operations thread", Process
.THREAD_PRIORITY_BACKGROUND
); 
 151         mOperationsHandler 
= new ServiceHandler(thread
.getLooper(), this); 
 152         mOperationsBinder 
= new OperationsServiceBinder(mOperationsHandler
); 
 154         /// Separated worker thread for download of folders (WIP) 
 155         thread 
= new HandlerThread("Syncfolder thread", Process
.THREAD_PRIORITY_BACKGROUND
); 
 157         mSyncFolderHandler 
= new SyncFolderHandler(thread
.getLooper(), this); 
 162      * Entry point to add a new operation to the queue of operations. 
 164      * New operations are added calling to startService(), resulting in a call to this method.  
 165      * This ensures the service will keep on working although the caller activity goes away. 
 168     public int onStartCommand(Intent intent
, int flags
, int startId
) { 
 169         // WIP: for the moment, only SYNC_FOLDER and CANCEL_SYNC_FOLDER is expected here; 
 170         // the rest of the operations are requested through the Binder 
 171         if (ACTION_SYNC_FOLDER
.equals(intent
.getAction())) { 
 172             if (!intent
.hasExtra(EXTRA_ACCOUNT
) || !intent
.hasExtra(EXTRA_REMOTE_PATH
)) { 
 173                 Log_OC
.e(TAG
, "Not enough information provided in intent"); 
 174                 return START_NOT_STICKY
; 
 176             Account account 
= intent
.getParcelableExtra(EXTRA_ACCOUNT
); 
 177             String remotePath 
= intent
.getStringExtra(EXTRA_REMOTE_PATH
); 
 179             Pair
<Account
, String
> itemSyncKey 
=  new Pair
<Account 
, String
>(account
, remotePath
); 
 181             Pair
<Target
, RemoteOperation
> itemToQueue 
= newOperation(intent
); 
 182             if (itemToQueue 
!= null
) { 
 183                 mSyncFolderHandler
.add(account
, remotePath
, (SynchronizeFolderOperation
)itemToQueue
.second
); 
 184                 Message msg 
= mSyncFolderHandler
.obtainMessage(); 
 186                 msg
.obj 
= itemSyncKey
; 
 187                 mSyncFolderHandler
.sendMessage(msg
); 
 189         } else if (ACTION_CANCEL_SYNC_FOLDER
.equals(intent
.getAction())) { 
 190             if (!intent
.hasExtra(EXTRA_ACCOUNT
) || !intent
.hasExtra(EXTRA_FILE
)) { 
 191                 Log_OC
.e(TAG
, "Not enough information provided in intent"); 
 192                 return START_NOT_STICKY
; 
 194             Account account 
= intent
.getParcelableExtra(EXTRA_ACCOUNT
); 
 195             OCFile file 
= intent
.getParcelableExtra(EXTRA_FILE
); 
 198             mSyncFolderHandler
.cancel(account
,file
); 
 200             Message msg 
= mOperationsHandler
.obtainMessage(); 
 202             mOperationsHandler
.sendMessage(msg
); 
 205         return START_NOT_STICKY
; 
 209     public void onDestroy() { 
 210         //Log_OC.wtf(TAG, "onDestroy init" ); 
 213             OwnCloudClientManagerFactory
.getDefaultSingleton(). 
 214                 saveAllClients(this, MainApp
.getAccountType()); 
 216             // TODO - get rid of these exceptions 
 217         } catch (AccountNotFoundException e
) { 
 219         } catch (AuthenticatorException e
) { 
 221         } catch (OperationCanceledException e
) { 
 223         } catch (IOException e
) { 
 227         //Log_OC.wtf(TAG, "Clear mUndispatchedFinisiedOperations" ); 
 228         mUndispatchedFinishedOperations
.clear(); 
 230         //Log_OC.wtf(TAG, "onDestroy end" ); 
 235      * Provides a binder object that clients can use to perform actions on the queue of operations,  
 236      * except the addition of new operations.  
 239     public IBinder 
onBind(Intent intent
) { 
 240         //Log_OC.wtf(TAG, "onBind" ); 
 241         return mOperationsBinder
; 
 246      * Called when ALL the bound clients were unbound. 
 249     public boolean onUnbind(Intent intent
) { 
 250         ((OperationsServiceBinder
)mOperationsBinder
).clearListeners(); 
 251         return false
;   // not accepting rebinding (default behaviour) 
 256      *  Binder to let client components to perform actions on the queue of operations. 
 258      *  It provides by itself the available operations. 
 260     public class OperationsServiceBinder 
extends Binder 
/* implements OnRemoteOperationListener */ { 
 263          * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance  
 265         private ConcurrentMap
<OnRemoteOperationListener
, Handler
> mBoundListeners 
=  
 266                 new ConcurrentHashMap
<OnRemoteOperationListener
, Handler
>(); 
 268         private ServiceHandler mServiceHandler 
= null
;    
 271         public OperationsServiceBinder(ServiceHandler serviceHandler
) { 
 272             mServiceHandler 
= serviceHandler
; 
 277          * Cancels an operation 
 281         public void cancel() { 
 286         public void clearListeners() { 
 288             mBoundListeners
.clear(); 
 293          * Adds a listener interested in being reported about the end of operations. 
 295          * @param listener          Object to notify about the end of operations.     
 296          * @param callbackHandler   {@link Handler} to access the listener without breaking Android threading protection. 
 298         public void addOperationListener (OnRemoteOperationListener listener
, Handler callbackHandler
) { 
 299             synchronized (mBoundListeners
) { 
 300                 mBoundListeners
.put(listener
, callbackHandler
); 
 306          * Removes a listener from the list of objects interested in the being reported about the end of operations. 
 308          * @param listener      Object to notify about progress of transfer.     
 310         public void removeOperationListener (OnRemoteOperationListener listener
) { 
 311             synchronized (mBoundListeners
) { 
 312                 mBoundListeners
.remove(listener
); 
 318          * TODO - IMPORTANT: update implementation when more operations are moved into the service  
 320          * @return  'True' when an operation that enforces the user to wait for completion is in process. 
 322         public boolean isPerformingBlockingOperation() { 
 323             return (!mServiceHandler
.mPendingOperations
.isEmpty()); 
 328          * Creates and adds to the queue a new operation, as described by operationIntent. 
 330          * Calls startService to make the operation is processed by the ServiceHandler. 
 332          * @param operationIntent       Intent describing a new operation to queue and execute. 
 333          * @return                      Identifier of the operation created, or null if failed. 
 335         public long queueNewOperation(Intent operationIntent
) { 
 336             Pair
<Target
, RemoteOperation
> itemToQueue 
= newOperation(operationIntent
); 
 337             if (itemToQueue 
!= null
) { 
 338                 mServiceHandler
.mPendingOperations
.add(itemToQueue
); 
 339                 startService(new Intent(OperationsService
.this, OperationsService
.class)); 
 340                 return itemToQueue
.second
.hashCode(); 
 343                 return Long
.MAX_VALUE
; 
 348         public boolean dispatchResultIfFinished(int operationId
, OnRemoteOperationListener listener
) { 
 349             Pair
<RemoteOperation
, RemoteOperationResult
> undispatched 
=  
 350                     mUndispatchedFinishedOperations
.remove(operationId
); 
 351             if (undispatched 
!= null
) { 
 352                 listener
.onRemoteOperationFinish(undispatched
.first
, undispatched
.second
); 
 354                 //Log_OC.wtf(TAG, "Sending callback later"); 
 356                 if (!mServiceHandler
.mPendingOperations
.isEmpty()) { 
 361                 //Log_OC.wtf(TAG, "Not finished yet"); 
 369      * SyncFolder worker. Performs the pending operations in the order they were requested. 
 371      * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}. 
 373     private static class SyncFolderHandler 
extends Handler 
{ 
 375         // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak 
 377         OperationsService mService
; 
 379         private ConcurrentMap
<String
,SynchronizeFolderOperation
> mPendingOperations 
= 
 380                 new ConcurrentHashMap
<String
,SynchronizeFolderOperation
>(); 
 381         private OwnCloudClient mOwnCloudClient 
= null
; 
 382         private FileDataStorageManager mStorageManager
; 
 383         private SynchronizeFolderOperation mCurrentSyncOperation
; 
 386         public SyncFolderHandler(Looper looper
, OperationsService service
) { 
 388             if (service 
== null
) { 
 389                 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'"); 
 395         public void handleMessage(Message msg
) { 
 396             Pair
<Account
, String
> itemSyncKey 
= (Pair
<Account
, String
>) msg
.obj
; 
 397             doOperation(itemSyncKey
.first
, itemSyncKey
.second
); 
 398             mService
.stopSelf(msg
.arg1
); 
 403          * Performs the next operation in the queue 
 405         private void doOperation(Account account
, String remotePath
) { 
 407             String syncKey 
= buildRemoteName(account
,remotePath
); 
 409             synchronized(mPendingOperations
) { 
 410                 mCurrentSyncOperation 
= mPendingOperations
.get(syncKey
); 
 413             if (mCurrentSyncOperation 
!= null
) { 
 417                     OwnCloudAccount ocAccount 
= new OwnCloudAccount(account
, mService
); 
 418                     mOwnCloudClient 
= OwnCloudClientManagerFactory
.getDefaultSingleton(). 
 419                             getClientFor(ocAccount
, mService
); 
 420                     mStorageManager 
= new FileDataStorageManager( 
 422                             mService
.getContentResolver() 
 425                     mCurrentSyncOperation
.execute(mOwnCloudClient
, mStorageManager
); 
 427                 } catch (AccountsException e
) { 
 428                     Log_OC
.e(TAG
, "Error while trying to get autorization", e
); 
 429                 } catch (IOException e
) { 
 430                     Log_OC
.e(TAG
, "Error while trying to get autorization", e
); 
 432                     synchronized(mPendingOperations
) { 
 433                         mPendingOperations
.remove(syncKey
); 
 439         public void add(Account account
, String remotePath
, SynchronizeFolderOperation syncFolderOperation
){ 
 440             String syncKey 
= buildRemoteName(account
,remotePath
); 
 441             mPendingOperations
.putIfAbsent(syncKey
,syncFolderOperation
); 
 446          * Cancels a pending or current sync operation. 
 448          * @param account       Owncloud account where the remote file is stored. 
 451         public void cancel(Account account
, OCFile file
) { 
 452             SynchronizeFolderOperation syncOperation 
= null
; 
 453             synchronized (mPendingOperations
) { 
 454                 syncOperation 
= mPendingOperations
.remove(buildRemoteName(account
, file
.getRemotePath())); 
 456             if (syncOperation 
!= null
) { 
 457                 syncOperation
.cancel(); 
 460             Intent intent 
= new Intent( MainApp
.getAppContext(), FileDownloader
.class); 
 461             intent
.setAction(FileDownloader
.ACTION_CANCEL_FILE_DOWNLOAD
); 
 462             intent
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
); 
 463             intent
.putExtra(FileDownloader
.EXTRA_FILE
, file
); 
 464             MainApp
.getAppContext().startService(intent
); 
 469          * Builds a key from the account and file to download 
 471          * @param account   Account where the file to download is stored 
 472          * @param path      File path 
 474         private String 
buildRemoteName(Account account
, String path
) { 
 475             return account
.name 
+ path
; 
 481      * Operations worker. Performs the pending operations in the order they were requested.  
 483      * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.  
 485     private static class ServiceHandler 
extends Handler 
{ 
 486         // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak 
 489         OperationsService mService
; 
 492         private ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>> mPendingOperations 
= 
 493                 new ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>>(); 
 494         private RemoteOperation mCurrentOperation 
= null
; 
 495         private Target mLastTarget 
= null
; 
 496         private OwnCloudClient mOwnCloudClient 
= null
; 
 497         private FileDataStorageManager mStorageManager
; 
 500         public ServiceHandler(Looper looper
, OperationsService service
) { 
 502             if (service 
== null
) { 
 503                 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'"); 
 509         public void handleMessage(Message msg
) { 
 511             mService
.stopSelf(msg
.arg1
); 
 516          * Performs the next operation in the queue 
 518         private void nextOperation() { 
 520             //Log_OC.wtf(TAG, "nextOperation init" ); 
 522             Pair
<Target
, RemoteOperation
> next 
= null
; 
 523             synchronized(mPendingOperations
) { 
 524                 next 
= mPendingOperations
.peek(); 
 529                 mCurrentOperation 
= next
.second
; 
 530                 RemoteOperationResult result 
= null
; 
 532                     /// prepare client object to send the request to the ownCloud server 
 533                     if (mLastTarget 
== null 
|| !mLastTarget
.equals(next
.first
)) { 
 534                         mLastTarget 
= next
.first
; 
 535                         if (mLastTarget
.mAccount 
!= null
) { 
 536                             OwnCloudAccount ocAccount 
= new OwnCloudAccount(mLastTarget
.mAccount
, mService
); 
 537                             mOwnCloudClient 
= OwnCloudClientManagerFactory
.getDefaultSingleton(). 
 538                                     getClientFor(ocAccount
, mService
); 
 539                             mStorageManager 
= new FileDataStorageManager( 
 540                                     mLastTarget
.mAccount
,  
 541                                     mService
.getContentResolver() 
 544                             OwnCloudCredentials credentials 
= null
; 
 545                             if (mLastTarget
.mUsername 
!= null 
&&  
 546                                     mLastTarget
.mUsername
.length() > 0) { 
 547                                 credentials 
= OwnCloudCredentialsFactory
.newBasicCredentials( 
 548                                         mLastTarget
.mUsername
,  
 549                                         mLastTarget
.mPassword
);  // basic 
 551                             } else if (mLastTarget
.mAuthToken 
!= null 
&&  
 552                                     mLastTarget
.mAuthToken
.length() > 0) { 
 553                                 credentials 
= OwnCloudCredentialsFactory
.newBearerCredentials( 
 554                                         mLastTarget
.mAuthToken
);  // bearer token 
 556                             } else if (mLastTarget
.mCookie 
!= null 
&& 
 557                                     mLastTarget
.mCookie
.length() > 0) { 
 558                                 credentials 
= OwnCloudCredentialsFactory
.newSamlSsoCredentials( 
 559                                         mLastTarget
.mCookie
); // SAML SSO 
 561                             OwnCloudAccount ocAccount 
= new OwnCloudAccount( 
 562                                     mLastTarget
.mServerUrl
, credentials
); 
 563                             mOwnCloudClient 
= OwnCloudClientManagerFactory
.getDefaultSingleton(). 
 564                                     getClientFor(ocAccount
, mService
); 
 565                             mStorageManager 
= null
; 
 569                     /// perform the operation 
 570                     if (mCurrentOperation 
instanceof SyncOperation
) { 
 571                         result 
= ((SyncOperation
)mCurrentOperation
).execute(mOwnCloudClient
, mStorageManager
); 
 573                         result 
= mCurrentOperation
.execute(mOwnCloudClient
); 
 576                 } catch (AccountsException e
) { 
 577                     if (mLastTarget
.mAccount 
== null
) { 
 578                         Log_OC
.e(TAG
, "Error while trying to get authorization for a NULL account", e
); 
 580                         Log_OC
.e(TAG
, "Error while trying to get authorization for " + mLastTarget
.mAccount
.name
, e
); 
 582                     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
); 
 588                         Log_OC
.e(TAG
, "Error while trying to get authorization for " + mLastTarget
.mAccount
.name
, e
); 
 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
); 
 595                         Log_OC
.e(TAG
, "Unexpected error for " + mLastTarget
.mAccount
.name
, e
); 
 597                     result 
= new RemoteOperationResult(e
); 
 600                     synchronized(mPendingOperations
) { 
 601                         mPendingOperations
.poll(); 
 605                 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result); 
 606                 mService
.dispatchResultToOperationListeners(mLastTarget
, mCurrentOperation
, result
); 
 616      * Creates a new operation, as described by operationIntent. 
 618      * TODO - move to ServiceHandler (probably) 
 620      * @param operationIntent       Intent describing a new operation to queue and execute. 
 621      * @return                      Pair with the new operation object and the information about its target server. 
 623     private Pair
<Target 
, RemoteOperation
> newOperation(Intent operationIntent
) { 
 624         RemoteOperation operation 
= null
; 
 625         Target target 
= null
; 
 627             if (!operationIntent
.hasExtra(EXTRA_ACCOUNT
) &&  
 628                     !operationIntent
.hasExtra(EXTRA_SERVER_URL
)) { 
 629                 Log_OC
.e(TAG
, "Not enough information provided in intent"); 
 632                 Account account 
= operationIntent
.getParcelableExtra(EXTRA_ACCOUNT
); 
 633                 String serverUrl 
= operationIntent
.getStringExtra(EXTRA_SERVER_URL
); 
 634                 String username 
= operationIntent
.getStringExtra(EXTRA_USERNAME
); 
 635                 String password 
= operationIntent
.getStringExtra(EXTRA_PASSWORD
); 
 636                 String authToken 
= operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN
); 
 637                 String cookie 
= operationIntent
.getStringExtra(EXTRA_COOKIE
); 
 640                         (serverUrl 
== null
) ? null 
: Uri
.parse(serverUrl
), 
 647                 String action 
= operationIntent
.getAction(); 
 648                 if (action
.equals(ACTION_CREATE_SHARE
)) {  // Create Share 
 649                     String remotePath 
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
); 
 650                     Intent sendIntent 
= operationIntent
.getParcelableExtra(EXTRA_SEND_INTENT
); 
 651                     if (remotePath
.length() > 0) { 
 652                         operation 
= new CreateShareOperation(remotePath
, ShareType
.PUBLIC_LINK
,  
 653                                 "", false
, "", 1, sendIntent
); 
 656                 } else if (action
.equals(ACTION_UNSHARE
)) {  // Unshare file 
 657                     String remotePath 
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
); 
 658                     if (remotePath
.length() > 0) { 
 659                         operation 
= new UnshareLinkOperation( 
 661                                 OperationsService
.this); 
 664                 } else if (action
.equals(ACTION_GET_SERVER_INFO
)) {  
 665                     // check OC server and get basic information from it 
 666                     operation 
= new GetServerInfoOperation(serverUrl
, OperationsService
.this); 
 668                 } else if (action
.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN
)) { 
 669                     /// GET ACCESS TOKEN to the OAuth server 
 670                     String oauth2QueryParameters 
= 
 671                             operationIntent
.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS
); 
 672                     operation 
= new OAuth2GetAccessToken( 
 673                             getString(R
.string
.oauth2_client_id
),  
 674                             getString(R
.string
.oauth2_redirect_uri
),        
 675                             getString(R
.string
.oauth2_grant_type
), 
 676                             oauth2QueryParameters
); 
 678                 } else if (action
.equals(ACTION_EXISTENCE_CHECK
)) { 
 680                     String remotePath 
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
); 
 681                     boolean successIfAbsent 
= operationIntent
.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT
, false
); 
 682                     operation 
= new ExistenceCheckRemoteOperation(remotePath
, OperationsService
.this, successIfAbsent
); 
 684                 } else if (action
.equals(ACTION_GET_USER_NAME
)) { 
 686                     operation 
= new GetRemoteUserNameOperation(); 
 688                 } else if (action
.equals(ACTION_RENAME
)) { 
 689                     // Rename file or folder 
 690                     String remotePath 
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
); 
 691                     String newName 
= operationIntent
.getStringExtra(EXTRA_NEWNAME
); 
 692                     operation 
= new RenameFileOperation(remotePath
, newName
); 
 694                 } else if (action
.equals(ACTION_REMOVE
)) { 
 695                     // Remove file or folder 
 696                     String remotePath 
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
); 
 697                     boolean onlyLocalCopy 
= operationIntent
.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL
, false
); 
 698                     operation 
= new RemoveFileOperation(remotePath
, onlyLocalCopy
); 
 700                 } else if (action
.equals(ACTION_CREATE_FOLDER
)) { 
 702                     String remotePath 
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
); 
 703                     boolean createFullPath 
= operationIntent
.getBooleanExtra(EXTRA_CREATE_FULL_PATH
, true
); 
 704                     operation 
= new CreateFolderOperation(remotePath
, createFullPath
); 
 706                 } else if (action
.equals(ACTION_SYNC_FILE
)) { 
 708                     String remotePath 
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
); 
 709                     boolean syncFileContents 
= operationIntent
.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS
, true
); 
 710                     operation 
= new SynchronizeFileOperation( 
 711                             remotePath
, account
, syncFileContents
, getApplicationContext() 
 714                 } else if (action
.equals(ACTION_SYNC_FOLDER
)) { 
 716                     String remotePath 
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
); 
 717                     operation 
= new SynchronizeFolderOperation( 
 718                             this,                       // TODO remove this dependency from construction time  
 721                             System
.currentTimeMillis()  // TODO remove this dependency from construction time 
 724                 } else if (action
.equals(ACTION_MOVE_FILE
)) { 
 726                     String remotePath 
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
); 
 727                     String newParentPath 
= operationIntent
.getStringExtra(EXTRA_NEW_PARENT_PATH
); 
 728                     operation 
= new MoveFileOperation(remotePath
,newParentPath
,account
); 
 733         } catch (IllegalArgumentException e
) { 
 734             Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage()); 
 738         if (operation 
!= null
) { 
 739             return new Pair
<Target 
, RemoteOperation
>(target
, operation
);   
 747      * Sends a broadcast when a new operation is added to the queue. 
 749      * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\ 
 751      * @param target            Account or URL pointing to an OC server. 
 752      * @param operation         Added operation. 
 754     private void sendBroadcastNewOperation(Target target
, RemoteOperation operation
) { 
 755         Intent intent 
= new Intent(ACTION_OPERATION_ADDED
); 
 756         if (target
.mAccount 
!= null
) { 
 757             intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);     
 759             intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);     
 761         //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this); 
 762         //lbm.sendBroadcast(intent); 
 763         sendStickyBroadcast(intent
); 
 767     // TODO - maybe add a notification for real start of operations 
 770      * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view 
 772      * Local broadcasts are only delivered to activities in the same process. 
 774      * @param target            Account or URL pointing to an OC server. 
 775      * @param operation         Finished operation. 
 776      * @param result            Result of the operation. 
 778     private void sendBroadcastOperationFinished(Target target
, RemoteOperation operation
, RemoteOperationResult result
) { 
 779         Intent intent 
= new Intent(ACTION_OPERATION_FINISHED
); 
 780         intent
.putExtra(EXTRA_RESULT
, result
); 
 781         if (target
.mAccount 
!= null
) { 
 782             intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);     
 784             intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);     
 786         //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this); 
 787         //lbm.sendBroadcast(intent); 
 788         sendStickyBroadcast(intent
); 
 793      * Notifies the currently subscribed listeners about the end of an operation. 
 795      * @param target            Account or URL pointing to an OC server. 
 796      * @param operation         Finished operation. 
 797      * @param result            Result of the operation. 
 799     private void dispatchResultToOperationListeners( 
 800             Target target
, final RemoteOperation operation
, final RemoteOperationResult result
) { 
 802         Iterator
<OnRemoteOperationListener
> listeners 
= mOperationsBinder
.mBoundListeners
.keySet().iterator(); 
 803         while (listeners
.hasNext()) { 
 804             final OnRemoteOperationListener listener 
= listeners
.next(); 
 805             final Handler handler 
= mOperationsBinder
.mBoundListeners
.get(listener
); 
 806             if (handler 
!= null
) {  
 807                 handler
.post(new Runnable() { 
 810                         listener
.onRemoteOperationFinish(operation
, result
); 
 817             //mOperationResults.put(operation.hashCode(), result); 
 818             Pair
<RemoteOperation
, RemoteOperationResult
> undispatched 
=  
 819                     new Pair
<RemoteOperation
, RemoteOperationResult
>(operation
, result
); 
 820             mUndispatchedFinishedOperations
.put(operation
.hashCode(), undispatched
); 
 822         Log_OC
.d(TAG
, "Called " + count 
+ " listeners");