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
; 
  23 import android
.accounts
.Account
; 
  24 import android
.app
.AlertDialog
; 
  25 import android
.app
.Dialog
; 
  26 import android
.app
.ProgressDialog
; 
  27 import android
.content
.BroadcastReceiver
; 
  28 import android
.content
.ComponentName
; 
  29 import android
.content
.ContentResolver
; 
  30 import android
.content
.Context
; 
  31 import android
.content
.DialogInterface
; 
  32 import android
.content
.Intent
; 
  33 import android
.content
.IntentFilter
; 
  34 import android
.content
.ServiceConnection
; 
  35 import android
.content
.SharedPreferences
; 
  36 import android
.content
.SyncRequest
; 
  37 import android
.content
.res
.Resources
.NotFoundException
; 
  38 import android
.database
.Cursor
; 
  39 import android
.net
.Uri
; 
  40 import android
.os
.Bundle
; 
  41 import android
.os
.IBinder
; 
  42 import android
.preference
.PreferenceManager
; 
  43 import android
.provider
.MediaStore
; 
  44 import android
.support
.v4
.app
.Fragment
; 
  45 import android
.support
.v4
.app
.FragmentManager
; 
  46 import android
.support
.v4
.app
.FragmentTransaction
; 
  47 //import android.support.v4.content.LocalBroadcastManager; 
  48 import android
.util
.Log
; 
  49 import android
.view
.View
; 
  50 import android
.view
.ViewGroup
; 
  51 import android
.widget
.ArrayAdapter
; 
  52 import android
.widget
.TextView
; 
  53 import android
.widget
.Toast
; 
  55 import com
.actionbarsherlock
.app
.ActionBar
; 
  56 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
; 
  57 import com
.actionbarsherlock
.view
.Menu
; 
  58 import com
.actionbarsherlock
.view
.MenuInflater
; 
  59 import com
.actionbarsherlock
.view
.MenuItem
; 
  60 import com
.actionbarsherlock
.view
.Window
; 
  61 import com
.owncloud
.android
.MainApp
; 
  62 import com
.owncloud
.android
.R
; 
  63 import com
.owncloud
.android
.datamodel
.OCFile
; 
  64 import com
.owncloud
.android
.files
.services
.FileDownloader
; 
  65 import com
.owncloud
.android
.files
.services
.FileObserverService
; 
  66 import com
.owncloud
.android
.files
.services
.FileUploader
; 
  67 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
; 
  68 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
; 
  69 import com
.owncloud
.android
.operations
.CreateFolderOperation
; 
  71 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
; 
  72 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
; 
  73 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
; 
  74 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
; 
  75 import com
.owncloud
.android
.operations
.CreateShareOperation
; 
  76 import com
.owncloud
.android
.operations
.RemoveFileOperation
; 
  77 import com
.owncloud
.android
.operations
.RenameFileOperation
; 
  78 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
; 
  79 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
; 
  80 import com
.owncloud
.android
.operations
.UnshareLinkOperation
; 
  81 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
; 
  82 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
; 
  83 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
; 
  84 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
; 
  85 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
; 
  86 import com
.owncloud
.android
.ui
.fragment
.FileFragment
; 
  87 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
; 
  88 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
; 
  89 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
; 
  90 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
; 
  91 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
; 
  92 import com
.owncloud
.android
.utils
.DisplayUtils
; 
  93 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
; 
  94 import com
.owncloud
.android
.utils
.Log_OC
; 
  98  * Displays, what files the user has available in his ownCloud. 
 100  * @author Bartek Przybylski 
 101  * @author David A. Velasco 
 104 public class FileDisplayActivity 
extends HookActivity 
implements 
 105 FileFragment
.ContainerActivity
, OnNavigationListener
, OnSslUntrustedCertListener 
{ 
 107     private ArrayAdapter
<String
> mDirectories
; 
 109     private SyncBroadcastReceiver mSyncBroadcastReceiver
; 
 110     private UploadFinishReceiver mUploadFinishReceiver
; 
 111     private DownloadFinishReceiver mDownloadFinishReceiver
; 
 112     private RemoteOperationResult mLastSslUntrustedServerResult 
= null
; 
 114     private boolean mDualPane
; 
 115     private View mLeftFragmentContainer
; 
 116     private View mRightFragmentContainer
; 
 118     private static final String KEY_WAITING_TO_PREVIEW 
= "WAITING_TO_PREVIEW"; 
 119     private static final String KEY_SYNC_IN_PROGRESS 
= "SYNC_IN_PROGRESS"; 
 120     private static final String KEY_WAITING_TO_SEND 
= "WAITING_TO_SEND"; 
 122     public static final int DIALOG_SHORT_WAIT 
= 0; 
 123     private static final int DIALOG_CHOOSE_UPLOAD_SOURCE 
= 1; 
 124     private static final int DIALOG_CERT_NOT_SAVED 
= 2; 
 126     public static final String ACTION_DETAILS 
= "com.owncloud.android.ui.activity.action.DETAILS"; 
 128     private static final int ACTION_SELECT_CONTENT_FROM_APPS 
= 1; 
 129     private static final int ACTION_SELECT_MULTIPLE_FILES 
= 2; 
 131     private static final String TAG 
= FileDisplayActivity
.class.getSimpleName(); 
 133     private static final String TAG_LIST_OF_FILES 
= "LIST_OF_FILES"; 
 134     private static final String TAG_SECOND_FRAGMENT 
= "SECOND_FRAGMENT"; 
 136     private OCFile mWaitingToPreview
; 
 138     private boolean mSyncInProgress 
= false
; 
 140     private String DIALOG_UNTRUSTED_CERT
; 
 142     private OCFile mWaitingToSend
; 
 145     protected void onCreate(Bundle savedInstanceState
) { 
 146         Log_OC
.d(TAG
, "onCreate() start"); 
 147         requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
); 
 149         super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid 
 151         // PIN CODE request ;  best location is to decide, let's try this first 
 152         if (getIntent().getAction() != null 
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState 
== null
) { 
 154         } else if (getIntent().getAction() == null 
&& savedInstanceState 
== null
) { 
 159         Intent observer_intent 
= new Intent(this, FileObserverService
.class); 
 160         observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
); 
 161         startService(observer_intent
); 
 163         /// Load of saved instance state 
 164         if(savedInstanceState 
!= null
) { 
 165             mWaitingToPreview 
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
); 
 166             mSyncInProgress 
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
); 
 167             mWaitingToSend 
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
); 
 170             mWaitingToPreview 
= null
; 
 171             mSyncInProgress 
= false
; 
 172             mWaitingToSend 
= null
; 
 177         // Inflate and set the layout view 
 178         setContentView(R
.layout
.files
);     
 179         mDualPane 
= getResources().getBoolean(R
.bool
.large_land_layout
); 
 180         mLeftFragmentContainer 
= findViewById(R
.id
.left_fragment_container
); 
 181         mRightFragmentContainer 
= findViewById(R
.id
.right_fragment_container
); 
 182         if (savedInstanceState 
== null
) { 
 183             createMinFragments(); 
 187         mDirectories 
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
); 
 188         getSupportActionBar().setHomeButtonEnabled(true
);       // mandatory since Android ICS, according to the official documentation 
 189         setSupportProgressBarIndeterminateVisibility(mSyncInProgress 
/*|| mRefreshSharesInProgress*/);    // always AFTER setContentView(...) ; to work around bug in its implementation 
 191         Log_OC
.d(TAG
, "onCreate() end"); 
 195     protected void onStart() { 
 197         getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId()); 
 201     protected void onDestroy() { 
 206      *  Called when the ownCloud {@link Account} associated to the Activity was just updated. 
 209     protected void onAccountSet(boolean stateWasRecovered
) { 
 210         super.onAccountSet(stateWasRecovered
); 
 211         if (getAccount() != null
) { 
 212             /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account 
 213             OCFile file 
= getFile(); 
 214             // get parent from path 
 215             String parentPath 
= ""; 
 217                 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) { 
 218                     // upload in progress - right now, files are not inserted in the local cache until the upload is successful 
 219                     // get parent from path 
 220                     parentPath 
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName())); 
 221                     if (getStorageManager().getFileByPath(parentPath
) ==  null
) 
 222                         file 
= null
; // not able to know the directory where the file is uploading 
 224                     file 
= getStorageManager().getFileByPath(file
.getRemotePath());   // currentDir = null if not in the current Account 
 228                 // fall back to root folder 
 229                 file 
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);  // never returns null 
 232             setNavigationListWithFolder(file
); 
 234             if (!stateWasRecovered
) { 
 235                 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged.."); 
 236                 initFragmentsWithFile(); 
 237                 if (file
.isFolder()) { 
 238                     startSyncFolderOperation(file
); 
 242                 updateFragmentsVisibility(!file
.isFolder()); 
 243                 updateNavigationElementsInActionBar(file
.isFolder() ? null 
: file
); 
 249     private void setNavigationListWithFolder(OCFile file
) { 
 250         mDirectories
.clear(); 
 251         OCFile fileIt 
= file
; 
 253         while(fileIt 
!= null 
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) { 
 254             if (fileIt
.isFolder()) { 
 255                 mDirectories
.add(fileIt
.getFileName()); 
 257             // get parent from path 
 258             parentPath 
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName())); 
 259             fileIt 
= getStorageManager().getFileByPath(parentPath
); 
 261         mDirectories
.add(OCFile
.PATH_SEPARATOR
); 
 265     private void createMinFragments() { 
 266         OCFileListFragment listOfFiles 
= new OCFileListFragment(); 
 267         FragmentTransaction transaction 
= getSupportFragmentManager().beginTransaction(); 
 268         transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
); 
 269         transaction
.commit(); 
 272     private void initFragmentsWithFile() { 
 273         if (getAccount() != null 
&& getFile() != null
) { 
 275             OCFileListFragment listOfFiles 
= getListOfFilesFragment();  
 276             if (listOfFiles 
!= null
) { 
 277                 listOfFiles
.listDirectory(getCurrentDir());    
 279                 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >("); 
 283             OCFile file 
= getFile();  
 284             Fragment secondFragment 
= chooseInitialSecondFragment(file
); 
 285             if (secondFragment 
!= null
) { 
 286                 setSecondFragment(secondFragment
); 
 287                 updateFragmentsVisibility(true
); 
 288                 updateNavigationElementsInActionBar(file
); 
 291                 cleanSecondFragment(); 
 295             Log
.wtf(TAG
, "initFragments() called with invalid NULLs!"); 
 296             if (getAccount() == null
) { 
 297                 Log
.wtf(TAG
, "\t account is NULL"); 
 299             if (getFile() == null
) { 
 300                 Log
.wtf(TAG
, "\t file is NULL"); 
 305     private Fragment 
chooseInitialSecondFragment(OCFile file
) { 
 306         Fragment secondFragment 
= null
; 
 307         if (file 
!= null 
&& !file
.isFolder()) { 
 308             if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)  
 309                     && file
.getLastSyncDateForProperties() > 0  // temporal fix 
 311                 int startPlaybackPosition 
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0); 
 312                 boolean autoplay 
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
); 
 313                 secondFragment 
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
); 
 316                 secondFragment 
= new FileDetailFragment(file
, getAccount()); 
 319         return secondFragment
; 
 324      * Replaces the second fragment managed by the activity with the received as 
 327      * Assumes never will be more than two fragments managed at the same time.  
 329      * @param fragment      New second Fragment to set. 
 331     private void setSecondFragment(Fragment fragment
) { 
 332         FragmentTransaction transaction 
= getSupportFragmentManager().beginTransaction(); 
 333         transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
); 
 334         transaction
.commit(); 
 338     private void updateFragmentsVisibility(boolean existsSecondFragment
) { 
 340             if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) { 
 341                 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
); 
 343             if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) { 
 344                 mRightFragmentContainer
.setVisibility(View
.VISIBLE
); 
 347         } else if (existsSecondFragment
) { 
 348             if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) { 
 349                 mLeftFragmentContainer
.setVisibility(View
.GONE
); 
 351             if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) { 
 352                 mRightFragmentContainer
.setVisibility(View
.VISIBLE
); 
 356             if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) { 
 357                 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
); 
 359             if (mRightFragmentContainer
.getVisibility() != View
.GONE
) { 
 360                 mRightFragmentContainer
.setVisibility(View
.GONE
); 
 366     private OCFileListFragment 
getListOfFilesFragment() { 
 367         Fragment listOfFiles 
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
); 
 368         if (listOfFiles 
!= null
) { 
 369             return (OCFileListFragment
)listOfFiles
; 
 371         Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!"); 
 375     public FileFragment 
getSecondFragment() { 
 376         Fragment second 
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
); 
 377         if (second 
!= null
) { 
 378             return (FileFragment
)second
; 
 383     protected void cleanSecondFragment() { 
 384         Fragment second 
= getSecondFragment(); 
 385         if (second 
!= null
) { 
 386             FragmentTransaction tr 
= getSupportFragmentManager().beginTransaction(); 
 390         updateFragmentsVisibility(false
); 
 391         updateNavigationElementsInActionBar(null
); 
 394     protected void refreshListOfFilesFragment() { 
 395         OCFileListFragment fileListFragment 
= getListOfFilesFragment(); 
 396         if (fileListFragment 
!= null
) {  
 397             fileListFragment
.listDirectory(); 
 401     protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) { 
 402         FileFragment secondFragment 
= getSecondFragment(); 
 403         boolean waitedPreview 
= (mWaitingToPreview 
!= null 
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
)); 
 404         if (secondFragment 
!= null 
&& secondFragment 
instanceof FileDetailFragment
) { 
 405             FileDetailFragment detailsFragment 
= (FileDetailFragment
) secondFragment
; 
 406             OCFile fileInFragment 
= detailsFragment
.getFile(); 
 407             if (fileInFragment 
!= null 
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) { 
 408                 // the user browsed to other file ; forget the automatic preview  
 409                 mWaitingToPreview 
= null
; 
 411             } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) { 
 412                 // grant that the right panel updates the progress bar 
 413                 detailsFragment
.listenForTransferProgress(); 
 414                 detailsFragment
.updateFileDetails(true
, false
); 
 416             } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) { 
 417                 //  update the right panel 
 418                 boolean detailsFragmentChanged 
= false
; 
 421                         mWaitingToPreview 
= getStorageManager().getFileById(mWaitingToPreview
.getFileId());   // update the file from database, for the local storage path 
 422                         if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) { 
 423                             startMediaPreview(mWaitingToPreview
, 0, true
); 
 424                             detailsFragmentChanged 
= true
; 
 426                             getFileOperationsHelper().openFile(mWaitingToPreview
); 
 429                     mWaitingToPreview 
= null
; 
 431                 if (!detailsFragmentChanged
) { 
 432                     detailsFragment
.updateFileDetails(false
, (success
)); 
 439     public boolean onCreateOptionsMenu(Menu menu
) { 
 440         MenuInflater inflater 
= getSherlock().getMenuInflater(); 
 441         inflater
.inflate(R
.menu
.main_menu
, menu
); 
 446     public boolean onOptionsItemSelected(MenuItem item
) { 
 447         boolean retval 
= true
; 
 448         switch (item
.getItemId()) { 
 449         case R
.id
.action_create_dir
: { 
 450             CreateFolderDialogFragment dialog 
=  
 451                     CreateFolderDialogFragment
.newInstance(getCurrentDir()); 
 452             dialog
.show(getSupportFragmentManager(), "createdirdialog"); 
 455         case R
.id
.action_sync_account
: { 
 456             startSynchronization(); 
 459         case R
.id
.action_upload
: { 
 460             showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
); 
 463         case R
.id
.action_settings
: { 
 464             Intent settingsIntent 
= new Intent(this, Preferences
.class); 
 465             startActivity(settingsIntent
); 
 468         case android
.R
.id
.home
: { 
 469             FileFragment second 
= getSecondFragment(); 
 470             OCFile currentDir 
= getCurrentDir(); 
 471             if((currentDir 
!= null 
&& currentDir
.getParentId() != 0) ||  
 472                     (second 
!= null 
&& second
.getFile() != null
)) {                 
 479             retval 
= super.onOptionsItemSelected(item
); 
 484     private void startSynchronization() { 
 485         Log_OC
.e(TAG
, "Got to start sync"); 
 486         if (android
.os
.Build
.VERSION
.SDK_INT 
< android
.os
.Build
.VERSION_CODES
.KITKAT
) { 
 487             Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority()); 
 488             ContentResolver
.cancelSync(null
, MainApp
.getAuthority());   // cancel the current synchronizations of any ownCloud account 
 489             Bundle bundle 
= new Bundle(); 
 490             bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
); 
 491             bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
); 
 492             Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name 
+ " at " + MainApp
.getAuthority()); 
 493             ContentResolver
.requestSync( 
 495                     MainApp
.getAuthority(), bundle
); 
 497             Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name 
+ " at " + MainApp
.getAuthority() + " with new API"); 
 498             SyncRequest
.Builder builder 
= new SyncRequest
.Builder(); 
 499             builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority()); 
 500             builder
.setExpedited(true
); 
 501             builder
.setManual(true
); 
 503             SyncRequest request 
= builder
.build(); 
 504             ContentResolver
.requestSync(request
); 
 510     public boolean onNavigationItemSelected(int itemPosition
, long itemId
) { 
 511         if (itemPosition 
!= 0) { 
 512             String targetPath 
= ""; 
 513             for (int i
=itemPosition
; i 
< mDirectories
.getCount() - 1; i
++) { 
 514                 targetPath 
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR 
+ targetPath
;  
 516             targetPath 
= OCFile
.PATH_SEPARATOR 
+ targetPath
; 
 517             OCFile targetFolder 
= getStorageManager().getFileByPath(targetPath
); 
 518             if (targetFolder 
!= null
) { 
 519                 browseTo(targetFolder
); 
 522             // the next operation triggers a new call to this method, but it's necessary to  
 523             // ensure that the name exposed in the action bar is the current directory when the  
 524             // user selected it in the navigation list 
 525             if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST  
&& itemPosition 
!= 0)  
 526                 getSupportActionBar().setSelectedNavigationItem(0); 
 532      * Called, when the user selected something for uploading 
 534     protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) { 
 535         super.onActivityResult(requestCode
, resultCode
, data
); 
 537         if (requestCode 
== ACTION_SELECT_CONTENT_FROM_APPS 
&& (resultCode 
== RESULT_OK 
|| resultCode 
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) { 
 538             requestSimpleUpload(data
, resultCode
); 
 540         } else if (requestCode 
== ACTION_SELECT_MULTIPLE_FILES 
&& (resultCode 
== RESULT_OK 
|| resultCode 
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) { 
 541             requestMultipleUpload(data
, resultCode
); 
 546     private void requestMultipleUpload(Intent data
, int resultCode
) { 
 547         String
[] filePaths 
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
); 
 548         if (filePaths 
!= null
) { 
 549             String
[] remotePaths 
= new String
[filePaths
.length
]; 
 550             String remotePathBase 
= ""; 
 551             for (int j 
= mDirectories
.getCount() - 2; j 
>= 0; --j
) { 
 552                 remotePathBase 
+= OCFile
.PATH_SEPARATOR 
+ mDirectories
.getItem(j
); 
 554             if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
)) 
 555                 remotePathBase 
+= OCFile
.PATH_SEPARATOR
; 
 556             for (int j 
= 0; j
< remotePaths
.length
; j
++) { 
 557                 remotePaths
[j
] = remotePathBase 
+ (new File(filePaths
[j
])).getName(); 
 560             Intent i 
= new Intent(this, FileUploader
.class); 
 561             i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount()); 
 562             i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
); 
 563             i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
); 
 564             i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
); 
 565             if (resultCode 
== UploadFilesActivity
.RESULT_OK_AND_MOVE
) 
 566                 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
); 
 570             Log_OC
.d(TAG
, "User clicked on 'Update' with no selection"); 
 571             Toast t 
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
); 
 578     private void requestSimpleUpload(Intent data
, int resultCode
) { 
 579         String filepath 
= null
; 
 581             Uri selectedImageUri 
= data
.getData(); 
 583             String filemanagerstring 
= selectedImageUri
.getPath(); 
 584             String selectedImagePath 
= getPath(selectedImageUri
); 
 586             if (selectedImagePath 
!= null
) 
 587                 filepath 
= selectedImagePath
; 
 589                 filepath 
= filemanagerstring
; 
 591         } catch (Exception e
) { 
 592             Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
); 
 596             if (filepath 
== null
) { 
 597                 Log_OC
.e(TAG
, "Couldnt resolve path to file"); 
 598                 Toast t 
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
); 
 604         Intent i 
= new Intent(this, FileUploader
.class); 
 605         i
.putExtra(FileUploader
.KEY_ACCOUNT
, 
 607         String remotepath 
= new String(); 
 608         for (int j 
= mDirectories
.getCount() - 2; j 
>= 0; --j
) { 
 609             remotepath 
+= OCFile
.PATH_SEPARATOR 
+ mDirectories
.getItem(j
); 
 611         if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
)) 
 612             remotepath 
+= OCFile
.PATH_SEPARATOR
; 
 613         remotepath 
+= new File(filepath
).getName(); 
 615         i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
); 
 616         i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
); 
 617         i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
); 
 618         if (resultCode 
== UploadFilesActivity
.RESULT_OK_AND_MOVE
) 
 619             i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
); 
 624     public void onBackPressed() { 
 625         OCFileListFragment listOfFiles 
= getListOfFilesFragment();  
 626         if (mDualPane 
|| getSecondFragment() == null
) { 
 627             if (listOfFiles 
!= null
) {  // should never be null, indeed 
 628                 if (mDirectories
.getCount() <= 1) { 
 632                 int levelsUp 
= listOfFiles
.onBrowseUp(); 
 633                 for (int i
=0; i 
< levelsUp 
&& mDirectories
.getCount() > 1 ; i
++) { 
 638         if (listOfFiles 
!= null
) {  // should never be null, indeed 
 639             setFile(listOfFiles
.getCurrentFile()); 
 641         cleanSecondFragment(); 
 646     protected void onSaveInstanceState(Bundle outState
) { 
 647         // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved 
 648         Log_OC
.e(TAG
, "onSaveInstanceState() start"); 
 649         super.onSaveInstanceState(outState
); 
 650         outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
); 
 651         outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
); 
 652         //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress); 
 653         outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
); 
 655         Log_OC
.d(TAG
, "onSaveInstanceState() end"); 
 661     protected void onResume() { 
 663         Log_OC
.e(TAG
, "onResume() start"); 
 665         // refresh list of files 
 666         refreshListOfFilesFragment(); 
 668         // Listen for sync messages 
 669         IntentFilter syncIntentFilter 
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
); 
 670         syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
); 
 671         syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
); 
 672         syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
); 
 673         syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
); 
 674         mSyncBroadcastReceiver 
= new SyncBroadcastReceiver(); 
 675         registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
); 
 676         //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter); 
 678         // Listen for upload messages 
 679         IntentFilter uploadIntentFilter 
= new IntentFilter(FileUploader
.getUploadFinishMessage()); 
 680         mUploadFinishReceiver 
= new UploadFinishReceiver(); 
 681         registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
); 
 683         // Listen for download messages 
 684         IntentFilter downloadIntentFilter 
= new IntentFilter(FileDownloader
.getDownloadAddedMessage()); 
 685         downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage()); 
 686         mDownloadFinishReceiver 
= new DownloadFinishReceiver(); 
 687         registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
); 
 689         Log_OC
.d(TAG
, "onResume() end"); 
 694     protected void onPause() { 
 695         Log_OC
.e(TAG
, "onPause() start"); 
 696         if (mSyncBroadcastReceiver 
!= null
) { 
 697             unregisterReceiver(mSyncBroadcastReceiver
); 
 698             //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver); 
 699             mSyncBroadcastReceiver 
= null
; 
 701         if (mUploadFinishReceiver 
!= null
) { 
 702             unregisterReceiver(mUploadFinishReceiver
); 
 703             mUploadFinishReceiver 
= null
; 
 705         if (mDownloadFinishReceiver 
!= null
) { 
 706             unregisterReceiver(mDownloadFinishReceiver
); 
 707             mDownloadFinishReceiver 
= null
; 
 711         Log_OC
.d(TAG
, "onPause() end"); 
 717     protected Dialog 
onCreateDialog(int id
) { 
 718         Dialog dialog 
= null
; 
 719         AlertDialog
.Builder builder
; 
 721         case DIALOG_SHORT_WAIT
: { 
 722             ProgressDialog working_dialog 
= new ProgressDialog(this); 
 723             working_dialog
.setMessage(getResources().getString( 
 724                     R
.string
.wait_a_moment
)); 
 725             working_dialog
.setIndeterminate(true
); 
 726             working_dialog
.setCancelable(false
); 
 727             dialog 
= working_dialog
; 
 730         case DIALOG_CHOOSE_UPLOAD_SOURCE
: { 
 732             String
[] items 
= null
; 
 734             String
[] allTheItems 
= { getString(R
.string
.actionbar_upload_files
), 
 735                     getString(R
.string
.actionbar_upload_from_apps
), 
 736                     getString(R
.string
.actionbar_failed_instant_upload
) }; 
 738             String
[] commonItems 
= { getString(R
.string
.actionbar_upload_files
), 
 739                     getString(R
.string
.actionbar_upload_from_apps
) }; 
 741             if (InstantUploadActivity
.IS_ENABLED
) 
 746             builder 
= new AlertDialog
.Builder(this); 
 747             builder
.setTitle(R
.string
.actionbar_upload
); 
 748             builder
.setItems(items
, new DialogInterface
.OnClickListener() { 
 749                 public void onClick(DialogInterface dialog
, int item
) { 
 752                             Intent action 
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class); 
 753                             action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount()); 
 754                             startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
); 
 756                             // TODO create and handle new fragment 
 757                             // LocalFileListFragment 
 759                     } else if (item 
== 1) { 
 760                         Intent action 
= new Intent(Intent
.ACTION_GET_CONTENT
); 
 761                         action 
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
); 
 762                         startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)), 
 763                                 ACTION_SELECT_CONTENT_FROM_APPS
); 
 764                     } else if (item 
== 2 && InstantUploadActivity
.IS_ENABLED
) { 
 765                         Intent action 
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class); 
 766                         action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount()); 
 767                         startActivity(action
); 
 771             dialog 
= builder
.create(); 
 774         case DIALOG_CERT_NOT_SAVED
: { 
 775             builder 
= new AlertDialog
.Builder(this); 
 776             builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
)); 
 777             builder
.setCancelable(false
); 
 778             builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() { 
 780                 public void onClick(DialogInterface dialog
, int which
) { 
 784             dialog 
= builder
.create(); 
 796      * Translates a content URI of an image to a physical path 
 798      * @param uri The URI to resolve 
 799      * @return The path to the image or null if it could not be found 
 801     public String 
getPath(Uri uri
) { 
 802         String
[] projection 
= { MediaStore
.Images
.Media
.DATA 
}; 
 803         Cursor cursor 
= managedQuery(uri
, projection
, null
, null
, null
); 
 804         if (cursor 
!= null
) { 
 805             int column_index 
= cursor
 
 806                     .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
); 
 807             cursor
.moveToFirst(); 
 808             return cursor
.getString(column_index
); 
 814      * Pushes a directory to the drop down list 
 815      * @param directory to push 
 816      * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false. 
 818     public void pushDirname(OCFile directory
) { 
 819         if(!directory
.isFolder()){ 
 820             throw new IllegalArgumentException("Only directories may be pushed!"); 
 822         mDirectories
.insert(directory
.getFileName(), 0); 
 827      * Pops a directory name from the drop down list 
 828      * @return True, unless the stack is empty 
 830     public boolean popDirname() { 
 831         mDirectories
.remove(mDirectories
.getItem(0)); 
 832         return !mDirectories
.isEmpty(); 
 835     // Custom array adapter to override text colors 
 836     private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> { 
 838         public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) { 
 842         public View 
getView(int position
, View convertView
, ViewGroup parent
) { 
 843             View v 
= super.getView(position
, convertView
, parent
); 
 845             ((TextView
) v
).setTextColor(getResources().getColorStateList( 
 846                     android
.R
.color
.white
)); 
 848             fixRoot((TextView
) v 
); 
 852         public View 
getDropDownView(int position
, View convertView
, 
 854             View v 
= super.getDropDownView(position
, convertView
, parent
); 
 856             ((TextView
) v
).setTextColor(getResources().getColorStateList( 
 857                     android
.R
.color
.white
)); 
 859             fixRoot((TextView
) v 
); 
 863         private void fixRoot(TextView v
) { 
 864             if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) { 
 865                 v
.setText(R
.string
.default_display_name_for_root_folder
); 
 871     private class SyncBroadcastReceiver 
extends BroadcastReceiver 
{ 
 874          * {@link BroadcastReceiver} to enable syncing feedback in UI 
 877         public void onReceive(Context context
, Intent intent
) { 
 879                 String event 
= intent
.getAction(); 
 880                 Log_OC
.d(TAG
, "Received broadcast " + event
); 
 881                 String accountName 
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
); 
 882                 String synchFolderRemotePath 
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);  
 883                 RemoteOperationResult synchResult 
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
); 
 884                 boolean sameAccount 
= (getAccount() != null 
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);  
 888                     if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) { 
 889                         mSyncInProgress 
= true
; 
 892                         OCFile currentFile 
= (getFile() == null
) ? null 
: getStorageManager().getFileByPath(getFile().getRemotePath()); 
 893                         OCFile currentDir 
= (getCurrentDir() == null
) ? null 
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath()); 
 895                         if (currentDir 
== null
) { 
 896                             // current folder was removed from the server  
 897                             Toast
.makeText( FileDisplayActivity
.this,  
 898                                             String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),  
 904                             if (currentFile 
== null 
&& !getFile().isFolder()) { 
 905                                 // currently selected file was removed in the server, and now we know it 
 906                                 cleanSecondFragment(); 
 907                                 currentFile 
= currentDir
; 
 910                             if (synchFolderRemotePath 
!= null 
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) { 
 911                                 OCFileListFragment fileListFragment 
= getListOfFilesFragment(); 
 912                                 if (fileListFragment 
!= null
) { 
 913                                     fileListFragment
.listDirectory(currentDir
); 
 916                             setFile(currentFile
); 
 919                         mSyncInProgress 
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
)); 
 922                         removeStickyBroadcast(intent
); 
 923                         Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
); 
 924                         setSupportProgressBarIndeterminateVisibility(mSyncInProgress 
/*|| mRefreshSharesInProgress*/); 
 928                 if (synchResult 
!= null
) { 
 929                     if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) { 
 930                         mLastSslUntrustedServerResult 
= synchResult
; 
 933             } catch (RuntimeException e
) { 
 934                 // avoid app crashes after changing the serial id of RemoteOperationResult  
 935                 // in owncloud library with broadcast notifications pending to process 
 936                 removeStickyBroadcast(intent
); 
 943      * Once the file upload has finished -> update view 
 945     private class UploadFinishReceiver 
extends BroadcastReceiver 
{ 
 947          * Once the file upload has finished -> update view 
 948          *  @author David A. Velasco 
 949          * {@link BroadcastReceiver} to enable upload feedback in UI 
 952         public void onReceive(Context context
, Intent intent
) { 
 953             String uploadedRemotePath 
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
); 
 954             String accountName 
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
); 
 955             boolean sameAccount 
= getAccount() != null 
&& accountName
.equals(getAccount().name
); 
 956             OCFile currentDir 
= getCurrentDir(); 
 957             boolean isDescendant 
= (currentDir 
!= null
) && (uploadedRemotePath 
!= null
) &&  
 958                     (uploadedRemotePath
.startsWith(currentDir
.getRemotePath())); 
 960             if (sameAccount 
&& isDescendant
) { 
 961                 refreshListOfFilesFragment(); 
 964             boolean uploadWasFine 
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
); 
 965             boolean renamedInUpload 
= getFile().getRemotePath(). 
 966                     equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
)); 
 967             boolean sameFile 
= getFile().getRemotePath().equals(uploadedRemotePath
) ||  
 969             FileFragment details 
= getSecondFragment(); 
 970             boolean detailFragmentIsShown 
= (details 
!= null 
&&  
 971                     details 
instanceof FileDetailFragment
); 
 973             if (sameAccount 
&& sameFile 
&& detailFragmentIsShown
) { 
 975                     setFile(getStorageManager().getFileByPath(uploadedRemotePath
)); 
 977                 if (renamedInUpload
) { 
 978                     String newName 
= (new File(uploadedRemotePath
)).getName(); 
 979                     Toast msg 
= Toast
.makeText( 
 982                                     getString(R
.string
.filedetails_renamed_in_upload_msg
),  
 987                 if (uploadWasFine 
|| getFile().fileExists()) { 
 988                     ((FileDetailFragment
)details
).updateFileDetails(false
, true
); 
 990                     cleanSecondFragment(); 
 993                 // Force the preview if the file is an image 
 994                 if (uploadWasFine 
&& PreviewImageFragment
.canBePreviewed(getFile())) { 
 995                     startImagePreview(getFile()); 
 996                 } // TODO what about other kind of previews? 
 999             removeStickyBroadcast(intent
); 
1007      * Class waiting for broadcast events from the {@link FielDownloader} service. 
1009      * Updates the UI when a download is started or finished, provided that it is relevant for the 
1012     private class DownloadFinishReceiver 
extends BroadcastReceiver 
{ 
1014         public void onReceive(Context context
, Intent intent
) { 
1015             boolean sameAccount 
= isSameAccount(context
, intent
); 
1016             String downloadedRemotePath 
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
); 
1017             boolean isDescendant 
= isDescendant(downloadedRemotePath
); 
1019             if (sameAccount 
&& isDescendant
) { 
1020                 refreshListOfFilesFragment(); 
1021                 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)); 
1024             if (mWaitingToSend 
!= null
) { 
1025                 mWaitingToSend 
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send 
1026                 if (mWaitingToSend
.isDown()) {  
1027                     sendDownloadedFile(); 
1031             removeStickyBroadcast(intent
); 
1034         private boolean isDescendant(String downloadedRemotePath
) { 
1035             OCFile currentDir 
= getCurrentDir(); 
1036             return (currentDir 
!= null 
&& downloadedRemotePath 
!= null 
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath())); 
1039         private boolean isSameAccount(Context context
, Intent intent
) { 
1040             String accountName 
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
); 
1041             return (accountName 
!= null 
&& getAccount() != null 
&& accountName
.equals(getAccount().name
)); 
1046     public void browseToRoot() { 
1047         OCFileListFragment listOfFiles 
= getListOfFilesFragment();  
1048         if (listOfFiles 
!= null
) {  // should never be null, indeed 
1049             while (mDirectories
.getCount() > 1) { 
1052             OCFile root 
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); 
1053             listOfFiles
.listDirectory(root
); 
1054             setFile(listOfFiles
.getCurrentFile()); 
1055             startSyncFolderOperation(root
); 
1057         cleanSecondFragment(); 
1061     public void browseTo(OCFile folder
) { 
1062         if (folder 
== null 
|| !folder
.isFolder()) { 
1063             throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
); 
1065         OCFileListFragment listOfFiles 
= getListOfFilesFragment();  
1066         if (listOfFiles 
!= null
) { 
1067             setNavigationListWithFolder(folder
); 
1068             listOfFiles
.listDirectory(folder
); 
1069             setFile(listOfFiles
.getCurrentFile()); 
1070             startSyncFolderOperation(folder
); 
1072             Log_OC
.e(TAG
, "Unexpected null when accessing list fragment"); 
1074         cleanSecondFragment(); 
1081      * Updates action bar and second fragment, if in dual pane mode. 
1084     public void onBrowsedDownTo(OCFile directory
) { 
1085         pushDirname(directory
); 
1086         cleanSecondFragment(); 
1089         startSyncFolderOperation(directory
); 
1094      * Shows the information of the {@link OCFile} received as a  
1095      * parameter in the second fragment. 
1097      * @param file          {@link OCFile} whose details will be shown 
1100     public void showDetails(OCFile file
) { 
1101         Fragment detailFragment 
= new FileDetailFragment(file
, getAccount()); 
1102         setSecondFragment(detailFragment
); 
1103         updateFragmentsVisibility(true
); 
1104         updateNavigationElementsInActionBar(file
); 
1112     private void updateNavigationElementsInActionBar(OCFile chosenFile
) { 
1113         ActionBar actionBar 
= getSupportActionBar();  
1114         if (chosenFile 
== null 
|| mDualPane
) { 
1115             // only list of files - set for browsing through folders 
1116             OCFile currentDir 
= getCurrentDir(); 
1117             boolean noRoot 
= (currentDir 
!= null 
&& currentDir
.getParentId() != 0); 
1118             actionBar
.setDisplayHomeAsUpEnabled(noRoot
); 
1119             actionBar
.setDisplayShowTitleEnabled(!noRoot
);  
1121                 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
)); 
1123             actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD 
: ActionBar
.NAVIGATION_MODE_LIST
); 
1124             actionBar
.setListNavigationCallbacks(mDirectories
, this);   // assuming mDirectories is updated 
1127             actionBar
.setDisplayHomeAsUpEnabled(true
); 
1128             actionBar
.setDisplayShowTitleEnabled(true
); 
1129             actionBar
.setTitle(chosenFile
.getFileName()); 
1130             actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
); 
1136     protected ServiceConnection 
newTransferenceServiceConnection() { 
1137         return new ListServiceConnection(); 
1140     /** Defines callbacks for service binding, passed to bindService() */ 
1141     private class ListServiceConnection 
implements ServiceConnection 
{ 
1144         public void onServiceConnected(ComponentName component
, IBinder service
) { 
1145             if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) { 
1146                 Log_OC
.d(TAG
, "Download service connected"); 
1147                 mDownloaderBinder 
= (FileDownloaderBinder
) service
; 
1148                 if (mWaitingToPreview 
!= null
) 
1149                     if (getStorageManager() != null
) { 
1150                         mWaitingToPreview 
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file 
1151                         if (!mWaitingToPreview
.isDown()) { 
1152                             requestForDownload(); 
1156             } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) { 
1157                 Log_OC
.d(TAG
, "Upload service connected"); 
1158                 mUploaderBinder 
= (FileUploaderBinder
) service
; 
1162             // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS 
1163             OCFileListFragment listOfFiles 
= getListOfFilesFragment();  
1164             if (listOfFiles 
!= null
) { 
1165                 listOfFiles
.listDirectory(); 
1167             FileFragment secondFragment 
= getSecondFragment(); 
1168             if (secondFragment 
!= null 
&& secondFragment 
instanceof FileDetailFragment
) { 
1169                 FileDetailFragment detailFragment 
= (FileDetailFragment
)secondFragment
; 
1170                 detailFragment
.listenForTransferProgress(); 
1171                 detailFragment
.updateFileDetails(false
, false
); 
1176         public void onServiceDisconnected(ComponentName component
) { 
1177             if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) { 
1178                 Log_OC
.d(TAG
, "Download service disconnected"); 
1179                 mDownloaderBinder 
= null
; 
1180             } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) { 
1181                 Log_OC
.d(TAG
, "Upload service disconnected"); 
1182                 mUploaderBinder 
= null
; 
1190      * Launch an intent to request the PIN code to the user before letting him use the app 
1192     private void requestPinCode() { 
1193         boolean pinStart 
= false
; 
1194         SharedPreferences appPrefs 
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext()); 
1195         pinStart 
= appPrefs
.getBoolean("set_pincode", false
); 
1197             Intent i 
= new Intent(getApplicationContext(), PinCodeActivity
.class); 
1198             i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity"); 
1205     public void onSavedCertificate() { 
1206         startSyncFolderOperation(getCurrentDir());                 
1211     public void onFailedSavingCertificate() { 
1212         showDialog(DIALOG_CERT_NOT_SAVED
); 
1216     public void onCancelCertificate() { 
1221      * Updates the view associated to the activity after the finish of some operation over files 
1222      * in the current account. 
1224      * @param operation     Removal operation performed. 
1225      * @param result        Result of the removal. 
1228     public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) { 
1229         super.onRemoteOperationFinish(operation
, result
); 
1231         if (operation 
instanceof RemoveFileOperation
) { 
1232             onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
); 
1234         } else if (operation 
instanceof RenameFileOperation
) { 
1235             onRenameFileOperationFinish((RenameFileOperation
)operation
, result
); 
1237         } else if (operation 
instanceof SynchronizeFileOperation
) { 
1238             onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
); 
1240         } else if (operation 
instanceof CreateFolderOperation
) { 
1241             onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
); 
1243         } else if (operation 
instanceof CreateShareOperation
) { 
1244             onCreateShareOperationFinish((CreateShareOperation
) operation
, result
); 
1246         } else if (operation 
instanceof UnshareLinkOperation
) { 
1247             onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
); 
1254     private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) { 
1255         if (result
.isSuccess()) { 
1256             refreshShowDetails(); 
1257             refreshListOfFilesFragment(); 
1262     private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) { 
1263         if (result
.isSuccess()) { 
1264             refreshShowDetails(); 
1265             refreshListOfFilesFragment(); 
1267         } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) { 
1268             cleanSecondFragment(); 
1269             refreshListOfFilesFragment(); 
1273     private void refreshShowDetails() { 
1274         FileFragment details 
= getSecondFragment(); 
1275         if (details 
!= null
) { 
1276             OCFile file 
= details
.getFile(); 
1278                 file 
= getStorageManager().getFileByPath(file
.getRemotePath());  
1279                 if (details 
instanceof PreviewMediaFragment
) { 
1280                     // Refresh  OCFile of the fragment 
1281                     ((PreviewMediaFragment
) details
).updateFile(file
); 
1286             invalidateOptionsMenu(); 
1291      * Updates the view associated to the activity after the finish of an operation trying to remove a  
1294      * @param operation     Removal operation performed. 
1295      * @param result        Result of the removal. 
1297     private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) { 
1298         dismissLoadingDialog(); 
1300         Toast msg 
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),  
1304         if (result
.isSuccess()) { 
1305             OCFile removedFile 
= operation
.getFile(); 
1306             FileFragment second 
= getSecondFragment(); 
1307             if (second 
!= null 
&& removedFile
.equals(second
.getFile())) { 
1308                 if (second 
instanceof PreviewMediaFragment
) { 
1309                     ((PreviewMediaFragment
)second
).stopPreview(true
); 
1311                 setFile(getStorageManager().getFileById(removedFile
.getParentId())); 
1312                 cleanSecondFragment(); 
1314             if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) { 
1315                 refreshListOfFilesFragment(); 
1317             invalidateOptionsMenu(); 
1319             if (result
.isSslRecoverableException()) { 
1320                 mLastSslUntrustedServerResult 
= result
; 
1321                 showUntrustedCertDialog(mLastSslUntrustedServerResult
); 
1328      * Updates the view associated to the activity after the finish of an operation trying create a new folder 
1330      * @param operation     Creation operation performed. 
1331      * @param result        Result of the creation. 
1333     private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) { 
1334         if (result
.isSuccess()) { 
1335             dismissLoadingDialog(); 
1336             refreshListOfFilesFragment(); 
1338             dismissLoadingDialog(); 
1340                 Toast msg 
= Toast
.makeText(FileDisplayActivity
.this,  
1341                         ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),  
1345             } catch (NotFoundException e
) { 
1346                 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
); 
1353      * Updates the view associated to the activity after the finish of an operation trying to rename a  
1356      * @param operation     Renaming operation performed. 
1357      * @param result        Result of the renaming. 
1359     private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) { 
1360         dismissLoadingDialog(); 
1361         OCFile renamedFile 
= operation
.getFile(); 
1362         if (result
.isSuccess()) { 
1363             FileFragment details 
= getSecondFragment(); 
1364             if (details 
!= null
) { 
1365                 if (details 
instanceof FileDetailFragment 
&& renamedFile
.equals(details
.getFile()) ) { 
1366                     ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount()); 
1367                     showDetails(renamedFile
); 
1369                 } else if (details 
instanceof PreviewMediaFragment 
&& renamedFile
.equals(details
.getFile())) { 
1370                     ((PreviewMediaFragment
) details
).updateFile(renamedFile
); 
1371                     if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) { 
1372                         int position 
= ((PreviewMediaFragment
)details
).getPosition(); 
1373                         startMediaPreview(renamedFile
, position
, true
); 
1375                         getFileOperationsHelper().openFile(renamedFile
); 
1380             if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) { 
1381                 refreshListOfFilesFragment(); 
1385             Toast msg 
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),  
1389             if (result
.isSslRecoverableException()) { 
1390                 mLastSslUntrustedServerResult 
= result
; 
1391                 showUntrustedCertDialog(mLastSslUntrustedServerResult
); 
1396     private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) { 
1397         dismissLoadingDialog(); 
1398         OCFile syncedFile 
= operation
.getLocalFile(); 
1399         if (!result
.isSuccess()) { 
1400             if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) { 
1401                 Intent i 
= new Intent(this, ConflictsResolveActivity
.class); 
1402                 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
); 
1403                 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount()); 
1409             if (operation
.transferWasRequested()) { 
1410                 onTransferStateChanged(syncedFile
, true
, true
); 
1413                 Toast msg 
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),  
1425     public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) { 
1426         refreshListOfFilesFragment(); 
1427         FileFragment details 
= getSecondFragment(); 
1428         if (details 
!= null 
&& details 
instanceof FileDetailFragment 
&& file
.equals(details
.getFile()) ) { 
1429             if (downloading 
|| uploading
) { 
1430                 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount()); 
1432                 if (!file
.fileExists()) { 
1433                     cleanSecondFragment(); 
1435                     ((FileDetailFragment
)details
).updateFileDetails(false
, true
); 
1443     private void requestForDownload() { 
1444         Account account 
= getAccount(); 
1445         if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) { 
1446             Intent i 
= new Intent(this, FileDownloader
.class); 
1447             i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
); 
1448             i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
); 
1454     private OCFile 
getCurrentDir() { 
1455         OCFile file 
= getFile(); 
1457             if (file
.isFolder()) { 
1459             } else if (getStorageManager() != null
) { 
1460                 String parentPath 
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName())); 
1461                 return getStorageManager().getFileByPath(parentPath
); 
1467     public void startSyncFolderOperation(OCFile folder
) { 
1468         long currentSyncTime 
= System
.currentTimeMillis();  
1470         mSyncInProgress 
= true
; 
1472         // perform folder synchronization 
1473         RemoteOperation synchFolderOp 
= new SynchronizeFolderOperation( folder
,   
1476                                                                         getFileOperationsHelper().isSharedSupported(), 
1477                                                                         getStorageManager(),  
1479                                                                         getApplicationContext() 
1481         synchFolderOp
.execute(getAccount(), this, null
, null
, this); 
1483         setSupportProgressBarIndeterminateVisibility(true
); 
1487      * Show untrusted cert dialog  
1489     public void showUntrustedCertDialog(RemoteOperationResult result
) { 
1490         // Show a dialog with the certificate info 
1491         SslUntrustedCertDialog dialog 
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException()); 
1492         FragmentManager fm 
= getSupportFragmentManager(); 
1493         FragmentTransaction ft 
= fm
.beginTransaction(); 
1494         dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
); 
1497     private void requestForDownload(OCFile file
) { 
1498         Account account 
= getAccount(); 
1499         if (!mDownloaderBinder
.isDownloading(account
, file
)) { 
1500             Intent i 
= new Intent(this, FileDownloader
.class); 
1501             i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
); 
1502             i
.putExtra(FileDownloader
.EXTRA_FILE
, file
); 
1507     private void sendDownloadedFile(){ 
1508         getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
); 
1509         mWaitingToSend 
= null
; 
1514      * Requests the download of the received {@link OCFile} , updates the UI 
1515      * to monitor the download progress and prepares the activity to send the file 
1516      * when the download finishes. 
1518      * @param file          {@link OCFile} to download and preview. 
1520     public void startDownloadForSending(OCFile file
) { 
1521         mWaitingToSend 
= file
; 
1522         requestForDownload(mWaitingToSend
); 
1523         boolean hasSecondFragment 
= (getSecondFragment()!= null
); 
1524         updateFragmentsVisibility(hasSecondFragment
); 
1528      * Opens the image gallery showing the image {@link OCFile} received as parameter. 
1530      * @param file                      Image {@link OCFile} to show. 
1532     public void startImagePreview(OCFile file
) { 
1533         Intent showDetailsIntent 
= new Intent(this, PreviewImageActivity
.class); 
1534         showDetailsIntent
.putExtra(EXTRA_FILE
, file
); 
1535         showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount()); 
1536         startActivity(showDetailsIntent
); 
1541      * Stars the preview of an already down media {@link OCFile}. 
1543      * @param file                      Media {@link OCFile} to preview. 
1544      * @param startPlaybackPosition     Media position where the playback will be started, in milliseconds. 
1545      * @param autoplay                  When 'true', the playback will start without user interactions. 
1547     public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) { 
1548         Fragment mediaFragment 
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
); 
1549         setSecondFragment(mediaFragment
); 
1550         updateFragmentsVisibility(true
); 
1551         updateNavigationElementsInActionBar(file
); 
1556      * Requests the download of the received {@link OCFile} , updates the UI 
1557      * to monitor the download progress and prepares the activity to preview 
1558      * or open the file when the download finishes. 
1560      * @param file          {@link OCFile} to download and preview. 
1562     public void startDownloadForPreview(OCFile file
) { 
1563         Fragment detailFragment 
= new FileDetailFragment(file
, getAccount()); 
1564         setSecondFragment(detailFragment
); 
1565         mWaitingToPreview 
= file
; 
1566         requestForDownload(); 
1567         updateFragmentsVisibility(true
); 
1568         updateNavigationElementsInActionBar(file
); 
1573     public void cancelTransference(OCFile file
) { 
1574         getFileOperationsHelper().cancelTransference(file
); 
1575         if (mWaitingToPreview 
!= null 
&&  
1576                 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) { 
1577             mWaitingToPreview 
= null
; 
1579         if (mWaitingToSend 
!= null 
&& 
1580                 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) { 
1581             mWaitingToSend 
= null
; 
1583         onTransferStateChanged(file
, false
, false
);