2  *   ownCloud Android client application 
   4  *   @author Bartek Przybylski 
   5  *   @author David A. Velasco 
   6  *   Copyright (C) 2011  Bartek Przybylski 
   7  *   Copyright (C) 2015 ownCloud Inc. 
   9  *   This program is free software: you can redistribute it and/or modify 
  10  *   it under the terms of the GNU General Public License version 2, 
  11  *   as published by the Free Software Foundation. 
  13  *   This program is distributed in the hope that it will be useful, 
  14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of 
  15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
  16  *   GNU General Public License for more details. 
  18  *   You should have received a copy of the GNU General Public License 
  19  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. 
  23 package com
.owncloud
.android
.ui
.activity
; 
  25 import android
.accounts
.Account
; 
  26 import android
.accounts
.AccountManager
; 
  27 import android
.accounts
.AuthenticatorException
; 
  28 import android
.annotation
.TargetApi
; 
  29 import android
.support
.v7
.app
.AlertDialog
; 
  30 import android
.content
.BroadcastReceiver
; 
  31 import android
.content
.ComponentName
; 
  32 import android
.content
.ContentResolver
; 
  33 import android
.content
.Context
; 
  34 import android
.content
.DialogInterface
; 
  35 import android
.content
.Intent
; 
  36 import android
.content
.IntentFilter
; 
  37 import android
.content
.ServiceConnection
; 
  38 import android
.content
.SharedPreferences
; 
  39 import android
.content
.SyncRequest
; 
  40 import android
.content
.res
.Resources
.NotFoundException
; 
  41 import android
.database
.Cursor
; 
  42 import android
.net
.Uri
; 
  43 import android
.os
.Build
; 
  44 import android
.os
.Bundle
; 
  45 import android
.os
.IBinder
; 
  46 import android
.preference
.PreferenceManager
; 
  47 import android
.provider
.OpenableColumns
; 
  48 import android
.support
.v4
.app
.Fragment
; 
  49 import android
.support
.v4
.app
.FragmentManager
; 
  50 import android
.support
.v4
.app
.FragmentTransaction
; 
  51 import android
.support
.v4
.content
.ContextCompat
; 
  52 import android
.support
.v4
.view
.GravityCompat
; 
  53 import android
.view
.Menu
; 
  54 import android
.view
.MenuInflater
; 
  55 import android
.view
.MenuItem
; 
  56 import android
.view
.View
; 
  57 import android
.widget
.ProgressBar
; 
  58 import android
.widget
.RelativeLayout
; 
  59 import android
.widget
.TextView
; 
  60 import android
.widget
.Toast
; 
  62 import com
.owncloud
.android
.MainApp
; 
  63 import com
.owncloud
.android
.R
; 
  64 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
; 
  65 import com
.owncloud
.android
.datamodel
.OCFile
; 
  66 import com
.owncloud
.android
.files
.services
.FileDownloader
; 
  67 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
; 
  68 import com
.owncloud
.android
.files
.services
.FileUploader
; 
  69 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
; 
  70 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
; 
  71 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
; 
  72 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
; 
  73 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
; 
  74 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
; 
  75 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
; 
  76 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
; 
  77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
; 
  78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
; 
  79 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
; 
  80 import com
.owncloud
.android
.operations
.CreateFolderOperation
; 
  81 import com
.owncloud
.android
.operations
.CreateShareOperation
; 
  82 import com
.owncloud
.android
.operations
.MoveFileOperation
; 
  83 import com
.owncloud
.android
.operations
.RefreshFolderOperation
; 
  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
.UnshareLinkOperation
; 
  88 import com
.owncloud
.android
.services
.observer
.FileObserverService
; 
  89 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
; 
  90 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
; 
  91 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
; 
  92 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
; 
  93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
; 
  94 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
; 
  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
.PreviewTextFragment
; 
 102 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
; 
 103 import com
.owncloud
.android
.utils
.DisplayUtils
; 
 104 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
; 
 105 import com
.owncloud
.android
.utils
.FileStorageUtils
; 
 106 import com
.owncloud
.android
.utils
.UriUtils
; 
 111  * Displays, what files the user has available in his ownCloud. 
 114 public class FileDisplayActivity 
extends HookActivity
 
 115         implements FileFragment
.ContainerActivity
, 
 116         OnSslUntrustedCertListener
, OnEnforceableRefreshListener 
{ 
 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
; 
 128     private ProgressBar mProgressBar
; 
 130     private static final String KEY_WAITING_TO_PREVIEW 
= "WAITING_TO_PREVIEW"; 
 131     private static final String KEY_SYNC_IN_PROGRESS 
= "SYNC_IN_PROGRESS"; 
 132     private static final String KEY_WAITING_TO_SEND 
= "WAITING_TO_SEND"; 
 134     public static final String ACTION_DETAILS 
= "com.owncloud.android.ui.activity.action.DETAILS"; 
 136     public static final int ACTION_SELECT_CONTENT_FROM_APPS 
= 1; 
 137     public static final int ACTION_SELECT_MULTIPLE_FILES 
= 2; 
 138     public static final int ACTION_MOVE_FILES 
= 3; 
 140     private static final String TAG 
= FileDisplayActivity
.class.getSimpleName(); 
 142     private static final String TAG_LIST_OF_FILES 
= "LIST_OF_FILES"; 
 143     private static final String TAG_SECOND_FRAGMENT 
= "SECOND_FRAGMENT"; 
 145     private OCFile mWaitingToPreview
; 
 147     private boolean mSyncInProgress 
= false
; 
 149     private static String DIALOG_UNTRUSTED_CERT 
= "DIALOG_UNTRUSTED_CERT"; 
 150     private static String DIALOG_CREATE_FOLDER 
= "DIALOG_CREATE_FOLDER"; 
 151     private static String DIALOG_UPLOAD_SOURCE 
= "DIALOG_UPLOAD_SOURCE"; 
 152     private static String DIALOG_CERT_NOT_SAVED 
= "DIALOG_CERT_NOT_SAVED"; 
 154     private OCFile mWaitingToSend
; 
 158     protected void onCreate(Bundle savedInstanceState
) { 
 159         Log_OC
.v(TAG
, "onCreate() start"); 
 161         super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account 
 164         /// grant that FileObserverService is watching favorite files 
 165         if (savedInstanceState 
== null
) { 
 166             Intent initObserversIntent 
= FileObserverService
.makeInitIntent(this); 
 167             startService(initObserversIntent
); 
 170         /// Load of saved instance state 
 171         if(savedInstanceState 
!= null
) { 
 172             mWaitingToPreview 
= (OCFile
) savedInstanceState
.getParcelable( 
 173                     FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
); 
 174             mSyncInProgress 
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
); 
 175             mWaitingToSend 
= (OCFile
) savedInstanceState
.getParcelable( 
 176                     FileDisplayActivity
.KEY_WAITING_TO_SEND
); 
 178             mWaitingToPreview 
= null
; 
 179             mSyncInProgress 
= false
; 
 180             mWaitingToSend 
= null
; 
 185         // Inflate and set the layout view 
 186         setContentView(R
.layout
.files
); 
 191         mProgressBar 
= (ProgressBar
) findViewById(R
.id
.progressBar
); 
 192         mProgressBar
.setIndeterminateDrawable( 
 193                 ContextCompat
.getDrawable(this, 
 194                         R
.drawable
.actionbar_progress_indeterminate_horizontal
)); 
 196         mDualPane 
= getResources().getBoolean(R
.bool
.large_land_layout
); 
 197         mLeftFragmentContainer 
= findViewById(R
.id
.left_fragment_container
); 
 198         mRightFragmentContainer 
= findViewById(R
.id
.right_fragment_container
); 
 199         if (savedInstanceState 
== null
) { 
 200             createMinFragments(); 
 204         getSupportActionBar().setHomeButtonEnabled(true
);       // mandatory since Android ICS, 
 205                                                                 // according to the official 
 208         // enable ActionBar app icon to behave as action to toggle nav drawer 
 209         //getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
 210         getSupportActionBar().setHomeButtonEnabled(true
); 
 212         mProgressBar
.setIndeterminate(mSyncInProgress
); 
 213         // always AFTER setContentView(...) ; to work around bug in its implementation 
 217         Log_OC
.v(TAG
, "onCreate() end"); 
 221     protected void onStart() { 
 222         Log_OC
.v(TAG
, "onStart() start"); 
 224         Log_OC
.v(TAG
, "onStart() end"); 
 228     protected void onDestroy() { 
 229         Log_OC
.v(TAG
, "onDestroy() start"); 
 231         Log_OC
.v(TAG
, "onDestroy() end"); 
 235      * Called when the ownCloud {@link Account} associated to the Activity was just updated. 
 238     protected void onAccountSet(boolean stateWasRecovered
) { 
 239         super.onAccountSet(stateWasRecovered
); 
 240         if (getAccount() != null
) { 
 241             /// Check whether the 'main' OCFile handled by the Activity is contained in the 
 243             OCFile file 
= getFile(); 
 244             // get parent from path 
 245             String parentPath 
= ""; 
 247                 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) { 
 248                     // upload in progress - right now, files are not inserted in the local 
 249                     // cache until the upload is successful get parent from path 
 250                     parentPath 
= file
.getRemotePath().substring(0, 
 251                             file
.getRemotePath().lastIndexOf(file
.getFileName())); 
 252                     if (getStorageManager().getFileByPath(parentPath
) ==  null
) 
 253                         file 
= null
; // not able to know the directory where the file is uploading 
 255                     file 
= getStorageManager().getFileByPath(file
.getRemotePath()); 
 256                     // currentDir = null if not in the current Account 
 260                 // fall back to root folder 
 261                 file 
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);  // never returns null 
 265             if (mAccountWasSet
) { 
 266                 RelativeLayout navigationDrawerLayout 
= (RelativeLayout
) findViewById(R
.id
.left_drawer
); 
 267                 if (navigationDrawerLayout 
!= null 
&& getAccount() != null
) { 
 268                     TextView username 
= (TextView
) navigationDrawerLayout
.findViewById(R
.id
.drawer_username
); 
 269                     int lastAtPos 
= getAccount().name
.lastIndexOf("@"); 
 270                     username
.setText(getAccount().name
.substring(0, lastAtPos
)); 
 274             if (!stateWasRecovered
) { 
 275                 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged.."); 
 276                 initFragmentsWithFile(); 
 277                 if (file
.isFolder()) { 
 278                     startSyncFolderOperation(file
, false
); 
 282                 updateFragmentsVisibility(!file
.isFolder()); 
 283                 updateActionBarTitleAndHomeButton(file
.isFolder() ? null 
: file
); 
 288     private void createMinFragments() { 
 289         OCFileListFragment listOfFiles 
= new OCFileListFragment(); 
 290         FragmentTransaction transaction 
= getSupportFragmentManager().beginTransaction(); 
 291         transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
); 
 292         transaction
.commit(); 
 295     private void initFragmentsWithFile() { 
 296         if (getAccount() != null 
&& getFile() != null
) { 
 298             OCFileListFragment listOfFiles 
= getListOfFilesFragment(); 
 299             if (listOfFiles 
!= null
) { 
 300                 listOfFiles
.listDirectory(getCurrentDir()); 
 301                 // TODO Enable when "On Device" is recovered 
 302                 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice()); 
 305                 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >("); 
 309             OCFile file 
= getFile(); 
 310             Fragment secondFragment 
= chooseInitialSecondFragment(file
); 
 311             if (secondFragment 
!= null
) { 
 312                 setSecondFragment(secondFragment
); 
 313                 updateFragmentsVisibility(true
); 
 314                 updateActionBarTitleAndHomeButton(file
); 
 317                 cleanSecondFragment(); 
 318                 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) 
 319                     startTextPreview(file
); 
 323             Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!"); 
 324             if (getAccount() == null
) { 
 325                 Log_OC
.wtf(TAG
, "\t account is NULL"); 
 327             if (getFile() == null
) { 
 328                 Log_OC
.wtf(TAG
, "\t file is NULL"); 
 333     private Fragment 
chooseInitialSecondFragment(OCFile file
) { 
 334         Fragment secondFragment 
= null
; 
 335         if (file 
!= null 
&& !file
.isFolder()) { 
 336             if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
) 
 337                     && file
.getLastSyncDateForProperties() > 0  // temporal fix 
 339                 int startPlaybackPosition 
= 
 340                         getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0); 
 342                         getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
); 
 343                 secondFragment 
= new PreviewMediaFragment(file
, getAccount(), 
 344                         startPlaybackPosition
, autoplay
); 
 346             } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) { 
 347                 secondFragment 
= null
; 
 349             secondFragment 
= FileDetailFragment
.newInstance(file
, getAccount()); 
 352         return secondFragment
; 
 357      * Replaces the second fragment managed by the activity with the received as 
 360      * Assumes never will be more than two fragments managed at the same time. 
 362      * @param fragment New second Fragment to set. 
 364     private void setSecondFragment(Fragment fragment
) { 
 365         FragmentTransaction transaction 
= getSupportFragmentManager().beginTransaction(); 
 366         transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
); 
 367         transaction
.commit(); 
 371     private void updateFragmentsVisibility(boolean existsSecondFragment
) { 
 373             if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) { 
 374                 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
); 
 376             if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) { 
 377                 mRightFragmentContainer
.setVisibility(View
.VISIBLE
); 
 380         } else if (existsSecondFragment
) { 
 381             if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) { 
 382                 mLeftFragmentContainer
.setVisibility(View
.GONE
); 
 384             if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) { 
 385                 mRightFragmentContainer
.setVisibility(View
.VISIBLE
); 
 389             if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) { 
 390                 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
); 
 392             if (mRightFragmentContainer
.getVisibility() != View
.GONE
) { 
 393                 mRightFragmentContainer
.setVisibility(View
.GONE
); 
 399     private OCFileListFragment 
getListOfFilesFragment() { 
 400         Fragment listOfFiles 
= getSupportFragmentManager().findFragmentByTag( 
 401                 FileDisplayActivity
.TAG_LIST_OF_FILES
); 
 402         if (listOfFiles 
!= null
) { 
 403             return (OCFileListFragment
) listOfFiles
; 
 405         Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!"); 
 409     public FileFragment 
getSecondFragment() { 
 410         Fragment second 
= getSupportFragmentManager().findFragmentByTag( 
 411                 FileDisplayActivity
.TAG_SECOND_FRAGMENT
); 
 412         if (second 
!= null
) { 
 413             return (FileFragment
) second
; 
 418     protected void cleanSecondFragment() { 
 419         Fragment second 
= getSecondFragment(); 
 420         if (second 
!= null
) { 
 421             FragmentTransaction tr 
= getSupportFragmentManager().beginTransaction(); 
 425         updateFragmentsVisibility(false
); 
 426         updateActionBarTitleAndHomeButton(null
); 
 429     protected void refreshListOfFilesFragment() { 
 430         OCFileListFragment fileListFragment 
= getListOfFilesFragment(); 
 431         if (fileListFragment 
!= null
) { 
 432             fileListFragment
.listDirectory(); 
 433             // TODO Enable when "On Device" is recovered ? 
 434             // fileListFragment.listDirectory(MainApp.getOnlyOnDevice()); 
 438     protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, 
 440         FileFragment secondFragment 
= getSecondFragment(); 
 441         boolean waitedPreview 
= (mWaitingToPreview 
!= null 
&& 
 442                 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
)); 
 443         if (secondFragment 
!= null 
&& secondFragment 
instanceof FileDetailFragment
) { 
 444             FileDetailFragment detailsFragment 
= (FileDetailFragment
) secondFragment
; 
 445             OCFile fileInFragment 
= detailsFragment
.getFile(); 
 446             if (fileInFragment 
!= null 
&& 
 447                     !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) { 
 448                 // the user browsed to other file ; forget the automatic preview  
 449                 mWaitingToPreview 
= null
; 
 451             } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) { 
 452                 // grant that the right panel updates the progress bar 
 453                 detailsFragment
.listenForTransferProgress(); 
 454                 detailsFragment
.updateFileDetails(true
, false
); 
 456             } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) { 
 457                 //  update the right panel 
 458                 boolean detailsFragmentChanged 
= false
; 
 461                         mWaitingToPreview 
= getStorageManager().getFileById( 
 462                                 mWaitingToPreview
.getFileId());   // update the file from database, 
 463                                                                   // for the local storage path 
 464                         if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) { 
 465                             startMediaPreview(mWaitingToPreview
, 0, true
); 
 466                             detailsFragmentChanged 
= true
; 
 467                         } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) { 
 468                             startTextPreview(mWaitingToPreview
); 
 469                             detailsFragmentChanged 
= true
; 
 471                             getFileOperationsHelper().openFile(mWaitingToPreview
); 
 474                     mWaitingToPreview 
= null
; 
 476                 if (!detailsFragmentChanged
) { 
 477                     detailsFragment
.updateFileDetails(false
, (success
)); 
 484     public boolean onPrepareOptionsMenu(Menu menu
) { 
 485         boolean drawerOpen 
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
); 
 486         menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
); 
 487         menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
); 
 488         menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
); 
 489         menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
); 
 491         return super.onPrepareOptionsMenu(menu
); 
 495     public boolean onCreateOptionsMenu(Menu menu
) { 
 496         MenuInflater inflater 
= getMenuInflater(); 
 497         inflater
.inflate(R
.menu
.main_menu
, menu
); 
 503     public boolean onOptionsItemSelected(MenuItem item
) { 
 504         boolean retval 
= true
; 
 505         switch (item
.getItemId()) { 
 506             case R
.id
.action_create_dir
: { 
 507                 CreateFolderDialogFragment dialog 
= 
 508                         CreateFolderDialogFragment
.newInstance(getCurrentDir()); 
 509                 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
); 
 513             case R
.id
.action_sync_account
: { 
 514                 startSynchronization(); 
 517             case R
.id
.action_upload
: { 
 518                 UploadSourceDialogFragment dialog 
= 
 519                         UploadSourceDialogFragment
.newInstance(getAccount()); 
 520                 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
); 
 523             case android
.R
.id
.home
: { 
 524                 FileFragment second 
= getSecondFragment(); 
 525                 OCFile currentDir 
= getCurrentDir(); 
 526                 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) { 
 527                     mDrawerLayout
.closeDrawer(GravityCompat
.START
); 
 528                 } else if((currentDir 
!= null 
&& currentDir
.getParentId() != 0) || 
 529                         (second 
!= null 
&& second
.getFile() != null
)) { 
 533                     mDrawerLayout
.openDrawer(GravityCompat
.START
); 
 537             case R
.id
.action_sort
: { 
 538                 SharedPreferences appPreferences 
= PreferenceManager
 
 539                         .getDefaultSharedPreferences(this); 
 541                 // Read sorting order, default to sort by name ascending 
 542                 Integer sortOrder 
= appPreferences
 
 543                         .getInt("sortOrder", FileStorageUtils
.SORT_NAME
); 
 545                 AlertDialog
.Builder builder 
= new AlertDialog
.Builder(this); 
 546                 builder
.setTitle(R
.string
.actionbar_sort_title
) 
 547                         .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder 
, 
 548                                 new DialogInterface
.OnClickListener() { 
 549                             public void onClick(DialogInterface dialog
, int which
) { 
 562                 builder
.create().show(); 
 566             retval 
= super.onOptionsItemSelected(item
); 
 571     private void startSynchronization() { 
 572         Log_OC
.d(TAG
, "Got to start sync"); 
 573         if (android
.os
.Build
.VERSION
.SDK_INT 
< android
.os
.Build
.VERSION_CODES
.KITKAT
) { 
 574             Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority()); 
 575             ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); 
 576             // cancel the current synchronizations of any ownCloud account 
 577             Bundle bundle 
= new Bundle(); 
 578             bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
); 
 579             bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
); 
 580             Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name 
+ " at " + 
 581                     MainApp
.getAuthority()); 
 582             ContentResolver
.requestSync( 
 584                     MainApp
.getAuthority(), bundle
); 
 586             Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name 
+ " at " + 
 587                     MainApp
.getAuthority() + " with new API"); 
 588             SyncRequest
.Builder builder 
= new SyncRequest
.Builder(); 
 589             builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority()); 
 590             builder
.setExpedited(true
); 
 591             builder
.setManual(true
); 
 594             // Fix bug in Android Lollipop when you click on refresh the whole account 
 595             Bundle extras 
= new Bundle(); 
 596             builder
.setExtras(extras
); 
 598             SyncRequest request 
= builder
.build(); 
 599             ContentResolver
.requestSync(request
); 
 604      * Called, when the user selected something for uploading 
 607     @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
) 
 609     protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) { 
 611         if (requestCode 
== ACTION_SELECT_CONTENT_FROM_APPS 
&& (resultCode 
== RESULT_OK 
|| 
 612                 resultCode 
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) { 
 613             //getClipData is only supported on api level 16+, Jelly Bean 
 614             if (data
.getData() == null 
&& Build
.VERSION
.SDK_INT 
>= Build
.VERSION_CODES
.JELLY_BEAN
){ 
 615                 for( int i 
= 0; i 
< data
.getClipData().getItemCount(); i
++){ 
 616                     Intent intent 
= new Intent(); 
 617                     intent
.setData(data
.getClipData().getItemAt(i
).getUri()); 
 618                     requestSimpleUpload(intent
, resultCode
); 
 621                 requestSimpleUpload(data
, resultCode
); 
 623         } else if (requestCode 
== ACTION_SELECT_MULTIPLE_FILES 
&& (resultCode 
== RESULT_OK 
|| 
 624                 resultCode 
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) { 
 625             requestMultipleUpload(data
, resultCode
); 
 627         } else if (requestCode 
== ACTION_MOVE_FILES 
&& resultCode 
== RESULT_OK
) { 
 629             final Intent fData 
= data
; 
 630             final int fResultCode 
= resultCode
; 
 631             getHandler().postDelayed( 
 635                             requestMoveOperation(fData
, fResultCode
); 
 638                     DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
 
 642             super.onActivityResult(requestCode
, resultCode
, data
); 
 647     private void requestMultipleUpload(Intent data
, int resultCode
) { 
 648         String
[] filePaths 
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
); 
 649         if (filePaths 
!= null
) { 
 650             String
[] remotePaths 
= new String
[filePaths
.length
]; 
 651             String remotePathBase 
= getCurrentDir().getRemotePath(); 
 652             for (int j 
= 0; j
< remotePaths
.length
; j
++) { 
 653                 remotePaths
[j
] = remotePathBase 
+ (new File(filePaths
[j
])).getName(); 
 656             Intent i 
= new Intent(this, FileUploader
.class); 
 657             i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount()); 
 658             i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
); 
 659             i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
); 
 660             i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
); 
 661             if (resultCode 
== UploadFilesActivity
.RESULT_OK_AND_MOVE
) 
 662                 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
); 
 666             Log_OC
.d(TAG
, "User clicked on 'Update' with no selection"); 
 667             Toast t 
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), 
 675     private void requestSimpleUpload(Intent data
, int resultCode
) { 
 676         String filePath 
= null
; 
 677         String mimeType 
= null
; 
 679         Uri selectedImageUri 
= data
.getData(); 
 682             mimeType 
= getContentResolver().getType(selectedImageUri
); 
 684             String fileManagerString 
= selectedImageUri
.getPath(); 
 685             String selectedImagePath 
= UriUtils
.getLocalPath(selectedImageUri
, this); 
 687             if (selectedImagePath 
!= null
) 
 688                 filePath 
= selectedImagePath
; 
 690                 filePath 
= fileManagerString
; 
 692         } catch (Exception e
) { 
 693             Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " + 
 694                     "Intent.ACTION_GET_CONTENT", e
); 
 697             if (filePath 
== null
) { 
 698                 Log_OC
.e(TAG
, "Couldn't resolve path to file"); 
 699                 Toast t 
= Toast
.makeText( 
 700                         this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), 
 708         Intent i 
= new Intent(this, FileUploader
.class); 
 709         i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount()); 
 710         OCFile currentDir 
= getCurrentDir(); 
 711         String remotePath 
=  (currentDir 
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
; 
 713         if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) { 
 714             Cursor cursor 
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
); 
 716                 if (cursor 
!= null 
&& cursor
.moveToFirst()) { 
 717                     String displayName 
= cursor
.getString(cursor
.getColumnIndex( 
 718                             OpenableColumns
.DISPLAY_NAME
)); 
 719                     Log_OC
.v(TAG
, "Display Name: " + displayName 
); 
 721                     displayName
.replace(File
.separatorChar
, '_'); 
 722                     displayName
.replace(File
.pathSeparatorChar
, '_'); 
 723                     remotePath 
+= displayName 
+ DisplayUtils
.getComposedFileExtension(filePath
); 
 726                 // and what happens in case of error?; wrong target name for the upload 
 732             remotePath 
+= new File(filePath
).getName(); 
 735         i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
); 
 736         i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
); 
 737         i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
); 
 738         i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
); 
 739         if (resultCode 
== UploadFilesActivity
.RESULT_OK_AND_MOVE
) 
 740         i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
); 
 745      * Request the operation for moving the file/folder from one path to another 
 747      * @param data       Intent received 
 748      * @param resultCode Result code received 
 750     private void requestMoveOperation(Intent data
, int resultCode
) { 
 751         OCFile folderToMoveAt 
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
); 
 752         OCFile targetFile 
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
); 
 753         getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
); 
 757     public void onBackPressed() { 
 758         if (!isDrawerOpen()){ 
 759             OCFileListFragment listOfFiles 
= getListOfFilesFragment(); 
 760             if (mDualPane 
|| getSecondFragment() == null
) { 
 761                 OCFile currentDir 
= getCurrentDir(); 
 762                 if (currentDir 
== null 
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) { 
 766                 if (listOfFiles 
!= null
) {  // should never be null, indeed 
 767                     listOfFiles
.onBrowseUp(); 
 770             if (listOfFiles 
!= null
) {  // should never be null, indeed 
 771                 setFile(listOfFiles
.getCurrentFile()); 
 773             cleanSecondFragment(); 
 775             super.onBackPressed(); 
 780     protected void onSaveInstanceState(Bundle outState
) { 
 781         // responsibility of restore is preferred in onCreate() before than in 
 782         // onRestoreInstanceState when there are Fragments involved 
 783         Log_OC
.v(TAG
, "onSaveInstanceState() start"); 
 784         super.onSaveInstanceState(outState
); 
 785         outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
); 
 786         outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
); 
 787         //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, 
 788         // mRefreshSharesInProgress); 
 789         outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
); 
 791         Log_OC
.v(TAG
, "onSaveInstanceState() end"); 
 796     protected void onResume() { 
 797         Log_OC
.v(TAG
, "onResume() start"); 
 799         // refresh Navigation Drawer account list 
 800         mNavigationDrawerAdapter
.updateAccountList(); 
 802         // refresh list of files 
 803         refreshListOfFilesFragment(); 
 805         // Listen for sync messages 
 806         IntentFilter syncIntentFilter 
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
); 
 807         syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
); 
 808         syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
); 
 809         syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
); 
 810         syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
); 
 811         mSyncBroadcastReceiver 
= new SyncBroadcastReceiver(); 
 812         registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
); 
 813         //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, 
 814         // syncIntentFilter); 
 816         // Listen for upload messages 
 817         IntentFilter uploadIntentFilter 
= new IntentFilter(FileUploader
.getUploadFinishMessage()); 
 818         mUploadFinishReceiver 
= new UploadFinishReceiver(); 
 819         registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
); 
 821         // Listen for download messages 
 822         IntentFilter downloadIntentFilter 
= new IntentFilter( 
 823                 FileDownloader
.getDownloadAddedMessage()); 
 824         downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage()); 
 825         mDownloadFinishReceiver 
= new DownloadFinishReceiver(); 
 826         registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
); 
 827         Log_OC
.v(TAG
, "onResume() end"); 
 833     protected void onPause() { 
 834         Log_OC
.v(TAG
, "onPause() start"); 
 835         if (mSyncBroadcastReceiver 
!= null
) { 
 836             unregisterReceiver(mSyncBroadcastReceiver
); 
 837             //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver); 
 838             mSyncBroadcastReceiver 
= null
; 
 840         if (mUploadFinishReceiver 
!= null
) { 
 841             unregisterReceiver(mUploadFinishReceiver
); 
 842             mUploadFinishReceiver 
= null
; 
 844         if (mDownloadFinishReceiver 
!= null
) { 
 845             unregisterReceiver(mDownloadFinishReceiver
); 
 846             mDownloadFinishReceiver 
= null
; 
 850         Log_OC
.v(TAG
, "onPause() end"); 
 854     private class SyncBroadcastReceiver 
extends BroadcastReceiver 
{ 
 857          * {@link BroadcastReceiver} to enable syncing feedback in UI 
 860         public void onReceive(Context context
, Intent intent
) { 
 862                 String event 
= intent
.getAction(); 
 863                 Log_OC
.d(TAG
, "Received broadcast " + event
); 
 864                 String accountName 
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
); 
 865                 String synchFolderRemotePath 
= 
 866                         intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
); 
 867                 RemoteOperationResult synchResult 
= 
 868                         (RemoteOperationResult
)intent
.getSerializableExtra( 
 869                                 FileSyncAdapter
.EXTRA_RESULT
); 
 870                 boolean sameAccount 
= (getAccount() != null 
&& 
 871                         accountName
.equals(getAccount().name
) && getStorageManager() != null
); 
 875                     if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) { 
 876                         mSyncInProgress 
= true
; 
 879                         OCFile currentFile 
= (getFile() == null
) ? null 
: 
 880                                 getStorageManager().getFileByPath(getFile().getRemotePath()); 
 881                         OCFile currentDir 
= (getCurrentDir() == null
) ? null 
: 
 882                                 getStorageManager().getFileByPath(getCurrentDir().getRemotePath()); 
 884                         if (currentDir 
== null
) { 
 885                             // current folder was removed from the server  
 886                             Toast
.makeText( FileDisplayActivity
.this,  
 889                                                             sync_current_folder_was_removed
), 
 890                                                    synchFolderRemotePath
), 
 897                             if (currentFile 
== null 
&& !getFile().isFolder()) { 
 898                                 // currently selected file was removed in the server, and now we 
 900                                 cleanSecondFragment(); 
 901                                 currentFile 
= currentDir
; 
 904                             if (synchFolderRemotePath 
!= null 
&& 
 905                                     currentDir
.getRemotePath().equals(synchFolderRemotePath
)) { 
 906                                 OCFileListFragment fileListFragment 
= getListOfFilesFragment(); 
 907                                 if (fileListFragment 
!= null
) { 
 908                                     fileListFragment
.listDirectory(); 
 909                                     // TODO Enable when "On Device" is recovered ? 
 910                                     // fileListFragment.listDirectory(currentDir, 
 911                                     // MainApp.getOnlyOnDevice()); 
 914                             setFile(currentFile
); 
 917                         mSyncInProgress 
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && 
 918                                 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
 
 921                         if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
. 
 922                                     equals(event
) &&/// TODO refactor and make common 
 923                                 synchResult 
!= null 
&& !synchResult
.isSuccess() && 
 924                                 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED 
|| 
 925                                         synchResult
.isIdPRedirection() || 
 926                                         (synchResult
.isException() && synchResult
.getException() 
 927                                                 instanceof AuthenticatorException
))) { 
 931                                 OwnCloudClient client
; 
 932                                 OwnCloudAccount ocAccount 
= 
 933                                         new OwnCloudAccount(getAccount(), context
); 
 934                                 client 
= (OwnCloudClientManagerFactory
.getDefaultSingleton(). 
 935                                         removeClientFor(ocAccount
)); 
 936                                 if (client 
!= null
) { 
 937                                     OwnCloudCredentials cred 
= client
.getCredentials(); 
 939                                         AccountManager am 
= AccountManager
.get(context
); 
 940                                         if (cred
.authTokenExpires()) { 
 941                                             am
.invalidateAuthToken( 
 946                                             am
.clearPassword(getAccount()); 
 950                                 requestCredentialsUpdate(); 
 952                             } catch (AccountNotFoundException e
) { 
 953                                 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
); 
 958                     removeStickyBroadcast(intent
); 
 959                     Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
); 
 960                     mProgressBar
.setIndeterminate(mSyncInProgress
); 
 961                     //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE); 
 962                     //setSupportProgressBarIndeterminateVisibility(mSyncInProgress 
 963                     /*|| mRefreshSharesInProgress*/ //); 
 969                 if (synchResult 
!= null
) { 
 970                     if (synchResult
.getCode().equals( 
 971                             RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) { 
 972                         mLastSslUntrustedServerResult 
= synchResult
; 
 975             } catch (RuntimeException e
) { 
 976                 // avoid app crashes after changing the serial id of RemoteOperationResult  
 977                 // in owncloud library with broadcast notifications pending to process 
 978                 removeStickyBroadcast(intent
); 
 984      * Show a text message on screen view for notifying user if content is 
 985      * loading or folder is empty 
 987     private void setBackgroundText() { 
 988         OCFileListFragment ocFileListFragment 
= getListOfFilesFragment(); 
 989         if (ocFileListFragment 
!= null
) { 
 990             int message 
= R
.string
.file_list_loading
; 
 991             if (!mSyncInProgress
) { 
 992                 // In case file list is empty 
 993                 message 
= R
.string
.file_list_empty
; 
 995             ocFileListFragment
.setMessageForEmptyList(getString(message
)); 
 997             Log_OC
.e(TAG
, "OCFileListFragment is null"); 
1002      * Once the file upload has finished -> update view 
1004     private class UploadFinishReceiver 
extends BroadcastReceiver 
{ 
1006          * Once the file upload has finished -> update view 
1008          * @author David A. Velasco 
1009          * {@link BroadcastReceiver} to enable upload feedback in UI 
1012         public void onReceive(Context context
, Intent intent
) { 
1014                 String uploadedRemotePath 
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
); 
1015                 String accountName 
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
); 
1016                 boolean sameAccount 
= getAccount() != null 
&& accountName
.equals(getAccount().name
); 
1017                 OCFile currentDir 
= getCurrentDir(); 
1018                 boolean isDescendant 
= (currentDir 
!= null
) && (uploadedRemotePath 
!= null
) && 
1019                         (uploadedRemotePath
.startsWith(currentDir
.getRemotePath())); 
1021                 if (sameAccount 
&& isDescendant
) { 
1022                     refreshListOfFilesFragment(); 
1024                 boolean uploadWasFine 
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, 
1026                 boolean renamedInUpload 
= getFile().getRemotePath(). 
1027                         equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
)); 
1028                 boolean sameFile 
= getFile().getRemotePath().equals(uploadedRemotePath
) || 
1030                 FileFragment details 
= getSecondFragment(); 
1031                 boolean detailFragmentIsShown 
= (details 
!= null 
&& 
1032                         details 
instanceof FileDetailFragment
); 
1034                 if (sameAccount 
&& sameFile 
&& detailFragmentIsShown
) { 
1035                     if (uploadWasFine
) { 
1036                         setFile(getStorageManager().getFileByPath(uploadedRemotePath
)); 
1038                     if (renamedInUpload
) { 
1039                         String newName 
= (new File(uploadedRemotePath
)).getName(); 
1040                         Toast msg 
= Toast
.makeText( 
1043                                         getString(R
.string
.filedetails_renamed_in_upload_msg
), 
1048                     if (uploadWasFine 
|| getFile().fileExists()) { 
1049                         ((FileDetailFragment
) details
).updateFileDetails(false
, true
); 
1051                         cleanSecondFragment(); 
1054                     // Force the preview if the file is an image or text file 
1055                     if (uploadWasFine
) { 
1056                         OCFile ocFile 
= getFile(); 
1057                         if (PreviewImageFragment
.canBePreviewed(ocFile
)) 
1058                             startImagePreview(getFile()); 
1059                         else if (PreviewTextFragment
.canBePreviewed(ocFile
)) 
1060                             startTextPreview(ocFile
); 
1061                         // TODO what about other kind of previews? 
1065                 mProgressBar
.setIndeterminate(false
); 
1067                 if (intent 
!= null
) { 
1068                     removeStickyBroadcast(intent
); 
1078      * Class waiting for broadcast events from the {@link FileDownloader} service. 
1080      * Updates the UI when a download is started or finished, provided that it is relevant for the 
1083     private class DownloadFinishReceiver 
extends BroadcastReceiver 
{ 
1085         //int refreshCounter = 0; 
1087         public void onReceive(Context context
, Intent intent
) { 
1089                 boolean sameAccount 
= isSameAccount(context
, intent
); 
1090                 String downloadedRemotePath 
= 
1091                         intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
); 
1092                 boolean isDescendant 
= isDescendant(downloadedRemotePath
); 
1094                 if (sameAccount 
&& isDescendant
) { 
1095                     String linkedToRemotePath 
= 
1096                             intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
); 
1097                     if (linkedToRemotePath 
== null 
|| isAscendant(linkedToRemotePath
)) { 
1098                         //Log_OC.v(TAG, "refresh #" + ++refreshCounter); 
1099                         refreshListOfFilesFragment(); 
1101                     refreshSecondFragment( 
1103                             downloadedRemotePath
, 
1104                             intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
) 
1108                 if (mWaitingToSend 
!= null
) { 
1110                             getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); 
1111                     if (mWaitingToSend
.isDown()) { 
1112                         sendDownloadedFile(); 
1117                 if (intent 
!= null
) { 
1118                     removeStickyBroadcast(intent
); 
1123         private boolean isDescendant(String downloadedRemotePath
) { 
1124             OCFile currentDir 
= getCurrentDir(); 
1126                 currentDir 
!= null 
&& 
1127                 downloadedRemotePath 
!= null 
&& 
1128                 downloadedRemotePath
.startsWith(currentDir
.getRemotePath()) 
1132         private boolean isAscendant(String linkedToRemotePath
) { 
1133             OCFile currentDir 
= getCurrentDir(); 
1135                 currentDir 
!= null 
&& 
1136                 currentDir
.getRemotePath().startsWith(linkedToRemotePath
) 
1140         private boolean isSameAccount(Context context
, Intent intent
) { 
1141             String accountName 
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
); 
1142             return (accountName 
!= null 
&& getAccount() != null 
&& 
1143                     accountName
.equals(getAccount().name
)); 
1148     public void browseToRoot() { 
1149         OCFileListFragment listOfFiles 
= getListOfFilesFragment(); 
1150         if (listOfFiles 
!= null
) {  // should never be null, indeed 
1151             OCFile root 
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); 
1152             listOfFiles
.listDirectory(root
); 
1153             // TODO Enable when "On Device" is recovered ? 
1154             // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice()); 
1155             setFile(listOfFiles
.getCurrentFile()); 
1156             startSyncFolderOperation(root
, false
); 
1158         cleanSecondFragment(); 
1165      * Updates action bar and second fragment, if in dual pane mode. 
1168     public void onBrowsedDownTo(OCFile directory
) { 
1170         cleanSecondFragment(); 
1172         startSyncFolderOperation(directory
, false
); 
1176      * Shows the information of the {@link OCFile} received as a 
1177      * parameter in the second fragment. 
1179      * @param file {@link OCFile} whose details will be shown 
1182     public void showDetails(OCFile file
) { 
1183         Fragment detailFragment 
= FileDetailFragment
.newInstance(file
, getAccount()); 
1184         setSecondFragment(detailFragment
); 
1185         updateFragmentsVisibility(true
); 
1186         updateActionBarTitleAndHomeButton(file
); 
1191     protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) { 
1193             // in dual pane mode, keep the focus of title an action bar in the current folder 
1194             super.updateActionBarTitleAndHomeButton(getCurrentDir()); 
1197             super.updateActionBarTitleAndHomeButton(chosenFile
); 
1203     protected ServiceConnection 
newTransferenceServiceConnection() { 
1204         return new ListServiceConnection(); 
1208      * Defines callbacks for service binding, passed to bindService() 
1210     private class ListServiceConnection 
implements ServiceConnection 
{ 
1213         public void onServiceConnected(ComponentName component
, IBinder service
) { 
1214             if (component
.equals(new ComponentName( 
1215                     FileDisplayActivity
.this, FileDownloader
.class))) { 
1216                 Log_OC
.d(TAG
, "Download service connected"); 
1217                 mDownloaderBinder 
= (FileDownloaderBinder
) service
; 
1218                 if (mWaitingToPreview 
!= null
) 
1219                     if (getStorageManager() != null
) { 
1222                                 getStorageManager().getFileById(mWaitingToPreview
.getFileId()); 
1223                         if (!mWaitingToPreview
.isDown()) { 
1224                             requestForDownload(); 
1228             } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, 
1229                     FileUploader
.class))) { 
1230                 Log_OC
.d(TAG
, "Upload service connected"); 
1231                 mUploaderBinder 
= (FileUploaderBinder
) service
; 
1235             // a new chance to get the mDownloadBinder through 
1236             // getFileDownloadBinder() - THIS IS A MESS 
1237             OCFileListFragment listOfFiles 
= getListOfFilesFragment(); 
1238             if (listOfFiles 
!= null
) { 
1239                 listOfFiles
.listDirectory(); 
1240                 // TODO Enable when "On Device" is recovered ? 
1241                 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice()); 
1243             FileFragment secondFragment 
= getSecondFragment(); 
1244             if (secondFragment 
!= null 
&& secondFragment 
instanceof FileDetailFragment
) { 
1245                 FileDetailFragment detailFragment 
= (FileDetailFragment
) secondFragment
; 
1246                 detailFragment
.listenForTransferProgress(); 
1247                 detailFragment
.updateFileDetails(false
, false
); 
1252         public void onServiceDisconnected(ComponentName component
) { 
1253             if (component
.equals(new ComponentName(FileDisplayActivity
.this, 
1254                     FileDownloader
.class))) { 
1255                 Log_OC
.d(TAG
, "Download service disconnected"); 
1256                 mDownloaderBinder 
= null
; 
1257             } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, 
1258                     FileUploader
.class))) { 
1259                 Log_OC
.d(TAG
, "Upload service disconnected"); 
1260                 mUploaderBinder 
= null
; 
1266     public void onSavedCertificate() { 
1267         startSyncFolderOperation(getCurrentDir(), false
); 
1272     public void onFailedSavingCertificate() { 
1273         ConfirmationDialogFragment dialog 
= ConfirmationDialogFragment
.newInstance( 
1274                 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1 
1276         dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
); 
1280     public void onCancelCertificate() { 
1285      * Updates the view associated to the activity after the finish of some operation over files 
1286      * in the current account. 
1288      * @param operation Removal operation performed. 
1289      * @param result    Result of the removal. 
1292     public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) { 
1293         super.onRemoteOperationFinish(operation
, result
); 
1295         if (operation 
instanceof RemoveFileOperation
) { 
1296             onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
); 
1298         } else if (operation 
instanceof RenameFileOperation
) { 
1299             onRenameFileOperationFinish((RenameFileOperation
) operation
, result
); 
1301         } else if (operation 
instanceof SynchronizeFileOperation
) { 
1302             onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
); 
1304         } else if (operation 
instanceof CreateFolderOperation
) { 
1305             onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
); 
1307         } else if (operation 
instanceof CreateShareOperation
) { 
1308             onCreateShareOperationFinish((CreateShareOperation
) operation
, result
); 
1310         } else if (operation 
instanceof UnshareLinkOperation
) { 
1311             onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
); 
1313         } else if (operation 
instanceof MoveFileOperation
) { 
1314             onMoveFileOperationFinish((MoveFileOperation
) operation
, result
); 
1319     private void onCreateShareOperationFinish(CreateShareOperation operation
, 
1320                                               RemoteOperationResult result
) { 
1321         if (result
.isSuccess()) { 
1322             refreshShowDetails(); 
1323             refreshListOfFilesFragment(); 
1327     private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, 
1328                                               RemoteOperationResult result
) { 
1329         if (result
.isSuccess()) { 
1330             refreshShowDetails(); 
1331             refreshListOfFilesFragment(); 
1333         } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) { 
1334             cleanSecondFragment(); 
1335             refreshListOfFilesFragment(); 
1339     private void refreshShowDetails() { 
1340         FileFragment details 
= getSecondFragment(); 
1341         if (details 
!= null
) { 
1342             OCFile file 
= details
.getFile(); 
1344                 file 
= getStorageManager().getFileByPath(file
.getRemotePath()); 
1345                 if (details 
instanceof PreviewMediaFragment
) { 
1346                     // Refresh  OCFile of the fragment 
1347                     ((PreviewMediaFragment
) details
).updateFile(file
); 
1348                 } else if (details 
instanceof PreviewTextFragment
) { 
1349                     // Refresh  OCFile of the fragment 
1350                     ((PreviewTextFragment
) details
).updateFile(file
); 
1354             invalidateOptionsMenu(); 
1359      * Updates the view associated to the activity after the finish of an operation trying to 
1362      * @param operation     Removal operation performed. 
1363      * @param result        Result of the removal. 
1365     private void onRemoveFileOperationFinish(RemoveFileOperation operation
, 
1366                                              RemoteOperationResult result
) { 
1367         dismissLoadingDialog(); 
1368         Toast msg 
= Toast
.makeText(this, 
1369                 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()), 
1373         if (result
.isSuccess()) { 
1374             OCFile removedFile 
= operation
.getFile(); 
1375             FileFragment second 
= getSecondFragment(); 
1376             if (second 
!= null 
&& removedFile
.equals(second
.getFile())) { 
1377                 if (second 
instanceof PreviewMediaFragment
) { 
1378                     ((PreviewMediaFragment
) second
).stopPreview(true
); 
1380                 setFile(getStorageManager().getFileById(removedFile
.getParentId())); 
1381                 cleanSecondFragment(); 
1383             if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){ 
1384                 refreshListOfFilesFragment(); 
1386             invalidateOptionsMenu(); 
1388             if (result
.isSslRecoverableException()) { 
1389                 mLastSslUntrustedServerResult 
= result
; 
1390                 showUntrustedCertDialog(mLastSslUntrustedServerResult
); 
1397      * Updates the view associated to the activity after the finish of an operation trying to move a 
1400      * @param operation Move operation performed. 
1401      * @param result    Result of the move operation. 
1403     private void onMoveFileOperationFinish(MoveFileOperation operation
, 
1404                                            RemoteOperationResult result
) { 
1405         if (result
.isSuccess()) { 
1406             dismissLoadingDialog(); 
1407             refreshListOfFilesFragment(); 
1409             dismissLoadingDialog(); 
1411                 Toast msg 
= Toast
.makeText(FileDisplayActivity
.this, 
1412                         ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()), 
1416             } catch (NotFoundException e
) { 
1417                 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
); 
1424      * Updates the view associated to the activity after the finish of an operation trying to rename 
1427      * @param operation     Renaming operation performed. 
1428      * @param result        Result of the renaming. 
1430     private void onRenameFileOperationFinish(RenameFileOperation operation
, 
1431                                              RemoteOperationResult result
) { 
1432         dismissLoadingDialog(); 
1433         OCFile renamedFile 
= operation
.getFile(); 
1434         if (result
.isSuccess()) { 
1435             FileFragment details 
= getSecondFragment(); 
1436             if (details 
!= null
) { 
1437                 if (details 
instanceof FileDetailFragment 
&& 
1438                         renamedFile
.equals(details
.getFile()) ) { 
1439                     ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount()); 
1440                     showDetails(renamedFile
); 
1442                 } else if (details 
instanceof PreviewMediaFragment 
&& 
1443                         renamedFile
.equals(details
.getFile())) { 
1444                     ((PreviewMediaFragment
) details
).updateFile(renamedFile
); 
1445                     if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) { 
1446                         int position 
= ((PreviewMediaFragment
) details
).getPosition(); 
1447                         startMediaPreview(renamedFile
, position
, true
); 
1449                         getFileOperationsHelper().openFile(renamedFile
); 
1451                 } else if (details 
instanceof PreviewTextFragment 
&& 
1452                         renamedFile
.equals(details
.getFile())) { 
1453                     ((PreviewTextFragment
) details
).updateFile(renamedFile
); 
1454                     if (PreviewTextFragment
.canBePreviewed(renamedFile
)) { 
1455                         startTextPreview(renamedFile
); 
1457                         getFileOperationsHelper().openFile(renamedFile
); 
1462             if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){ 
1463                 refreshListOfFilesFragment(); 
1467             Toast msg 
= Toast
.makeText(this, 
1468                     ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()), 
1472             if (result
.isSslRecoverableException()) { 
1473                 mLastSslUntrustedServerResult 
= result
; 
1474                 showUntrustedCertDialog(mLastSslUntrustedServerResult
); 
1479     private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, 
1480                                                   RemoteOperationResult result
) { 
1481         if (result
.isSuccess()) { 
1482             if (operation
.transferWasRequested()) { 
1483                 OCFile syncedFile 
= operation
.getLocalFile(); 
1484                 onTransferStateChanged(syncedFile
, true
, true
); 
1485                 invalidateOptionsMenu(); 
1491      * Updates the view associated to the activity after the finish of an operation trying create a 
1494      * @param operation     Creation operation performed. 
1495      * @param result        Result of the creation. 
1497     private void onCreateFolderOperationFinish(CreateFolderOperation operation
, 
1498                                                RemoteOperationResult result
) { 
1499         if (result
.isSuccess()) { 
1500             dismissLoadingDialog(); 
1501             refreshListOfFilesFragment(); 
1503             dismissLoadingDialog(); 
1505                 Toast msg 
= Toast
.makeText(FileDisplayActivity
.this, 
1506                         ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()), 
1510             } catch (NotFoundException e
) { 
1511                 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
); 
1521     public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) { 
1522         refreshListOfFilesFragment(); 
1523         FileFragment details 
= getSecondFragment(); 
1524         if (details 
!= null 
&& details 
instanceof FileDetailFragment 
&& 
1525                 file
.equals(details
.getFile()) ) { 
1526             if (downloading 
|| uploading
) { 
1527                 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount()); 
1529                 if (!file
.fileExists()) { 
1530                     cleanSecondFragment(); 
1532                     ((FileDetailFragment
) details
).updateFileDetails(false
, true
); 
1540     private void requestForDownload() { 
1541         Account account 
= getAccount(); 
1542         //if (!mWaitingToPreview.isDownloading()) { 
1543         if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) { 
1544             Intent i 
= new Intent(this, FileDownloader
.class); 
1545             i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
); 
1546             i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
); 
1552     private OCFile 
getCurrentDir() { 
1553         OCFile file 
= getFile(); 
1555             if (file
.isFolder()) { 
1557             } else if (getStorageManager() != null
) { 
1558                 String parentPath 
= file
.getRemotePath().substring(0, 
1559                         file
.getRemotePath().lastIndexOf(file
.getFileName())); 
1560                 return getStorageManager().getFileByPath(parentPath
); 
1566     public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) { 
1567         long currentSyncTime 
= System
.currentTimeMillis(); 
1569         mSyncInProgress 
= true
; 
1571         // perform folder synchronization 
1572         RemoteOperation synchFolderOp 
= new RefreshFolderOperation( folder
, 
1575                 getFileOperationsHelper().isSharedSupported(), 
1577                 getStorageManager(), 
1579                 getApplicationContext() 
1581         synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
); 
1583         mProgressBar
.setIndeterminate(true
); 
1585         setBackgroundText(); 
1589      * Show untrusted cert dialog 
1591     public void showUntrustedCertDialog(RemoteOperationResult result
) { 
1592         // Show a dialog with the certificate info 
1593         SslUntrustedCertDialog dialog 
= SslUntrustedCertDialog
.newInstanceForFullSslError( 
1594                 (CertificateCombinedException
) result
.getException()); 
1595         FragmentManager fm 
= getSupportFragmentManager(); 
1596         FragmentTransaction ft 
= fm
.beginTransaction(); 
1597         dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
); 
1600     private void requestForDownload(OCFile file
) { 
1601         Account account 
= getAccount(); 
1602         if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) { 
1603             Intent i 
= new Intent(this, FileDownloader
.class); 
1604             i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
); 
1605             i
.putExtra(FileDownloader
.EXTRA_FILE
, file
); 
1610     private void sendDownloadedFile() { 
1611         getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
); 
1612         mWaitingToSend 
= null
; 
1617      * Requests the download of the received {@link OCFile} , updates the UI 
1618      * to monitor the download progress and prepares the activity to send the file 
1619      * when the download finishes. 
1621      * @param file {@link OCFile} to download and preview. 
1623     public void startDownloadForSending(OCFile file
) { 
1624         mWaitingToSend 
= file
; 
1625         requestForDownload(mWaitingToSend
); 
1626         boolean hasSecondFragment 
= (getSecondFragment() != null
); 
1627         updateFragmentsVisibility(hasSecondFragment
); 
1631      * Opens the image gallery showing the image {@link OCFile} received as parameter. 
1633      * @param file Image {@link OCFile} to show. 
1635     public void startImagePreview(OCFile file
) { 
1636         Intent showDetailsIntent 
= new Intent(this, PreviewImageActivity
.class); 
1637         showDetailsIntent
.putExtra(EXTRA_FILE
, file
); 
1638         showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount()); 
1639         startActivity(showDetailsIntent
); 
1643      * Stars the preview of an already down media {@link OCFile}. 
1645      * @param file                      Media {@link OCFile} to preview. 
1646      * @param startPlaybackPosition     Media position where the playback will be started, 
1648      * @param autoplay                  When 'true', the playback will start without user 
1651     public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) { 
1652         Fragment mediaFragment 
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, 
1654         setSecondFragment(mediaFragment
); 
1655         updateFragmentsVisibility(true
); 
1656         updateActionBarTitleAndHomeButton(file
); 
1661      * Stars the preview of a text file {@link OCFile}. 
1663      * @param file Text {@link OCFile} to preview. 
1665     public void startTextPreview(OCFile file
) { 
1666         Bundle args 
= new Bundle(); 
1667         args
.putParcelable(EXTRA_FILE
, file
); 
1668         args
.putParcelable(EXTRA_ACCOUNT
, getAccount()); 
1669         Fragment textPreviewFragment 
= Fragment
.instantiate(getApplicationContext(), 
1670                 PreviewTextFragment
.class.getName(), args
); 
1671         setSecondFragment(textPreviewFragment
); 
1672         updateFragmentsVisibility(true
); 
1673         //updateNavigationElementsInActionBar(file); 
1678      * Requests the download of the received {@link OCFile} , updates the UI 
1679      * to monitor the download progress and prepares the activity to preview 
1680      * or open the file when the download finishes. 
1682      * @param file {@link OCFile} to download and preview. 
1684     public void startDownloadForPreview(OCFile file
) { 
1685         Fragment detailFragment 
= FileDetailFragment
.newInstance(file
, getAccount()); 
1686         setSecondFragment(detailFragment
); 
1687         mWaitingToPreview 
= file
; 
1688         requestForDownload(); 
1689         updateFragmentsVisibility(true
); 
1690         updateActionBarTitleAndHomeButton(file
); 
1695     public void cancelTransference(OCFile file
) { 
1696         getFileOperationsHelper().cancelTransference(file
); 
1697         if (mWaitingToPreview 
!= null 
&& 
1698                 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) { 
1699             mWaitingToPreview 
= null
; 
1701         if (mWaitingToSend 
!= null 
&& 
1702                 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) { 
1703             mWaitingToSend 
= null
; 
1705         onTransferStateChanged(file
, false
, false
); 
1709     public void onRefresh(boolean ignoreETag
) { 
1710         refreshList(ignoreETag
); 
1714     public void onRefresh() { 
1718     private void refreshList(boolean ignoreETag
) { 
1719         OCFileListFragment listOfFiles 
= getListOfFilesFragment(); 
1720         if (listOfFiles 
!= null
) { 
1721             OCFile folder 
= listOfFiles
.getCurrentFile(); 
1722             if (folder 
!= null
) { 
1723                 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId()); 
1724                 listDirectory(mFile);*/ 
1725                 startSyncFolderOperation(folder
, ignoreETag
); 
1730     private void sortByDate(boolean ascending
) { 
1731         getListOfFilesFragment().sortByDate(ascending
); 
1734     private void sortBySize(boolean ascending
) { 
1735         getListOfFilesFragment().sortBySize(ascending
); 
1738     private void sortByName(boolean ascending
) { 
1739         getListOfFilesFragment().sortByName(ascending
); 
1742    public void allFilesOption() {