1 /* ownCloud Android client application 
   2  *   Copyright (C) 2011  Bartek Przybylski 
   3  *   Copyright (C) 2012-2014 ownCloud Inc. 
   5  *   This program is free software: you can redistribute it and/or modify 
   6  *   it under the terms of the GNU General Public License version 2, 
   7  *   as published by the Free Software Foundation. 
   9  *   This program is distributed in the hope that it will be useful, 
  10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of 
  11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
  12  *   GNU General Public License for more details. 
  14  *   You should have received a copy of the GNU General Public License 
  15  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. 
  19 package com
.owncloud
.android
.ui
.activity
; 
  22 import java
.io
.IOException
; 
  24 import android
.accounts
.Account
; 
  25 import android
.accounts
.AccountManager
; 
  26 import android
.accounts
.AuthenticatorException
; 
  27 import android
.accounts
.OperationCanceledException
; 
  28 import android
.app
.AlertDialog
; 
  29 import android
.app
.Dialog
; 
  30 import android
.app
.ProgressDialog
; 
  31 import android
.content
.BroadcastReceiver
; 
  32 import android
.content
.ComponentName
; 
  33 import android
.content
.ContentResolver
; 
  34 import android
.content
.Context
; 
  35 import android
.content
.DialogInterface
; 
  36 import android
.content
.Intent
; 
  37 import android
.content
.IntentFilter
; 
  38 import android
.content
.ServiceConnection
; 
  39 import android
.content
.SharedPreferences
; 
  40 import android
.content
.SyncRequest
; 
  41 import android
.content
.res
.Resources
.NotFoundException
; 
  42 import android
.database
.Cursor
; 
  43 import android
.net
.Uri
; 
  44 import android
.os
.Bundle
; 
  45 import android
.os
.IBinder
; 
  46 import android
.preference
.PreferenceManager
; 
  47 import android
.provider
.MediaStore
; 
  48 import android
.support
.v4
.app
.Fragment
; 
  49 import android
.support
.v4
.app
.FragmentManager
; 
  50 import android
.support
.v4
.app
.FragmentTransaction
; 
  51 import android
.view
.View
; 
  52 import android
.view
.ViewGroup
; 
  53 import android
.widget
.ArrayAdapter
; 
  54 import android
.widget
.TextView
; 
  55 import android
.widget
.Toast
; 
  57 import com
.actionbarsherlock
.app
.ActionBar
; 
  58 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
; 
  59 import com
.actionbarsherlock
.view
.Menu
; 
  60 import com
.actionbarsherlock
.view
.MenuInflater
; 
  61 import com
.actionbarsherlock
.view
.MenuItem
; 
  62 import com
.actionbarsherlock
.view
.Window
; 
  63 import com
.owncloud
.android
.BuildConfig
; 
  64 import com
.owncloud
.android
.MainApp
; 
  65 import com
.owncloud
.android
.R
; 
  66 import com
.owncloud
.android
.datamodel
.OCFile
; 
  67 import com
.owncloud
.android
.files
.services
.FileDownloader
; 
  68 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
; 
  69 import com
.owncloud
.android
.files
.services
.FileUploader
; 
  70 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
; 
  71 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
; 
  72 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
; 
  73 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
; 
  74 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
; 
  75 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
; 
  76 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
; 
  77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
; 
  78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
; 
  79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
; 
  80 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
; 
  81 import com
.owncloud
.android
.operations
.CreateFolderOperation
; 
  82 import com
.owncloud
.android
.operations
.CreateShareOperation
; 
  83 import com
.owncloud
.android
.operations
.MoveFileOperation
; 
  84 import com
.owncloud
.android
.operations
.RemoveFileOperation
; 
  85 import com
.owncloud
.android
.operations
.RenameFileOperation
; 
  86 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
; 
  87 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
; 
  88 import com
.owncloud
.android
.operations
.UnshareLinkOperation
; 
  89 import com
.owncloud
.android
.services
.observer
.FileObserverService
; 
  90 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
; 
  91 import com
.owncloud
.android
.ui
.adapter
.FileListListAdapter
; 
  92 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
; 
  93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
; 
  94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
; 
  95 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
; 
  96 import com
.owncloud
.android
.ui
.fragment
.FileFragment
; 
  97 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
; 
  98 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
; 
  99 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
; 
 100 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
; 
 101 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
; 
 102 import com
.owncloud
.android
.utils
.DisplayUtils
; 
 103 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
; 
 107  * Displays, what files the user has available in his ownCloud. 
 109  * @author Bartek Przybylski 
 110  * @author David A. Velasco 
 113 public class FileDisplayActivity 
extends HookActivity 
implements 
 114 FileFragment
.ContainerActivity
, OnNavigationListener
,  
 115 OnSslUntrustedCertListener
, OnEnforceableRefreshListener 
{ 
 117     private ArrayAdapter
<String
> mDirectories
; 
 119     private SyncBroadcastReceiver mSyncBroadcastReceiver
; 
 120     private UploadFinishReceiver mUploadFinishReceiver
; 
 121     private DownloadFinishReceiver mDownloadFinishReceiver
; 
 122     private RemoteOperationResult mLastSslUntrustedServerResult 
= null
; 
 124     private boolean mDualPane
; 
 125     private View mLeftFragmentContainer
; 
 126     private View mRightFragmentContainer
; 
 128     private static final String KEY_WAITING_TO_PREVIEW 
= "WAITING_TO_PREVIEW"; 
 129     private static final String KEY_SYNC_IN_PROGRESS 
= "SYNC_IN_PROGRESS"; 
 130     private static final String KEY_WAITING_TO_SEND 
= "WAITING_TO_SEND"; 
 132     public static final int DIALOG_SHORT_WAIT 
= 0; 
 133     private static final int DIALOG_CHOOSE_UPLOAD_SOURCE 
= 1; 
 134     private static final int DIALOG_CERT_NOT_SAVED 
= 2; 
 136     public static final String ACTION_DETAILS 
= "com.owncloud.android.ui.activity.action.DETAILS"; 
 138     private static final int ACTION_SELECT_CONTENT_FROM_APPS 
= 1; 
 139     private static final int ACTION_SELECT_MULTIPLE_FILES 
= 2; 
 140     public static final int ACTION_MOVE_FILES 
= 3; 
 142     private static final String TAG 
= FileDisplayActivity
.class.getSimpleName(); 
 144     private static final String TAG_LIST_OF_FILES 
= "LIST_OF_FILES"; 
 145     private static final String TAG_SECOND_FRAGMENT 
= "SECOND_FRAGMENT"; 
 147     private OCFile mWaitingToPreview
; 
 149     private boolean mSyncInProgress 
= false
; 
 151     private String DIALOG_UNTRUSTED_CERT
; 
 153     private OCFile mWaitingToSend
; 
 156     protected void onCreate(Bundle savedInstanceState
) { 
 157         Log_OC
.d(TAG
, "onCreate() start"); 
 158         requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
); 
 160         super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid 
 162         // PIN CODE request ;  best location is to decide, let's try this first 
 163         if (getIntent().getAction() != null 
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState 
== null
) { 
 165         } else if (getIntent().getAction() == null 
&& savedInstanceState 
== null
) { 
 169         /// grant that FileObserverService is watching favourite files 
 170         if (savedInstanceState 
== null
) { 
 171             Intent initObserversIntent 
= FileObserverService
.makeInitIntent(this); 
 172             startService(initObserversIntent
); 
 175         /// Load of saved instance state 
 176         if(savedInstanceState 
!= null
) { 
 177             mWaitingToPreview 
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
); 
 178             mSyncInProgress 
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
); 
 179             mWaitingToSend 
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
); 
 182             mWaitingToPreview 
= null
; 
 183             mSyncInProgress 
= false
; 
 184             mWaitingToSend 
= null
; 
 189         // Inflate and set the layout view 
 190         setContentView(R
.layout
.files
);     
 191         mDualPane 
= getResources().getBoolean(R
.bool
.large_land_layout
); 
 192         mLeftFragmentContainer 
= findViewById(R
.id
.left_fragment_container
); 
 193         mRightFragmentContainer 
= findViewById(R
.id
.right_fragment_container
); 
 194         if (savedInstanceState 
== null
) { 
 195             createMinFragments(); 
 199         mDirectories 
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
); 
 200         getSupportActionBar().setHomeButtonEnabled(true
);       // mandatory since Android ICS, according to the official documentation 
 201         setSupportProgressBarIndeterminateVisibility(mSyncInProgress 
/*|| mRefreshSharesInProgress*/);    // always AFTER setContentView(...) ; to work around bug in its implementation 
 205         Log_OC
.d(TAG
, "onCreate() end"); 
 209     protected void onStart() { 
 211         getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId()); 
 215     protected void onDestroy() { 
 220      *  Called when the ownCloud {@link Account} associated to the Activity was just updated. 
 223     protected void onAccountSet(boolean stateWasRecovered
) { 
 224         super.onAccountSet(stateWasRecovered
); 
 225         if (getAccount() != null
) { 
 226             /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account 
 227             OCFile file 
= getFile(); 
 228             // get parent from path 
 229             String parentPath 
= ""; 
 231                 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) { 
 232                     // upload in progress - right now, files are not inserted in the local cache until the upload is successful 
 233                     // get parent from path 
 234                     parentPath 
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName())); 
 235                     if (getStorageManager().getFileByPath(parentPath
) ==  null
) 
 236                         file 
= null
; // not able to know the directory where the file is uploading 
 238                     file 
= getStorageManager().getFileByPath(file
.getRemotePath());   // currentDir = null if not in the current Account 
 242                 // fall back to root folder 
 243                 file 
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);  // never returns null 
 246             setNavigationListWithFolder(file
); 
 248             if (!stateWasRecovered
) { 
 249                 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged.."); 
 250                 initFragmentsWithFile(); 
 251                 if (file
.isFolder()) { 
 252                     startSyncFolderOperation(file
, false
); 
 256                 updateFragmentsVisibility(!file
.isFolder()); 
 257                 updateNavigationElementsInActionBar(file
.isFolder() ? null 
: file
); 
 263     private void setNavigationListWithFolder(OCFile file
) { 
 264         mDirectories
.clear(); 
 265         OCFile fileIt 
= file
; 
 267         while(fileIt 
!= null 
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) { 
 268             if (fileIt
.isFolder()) { 
 269                 mDirectories
.add(fileIt
.getFileName()); 
 271             // get parent from path 
 272             parentPath 
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName())); 
 273             fileIt 
= getStorageManager().getFileByPath(parentPath
); 
 275         mDirectories
.add(OCFile
.PATH_SEPARATOR
); 
 279     private void createMinFragments() { 
 280         OCFileListFragment listOfFiles 
= new OCFileListFragment(); 
 281         FragmentTransaction transaction 
= getSupportFragmentManager().beginTransaction(); 
 282         transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
); 
 283         transaction
.commit(); 
 286     private void initFragmentsWithFile() { 
 287         if (getAccount() != null 
&& getFile() != null
) { 
 289             OCFileListFragment listOfFiles 
= getListOfFilesFragment();  
 290             if (listOfFiles 
!= null
) { 
 291                 listOfFiles
.listDirectory(getCurrentDir());    
 293                 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >("); 
 297             OCFile file 
= getFile();  
 298             Fragment secondFragment 
= chooseInitialSecondFragment(file
); 
 299             if (secondFragment 
!= null
) { 
 300                 setSecondFragment(secondFragment
); 
 301                 updateFragmentsVisibility(true
); 
 302                 updateNavigationElementsInActionBar(file
); 
 305                 cleanSecondFragment(); 
 309             Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!"); 
 310             if (getAccount() == null
) { 
 311                 Log_OC
.wtf(TAG
, "\t account is NULL"); 
 313             if (getFile() == null
) { 
 314                 Log_OC
.wtf(TAG
, "\t file is NULL"); 
 319     private Fragment 
chooseInitialSecondFragment(OCFile file
) { 
 320         Fragment secondFragment 
= null
; 
 321         if (file 
!= null 
&& !file
.isFolder()) { 
 322             if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)  
 323                     && file
.getLastSyncDateForProperties() > 0  // temporal fix 
 325                 int startPlaybackPosition 
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0); 
 326                 boolean autoplay 
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
); 
 327                 secondFragment 
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
); 
 330                 secondFragment 
= new FileDetailFragment(file
, getAccount()); 
 333         return secondFragment
; 
 338      * Replaces the second fragment managed by the activity with the received as 
 341      * Assumes never will be more than two fragments managed at the same time.  
 343      * @param fragment      New second Fragment to set. 
 345     private void setSecondFragment(Fragment fragment
) { 
 346         FragmentTransaction transaction 
= getSupportFragmentManager().beginTransaction(); 
 347         transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
); 
 348         transaction
.commit(); 
 352     private void updateFragmentsVisibility(boolean existsSecondFragment
) { 
 354             if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) { 
 355                 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
); 
 357             if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) { 
 358                 mRightFragmentContainer
.setVisibility(View
.VISIBLE
); 
 361         } else if (existsSecondFragment
) { 
 362             if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) { 
 363                 mLeftFragmentContainer
.setVisibility(View
.GONE
); 
 365             if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) { 
 366                 mRightFragmentContainer
.setVisibility(View
.VISIBLE
); 
 370             if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) { 
 371                 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
); 
 373             if (mRightFragmentContainer
.getVisibility() != View
.GONE
) { 
 374                 mRightFragmentContainer
.setVisibility(View
.GONE
); 
 380     private OCFileListFragment 
getListOfFilesFragment() { 
 381         Fragment listOfFiles 
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
); 
 382         if (listOfFiles 
!= null
) { 
 383             return (OCFileListFragment
)listOfFiles
; 
 385         Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!"); 
 389     public FileFragment 
getSecondFragment() { 
 390         Fragment second 
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
); 
 391         if (second 
!= null
) { 
 392             return (FileFragment
)second
; 
 397     protected void cleanSecondFragment() { 
 398         Fragment second 
= getSecondFragment(); 
 399         if (second 
!= null
) { 
 400             FragmentTransaction tr 
= getSupportFragmentManager().beginTransaction(); 
 404         updateFragmentsVisibility(false
); 
 405         updateNavigationElementsInActionBar(null
); 
 408     protected void refreshListOfFilesFragment() { 
 409         OCFileListFragment fileListFragment 
= getListOfFilesFragment(); 
 410         if (fileListFragment 
!= null
) {  
 411             fileListFragment
.listDirectory(); 
 415     protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) { 
 416         FileFragment secondFragment 
= getSecondFragment(); 
 417         boolean waitedPreview 
= (mWaitingToPreview 
!= null 
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
)); 
 418         if (secondFragment 
!= null 
&& secondFragment 
instanceof FileDetailFragment
) { 
 419             FileDetailFragment detailsFragment 
= (FileDetailFragment
) secondFragment
; 
 420             OCFile fileInFragment 
= detailsFragment
.getFile(); 
 421             if (fileInFragment 
!= null 
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) { 
 422                 // the user browsed to other file ; forget the automatic preview  
 423                 mWaitingToPreview 
= null
; 
 425             } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) { 
 426                 // grant that the right panel updates the progress bar 
 427                 detailsFragment
.listenForTransferProgress(); 
 428                 detailsFragment
.updateFileDetails(true
, false
); 
 430             } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) { 
 431                 //  update the right panel 
 432                 boolean detailsFragmentChanged 
= false
; 
 435                         mWaitingToPreview 
= getStorageManager().getFileById(mWaitingToPreview
.getFileId());   // update the file from database, for the local storage path 
 436                         if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) { 
 437                             startMediaPreview(mWaitingToPreview
, 0, true
); 
 438                             detailsFragmentChanged 
= true
; 
 440                             getFileOperationsHelper().openFile(mWaitingToPreview
); 
 443                     mWaitingToPreview 
= null
; 
 445                 if (!detailsFragmentChanged
) { 
 446                     detailsFragment
.updateFileDetails(false
, (success
)); 
 453     public boolean onPrepareOptionsMenu(Menu menu
) { 
 454         if (BuildConfig
.DEBUG
) { 
 455             menu
.findItem(R
.id
.action_logger
).setVisible(true
); 
 457             menu
.findItem(R
.id
.action_logger
).setVisible(false
); 
 459         return super.onPrepareOptionsMenu(menu
); 
 463     public boolean onCreateOptionsMenu(Menu menu
) { 
 464         MenuInflater inflater 
= getSherlock().getMenuInflater(); 
 465         inflater
.inflate(R
.menu
.main_menu
, menu
); 
 470     public boolean onOptionsItemSelected(MenuItem item
) { 
 471         boolean retval 
= true
; 
 472         switch (item
.getItemId()) { 
 473         case R
.id
.action_create_dir
: { 
 474             CreateFolderDialogFragment dialog 
=  
 475                     CreateFolderDialogFragment
.newInstance(getCurrentDir()); 
 476             dialog
.show(getSupportFragmentManager(), "createdirdialog"); 
 479         case R
.id
.action_sync_account
: { 
 480             startSynchronization(); 
 483         case R
.id
.action_upload
: { 
 484             showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
); 
 487         case R
.id
.action_settings
: { 
 488             Intent settingsIntent 
= new Intent(this, Preferences
.class); 
 489             startActivity(settingsIntent
); 
 492         case R
.id
.action_logger
: { 
 493             Intent loggerIntent 
= new Intent(getApplicationContext(),LogHistoryActivity
.class); 
 494             startActivity(loggerIntent
); 
 497         case android
.R
.id
.home
: { 
 498             FileFragment second 
= getSecondFragment(); 
 499             OCFile currentDir 
= getCurrentDir(); 
 500             if((currentDir 
!= null 
&& currentDir
.getParentId() != 0) ||  
 501                     (second 
!= null 
&& second
.getFile() != null
)) {                 
 507         case R
.id
.action_sort
: { 
 508             SharedPreferences appPreferences 
= PreferenceManager
 
 509                     .getDefaultSharedPreferences(this); 
 511             // Read sorting order, default to sort by name ascending 
 512             Integer sortOrder 
= appPreferences
 
 513                     .getInt("sortOrder", FileListListAdapter
.SORT_NAME
); 
 515             AlertDialog
.Builder builder 
= new AlertDialog
.Builder(this); 
 516             builder
.setTitle(R
.string
.actionbar_sort_title
) 
 517             .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder 
, new DialogInterface
.OnClickListener() { 
 518                 public void onClick(DialogInterface dialog
, int which
) { 
 528 // TODO re-enable when server-side folder size calculation is available                        
 530 //                        sortBySize(false); 
 538             builder
.create().show(); 
 542             retval 
= super.onOptionsItemSelected(item
); 
 547     private void startSynchronization() { 
 548         Log_OC
.e(TAG
, "Got to start sync"); 
 549         if (android
.os
.Build
.VERSION
.SDK_INT 
< android
.os
.Build
.VERSION_CODES
.KITKAT
) { 
 550             Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority()); 
 551             ContentResolver
.cancelSync(null
, MainApp
.getAuthority());   // cancel the current synchronizations of any ownCloud account 
 552             Bundle bundle 
= new Bundle(); 
 553             bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
); 
 554             bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
); 
 555             Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name 
+ " at " + MainApp
.getAuthority()); 
 556             ContentResolver
.requestSync( 
 558                     MainApp
.getAuthority(), bundle
); 
 560             Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name 
+ " at " + MainApp
.getAuthority() + " with new API"); 
 561             SyncRequest
.Builder builder 
= new SyncRequest
.Builder(); 
 562             builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority()); 
 563             builder
.setExpedited(true
); 
 564             builder
.setManual(true
); 
 566             SyncRequest request 
= builder
.build(); 
 567             ContentResolver
.requestSync(request
); 
 573     public boolean onNavigationItemSelected(int itemPosition
, long itemId
) { 
 574         if (itemPosition 
!= 0) { 
 575             String targetPath 
= ""; 
 576             for (int i
=itemPosition
; i 
< mDirectories
.getCount() - 1; i
++) { 
 577                 targetPath 
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR 
+ targetPath
;  
 579             targetPath 
= OCFile
.PATH_SEPARATOR 
+ targetPath
; 
 580             OCFile targetFolder 
= getStorageManager().getFileByPath(targetPath
); 
 581             if (targetFolder 
!= null
) { 
 582                 browseTo(targetFolder
); 
 585             // the next operation triggers a new call to this method, but it's necessary to  
 586             // ensure that the name exposed in the action bar is the current directory when the  
 587             // user selected it in the navigation list 
 588             if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST  
&& itemPosition 
!= 0)  
 589                 getSupportActionBar().setSelectedNavigationItem(0); 
 595      * Called, when the user selected something for uploading 
 597     protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) { 
 598         super.onActivityResult(requestCode
, resultCode
, data
); 
 600         if (requestCode 
== ACTION_SELECT_CONTENT_FROM_APPS 
&& (resultCode 
== RESULT_OK 
|| resultCode 
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) { 
 601             requestSimpleUpload(data
, resultCode
); 
 603         } else if (requestCode 
== ACTION_SELECT_MULTIPLE_FILES 
&& (resultCode 
== RESULT_OK 
|| resultCode 
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) { 
 604             requestMultipleUpload(data
, resultCode
); 
 606         } else if (requestCode 
== ACTION_MOVE_FILES 
&& (resultCode 
== RESULT_OK 
||  
 607                 resultCode 
== MoveActivity
.RESULT_OK_AND_MOVE
)){ 
 609             final Intent fData 
= data
; 
 610             final int fResultCode 
= resultCode
;  
 611             getHandler().postDelayed( 
 615                         requestMoveOperation(fData
, fResultCode
); 
 618                 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
 
 623     private void requestMultipleUpload(Intent data
, int resultCode
) { 
 624         String
[] filePaths 
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
); 
 625         if (filePaths 
!= null
) { 
 626             String
[] remotePaths 
= new String
[filePaths
.length
]; 
 627             String remotePathBase 
= ""; 
 628             for (int j 
= mDirectories
.getCount() - 2; j 
>= 0; --j
) { 
 629                 remotePathBase 
+= OCFile
.PATH_SEPARATOR 
+ mDirectories
.getItem(j
); 
 631             if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
)) 
 632                 remotePathBase 
+= OCFile
.PATH_SEPARATOR
; 
 633             for (int j 
= 0; j
< remotePaths
.length
; j
++) { 
 634                 remotePaths
[j
] = remotePathBase 
+ (new File(filePaths
[j
])).getName(); 
 637             Intent i 
= new Intent(this, FileUploader
.class); 
 638             i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount()); 
 639             i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
); 
 640             i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
); 
 641             i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
); 
 642             if (resultCode 
== UploadFilesActivity
.RESULT_OK_AND_MOVE
) 
 643                 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
); 
 647             Log_OC
.d(TAG
, "User clicked on 'Update' with no selection"); 
 648             Toast t 
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
); 
 655     private void requestSimpleUpload(Intent data
, int resultCode
) { 
 656         String filepath 
= null
; 
 658             Uri selectedImageUri 
= data
.getData(); 
 660             String filemanagerstring 
= selectedImageUri
.getPath(); 
 661             String selectedImagePath 
= getPath(selectedImageUri
); 
 663             if (selectedImagePath 
!= null
) 
 664                 filepath 
= selectedImagePath
; 
 666                 filepath 
= filemanagerstring
; 
 668         } catch (Exception e
) { 
 669             Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
); 
 673             if (filepath 
== null
) { 
 674                 Log_OC
.e(TAG
, "Couldnt resolve path to file"); 
 675                 Toast t 
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
); 
 681         Intent i 
= new Intent(this, FileUploader
.class); 
 682         i
.putExtra(FileUploader
.KEY_ACCOUNT
, 
 684         String remotepath 
= new String(); 
 685         for (int j 
= mDirectories
.getCount() - 2; j 
>= 0; --j
) { 
 686             remotepath 
+= OCFile
.PATH_SEPARATOR 
+ mDirectories
.getItem(j
); 
 688         if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
)) 
 689             remotepath 
+= OCFile
.PATH_SEPARATOR
; 
 690         remotepath 
+= new File(filepath
).getName(); 
 692         i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
); 
 693         i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
); 
 694         i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
); 
 695         if (resultCode 
== UploadFilesActivity
.RESULT_OK_AND_MOVE
) 
 696             i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
); 
 701      * Request the operation for moving the file/folder from one path to another 
 703      * @param data              Intent received 
 704      * @param resultCode        Result code received 
 706     private void requestMoveOperation(Intent data
, int resultCode
) { 
 707         OCFile folderToMoveAt 
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
); 
 708         OCFile targetFile 
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
); 
 709         getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
); 
 713     public void onBackPressed() { 
 714         OCFileListFragment listOfFiles 
= getListOfFilesFragment();  
 715         if (mDualPane 
|| getSecondFragment() == null
) { 
 716             if (listOfFiles 
!= null
) {  // should never be null, indeed 
 717                 if (mDirectories
.getCount() <= 1) { 
 721                 int levelsUp 
= listOfFiles
.onBrowseUp(); 
 722                 for (int i
=0; i 
< levelsUp 
&& mDirectories
.getCount() > 1 ; i
++) { 
 727         if (listOfFiles 
!= null
) {  // should never be null, indeed 
 728             setFile(listOfFiles
.getCurrentFile()); 
 730         cleanSecondFragment(); 
 735     protected void onSaveInstanceState(Bundle outState
) { 
 736         // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved 
 737         Log_OC
.e(TAG
, "onSaveInstanceState() start"); 
 738         super.onSaveInstanceState(outState
); 
 739         outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
); 
 740         outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
); 
 741         //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress); 
 742         outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
); 
 744         Log_OC
.d(TAG
, "onSaveInstanceState() end"); 
 750     protected void onResume() { 
 752         Log_OC
.e(TAG
, "onResume() start"); 
 754         // refresh list of files 
 755         refreshListOfFilesFragment(); 
 757         // Listen for sync messages 
 758         IntentFilter syncIntentFilter 
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
); 
 759         syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
); 
 760         syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
); 
 761         syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
); 
 762         syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
); 
 763         mSyncBroadcastReceiver 
= new SyncBroadcastReceiver(); 
 764         registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
); 
 765         //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter); 
 767         // Listen for upload messages 
 768         IntentFilter uploadIntentFilter 
= new IntentFilter(FileUploader
.getUploadFinishMessage()); 
 769         mUploadFinishReceiver 
= new UploadFinishReceiver(); 
 770         registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
); 
 772         // Listen for download messages 
 773         IntentFilter downloadIntentFilter 
= new IntentFilter(FileDownloader
.getDownloadAddedMessage()); 
 774         downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage()); 
 775         mDownloadFinishReceiver 
= new DownloadFinishReceiver(); 
 776         registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
); 
 778         Log_OC
.d(TAG
, "onResume() end"); 
 783     protected void onPause() { 
 784         Log_OC
.e(TAG
, "onPause() start"); 
 785         if (mSyncBroadcastReceiver 
!= null
) { 
 786             unregisterReceiver(mSyncBroadcastReceiver
); 
 787             //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver); 
 788             mSyncBroadcastReceiver 
= null
; 
 790         if (mUploadFinishReceiver 
!= null
) { 
 791             unregisterReceiver(mUploadFinishReceiver
); 
 792             mUploadFinishReceiver 
= null
; 
 794         if (mDownloadFinishReceiver 
!= null
) { 
 795             unregisterReceiver(mDownloadFinishReceiver
); 
 796             mDownloadFinishReceiver 
= null
; 
 800         Log_OC
.d(TAG
, "onPause() end"); 
 806     protected Dialog 
onCreateDialog(int id
) { 
 807         Dialog dialog 
= null
; 
 808         AlertDialog
.Builder builder
; 
 810         case DIALOG_SHORT_WAIT
: { 
 811             ProgressDialog working_dialog 
= new ProgressDialog(this); 
 812             working_dialog
.setMessage(getResources().getString( 
 813                     R
.string
.wait_a_moment
)); 
 814             working_dialog
.setIndeterminate(true
); 
 815             working_dialog
.setCancelable(false
); 
 816             dialog 
= working_dialog
; 
 819         case DIALOG_CHOOSE_UPLOAD_SOURCE
: { 
 822             String
[] allTheItems 
= { getString(R
.string
.actionbar_upload_files
), 
 823                     getString(R
.string
.actionbar_upload_from_apps
) }; 
 825             builder 
= new AlertDialog
.Builder(this); 
 826             builder
.setTitle(R
.string
.actionbar_upload
); 
 827             builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() { 
 828                 public void onClick(DialogInterface dialog
, int item
) { 
 831                             Intent action 
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class); 
 832                             action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount()); 
 833                             startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
); 
 835                             // TODO create and handle new fragment 
 836                             // LocalFileListFragment 
 838                     } else if (item 
== 1) { 
 839                         Intent action 
= new Intent(Intent
.ACTION_GET_CONTENT
); 
 840                         action 
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
); 
 841                         startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)), 
 842                                 ACTION_SELECT_CONTENT_FROM_APPS
); 
 846             dialog 
= builder
.create(); 
 849         case DIALOG_CERT_NOT_SAVED
: { 
 850             builder 
= new AlertDialog
.Builder(this); 
 851             builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
)); 
 852             builder
.setCancelable(false
); 
 853             builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() { 
 855                 public void onClick(DialogInterface dialog
, int which
) { 
 859             dialog 
= builder
.create(); 
 871      * Translates a content URI of an image to a physical path 
 873      * @param uri The URI to resolve 
 874      * @return The path to the image or null if it could not be found 
 876     public String 
getPath(Uri uri
) { 
 877         String
[] projection 
= { MediaStore
.Images
.Media
.DATA 
}; 
 878         Cursor cursor 
= managedQuery(uri
, projection
, null
, null
, null
); 
 879         if (cursor 
!= null
) { 
 880             int column_index 
= cursor
 
 881                     .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
); 
 882             cursor
.moveToFirst(); 
 883             return cursor
.getString(column_index
); 
 889      * Pushes a directory to the drop down list 
 890      * @param directory to push 
 891      * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false. 
 893     public void pushDirname(OCFile directory
) { 
 894         if(!directory
.isFolder()){ 
 895             throw new IllegalArgumentException("Only directories may be pushed!"); 
 897         mDirectories
.insert(directory
.getFileName(), 0); 
 902      * Pops a directory name from the drop down list 
 903      * @return True, unless the stack is empty 
 905     public boolean popDirname() { 
 906         mDirectories
.remove(mDirectories
.getItem(0)); 
 907         return !mDirectories
.isEmpty(); 
 910     // Custom array adapter to override text colors 
 911     private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> { 
 913         public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) { 
 917         public View 
getView(int position
, View convertView
, ViewGroup parent
) { 
 918             View v 
= super.getView(position
, convertView
, parent
); 
 920             ((TextView
) v
).setTextColor(getResources().getColorStateList( 
 921                     android
.R
.color
.white
)); 
 923             fixRoot((TextView
) v 
); 
 927         public View 
getDropDownView(int position
, View convertView
, 
 929             View v 
= super.getDropDownView(position
, convertView
, parent
); 
 931             ((TextView
) v
).setTextColor(getResources().getColorStateList( 
 932                     android
.R
.color
.white
)); 
 934             fixRoot((TextView
) v 
); 
 938         private void fixRoot(TextView v
) { 
 939             if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) { 
 940                 v
.setText(R
.string
.default_display_name_for_root_folder
); 
 946     private class SyncBroadcastReceiver 
extends BroadcastReceiver 
{ 
 949          * {@link BroadcastReceiver} to enable syncing feedback in UI 
 952         public void onReceive(Context context
, Intent intent
) { 
 954                 String event 
= intent
.getAction(); 
 955                 Log_OC
.d(TAG
, "Received broadcast " + event
); 
 956                 String accountName 
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
); 
 957                 String synchFolderRemotePath 
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);  
 958                 RemoteOperationResult synchResult 
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
); 
 959                 boolean sameAccount 
= (getAccount() != null 
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);  
 963                     if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) { 
 964                         mSyncInProgress 
= true
; 
 967                         OCFile currentFile 
= (getFile() == null
) ? null 
: getStorageManager().getFileByPath(getFile().getRemotePath()); 
 968                         OCFile currentDir 
= (getCurrentDir() == null
) ? null 
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath()); 
 970                         if (currentDir 
== null
) { 
 971                             // current folder was removed from the server  
 972                             Toast
.makeText( FileDisplayActivity
.this,  
 973                                             String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),  
 979                             if (currentFile 
== null 
&& !getFile().isFolder()) { 
 980                                 // currently selected file was removed in the server, and now we know it 
 981                                 cleanSecondFragment(); 
 982                                 currentFile 
= currentDir
; 
 985                             if (synchFolderRemotePath 
!= null 
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) { 
 986                                 OCFileListFragment fileListFragment 
= getListOfFilesFragment(); 
 987                                 if (fileListFragment 
!= null
) { 
 988                                     fileListFragment
.listDirectory(currentDir
); 
 991                             setFile(currentFile
); 
 994                         mSyncInProgress 
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
)); 
 996                         if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
. 
 998                                 /// TODO refactor and make common 
 999                                 synchResult 
!= null 
&& !synchResult
.isSuccess() &&   
1000                                 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED   
||  
1001                                     synchResult
.isIdPRedirection()                  || 
1002                                     (synchResult
.isException() && synchResult
.getException()  
1003                                             instanceof AuthenticatorException
))) { 
1005                             OwnCloudClient client 
= null
; 
1007                                 OwnCloudAccount ocAccount 
=  
1008                                         new OwnCloudAccount(getAccount(), context
); 
1009                                 client 
= (OwnCloudClientManagerFactory
.getDefaultSingleton(). 
1010                                         removeClientFor(ocAccount
)); 
1011                                 // TODO get rid of these exceptions 
1012                             } catch (AccountNotFoundException e
) { 
1013                                 e
.printStackTrace(); 
1014                             } catch (AuthenticatorException e
) { 
1015                                 e
.printStackTrace(); 
1016                             } catch (OperationCanceledException e
) { 
1017                                 e
.printStackTrace(); 
1018                             } catch (IOException e
) { 
1019                                 e
.printStackTrace(); 
1022                             if (client 
!= null
) { 
1023                                 OwnCloudCredentials cred 
= client
.getCredentials(); 
1025                                     AccountManager am 
= AccountManager
.get(context
); 
1026                                     if (cred
.authTokenExpires()) { 
1027                                         am
.invalidateAuthToken( 
1032                                         am
.clearPassword(getAccount()); 
1037                             requestCredentialsUpdate(); 
1041                     removeStickyBroadcast(intent
); 
1042                     Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
); 
1043                     setSupportProgressBarIndeterminateVisibility(mSyncInProgress 
/*|| mRefreshSharesInProgress*/); 
1045                     setBackgroundText(); 
1049                 if (synchResult 
!= null
) { 
1050                     if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) { 
1051                         mLastSslUntrustedServerResult 
= synchResult
; 
1054             } catch (RuntimeException e
) { 
1055                 // avoid app crashes after changing the serial id of RemoteOperationResult  
1056                 // in owncloud library with broadcast notifications pending to process 
1057                 removeStickyBroadcast(intent
); 
1063      * Show a text message on screen view for notifying user if content is 
1064      * loading or folder is empty 
1066     private void setBackgroundText() { 
1067         OCFileListFragment ocFileListFragment 
= getListOfFilesFragment(); 
1068         if (ocFileListFragment 
!= null
) { 
1069             int message 
= R
.string
.file_list_loading
; 
1070             if (!mSyncInProgress
) { 
1071                 // In case file list is empty 
1072                 message 
= R
.string
.file_list_empty
; 
1074             ocFileListFragment
.setMessageForEmptyList(getString(message
)); 
1076             Log_OC
.e(TAG
, "OCFileListFragment is null"); 
1081      * Once the file upload has finished -> update view 
1083     private class UploadFinishReceiver 
extends BroadcastReceiver 
{ 
1085          * Once the file upload has finished -> update view 
1086          *  @author David A. Velasco 
1087          * {@link BroadcastReceiver} to enable upload feedback in UI 
1090         public void onReceive(Context context
, Intent intent
) { 
1092                 String uploadedRemotePath 
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
); 
1093                 String accountName 
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
); 
1094                 boolean sameAccount 
= getAccount() != null 
&& accountName
.equals(getAccount().name
); 
1095                 OCFile currentDir 
= getCurrentDir(); 
1096                 boolean isDescendant 
= (currentDir 
!= null
) && (uploadedRemotePath 
!= null
) &&  
1097                         (uploadedRemotePath
.startsWith(currentDir
.getRemotePath())); 
1099                 if (sameAccount 
&& isDescendant
) { 
1100                     refreshListOfFilesFragment(); 
1103                 boolean uploadWasFine 
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
); 
1104                 boolean renamedInUpload 
= getFile().getRemotePath(). 
1105                         equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
)); 
1106                 boolean sameFile 
= getFile().getRemotePath().equals(uploadedRemotePath
) ||  
1108                 FileFragment details 
= getSecondFragment(); 
1109                 boolean detailFragmentIsShown 
= (details 
!= null 
&&  
1110                         details 
instanceof FileDetailFragment
); 
1112                 if (sameAccount 
&& sameFile 
&& detailFragmentIsShown
) { 
1113                     if (uploadWasFine
) { 
1114                         setFile(getStorageManager().getFileByPath(uploadedRemotePath
)); 
1116                     if (renamedInUpload
) { 
1117                         String newName 
= (new File(uploadedRemotePath
)).getName(); 
1118                         Toast msg 
= Toast
.makeText( 
1121                                         getString(R
.string
.filedetails_renamed_in_upload_msg
),  
1126                     if (uploadWasFine 
|| getFile().fileExists()) { 
1127                         ((FileDetailFragment
)details
).updateFileDetails(false
, true
); 
1129                         cleanSecondFragment(); 
1132                     // Force the preview if the file is an image 
1133                     if (uploadWasFine 
&& PreviewImageFragment
.canBePreviewed(getFile())) { 
1134                         startImagePreview(getFile()); 
1135                     } // TODO what about other kind of previews? 
1139                 if (intent 
!= null
) { 
1140                     removeStickyBroadcast(intent
); 
1150      * Class waiting for broadcast events from the {@link FielDownloader} service. 
1152      * Updates the UI when a download is started or finished, provided that it is relevant for the 
1155     private class DownloadFinishReceiver 
extends BroadcastReceiver 
{ 
1157         public void onReceive(Context context
, Intent intent
) { 
1159                 boolean sameAccount 
= isSameAccount(context
, intent
); 
1160                 String downloadedRemotePath 
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
); 
1161                 boolean isDescendant 
= isDescendant(downloadedRemotePath
); 
1163                 if (sameAccount 
&& isDescendant
) { 
1164                     refreshListOfFilesFragment(); 
1165                     refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)); 
1168                 if (mWaitingToSend 
!= null
) { 
1169                     mWaitingToSend 
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send 
1170                     if (mWaitingToSend
.isDown()) {  
1171                         sendDownloadedFile(); 
1176                 if (intent 
!= null
) { 
1177                     removeStickyBroadcast(intent
); 
1182         private boolean isDescendant(String downloadedRemotePath
) { 
1183             OCFile currentDir 
= getCurrentDir(); 
1184             return (currentDir 
!= null 
&& downloadedRemotePath 
!= null 
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath())); 
1187         private boolean isSameAccount(Context context
, Intent intent
) { 
1188             String accountName 
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
); 
1189             return (accountName 
!= null 
&& getAccount() != null 
&& accountName
.equals(getAccount().name
)); 
1194     public void browseToRoot() { 
1195         OCFileListFragment listOfFiles 
= getListOfFilesFragment();  
1196         if (listOfFiles 
!= null
) {  // should never be null, indeed 
1197             while (mDirectories
.getCount() > 1) { 
1200             OCFile root 
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); 
1201             listOfFiles
.listDirectory(root
); 
1202             setFile(listOfFiles
.getCurrentFile()); 
1203             startSyncFolderOperation(root
, false
); 
1205         cleanSecondFragment(); 
1209     public void browseTo(OCFile folder
) { 
1210         if (folder 
== null 
|| !folder
.isFolder()) { 
1211             throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
); 
1213         OCFileListFragment listOfFiles 
= getListOfFilesFragment();  
1214         if (listOfFiles 
!= null
) { 
1215             setNavigationListWithFolder(folder
); 
1216             listOfFiles
.listDirectory(folder
); 
1217             setFile(listOfFiles
.getCurrentFile()); 
1218             startSyncFolderOperation(folder
, false
); 
1220             Log_OC
.e(TAG
, "Unexpected null when accessing list fragment"); 
1222         cleanSecondFragment(); 
1229      * Updates action bar and second fragment, if in dual pane mode. 
1232     public void onBrowsedDownTo(OCFile directory
) { 
1233         pushDirname(directory
); 
1234         cleanSecondFragment(); 
1237         startSyncFolderOperation(directory
, false
); 
1242      * Shows the information of the {@link OCFile} received as a  
1243      * parameter in the second fragment. 
1245      * @param file          {@link OCFile} whose details will be shown 
1248     public void showDetails(OCFile file
) { 
1249         Fragment detailFragment 
= new FileDetailFragment(file
, getAccount()); 
1250         setSecondFragment(detailFragment
); 
1251         updateFragmentsVisibility(true
); 
1252         updateNavigationElementsInActionBar(file
); 
1260     private void updateNavigationElementsInActionBar(OCFile chosenFile
) { 
1261         ActionBar actionBar 
= getSupportActionBar();  
1262         if (chosenFile 
== null 
|| mDualPane
) { 
1263             // only list of files - set for browsing through folders 
1264             OCFile currentDir 
= getCurrentDir(); 
1265             boolean noRoot 
= (currentDir 
!= null 
&& currentDir
.getParentId() != 0); 
1266             actionBar
.setDisplayHomeAsUpEnabled(noRoot
); 
1267             actionBar
.setDisplayShowTitleEnabled(!noRoot
);  
1269                 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
)); 
1271             actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD 
: ActionBar
.NAVIGATION_MODE_LIST
); 
1272             actionBar
.setListNavigationCallbacks(mDirectories
, this);   // assuming mDirectories is updated 
1275             actionBar
.setDisplayHomeAsUpEnabled(true
); 
1276             actionBar
.setDisplayShowTitleEnabled(true
); 
1277             actionBar
.setTitle(chosenFile
.getFileName()); 
1278             actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
); 
1284     protected ServiceConnection 
newTransferenceServiceConnection() { 
1285         return new ListServiceConnection(); 
1288     /** Defines callbacks for service binding, passed to bindService() */ 
1289     private class ListServiceConnection 
implements ServiceConnection 
{ 
1292         public void onServiceConnected(ComponentName component
, IBinder service
) { 
1293             if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) { 
1294                 Log_OC
.d(TAG
, "Download service connected"); 
1295                 mDownloaderBinder 
= (FileDownloaderBinder
) service
; 
1296                 if (mWaitingToPreview 
!= null
) 
1297                     if (getStorageManager() != null
) { 
1298                         mWaitingToPreview 
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file 
1299                         if (!mWaitingToPreview
.isDown()) { 
1300                             requestForDownload(); 
1304             } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) { 
1305                 Log_OC
.d(TAG
, "Upload service connected"); 
1306                 mUploaderBinder 
= (FileUploaderBinder
) service
; 
1310             // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS 
1311             OCFileListFragment listOfFiles 
= getListOfFilesFragment();  
1312             if (listOfFiles 
!= null
) { 
1313                 listOfFiles
.listDirectory(); 
1315             FileFragment secondFragment 
= getSecondFragment(); 
1316             if (secondFragment 
!= null 
&& secondFragment 
instanceof FileDetailFragment
) { 
1317                 FileDetailFragment detailFragment 
= (FileDetailFragment
)secondFragment
; 
1318                 detailFragment
.listenForTransferProgress(); 
1319                 detailFragment
.updateFileDetails(false
, false
); 
1324         public void onServiceDisconnected(ComponentName component
) { 
1325             if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) { 
1326                 Log_OC
.d(TAG
, "Download service disconnected"); 
1327                 mDownloaderBinder 
= null
; 
1328             } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) { 
1329                 Log_OC
.d(TAG
, "Upload service disconnected"); 
1330                 mUploaderBinder 
= null
; 
1338      * Launch an intent to request the PIN code to the user before letting him use the app 
1340     private void requestPinCode() { 
1341         boolean pinStart 
= false
; 
1342         SharedPreferences appPrefs 
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext()); 
1343         pinStart 
= appPrefs
.getBoolean("set_pincode", false
); 
1345             Intent i 
= new Intent(getApplicationContext(), PinCodeActivity
.class); 
1346             i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity"); 
1353     public void onSavedCertificate() { 
1354         startSyncFolderOperation(getCurrentDir(), false
); 
1359     public void onFailedSavingCertificate() { 
1360         showDialog(DIALOG_CERT_NOT_SAVED
); 
1364     public void onCancelCertificate() { 
1369      * Updates the view associated to the activity after the finish of some operation over files 
1370      * in the current account. 
1372      * @param operation     Removal operation performed. 
1373      * @param result        Result of the removal. 
1376     public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) { 
1377         super.onRemoteOperationFinish(operation
, result
); 
1379         if (operation 
instanceof RemoveFileOperation
) { 
1380             onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
); 
1382         } else if (operation 
instanceof RenameFileOperation
) { 
1383             onRenameFileOperationFinish((RenameFileOperation
)operation
, result
); 
1385         } else if (operation 
instanceof SynchronizeFileOperation
) { 
1386             onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
); 
1388         } else if (operation 
instanceof CreateFolderOperation
) { 
1389             onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
); 
1391         } else if (operation 
instanceof CreateShareOperation
) { 
1392             onCreateShareOperationFinish((CreateShareOperation
) operation
, result
); 
1394         } else if (operation 
instanceof UnshareLinkOperation
) { 
1395             onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
); 
1397         } else if (operation 
instanceof MoveFileOperation
) { 
1398             onMoveFileOperationFinish((MoveFileOperation
)operation
, result
); 
1404     private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) { 
1405         if (result
.isSuccess()) { 
1406             refreshShowDetails(); 
1407             refreshListOfFilesFragment(); 
1412     private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) { 
1413         if (result
.isSuccess()) { 
1414             refreshShowDetails(); 
1415             refreshListOfFilesFragment(); 
1417         } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) { 
1418             cleanSecondFragment(); 
1419             refreshListOfFilesFragment(); 
1423     private void refreshShowDetails() { 
1424         FileFragment details 
= getSecondFragment(); 
1425         if (details 
!= null
) { 
1426             OCFile file 
= details
.getFile(); 
1428                 file 
= getStorageManager().getFileByPath(file
.getRemotePath());  
1429                 if (details 
instanceof PreviewMediaFragment
) { 
1430                     // Refresh  OCFile of the fragment 
1431                     ((PreviewMediaFragment
) details
).updateFile(file
); 
1436             invalidateOptionsMenu(); 
1441      * Updates the view associated to the activity after the finish of an operation trying to remove a  
1444      * @param operation     Removal operation performed. 
1445      * @param result        Result of the removal. 
1447     private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) { 
1448         dismissLoadingDialog(); 
1450         Toast msg 
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),  
1454         if (result
.isSuccess()) { 
1455             OCFile removedFile 
= operation
.getFile(); 
1456             FileFragment second 
= getSecondFragment(); 
1457             if (second 
!= null 
&& removedFile
.equals(second
.getFile())) { 
1458                 if (second 
instanceof PreviewMediaFragment
) { 
1459                     ((PreviewMediaFragment
)second
).stopPreview(true
); 
1461                 setFile(getStorageManager().getFileById(removedFile
.getParentId())); 
1462                 cleanSecondFragment(); 
1464             if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) { 
1465                 refreshListOfFilesFragment(); 
1467             invalidateOptionsMenu(); 
1469             if (result
.isSslRecoverableException()) { 
1470                 mLastSslUntrustedServerResult 
= result
; 
1471                 showUntrustedCertDialog(mLastSslUntrustedServerResult
); 
1478      * Updates the view associated to the activity after the finish of an operation trying to move a  
1481      * @param operation     Move operation performed. 
1482      * @param result        Result of the move operation. 
1484     private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) { 
1485         if (result
.isSuccess()) { 
1486             dismissLoadingDialog(); 
1487             refreshListOfFilesFragment(); 
1489             dismissLoadingDialog(); 
1491                 Toast msg 
= Toast
.makeText(FileDisplayActivity
.this,  
1492                         ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),  
1496             } catch (NotFoundException e
) { 
1497                 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
); 
1504      * Updates the view associated to the activity after the finish of an operation trying to rename a  
1507      * @param operation     Renaming operation performed. 
1508      * @param result        Result of the renaming. 
1510     private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) { 
1511         dismissLoadingDialog(); 
1512         OCFile renamedFile 
= operation
.getFile(); 
1513         if (result
.isSuccess()) { 
1514             FileFragment details 
= getSecondFragment(); 
1515             if (details 
!= null
) { 
1516                 if (details 
instanceof FileDetailFragment 
&& renamedFile
.equals(details
.getFile()) ) { 
1517                     ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount()); 
1518                     showDetails(renamedFile
); 
1520                 } else if (details 
instanceof PreviewMediaFragment 
&& renamedFile
.equals(details
.getFile())) { 
1521                     ((PreviewMediaFragment
) details
).updateFile(renamedFile
); 
1522                     if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) { 
1523                         int position 
= ((PreviewMediaFragment
)details
).getPosition(); 
1524                         startMediaPreview(renamedFile
, position
, true
); 
1526                         getFileOperationsHelper().openFile(renamedFile
); 
1531             if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) { 
1532                 refreshListOfFilesFragment(); 
1536             Toast msg 
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),  
1540             if (result
.isSslRecoverableException()) { 
1541                 mLastSslUntrustedServerResult 
= result
; 
1542                 showUntrustedCertDialog(mLastSslUntrustedServerResult
); 
1547     private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) { 
1548         dismissLoadingDialog(); 
1549         OCFile syncedFile 
= operation
.getLocalFile(); 
1550         if (!result
.isSuccess()) { 
1551             if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) { 
1552                 Intent i 
= new Intent(this, ConflictsResolveActivity
.class); 
1553                 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
); 
1554                 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount()); 
1560             if (operation
.transferWasRequested()) { 
1561                 onTransferStateChanged(syncedFile
, true
, true
); 
1564                 Toast msg 
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),  
1572      * Updates the view associated to the activity after the finish of an operation trying create a new folder 
1574      * @param operation     Creation operation performed. 
1575      * @param result        Result of the creation. 
1577     private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) { 
1578         if (result
.isSuccess()) { 
1579             dismissLoadingDialog(); 
1580             refreshListOfFilesFragment(); 
1582             dismissLoadingDialog(); 
1584                 Toast msg 
= Toast
.makeText(FileDisplayActivity
.this,  
1585                         ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),  
1589             } catch (NotFoundException e
) { 
1590                 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
); 
1600     public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) { 
1601         refreshListOfFilesFragment(); 
1602         FileFragment details 
= getSecondFragment(); 
1603         if (details 
!= null 
&& details 
instanceof FileDetailFragment 
&& file
.equals(details
.getFile()) ) { 
1604             if (downloading 
|| uploading
) { 
1605                 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount()); 
1607                 if (!file
.fileExists()) { 
1608                     cleanSecondFragment(); 
1610                     ((FileDetailFragment
)details
).updateFileDetails(false
, true
); 
1618     private void requestForDownload() { 
1619         Account account 
= getAccount(); 
1620         if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) { 
1621             Intent i 
= new Intent(this, FileDownloader
.class); 
1622             i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
); 
1623             i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
); 
1629     private OCFile 
getCurrentDir() { 
1630         OCFile file 
= getFile(); 
1632             if (file
.isFolder()) { 
1634             } else if (getStorageManager() != null
) { 
1635                 String parentPath 
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName())); 
1636                 return getStorageManager().getFileByPath(parentPath
); 
1642     public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) { 
1643         long currentSyncTime 
= System
.currentTimeMillis();  
1645         mSyncInProgress 
= true
; 
1647         // perform folder synchronization 
1648         RemoteOperation synchFolderOp 
= new SynchronizeFolderOperation( folder
,   
1651                                                                         getFileOperationsHelper().isSharedSupported(), 
1653                                                                         getStorageManager(),  
1655                                                                         getApplicationContext() 
1657         synchFolderOp
.execute(getAccount(), this, null
, null
); 
1659         setSupportProgressBarIndeterminateVisibility(true
); 
1661         setBackgroundText(); 
1665      * Show untrusted cert dialog  
1667     public void showUntrustedCertDialog(RemoteOperationResult result
) { 
1668         // Show a dialog with the certificate info 
1669         SslUntrustedCertDialog dialog 
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException()); 
1670         FragmentManager fm 
= getSupportFragmentManager(); 
1671         FragmentTransaction ft 
= fm
.beginTransaction(); 
1672         dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
); 
1675     private void requestForDownload(OCFile file
) { 
1676         Account account 
= getAccount(); 
1677         if (!mDownloaderBinder
.isDownloading(account
, file
)) { 
1678             Intent i 
= new Intent(this, FileDownloader
.class); 
1679             i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
); 
1680             i
.putExtra(FileDownloader
.EXTRA_FILE
, file
); 
1685     private void sendDownloadedFile(){ 
1686         getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
); 
1687         mWaitingToSend 
= null
; 
1692      * Requests the download of the received {@link OCFile} , updates the UI 
1693      * to monitor the download progress and prepares the activity to send the file 
1694      * when the download finishes. 
1696      * @param file          {@link OCFile} to download and preview. 
1698     public void startDownloadForSending(OCFile file
) { 
1699         mWaitingToSend 
= file
; 
1700         requestForDownload(mWaitingToSend
); 
1701         boolean hasSecondFragment 
= (getSecondFragment()!= null
); 
1702         updateFragmentsVisibility(hasSecondFragment
); 
1706      * Opens the image gallery showing the image {@link OCFile} received as parameter. 
1708      * @param file                      Image {@link OCFile} to show. 
1710     public void startImagePreview(OCFile file
) { 
1711         Intent showDetailsIntent 
= new Intent(this, PreviewImageActivity
.class); 
1712         showDetailsIntent
.putExtra(EXTRA_FILE
, file
); 
1713         showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount()); 
1714         startActivity(showDetailsIntent
); 
1719      * Stars the preview of an already down media {@link OCFile}. 
1721      * @param file                      Media {@link OCFile} to preview. 
1722      * @param startPlaybackPosition     Media position where the playback will be started, in milliseconds. 
1723      * @param autoplay                  When 'true', the playback will start without user interactions. 
1725     public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) { 
1726         Fragment mediaFragment 
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
); 
1727         setSecondFragment(mediaFragment
); 
1728         updateFragmentsVisibility(true
); 
1729         updateNavigationElementsInActionBar(file
); 
1734      * Requests the download of the received {@link OCFile} , updates the UI 
1735      * to monitor the download progress and prepares the activity to preview 
1736      * or open the file when the download finishes. 
1738      * @param file          {@link OCFile} to download and preview. 
1740     public void startDownloadForPreview(OCFile file
) { 
1741         Fragment detailFragment 
= new FileDetailFragment(file
, getAccount()); 
1742         setSecondFragment(detailFragment
); 
1743         mWaitingToPreview 
= file
; 
1744         requestForDownload(); 
1745         updateFragmentsVisibility(true
); 
1746         updateNavigationElementsInActionBar(file
); 
1751     public void cancelTransference(OCFile file
) { 
1752         getFileOperationsHelper().cancelTransference(file
); 
1753         if (mWaitingToPreview 
!= null 
&&  
1754                 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) { 
1755             mWaitingToPreview 
= null
; 
1757         if (mWaitingToSend 
!= null 
&& 
1758                 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) { 
1759             mWaitingToSend 
= null
; 
1761         onTransferStateChanged(file
, false
, false
); 
1765     public void onRefresh(boolean ignoreETag
) { 
1766         refreshList(ignoreETag
); 
1770     public void onRefresh() { 
1774     private void refreshList(boolean ignoreETag
) { 
1775         OCFileListFragment listOfFiles 
= getListOfFilesFragment(); 
1776         if (listOfFiles 
!= null
) { 
1777             OCFile folder 
= listOfFiles
.getCurrentFile(); 
1778             if (folder 
!= null
) { 
1779                 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId()); 
1780                 listDirectory(mFile);*/ 
1781                 startSyncFolderOperation(folder
, ignoreETag
); 
1786     private void sortByDate(boolean ascending
){ 
1787         getListOfFilesFragment().sortByDate(ascending
); 
1790     private void sortBySize(boolean ascending
){ 
1791         getListOfFilesFragment().sortBySize(ascending
); 
1794     private void sortByName(boolean ascending
){ 
1795         getListOfFilesFragment().sortByName(ascending
);