1 /* ownCloud Android client application 
   2  *   Copyright (C) 2011  Bartek Przybylski 
   3  *   Copyright (C) 2012-2014 ownCloud Inc. 
   5  *   This program is free software: you can redistribute it and/or modify 
   6  *   it under the terms of the GNU General Public License version 2, 
   7  *   as published by the Free Software Foundation. 
   9  *   This program is distributed in the hope that it will be useful, 
  10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of 
  11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
  12  *   GNU General Public License for more details. 
  14  *   You should have received a copy of the GNU General Public License 
  15  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. 
  19 package com
.owncloud
.android
.ui
.activity
; 
  22 import java
.io
.IOException
; 
  24 import android
.accounts
.Account
; 
  25 import android
.accounts
.AccountManager
; 
  26 import android
.accounts
.AuthenticatorException
; 
  27 import android
.accounts
.OperationCanceledException
; 
  28 import android
.app
.AlertDialog
; 
  29 import android
.app
.Dialog
; 
  30 import android
.app
.ProgressDialog
; 
  31 import android
.content
.BroadcastReceiver
; 
  32 import android
.content
.ComponentName
; 
  33 import android
.content
.ContentResolver
; 
  34 import android
.content
.Context
; 
  35 import android
.content
.DialogInterface
; 
  36 import android
.content
.Intent
; 
  37 import android
.content
.IntentFilter
; 
  38 import android
.content
.ServiceConnection
; 
  39 import android
.content
.SharedPreferences
; 
  40 import android
.content
.SyncRequest
; 
  41 import android
.content
.res
.Resources
.NotFoundException
; 
  42 import android
.database
.Cursor
; 
  43 import android
.net
.Uri
; 
  44 import android
.os
.Bundle
; 
  45 import android
.os
.IBinder
; 
  46 import android
.preference
.PreferenceManager
; 
  47 import android
.provider
.MediaStore
; 
  48 import android
.support
.v4
.app
.Fragment
; 
  49 import android
.support
.v4
.app
.FragmentManager
; 
  50 import android
.support
.v4
.app
.FragmentTransaction
; 
  51 import android
.view
.View
; 
  52 import android
.view
.ViewGroup
; 
  53 import android
.widget
.ArrayAdapter
; 
  54 import android
.widget
.TextView
; 
  55 import android
.widget
.Toast
; 
  57 import com
.actionbarsherlock
.app
.ActionBar
; 
  58 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
; 
  59 import com
.actionbarsherlock
.view
.Menu
; 
  60 import com
.actionbarsherlock
.view
.MenuInflater
; 
  61 import com
.actionbarsherlock
.view
.MenuItem
; 
  62 import com
.actionbarsherlock
.view
.Window
; 
  63 import com
.owncloud
.android
.BuildConfig
; 
  64 import com
.owncloud
.android
.MainApp
; 
  65 import com
.owncloud
.android
.R
; 
  66 import com
.owncloud
.android
.datamodel
.OCFile
; 
  67 import com
.owncloud
.android
.files
.services
.FileDownloader
; 
  68 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
; 
  69 import com
.owncloud
.android
.files
.services
.FileUploader
; 
  70 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
; 
  71 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
; 
  72 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
; 
  73 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
; 
  74 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
; 
  75 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
; 
  76 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
; 
  77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
; 
  78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
; 
  79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
; 
  80 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
; 
  81 import com
.owncloud
.android
.operations
.CreateFolderOperation
; 
  82 import com
.owncloud
.android
.operations
.CreateShareOperation
; 
  83 import com
.owncloud
.android
.operations
.MoveFileOperation
; 
  84 import com
.owncloud
.android
.operations
.RemoveFileOperation
; 
  85 import com
.owncloud
.android
.operations
.RenameFileOperation
; 
  86 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
; 
  87 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
; 
  88 import com
.owncloud
.android
.operations
.UnshareLinkOperation
; 
  89 import com
.owncloud
.android
.services
.observer
.FileObserverService
; 
  90 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
; 
  91 import com
.owncloud
.android
.ui
.adapter
.FileListListAdapter
; 
  92 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
; 
  93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
; 
  94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
; 
  95 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
; 
  96 import com
.owncloud
.android
.ui
.fragment
.FileFragment
; 
  97 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
; 
  98 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
; 
  99 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
; 
 100 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
; 
 101 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
; 
 102 import com
.owncloud
.android
.utils
.DisplayUtils
; 
 103 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
; 
 104 import com
.owncloud
.android
.utils
.FileStorageUtils
; 
 108  * Displays, what files the user has available in his ownCloud. 
 110  * @author Bartek Przybylski 
 111  * @author David A. Velasco 
 114 public class FileDisplayActivity 
extends HookActivity 
implements 
 115 FileFragment
.ContainerActivity
, OnNavigationListener
,  
 116 OnSslUntrustedCertListener
, OnEnforceableRefreshListener 
{ 
 118     private ArrayAdapter
<String
> mDirectories
; 
 120     private SyncBroadcastReceiver mSyncBroadcastReceiver
; 
 121     private UploadFinishReceiver mUploadFinishReceiver
; 
 122     private DownloadFinishReceiver mDownloadFinishReceiver
; 
 123     private RemoteOperationResult mLastSslUntrustedServerResult 
= null
; 
 125     private boolean mDualPane
; 
 126     private View mLeftFragmentContainer
; 
 127     private View mRightFragmentContainer
; 
 129     private static final String KEY_WAITING_TO_PREVIEW 
= "WAITING_TO_PREVIEW"; 
 130     private static final String KEY_SYNC_IN_PROGRESS 
= "SYNC_IN_PROGRESS"; 
 131     private static final String KEY_WAITING_TO_SEND 
= "WAITING_TO_SEND"; 
 133     public static final int DIALOG_SHORT_WAIT 
= 0; 
 134     private static final int DIALOG_CHOOSE_UPLOAD_SOURCE 
= 1; 
 135     private static final int DIALOG_CERT_NOT_SAVED 
= 2; 
 137     public static final String ACTION_DETAILS 
= "com.owncloud.android.ui.activity.action.DETAILS"; 
 139     private static final int ACTION_SELECT_CONTENT_FROM_APPS 
= 1; 
 140     private static final int ACTION_SELECT_MULTIPLE_FILES 
= 2; 
 141     public static final int ACTION_MOVE_FILES 
= 3; 
 143     private static final String TAG 
= FileDisplayActivity
.class.getSimpleName(); 
 145     private static final String TAG_LIST_OF_FILES 
= "LIST_OF_FILES"; 
 146     private static final String TAG_SECOND_FRAGMENT 
= "SECOND_FRAGMENT"; 
 148     private OCFile mWaitingToPreview
; 
 150     private boolean mSyncInProgress 
= false
; 
 152     private String DIALOG_UNTRUSTED_CERT
; 
 154     private OCFile mWaitingToSend
; 
 157     protected void onCreate(Bundle savedInstanceState
) { 
 158         Log_OC
.d(TAG
, "onCreate() start"); 
 159         requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
); 
 161         super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid 
 163         // PIN CODE request ;  best location is to decide, let's try this first 
 164         if (getIntent().getAction() != null 
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState 
== null
) { 
 166         } else if (getIntent().getAction() == null 
&& savedInstanceState 
== null
) { 
 170         /// grant that FileObserverService is watching favourite files 
 171         if (savedInstanceState 
== null
) { 
 172             Intent initObserversIntent 
= FileObserverService
.makeInitIntent(this); 
 173             startService(initObserversIntent
); 
 176         /// Load of saved instance state 
 177         if(savedInstanceState 
!= null
) { 
 178             mWaitingToPreview 
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
); 
 179             mSyncInProgress 
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
); 
 180             mWaitingToSend 
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
); 
 183             mWaitingToPreview 
= null
; 
 184             mSyncInProgress 
= false
; 
 185             mWaitingToSend 
= null
; 
 190         // Inflate and set the layout view 
 191         setContentView(R
.layout
.files
);     
 192         mDualPane 
= getResources().getBoolean(R
.bool
.large_land_layout
); 
 193         mLeftFragmentContainer 
= findViewById(R
.id
.left_fragment_container
); 
 194         mRightFragmentContainer 
= findViewById(R
.id
.right_fragment_container
); 
 195         if (savedInstanceState 
== null
) { 
 196             createMinFragments(); 
 200         mDirectories 
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
); 
 201         getSupportActionBar().setHomeButtonEnabled(true
);       // mandatory since Android ICS, according to the official documentation 
 202         setSupportProgressBarIndeterminateVisibility(mSyncInProgress 
/*|| mRefreshSharesInProgress*/);    // always AFTER setContentView(...) ; to work around bug in its implementation 
 206         Log_OC
.d(TAG
, "onCreate() end"); 
 210     protected void onStart() { 
 212         getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId()); 
 216     protected void onDestroy() { 
 221      *  Called when the ownCloud {@link Account} associated to the Activity was just updated. 
 224     protected void onAccountSet(boolean stateWasRecovered
) { 
 225         super.onAccountSet(stateWasRecovered
); 
 226         if (getAccount() != null
) { 
 227             /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account 
 228             OCFile file 
= getFile(); 
 229             // get parent from path 
 230             String parentPath 
= ""; 
 232                 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) { 
 233                     // upload in progress - right now, files are not inserted in the local cache until the upload is successful 
 234                     // get parent from path 
 235                     parentPath 
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName())); 
 236                     if (getStorageManager().getFileByPath(parentPath
) ==  null
) 
 237                         file 
= null
; // not able to know the directory where the file is uploading 
 239                     file 
= getStorageManager().getFileByPath(file
.getRemotePath());   // currentDir = null if not in the current Account 
 243                 // fall back to root folder 
 244                 file 
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);  // never returns null 
 247             setNavigationListWithFolder(file
); 
 249             if (!stateWasRecovered
) { 
 250                 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged.."); 
 251                 initFragmentsWithFile(); 
 252                 if (file
.isFolder()) { 
 253                     startSyncFolderOperation(file
, false
); 
 257                 updateFragmentsVisibility(!file
.isFolder()); 
 258                 updateNavigationElementsInActionBar(file
.isFolder() ? null 
: file
); 
 264     private void setNavigationListWithFolder(OCFile file
) { 
 265         mDirectories
.clear(); 
 266         OCFile fileIt 
= file
; 
 268         while(fileIt 
!= null 
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) { 
 269             if (fileIt
.isFolder()) { 
 270                 mDirectories
.add(fileIt
.getFileName()); 
 272             // get parent from path 
 273             parentPath 
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName())); 
 274             fileIt 
= getStorageManager().getFileByPath(parentPath
); 
 276         mDirectories
.add(OCFile
.PATH_SEPARATOR
); 
 280     private void createMinFragments() { 
 281         OCFileListFragment listOfFiles 
= new OCFileListFragment(); 
 282         FragmentTransaction transaction 
= getSupportFragmentManager().beginTransaction(); 
 283         transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
); 
 284         transaction
.commit(); 
 287     private void initFragmentsWithFile() { 
 288         if (getAccount() != null 
&& getFile() != null
) { 
 290             OCFileListFragment listOfFiles 
= getListOfFilesFragment();  
 291             if (listOfFiles 
!= null
) { 
 292                 listOfFiles
.listDirectory(getCurrentDir());    
 294                 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >("); 
 298             OCFile file 
= getFile();  
 299             Fragment secondFragment 
= chooseInitialSecondFragment(file
); 
 300             if (secondFragment 
!= null
) { 
 301                 setSecondFragment(secondFragment
); 
 302                 updateFragmentsVisibility(true
); 
 303                 updateNavigationElementsInActionBar(file
); 
 306                 cleanSecondFragment(); 
 310             Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!"); 
 311             if (getAccount() == null
) { 
 312                 Log_OC
.wtf(TAG
, "\t account is NULL"); 
 314             if (getFile() == null
) { 
 315                 Log_OC
.wtf(TAG
, "\t file is NULL"); 
 320     private Fragment 
chooseInitialSecondFragment(OCFile file
) { 
 321         Fragment secondFragment 
= null
; 
 322         if (file 
!= null 
&& !file
.isFolder()) { 
 323             if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)  
 324                     && file
.getLastSyncDateForProperties() > 0  // temporal fix 
 326                 int startPlaybackPosition 
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0); 
 327                 boolean autoplay 
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
); 
 328                 secondFragment 
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
); 
 331                 secondFragment 
= new FileDetailFragment(file
, getAccount()); 
 334         return secondFragment
; 
 339      * Replaces the second fragment managed by the activity with the received as 
 342      * Assumes never will be more than two fragments managed at the same time.  
 344      * @param fragment      New second Fragment to set. 
 346     private void setSecondFragment(Fragment fragment
) { 
 347         FragmentTransaction transaction 
= getSupportFragmentManager().beginTransaction(); 
 348         transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
); 
 349         transaction
.commit(); 
 353     private void updateFragmentsVisibility(boolean existsSecondFragment
) { 
 355             if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) { 
 356                 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
); 
 358             if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) { 
 359                 mRightFragmentContainer
.setVisibility(View
.VISIBLE
); 
 362         } else if (existsSecondFragment
) { 
 363             if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) { 
 364                 mLeftFragmentContainer
.setVisibility(View
.GONE
); 
 366             if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) { 
 367                 mRightFragmentContainer
.setVisibility(View
.VISIBLE
); 
 371             if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) { 
 372                 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
); 
 374             if (mRightFragmentContainer
.getVisibility() != View
.GONE
) { 
 375                 mRightFragmentContainer
.setVisibility(View
.GONE
); 
 381     private OCFileListFragment 
getListOfFilesFragment() { 
 382         Fragment listOfFiles 
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
); 
 383         if (listOfFiles 
!= null
) { 
 384             return (OCFileListFragment
)listOfFiles
; 
 386         Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!"); 
 390     public FileFragment 
getSecondFragment() { 
 391         Fragment second 
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
); 
 392         if (second 
!= null
) { 
 393             return (FileFragment
)second
; 
 398     protected void cleanSecondFragment() { 
 399         Fragment second 
= getSecondFragment(); 
 400         if (second 
!= null
) { 
 401             FragmentTransaction tr 
= getSupportFragmentManager().beginTransaction(); 
 405         updateFragmentsVisibility(false
); 
 406         updateNavigationElementsInActionBar(null
); 
 409     protected void refreshListOfFilesFragment() { 
 410         OCFileListFragment fileListFragment 
= getListOfFilesFragment(); 
 411         if (fileListFragment 
!= null
) {  
 412             fileListFragment
.listDirectory(); 
 416     protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) { 
 417         FileFragment secondFragment 
= getSecondFragment(); 
 418         boolean waitedPreview 
= (mWaitingToPreview 
!= null 
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
)); 
 419         if (secondFragment 
!= null 
&& secondFragment 
instanceof FileDetailFragment
) { 
 420             FileDetailFragment detailsFragment 
= (FileDetailFragment
) secondFragment
; 
 421             OCFile fileInFragment 
= detailsFragment
.getFile(); 
 422             if (fileInFragment 
!= null 
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) { 
 423                 // the user browsed to other file ; forget the automatic preview  
 424                 mWaitingToPreview 
= null
; 
 426             } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) { 
 427                 // grant that the right panel updates the progress bar 
 428                 detailsFragment
.listenForTransferProgress(); 
 429                 detailsFragment
.updateFileDetails(true
, false
); 
 431             } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) { 
 432                 //  update the right panel 
 433                 boolean detailsFragmentChanged 
= false
; 
 436                         mWaitingToPreview 
= getStorageManager().getFileById(mWaitingToPreview
.getFileId());   // update the file from database, for the local storage path 
 437                         if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) { 
 438                             startMediaPreview(mWaitingToPreview
, 0, true
); 
 439                             detailsFragmentChanged 
= true
; 
 441                             getFileOperationsHelper().openFile(mWaitingToPreview
); 
 444                     mWaitingToPreview 
= null
; 
 446                 if (!detailsFragmentChanged
) { 
 447                     detailsFragment
.updateFileDetails(false
, (success
)); 
 454     public boolean onPrepareOptionsMenu(Menu menu
) { 
 455         if (BuildConfig
.DEBUG
) { 
 456             menu
.findItem(R
.id
.action_logger
).setVisible(true
); 
 458             menu
.findItem(R
.id
.action_logger
).setVisible(false
); 
 460         return super.onPrepareOptionsMenu(menu
); 
 464     public boolean onCreateOptionsMenu(Menu menu
) { 
 465         MenuInflater inflater 
= getSherlock().getMenuInflater(); 
 466         inflater
.inflate(R
.menu
.main_menu
, menu
); 
 471     public boolean onOptionsItemSelected(MenuItem item
) { 
 472         boolean retval 
= true
; 
 473         switch (item
.getItemId()) { 
 474         case R
.id
.action_create_dir
: { 
 475             CreateFolderDialogFragment dialog 
=  
 476                     CreateFolderDialogFragment
.newInstance(getCurrentDir()); 
 477             dialog
.show(getSupportFragmentManager(), "createdirdialog"); 
 480         case R
.id
.action_sync_account
: { 
 481             startSynchronization(); 
 484         case R
.id
.action_upload
: { 
 485             showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
); 
 488         case R
.id
.action_settings
: { 
 489             Intent settingsIntent 
= new Intent(this, Preferences
.class); 
 490             startActivity(settingsIntent
); 
 493         case R
.id
.action_logger
: { 
 494             Intent loggerIntent 
= new Intent(getApplicationContext(),LogHistoryActivity
.class); 
 495             startActivity(loggerIntent
); 
 498         case android
.R
.id
.home
: { 
 499             FileFragment second 
= getSecondFragment(); 
 500             OCFile currentDir 
= getCurrentDir(); 
 501             if((currentDir 
!= null 
&& currentDir
.getParentId() != 0) ||  
 502                     (second 
!= null 
&& second
.getFile() != null
)) {                 
 508         case R
.id
.action_sort
: { 
 509             SharedPreferences appPreferences 
= PreferenceManager
 
 510                     .getDefaultSharedPreferences(this); 
 512             // Read sorting order, default to sort by name ascending 
 513             Integer sortOrder 
= appPreferences
 
 514                     .getInt("sortOrder", FileStorageUtils
.SORT_NAME
); 
 516             AlertDialog
.Builder builder 
= new AlertDialog
.Builder(this); 
 517             builder
.setTitle(R
.string
.actionbar_sort_title
) 
 518             .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder 
, new DialogInterface
.OnClickListener() { 
 519                 public void onClick(DialogInterface dialog
, int which
) { 
 529 // TODO re-enable when server-side folder size calculation is available                        
 531 //                        sortBySize(false); 
 539             builder
.create().show(); 
 543             retval 
= super.onOptionsItemSelected(item
); 
 548     private void startSynchronization() { 
 549         Log_OC
.e(TAG
, "Got to start sync"); 
 550         if (android
.os
.Build
.VERSION
.SDK_INT 
< android
.os
.Build
.VERSION_CODES
.KITKAT
) { 
 551             Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority()); 
 552             ContentResolver
.cancelSync(null
, MainApp
.getAuthority());   // cancel the current synchronizations of any ownCloud account 
 553             Bundle bundle 
= new Bundle(); 
 554             bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
); 
 555             bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
); 
 556             Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name 
+ " at " + MainApp
.getAuthority()); 
 557             ContentResolver
.requestSync( 
 559                     MainApp
.getAuthority(), bundle
); 
 561             Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name 
+ " at " + MainApp
.getAuthority() + " with new API"); 
 562             SyncRequest
.Builder builder 
= new SyncRequest
.Builder(); 
 563             builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority()); 
 564             builder
.setExpedited(true
); 
 565             builder
.setManual(true
); 
 567             SyncRequest request 
= builder
.build(); 
 568             ContentResolver
.requestSync(request
); 
 574     public boolean onNavigationItemSelected(int itemPosition
, long itemId
) { 
 575         if (itemPosition 
!= 0) { 
 576             String targetPath 
= ""; 
 577             for (int i
=itemPosition
; i 
< mDirectories
.getCount() - 1; i
++) { 
 578                 targetPath 
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR 
+ targetPath
;  
 580             targetPath 
= OCFile
.PATH_SEPARATOR 
+ targetPath
; 
 581             OCFile targetFolder 
= getStorageManager().getFileByPath(targetPath
); 
 582             if (targetFolder 
!= null
) { 
 583                 browseTo(targetFolder
); 
 586             // the next operation triggers a new call to this method, but it's necessary to  
 587             // ensure that the name exposed in the action bar is the current directory when the  
 588             // user selected it in the navigation list 
 589             if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST  
&& itemPosition 
!= 0)  
 590                 getSupportActionBar().setSelectedNavigationItem(0); 
 596      * Called, when the user selected something for uploading 
 598     protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) { 
 599         super.onActivityResult(requestCode
, resultCode
, data
); 
 601         if (requestCode 
== ACTION_SELECT_CONTENT_FROM_APPS 
&& (resultCode 
== RESULT_OK 
|| resultCode 
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) { 
 602             requestSimpleUpload(data
, resultCode
); 
 604         } else if (requestCode 
== ACTION_SELECT_MULTIPLE_FILES 
&& (resultCode 
== RESULT_OK 
|| resultCode 
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) { 
 605             requestMultipleUpload(data
, resultCode
); 
 607         } else if (requestCode 
== ACTION_MOVE_FILES 
&& (resultCode 
== RESULT_OK 
||  
 608                 resultCode 
== MoveActivity
.RESULT_OK_AND_MOVE
)){ 
 610             final Intent fData 
= data
; 
 611             final int fResultCode 
= resultCode
;  
 612             getHandler().postDelayed( 
 616                         requestMoveOperation(fData
, fResultCode
); 
 619                 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
 
 624     private void requestMultipleUpload(Intent data
, int resultCode
) { 
 625         String
[] filePaths 
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
); 
 626         if (filePaths 
!= null
) { 
 627             String
[] remotePaths 
= new String
[filePaths
.length
]; 
 628             String remotePathBase 
= ""; 
 629             for (int j 
= mDirectories
.getCount() - 2; j 
>= 0; --j
) { 
 630                 remotePathBase 
+= OCFile
.PATH_SEPARATOR 
+ mDirectories
.getItem(j
); 
 632             if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
)) 
 633                 remotePathBase 
+= OCFile
.PATH_SEPARATOR
; 
 634             for (int j 
= 0; j
< remotePaths
.length
; j
++) { 
 635                 remotePaths
[j
] = remotePathBase 
+ (new File(filePaths
[j
])).getName(); 
 638             Intent i 
= new Intent(this, FileUploader
.class); 
 639             i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount()); 
 640             i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
); 
 641             i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
); 
 642             i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
); 
 643             if (resultCode 
== UploadFilesActivity
.RESULT_OK_AND_MOVE
) 
 644                 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
); 
 648             Log_OC
.d(TAG
, "User clicked on 'Update' with no selection"); 
 649             Toast t 
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
); 
 656     private void requestSimpleUpload(Intent data
, int resultCode
) { 
 657         String filepath 
= null
; 
 659             Uri selectedImageUri 
= data
.getData(); 
 661             String filemanagerstring 
= selectedImageUri
.getPath(); 
 662             String selectedImagePath 
= getPath(selectedImageUri
); 
 664             if (selectedImagePath 
!= null
) 
 665                 filepath 
= selectedImagePath
; 
 667                 filepath 
= filemanagerstring
; 
 669         } catch (Exception e
) { 
 670             Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
); 
 674             if (filepath 
== null
) { 
 675                 Log_OC
.e(TAG
, "Couldnt resolve path to file"); 
 676                 Toast t 
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
); 
 682         Intent i 
= new Intent(this, FileUploader
.class); 
 683         i
.putExtra(FileUploader
.KEY_ACCOUNT
, 
 685         String remotepath 
= new String(); 
 686         for (int j 
= mDirectories
.getCount() - 2; j 
>= 0; --j
) { 
 687             remotepath 
+= OCFile
.PATH_SEPARATOR 
+ mDirectories
.getItem(j
); 
 689         if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
)) 
 690             remotepath 
+= OCFile
.PATH_SEPARATOR
; 
 691         remotepath 
+= new File(filepath
).getName(); 
 693         i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
); 
 694         i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
); 
 695         i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
); 
 696         if (resultCode 
== UploadFilesActivity
.RESULT_OK_AND_MOVE
) 
 697             i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
); 
 702      * Request the operation for moving the file/folder from one path to another 
 704      * @param data              Intent received 
 705      * @param resultCode        Result code received 
 707     private void requestMoveOperation(Intent data
, int resultCode
) { 
 708         OCFile folderToMoveAt 
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
); 
 709         OCFile targetFile 
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
); 
 710         getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
); 
 714     public void onBackPressed() { 
 715         OCFileListFragment listOfFiles 
= getListOfFilesFragment();  
 716         if (mDualPane 
|| getSecondFragment() == null
) { 
 717             if (listOfFiles 
!= null
) {  // should never be null, indeed 
 718                 if (mDirectories
.getCount() <= 1) { 
 722                 int levelsUp 
= listOfFiles
.onBrowseUp(); 
 723                 for (int i
=0; i 
< levelsUp 
&& mDirectories
.getCount() > 1 ; i
++) { 
 728         if (listOfFiles 
!= null
) {  // should never be null, indeed 
 729             setFile(listOfFiles
.getCurrentFile()); 
 731         cleanSecondFragment(); 
 736     protected void onSaveInstanceState(Bundle outState
) { 
 737         // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved 
 738         Log_OC
.e(TAG
, "onSaveInstanceState() start"); 
 739         super.onSaveInstanceState(outState
); 
 740         outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
); 
 741         outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
); 
 742         //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress); 
 743         outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
); 
 745         Log_OC
.d(TAG
, "onSaveInstanceState() end"); 
 751     protected void onResume() { 
 753         Log_OC
.e(TAG
, "onResume() start"); 
 755         // refresh list of files 
 756         refreshListOfFilesFragment(); 
 758         // Listen for sync messages 
 759         IntentFilter syncIntentFilter 
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
); 
 760         syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
); 
 761         syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
); 
 762         syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
); 
 763         syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
); 
 764         mSyncBroadcastReceiver 
= new SyncBroadcastReceiver(); 
 765         registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
); 
 766         //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter); 
 768         // Listen for upload messages 
 769         IntentFilter uploadIntentFilter 
= new IntentFilter(FileUploader
.getUploadFinishMessage()); 
 770         mUploadFinishReceiver 
= new UploadFinishReceiver(); 
 771         registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
); 
 773         // Listen for download messages 
 774         IntentFilter downloadIntentFilter 
= new IntentFilter(FileDownloader
.getDownloadAddedMessage()); 
 775         downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage()); 
 776         mDownloadFinishReceiver 
= new DownloadFinishReceiver(); 
 777         registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
); 
 779         Log_OC
.d(TAG
, "onResume() end"); 
 784     protected void onPause() { 
 785         Log_OC
.e(TAG
, "onPause() start"); 
 786         if (mSyncBroadcastReceiver 
!= null
) { 
 787             unregisterReceiver(mSyncBroadcastReceiver
); 
 788             //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver); 
 789             mSyncBroadcastReceiver 
= null
; 
 791         if (mUploadFinishReceiver 
!= null
) { 
 792             unregisterReceiver(mUploadFinishReceiver
); 
 793             mUploadFinishReceiver 
= null
; 
 795         if (mDownloadFinishReceiver 
!= null
) { 
 796             unregisterReceiver(mDownloadFinishReceiver
); 
 797             mDownloadFinishReceiver 
= null
; 
 801         Log_OC
.d(TAG
, "onPause() end"); 
 807     protected Dialog 
onCreateDialog(int id
) { 
 808         Dialog dialog 
= null
; 
 809         AlertDialog
.Builder builder
; 
 811         case DIALOG_SHORT_WAIT
: { 
 812             ProgressDialog working_dialog 
= new ProgressDialog(this); 
 813             working_dialog
.setMessage(getResources().getString( 
 814                     R
.string
.wait_a_moment
)); 
 815             working_dialog
.setIndeterminate(true
); 
 816             working_dialog
.setCancelable(false
); 
 817             dialog 
= working_dialog
; 
 820         case DIALOG_CHOOSE_UPLOAD_SOURCE
: { 
 823             String
[] allTheItems 
= { getString(R
.string
.actionbar_upload_files
), 
 824                     getString(R
.string
.actionbar_upload_from_apps
) }; 
 826             builder 
= new AlertDialog
.Builder(this); 
 827             builder
.setTitle(R
.string
.actionbar_upload
); 
 828             builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() { 
 829                 public void onClick(DialogInterface dialog
, int item
) { 
 832                             Intent action 
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class); 
 833                             action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount()); 
 834                             startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
); 
 836                             // TODO create and handle new fragment 
 837                             // LocalFileListFragment 
 839                     } else if (item 
== 1) { 
 840                         Intent action 
= new Intent(Intent
.ACTION_GET_CONTENT
); 
 841                         action 
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
); 
 842                         startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)), 
 843                                 ACTION_SELECT_CONTENT_FROM_APPS
); 
 847             dialog 
= builder
.create(); 
 850         case DIALOG_CERT_NOT_SAVED
: { 
 851             builder 
= new AlertDialog
.Builder(this); 
 852             builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
)); 
 853             builder
.setCancelable(false
); 
 854             builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() { 
 856                 public void onClick(DialogInterface dialog
, int which
) { 
 860             dialog 
= builder
.create(); 
 872      * Translates a content URI of an image to a physical path 
 874      * @param uri The URI to resolve 
 875      * @return The path to the image or null if it could not be found 
 877     public String 
getPath(Uri uri
) { 
 878         String
[] projection 
= { MediaStore
.Images
.Media
.DATA 
}; 
 879         Cursor cursor 
= managedQuery(uri
, projection
, null
, null
, null
); 
 880         if (cursor 
!= null
) { 
 881             int column_index 
= cursor
 
 882                     .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
); 
 883             cursor
.moveToFirst(); 
 884             return cursor
.getString(column_index
); 
 890      * Pushes a directory to the drop down list 
 891      * @param directory to push 
 892      * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false. 
 894     public void pushDirname(OCFile directory
) { 
 895         if(!directory
.isFolder()){ 
 896             throw new IllegalArgumentException("Only directories may be pushed!"); 
 898         mDirectories
.insert(directory
.getFileName(), 0); 
 903      * Pops a directory name from the drop down list 
 904      * @return True, unless the stack is empty 
 906     public boolean popDirname() { 
 907         mDirectories
.remove(mDirectories
.getItem(0)); 
 908         return !mDirectories
.isEmpty(); 
 911     // Custom array adapter to override text colors 
 912     private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> { 
 914         public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) { 
 918         public View 
getView(int position
, View convertView
, ViewGroup parent
) { 
 919             View v 
= super.getView(position
, convertView
, parent
); 
 921             ((TextView
) v
).setTextColor(getResources().getColorStateList( 
 922                     android
.R
.color
.white
)); 
 924             fixRoot((TextView
) v 
); 
 928         public View 
getDropDownView(int position
, View convertView
, 
 930             View v 
= super.getDropDownView(position
, convertView
, parent
); 
 932             ((TextView
) v
).setTextColor(getResources().getColorStateList( 
 933                     android
.R
.color
.white
)); 
 935             fixRoot((TextView
) v 
); 
 939         private void fixRoot(TextView v
) { 
 940             if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) { 
 941                 v
.setText(R
.string
.default_display_name_for_root_folder
); 
 947     private class SyncBroadcastReceiver 
extends BroadcastReceiver 
{ 
 950          * {@link BroadcastReceiver} to enable syncing feedback in UI 
 953         public void onReceive(Context context
, Intent intent
) { 
 955                 String event 
= intent
.getAction(); 
 956                 Log_OC
.d(TAG
, "Received broadcast " + event
); 
 957                 String accountName 
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
); 
 958                 String synchFolderRemotePath 
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);  
 959                 RemoteOperationResult synchResult 
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
); 
 960                 boolean sameAccount 
= (getAccount() != null 
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);  
 964                     if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) { 
 965                         mSyncInProgress 
= true
; 
 968                         OCFile currentFile 
= (getFile() == null
) ? null 
: getStorageManager().getFileByPath(getFile().getRemotePath()); 
 969                         OCFile currentDir 
= (getCurrentDir() == null
) ? null 
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath()); 
 971                         if (currentDir 
== null
) { 
 972                             // current folder was removed from the server  
 973                             Toast
.makeText( FileDisplayActivity
.this,  
 974                                             String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),  
 980                             if (currentFile 
== null 
&& !getFile().isFolder()) { 
 981                                 // currently selected file was removed in the server, and now we know it 
 982                                 cleanSecondFragment(); 
 983                                 currentFile 
= currentDir
; 
 986                             if (synchFolderRemotePath 
!= null 
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) { 
 987                                 OCFileListFragment fileListFragment 
= getListOfFilesFragment(); 
 988                                 if (fileListFragment 
!= null
) { 
 989                                     fileListFragment
.listDirectory(currentDir
); 
 992                             setFile(currentFile
); 
 995                         mSyncInProgress 
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
)); 
 997                         if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
. 
 999                                 /// TODO refactor and make common 
1000                                 synchResult 
!= null 
&& !synchResult
.isSuccess() &&   
1001                                 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED   
||  
1002                                     synchResult
.isIdPRedirection()                  || 
1003                                     (synchResult
.isException() && synchResult
.getException()  
1004                                             instanceof AuthenticatorException
))) { 
1006                             OwnCloudClient client 
= null
; 
1008                                 OwnCloudAccount ocAccount 
=  
1009                                         new OwnCloudAccount(getAccount(), context
); 
1010                                 client 
= (OwnCloudClientManagerFactory
.getDefaultSingleton(). 
1011                                         removeClientFor(ocAccount
)); 
1012                                 // TODO get rid of these exceptions 
1013                             } catch (AccountNotFoundException e
) { 
1014                                 e
.printStackTrace(); 
1015                             } catch (AuthenticatorException e
) { 
1016                                 e
.printStackTrace(); 
1017                             } catch (OperationCanceledException e
) { 
1018                                 e
.printStackTrace(); 
1019                             } catch (IOException e
) { 
1020                                 e
.printStackTrace(); 
1023                             if (client 
!= null
) { 
1024                                 OwnCloudCredentials cred 
= client
.getCredentials(); 
1026                                     AccountManager am 
= AccountManager
.get(context
); 
1027                                     if (cred
.authTokenExpires()) { 
1028                                         am
.invalidateAuthToken( 
1033                                         am
.clearPassword(getAccount()); 
1038                             requestCredentialsUpdate(); 
1042                     removeStickyBroadcast(intent
); 
1043                     Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
); 
1044                     setSupportProgressBarIndeterminateVisibility(mSyncInProgress 
/*|| mRefreshSharesInProgress*/); 
1046                     setBackgroundText(); 
1050                 if (synchResult 
!= null
) { 
1051                     if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) { 
1052                         mLastSslUntrustedServerResult 
= synchResult
; 
1055             } catch (RuntimeException e
) { 
1056                 // avoid app crashes after changing the serial id of RemoteOperationResult  
1057                 // in owncloud library with broadcast notifications pending to process 
1058                 removeStickyBroadcast(intent
); 
1064      * Show a text message on screen view for notifying user if content is 
1065      * loading or folder is empty 
1067     private void setBackgroundText() { 
1068         OCFileListFragment ocFileListFragment 
= getListOfFilesFragment(); 
1069         if (ocFileListFragment 
!= null
) { 
1070             int message 
= R
.string
.file_list_loading
; 
1071             if (!mSyncInProgress
) { 
1072                 // In case file list is empty 
1073                 message 
= R
.string
.file_list_empty
; 
1075             ocFileListFragment
.setMessageForEmptyList(getString(message
)); 
1077             Log_OC
.e(TAG
, "OCFileListFragment is null"); 
1082      * Once the file upload has finished -> update view 
1084     private class UploadFinishReceiver 
extends BroadcastReceiver 
{ 
1086          * Once the file upload has finished -> update view 
1087          *  @author David A. Velasco 
1088          * {@link BroadcastReceiver} to enable upload feedback in UI 
1091         public void onReceive(Context context
, Intent intent
) { 
1093                 String uploadedRemotePath 
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
); 
1094                 String accountName 
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
); 
1095                 boolean sameAccount 
= getAccount() != null 
&& accountName
.equals(getAccount().name
); 
1096                 OCFile currentDir 
= getCurrentDir(); 
1097                 boolean isDescendant 
= (currentDir 
!= null
) && (uploadedRemotePath 
!= null
) &&  
1098                         (uploadedRemotePath
.startsWith(currentDir
.getRemotePath())); 
1100                 if (sameAccount 
&& isDescendant
) { 
1101                     refreshListOfFilesFragment(); 
1104                 boolean uploadWasFine 
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
); 
1105                 boolean renamedInUpload 
= getFile().getRemotePath(). 
1106                         equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
)); 
1107                 boolean sameFile 
= getFile().getRemotePath().equals(uploadedRemotePath
) ||  
1109                 FileFragment details 
= getSecondFragment(); 
1110                 boolean detailFragmentIsShown 
= (details 
!= null 
&&  
1111                         details 
instanceof FileDetailFragment
); 
1113                 if (sameAccount 
&& sameFile 
&& detailFragmentIsShown
) { 
1114                     if (uploadWasFine
) { 
1115                         setFile(getStorageManager().getFileByPath(uploadedRemotePath
)); 
1117                     if (renamedInUpload
) { 
1118                         String newName 
= (new File(uploadedRemotePath
)).getName(); 
1119                         Toast msg 
= Toast
.makeText( 
1122                                         getString(R
.string
.filedetails_renamed_in_upload_msg
),  
1127                     if (uploadWasFine 
|| getFile().fileExists()) { 
1128                         ((FileDetailFragment
)details
).updateFileDetails(false
, true
); 
1130                         cleanSecondFragment(); 
1133                     // Force the preview if the file is an image 
1134                     if (uploadWasFine 
&& PreviewImageFragment
.canBePreviewed(getFile())) { 
1135                         startImagePreview(getFile()); 
1136                     } // TODO what about other kind of previews? 
1140                 if (intent 
!= null
) { 
1141                     removeStickyBroadcast(intent
); 
1151      * Class waiting for broadcast events from the {@link FielDownloader} service. 
1153      * Updates the UI when a download is started or finished, provided that it is relevant for the 
1156     private class DownloadFinishReceiver 
extends BroadcastReceiver 
{ 
1158         public void onReceive(Context context
, Intent intent
) { 
1160                 boolean sameAccount 
= isSameAccount(context
, intent
); 
1161                 String downloadedRemotePath 
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
); 
1162                 boolean isDescendant 
= isDescendant(downloadedRemotePath
); 
1164                 if (sameAccount 
&& isDescendant
) { 
1165                     refreshListOfFilesFragment(); 
1166                     refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)); 
1169                 if (mWaitingToSend 
!= null
) { 
1170                     mWaitingToSend 
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send 
1171                     if (mWaitingToSend
.isDown()) {  
1172                         sendDownloadedFile(); 
1177                 if (intent 
!= null
) { 
1178                     removeStickyBroadcast(intent
); 
1183         private boolean isDescendant(String downloadedRemotePath
) { 
1184             OCFile currentDir 
= getCurrentDir(); 
1185             return (currentDir 
!= null 
&& downloadedRemotePath 
!= null 
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath())); 
1188         private boolean isSameAccount(Context context
, Intent intent
) { 
1189             String accountName 
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
); 
1190             return (accountName 
!= null 
&& getAccount() != null 
&& accountName
.equals(getAccount().name
)); 
1195     public void browseToRoot() { 
1196         OCFileListFragment listOfFiles 
= getListOfFilesFragment();  
1197         if (listOfFiles 
!= null
) {  // should never be null, indeed 
1198             while (mDirectories
.getCount() > 1) { 
1201             OCFile root 
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); 
1202             listOfFiles
.listDirectory(root
); 
1203             setFile(listOfFiles
.getCurrentFile()); 
1204             startSyncFolderOperation(root
, false
); 
1206         cleanSecondFragment(); 
1210     public void browseTo(OCFile folder
) { 
1211         if (folder 
== null 
|| !folder
.isFolder()) { 
1212             throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
); 
1214         OCFileListFragment listOfFiles 
= getListOfFilesFragment();  
1215         if (listOfFiles 
!= null
) { 
1216             setNavigationListWithFolder(folder
); 
1217             listOfFiles
.listDirectory(folder
); 
1218             setFile(listOfFiles
.getCurrentFile()); 
1219             startSyncFolderOperation(folder
, false
); 
1221             Log_OC
.e(TAG
, "Unexpected null when accessing list fragment"); 
1223         cleanSecondFragment(); 
1230      * Updates action bar and second fragment, if in dual pane mode. 
1233     public void onBrowsedDownTo(OCFile directory
) { 
1234         pushDirname(directory
); 
1235         cleanSecondFragment(); 
1238         startSyncFolderOperation(directory
, false
); 
1243      * Shows the information of the {@link OCFile} received as a  
1244      * parameter in the second fragment. 
1246      * @param file          {@link OCFile} whose details will be shown 
1249     public void showDetails(OCFile file
) { 
1250         Fragment detailFragment 
= new FileDetailFragment(file
, getAccount()); 
1251         setSecondFragment(detailFragment
); 
1252         updateFragmentsVisibility(true
); 
1253         updateNavigationElementsInActionBar(file
); 
1261     private void updateNavigationElementsInActionBar(OCFile chosenFile
) { 
1262         ActionBar actionBar 
= getSupportActionBar();  
1263         if (chosenFile 
== null 
|| mDualPane
) { 
1264             // only list of files - set for browsing through folders 
1265             OCFile currentDir 
= getCurrentDir(); 
1266             boolean noRoot 
= (currentDir 
!= null 
&& currentDir
.getParentId() != 0); 
1267             actionBar
.setDisplayHomeAsUpEnabled(noRoot
); 
1268             actionBar
.setDisplayShowTitleEnabled(!noRoot
);  
1270                 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
)); 
1272             actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD 
: ActionBar
.NAVIGATION_MODE_LIST
); 
1273             actionBar
.setListNavigationCallbacks(mDirectories
, this);   // assuming mDirectories is updated 
1276             actionBar
.setDisplayHomeAsUpEnabled(true
); 
1277             actionBar
.setDisplayShowTitleEnabled(true
); 
1278             actionBar
.setTitle(chosenFile
.getFileName()); 
1279             actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
); 
1285     protected ServiceConnection 
newTransferenceServiceConnection() { 
1286         return new ListServiceConnection(); 
1289     /** Defines callbacks for service binding, passed to bindService() */ 
1290     private class ListServiceConnection 
implements ServiceConnection 
{ 
1293         public void onServiceConnected(ComponentName component
, IBinder service
) { 
1294             if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) { 
1295                 Log_OC
.d(TAG
, "Download service connected"); 
1296                 mDownloaderBinder 
= (FileDownloaderBinder
) service
; 
1297                 if (mWaitingToPreview 
!= null
) 
1298                     if (getStorageManager() != null
) { 
1299                         mWaitingToPreview 
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file 
1300                         if (!mWaitingToPreview
.isDown()) { 
1301                             requestForDownload(); 
1305             } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) { 
1306                 Log_OC
.d(TAG
, "Upload service connected"); 
1307                 mUploaderBinder 
= (FileUploaderBinder
) service
; 
1311             // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS 
1312             OCFileListFragment listOfFiles 
= getListOfFilesFragment();  
1313             if (listOfFiles 
!= null
) { 
1314                 listOfFiles
.listDirectory(); 
1316             FileFragment secondFragment 
= getSecondFragment(); 
1317             if (secondFragment 
!= null 
&& secondFragment 
instanceof FileDetailFragment
) { 
1318                 FileDetailFragment detailFragment 
= (FileDetailFragment
)secondFragment
; 
1319                 detailFragment
.listenForTransferProgress(); 
1320                 detailFragment
.updateFileDetails(false
, false
); 
1325         public void onServiceDisconnected(ComponentName component
) { 
1326             if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) { 
1327                 Log_OC
.d(TAG
, "Download service disconnected"); 
1328                 mDownloaderBinder 
= null
; 
1329             } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) { 
1330                 Log_OC
.d(TAG
, "Upload service disconnected"); 
1331                 mUploaderBinder 
= null
; 
1339      * Launch an intent to request the PIN code to the user before letting him use the app 
1341     private void requestPinCode() { 
1342         boolean pinStart 
= false
; 
1343         SharedPreferences appPrefs 
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext()); 
1344         pinStart 
= appPrefs
.getBoolean("set_pincode", false
); 
1346             Intent i 
= new Intent(getApplicationContext(), PinCodeActivity
.class); 
1347             i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity"); 
1354     public void onSavedCertificate() { 
1355         startSyncFolderOperation(getCurrentDir(), false
); 
1360     public void onFailedSavingCertificate() { 
1361         showDialog(DIALOG_CERT_NOT_SAVED
); 
1365     public void onCancelCertificate() { 
1370      * Updates the view associated to the activity after the finish of some operation over files 
1371      * in the current account. 
1373      * @param operation     Removal operation performed. 
1374      * @param result        Result of the removal. 
1377     public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) { 
1378         super.onRemoteOperationFinish(operation
, result
); 
1380         if (operation 
instanceof RemoveFileOperation
) { 
1381             onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
); 
1383         } else if (operation 
instanceof RenameFileOperation
) { 
1384             onRenameFileOperationFinish((RenameFileOperation
)operation
, result
); 
1386         } else if (operation 
instanceof SynchronizeFileOperation
) { 
1387             onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
); 
1389         } else if (operation 
instanceof CreateFolderOperation
) { 
1390             onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
); 
1392         } else if (operation 
instanceof CreateShareOperation
) { 
1393             onCreateShareOperationFinish((CreateShareOperation
) operation
, result
); 
1395         } else if (operation 
instanceof UnshareLinkOperation
) { 
1396             onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
); 
1398         } else if (operation 
instanceof MoveFileOperation
) { 
1399             onMoveFileOperationFinish((MoveFileOperation
)operation
, result
); 
1405     private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) { 
1406         if (result
.isSuccess()) { 
1407             refreshShowDetails(); 
1408             refreshListOfFilesFragment(); 
1413     private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) { 
1414         if (result
.isSuccess()) { 
1415             refreshShowDetails(); 
1416             refreshListOfFilesFragment(); 
1418         } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) { 
1419             cleanSecondFragment(); 
1420             refreshListOfFilesFragment(); 
1424     private void refreshShowDetails() { 
1425         FileFragment details 
= getSecondFragment(); 
1426         if (details 
!= null
) { 
1427             OCFile file 
= details
.getFile(); 
1429                 file 
= getStorageManager().getFileByPath(file
.getRemotePath());  
1430                 if (details 
instanceof PreviewMediaFragment
) { 
1431                     // Refresh  OCFile of the fragment 
1432                     ((PreviewMediaFragment
) details
).updateFile(file
); 
1437             invalidateOptionsMenu(); 
1442      * Updates the view associated to the activity after the finish of an operation trying to remove a  
1445      * @param operation     Removal operation performed. 
1446      * @param result        Result of the removal. 
1448     private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) { 
1449         dismissLoadingDialog(); 
1451         Toast msg 
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),  
1455         if (result
.isSuccess()) { 
1456             OCFile removedFile 
= operation
.getFile(); 
1457             FileFragment second 
= getSecondFragment(); 
1458             if (second 
!= null 
&& removedFile
.equals(second
.getFile())) { 
1459                 if (second 
instanceof PreviewMediaFragment
) { 
1460                     ((PreviewMediaFragment
)second
).stopPreview(true
); 
1462                 setFile(getStorageManager().getFileById(removedFile
.getParentId())); 
1463                 cleanSecondFragment(); 
1465             if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) { 
1466                 refreshListOfFilesFragment(); 
1468             invalidateOptionsMenu(); 
1470             if (result
.isSslRecoverableException()) { 
1471                 mLastSslUntrustedServerResult 
= result
; 
1472                 showUntrustedCertDialog(mLastSslUntrustedServerResult
); 
1479      * Updates the view associated to the activity after the finish of an operation trying to move a  
1482      * @param operation     Move operation performed. 
1483      * @param result        Result of the move operation. 
1485     private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) { 
1486         if (result
.isSuccess()) { 
1487             dismissLoadingDialog(); 
1488             refreshListOfFilesFragment(); 
1490             dismissLoadingDialog(); 
1492                 Toast msg 
= Toast
.makeText(FileDisplayActivity
.this,  
1493                         ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),  
1497             } catch (NotFoundException e
) { 
1498                 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
); 
1505      * Updates the view associated to the activity after the finish of an operation trying to rename a  
1508      * @param operation     Renaming operation performed. 
1509      * @param result        Result of the renaming. 
1511     private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) { 
1512         dismissLoadingDialog(); 
1513         OCFile renamedFile 
= operation
.getFile(); 
1514         if (result
.isSuccess()) { 
1515             FileFragment details 
= getSecondFragment(); 
1516             if (details 
!= null
) { 
1517                 if (details 
instanceof FileDetailFragment 
&& renamedFile
.equals(details
.getFile()) ) { 
1518                     ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount()); 
1519                     showDetails(renamedFile
); 
1521                 } else if (details 
instanceof PreviewMediaFragment 
&& renamedFile
.equals(details
.getFile())) { 
1522                     ((PreviewMediaFragment
) details
).updateFile(renamedFile
); 
1523                     if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) { 
1524                         int position 
= ((PreviewMediaFragment
)details
).getPosition(); 
1525                         startMediaPreview(renamedFile
, position
, true
); 
1527                         getFileOperationsHelper().openFile(renamedFile
); 
1532             if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) { 
1533                 refreshListOfFilesFragment(); 
1537             Toast msg 
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),  
1541             if (result
.isSslRecoverableException()) { 
1542                 mLastSslUntrustedServerResult 
= result
; 
1543                 showUntrustedCertDialog(mLastSslUntrustedServerResult
); 
1548     private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) { 
1549         dismissLoadingDialog(); 
1550         OCFile syncedFile 
= operation
.getLocalFile(); 
1551         if (!result
.isSuccess()) { 
1552             if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) { 
1553                 Intent i 
= new Intent(this, ConflictsResolveActivity
.class); 
1554                 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
); 
1555                 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount()); 
1561             if (operation
.transferWasRequested()) { 
1562                 onTransferStateChanged(syncedFile
, true
, true
); 
1565                 Toast msg 
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),  
1573      * Updates the view associated to the activity after the finish of an operation trying create a new folder 
1575      * @param operation     Creation operation performed. 
1576      * @param result        Result of the creation. 
1578     private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) { 
1579         if (result
.isSuccess()) { 
1580             dismissLoadingDialog(); 
1581             refreshListOfFilesFragment(); 
1583             dismissLoadingDialog(); 
1585                 Toast msg 
= Toast
.makeText(FileDisplayActivity
.this,  
1586                         ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),  
1590             } catch (NotFoundException e
) { 
1591                 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
); 
1601     public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) { 
1602         refreshListOfFilesFragment(); 
1603         FileFragment details 
= getSecondFragment(); 
1604         if (details 
!= null 
&& details 
instanceof FileDetailFragment 
&& file
.equals(details
.getFile()) ) { 
1605             if (downloading 
|| uploading
) { 
1606                 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount()); 
1608                 if (!file
.fileExists()) { 
1609                     cleanSecondFragment(); 
1611                     ((FileDetailFragment
)details
).updateFileDetails(false
, true
); 
1619     private void requestForDownload() { 
1620         Account account 
= getAccount(); 
1621         if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) { 
1622             Intent i 
= new Intent(this, FileDownloader
.class); 
1623             i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
); 
1624             i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
); 
1630     private OCFile 
getCurrentDir() { 
1631         OCFile file 
= getFile(); 
1633             if (file
.isFolder()) { 
1635             } else if (getStorageManager() != null
) { 
1636                 String parentPath 
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName())); 
1637                 return getStorageManager().getFileByPath(parentPath
); 
1643     public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) { 
1644         long currentSyncTime 
= System
.currentTimeMillis();  
1646         mSyncInProgress 
= true
; 
1648         // perform folder synchronization 
1649         RemoteOperation synchFolderOp 
= new SynchronizeFolderOperation( folder
,   
1652                                                                         getFileOperationsHelper().isSharedSupported(), 
1654                                                                         getStorageManager(),  
1656                                                                         getApplicationContext() 
1658         synchFolderOp
.execute(getAccount(), this, null
, null
); 
1660         setSupportProgressBarIndeterminateVisibility(true
); 
1662         setBackgroundText(); 
1666      * Show untrusted cert dialog  
1668     public void showUntrustedCertDialog(RemoteOperationResult result
) { 
1669         // Show a dialog with the certificate info 
1670         SslUntrustedCertDialog dialog 
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException()); 
1671         FragmentManager fm 
= getSupportFragmentManager(); 
1672         FragmentTransaction ft 
= fm
.beginTransaction(); 
1673         dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
); 
1676     private void requestForDownload(OCFile file
) { 
1677         Account account 
= getAccount(); 
1678         if (!mDownloaderBinder
.isDownloading(account
, file
)) { 
1679             Intent i 
= new Intent(this, FileDownloader
.class); 
1680             i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
); 
1681             i
.putExtra(FileDownloader
.EXTRA_FILE
, file
); 
1686     private void sendDownloadedFile(){ 
1687         getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
); 
1688         mWaitingToSend 
= null
; 
1693      * Requests the download of the received {@link OCFile} , updates the UI 
1694      * to monitor the download progress and prepares the activity to send the file 
1695      * when the download finishes. 
1697      * @param file          {@link OCFile} to download and preview. 
1699     public void startDownloadForSending(OCFile file
) { 
1700         mWaitingToSend 
= file
; 
1701         requestForDownload(mWaitingToSend
); 
1702         boolean hasSecondFragment 
= (getSecondFragment()!= null
); 
1703         updateFragmentsVisibility(hasSecondFragment
); 
1707      * Opens the image gallery showing the image {@link OCFile} received as parameter. 
1709      * @param file                      Image {@link OCFile} to show. 
1711     public void startImagePreview(OCFile file
) { 
1712         Intent showDetailsIntent 
= new Intent(this, PreviewImageActivity
.class); 
1713         showDetailsIntent
.putExtra(EXTRA_FILE
, file
); 
1714         showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount()); 
1715         startActivity(showDetailsIntent
); 
1720      * Stars the preview of an already down media {@link OCFile}. 
1722      * @param file                      Media {@link OCFile} to preview. 
1723      * @param startPlaybackPosition     Media position where the playback will be started, in milliseconds. 
1724      * @param autoplay                  When 'true', the playback will start without user interactions. 
1726     public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) { 
1727         Fragment mediaFragment 
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
); 
1728         setSecondFragment(mediaFragment
); 
1729         updateFragmentsVisibility(true
); 
1730         updateNavigationElementsInActionBar(file
); 
1735      * Requests the download of the received {@link OCFile} , updates the UI 
1736      * to monitor the download progress and prepares the activity to preview 
1737      * or open the file when the download finishes. 
1739      * @param file          {@link OCFile} to download and preview. 
1741     public void startDownloadForPreview(OCFile file
) { 
1742         Fragment detailFragment 
= new FileDetailFragment(file
, getAccount()); 
1743         setSecondFragment(detailFragment
); 
1744         mWaitingToPreview 
= file
; 
1745         requestForDownload(); 
1746         updateFragmentsVisibility(true
); 
1747         updateNavigationElementsInActionBar(file
); 
1752     public void cancelTransference(OCFile file
) { 
1753         getFileOperationsHelper().cancelTransference(file
); 
1754         if (mWaitingToPreview 
!= null 
&&  
1755                 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) { 
1756             mWaitingToPreview 
= null
; 
1758         if (mWaitingToSend 
!= null 
&& 
1759                 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) { 
1760             mWaitingToSend 
= null
; 
1762         onTransferStateChanged(file
, false
, false
); 
1766     public void onRefresh(boolean ignoreETag
) { 
1767         refreshList(ignoreETag
); 
1771     public void onRefresh() { 
1775     private void refreshList(boolean ignoreETag
) { 
1776         OCFileListFragment listOfFiles 
= getListOfFilesFragment(); 
1777         if (listOfFiles 
!= null
) { 
1778             OCFile folder 
= listOfFiles
.getCurrentFile(); 
1779             if (folder 
!= null
) { 
1780                 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId()); 
1781                 listDirectory(mFile);*/ 
1782                 startSyncFolderOperation(folder
, ignoreETag
); 
1787     private void sortByDate(boolean ascending
){ 
1788         getListOfFilesFragment().sortByDate(ascending
); 
1791     private void sortBySize(boolean ascending
){ 
1792         getListOfFilesFragment().sortBySize(ascending
); 
1795     private void sortByName(boolean ascending
){ 
1796         getListOfFilesFragment().sortByName(ascending
);