2 * ownCloud Android client application
4 * @author Bartek Przybylski
5 * @author David A. Velasco
6 * Copyright (C) 2011 Bartek Przybylski
7 * Copyright (C) 2015 ownCloud Inc.
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2,
11 * as published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 package com
.owncloud
.android
.ui
.activity
;
27 import android
.accounts
.Account
;
28 import android
.accounts
.AccountManager
;
29 import android
.accounts
.AuthenticatorException
;
30 import android
.accounts
.OperationCanceledException
;
31 import android
.annotation
.TargetApi
;
32 import android
.app
.AlertDialog
;
33 import android
.content
.BroadcastReceiver
;
34 import android
.content
.ComponentName
;
35 import android
.content
.ContentResolver
;
36 import android
.content
.Context
;
37 import android
.content
.DialogInterface
;
38 import android
.content
.Intent
;
39 import android
.content
.IntentFilter
;
40 import android
.content
.ServiceConnection
;
41 import android
.content
.SharedPreferences
;
42 import android
.content
.SyncRequest
;
43 import android
.content
.res
.Configuration
;
44 import android
.content
.res
.Resources
.NotFoundException
;
45 import android
.database
.Cursor
;
46 import android
.net
.Uri
;
47 import android
.os
.Build
;
48 import android
.os
.Bundle
;
49 import android
.os
.IBinder
;
50 import android
.preference
.PreferenceManager
;
51 import android
.provider
.OpenableColumns
;
52 import android
.support
.v4
.app
.ActionBarDrawerToggle
;
53 import android
.support
.v4
.app
.Fragment
;
54 import android
.support
.v4
.app
.FragmentManager
;
55 import android
.support
.v4
.app
.FragmentTransaction
;
56 import android
.support
.v4
.view
.GravityCompat
;
57 import android
.support
.v4
.widget
.DrawerLayout
;
58 import android
.util
.Log
;
59 import android
.view
.View
;
60 import android
.view
.ViewGroup
;
61 import android
.widget
.AdapterView
;
62 import android
.widget
.AdapterView
.OnItemClickListener
;
63 import android
.widget
.ArrayAdapter
;
64 import android
.widget
.ImageView
;
65 import android
.widget
.LinearLayout
;
66 import android
.widget
.ListView
;
67 import android
.widget
.TextView
;
68 import android
.widget
.Toast
;
70 import com
.actionbarsherlock
.app
.ActionBar
;
71 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
72 import com
.actionbarsherlock
.view
.Menu
;
73 import com
.actionbarsherlock
.view
.MenuInflater
;
74 import com
.actionbarsherlock
.view
.MenuItem
;
75 import com
.actionbarsherlock
.view
.Window
;
76 import com
.owncloud
.android
.MainApp
;
77 import com
.owncloud
.android
.R
;
78 import com
.owncloud
.android
.authentication
.AccountUtils
;
79 import com
.owncloud
.android
.datamodel
.OCFile
;
80 import com
.owncloud
.android
.files
.services
.FileDownloader
;
81 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
82 import com
.owncloud
.android
.files
.services
.FileUploader
;
83 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
84 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
85 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
86 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
87 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
88 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
89 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
90 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
91 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
92 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
93 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
94 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
95 import com
.owncloud
.android
.operations
.CreateShareOperation
;
96 import com
.owncloud
.android
.operations
.MoveFileOperation
;
97 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
98 import com
.owncloud
.android
.operations
.RenameFileOperation
;
99 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
100 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
101 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
102 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
103 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
104 import com
.owncloud
.android
.ui
.adapter
.FileListListAdapter
;
105 import com
.owncloud
.android
.ui
.adapter
.NavigationDrawerListAdapter
;
106 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
107 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
108 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
109 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
110 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
111 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
112 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
113 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
114 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
115 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
116 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
117 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
118 import com
.owncloud
.android
.utils
.DisplayUtils
;
119 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
120 import com
.owncloud
.android
.utils
.FileStorageUtils
;
121 import com
.owncloud
.android
.utils
.UriUtils
;
125 * Displays, what files the user has available in his ownCloud.
128 public class FileDisplayActivity
extends HookActivity
implements
129 FileFragment
.ContainerActivity
, OnNavigationListener
,
130 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
132 private ArrayAdapter
<String
> mDirectories
;
134 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
135 private UploadFinishReceiver mUploadFinishReceiver
;
136 private DownloadFinishReceiver mDownloadFinishReceiver
;
137 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
139 private boolean mDualPane
;
140 private View mLeftFragmentContainer
;
141 private View mRightFragmentContainer
;
143 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
144 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
145 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
147 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
149 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
150 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
151 public static final int ACTION_MOVE_FILES
= 3;
153 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
155 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
156 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
158 private OCFile mWaitingToPreview
;
160 private boolean mSyncInProgress
= false
;
162 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
163 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
164 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
165 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
168 private OCFile mWaitingToSend
;
170 private DrawerLayout mDrawerLayout
;
171 private ActionBarDrawerToggle mDrawerToggle
;
172 private boolean showAccounts
= false
;
175 protected void onCreate(Bundle savedInstanceState
) {
176 Log_OC
.v(TAG
, "onCreate() start");
177 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
179 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
181 /// grant that FileObserverService is watching favorite files
182 if (savedInstanceState
== null
) {
183 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
184 startService(initObserversIntent
);
187 /// Load of saved instance state
188 if(savedInstanceState
!= null
) {
189 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
190 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
191 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
194 mWaitingToPreview
= null
;
195 mSyncInProgress
= false
;
196 mWaitingToSend
= null
;
201 // Inflate and set the layout view
202 setContentView(R
.layout
.files
);
204 // TODO move to another place that all activity can use it
205 mDrawerLayout
= (DrawerLayout
) findViewById(R
.id
.drawer_layout
);
207 mDrawerToggle
= new ActionBarDrawerToggle(
210 R
.drawable
.ic_drawer
,
211 R
.string
.drawer_open
,
215 /** Called when a drawer has settled in a completely closed state. */
216 public void onDrawerClosed(View view
) {
217 super.onDrawerClosed(view
);
218 getSupportActionBar().setDisplayShowTitleEnabled(true
);
219 getSupportActionBar().setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
220 initFragmentsWithFile();
221 invalidateOptionsMenu();
224 /** Called when a drawer has settled in a completely open state. */
225 public void onDrawerOpened(View drawerView
) {
226 super.onDrawerOpened(drawerView
);
227 getSupportActionBar().setTitle(R
.string
.drawer_open
);
228 getSupportActionBar().setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
229 invalidateOptionsMenu();
233 mDrawerToggle
.setDrawerIndicatorEnabled(true
);
235 // Notification Drawer
236 LinearLayout notificatonDrawer
= (LinearLayout
) findViewById(R
.id
.left_drawer
);
239 ListView listView
= (ListView
) notificatonDrawer
.findViewById(R
.id
.drawer_list
);
240 final NavigationDrawerListAdapter adapter
= new NavigationDrawerListAdapter(getApplicationContext(), this);
242 listView
.setAdapter(adapter
);
244 listView
.setOnItemClickListener(new OnItemClickListener() {
246 public void onItemClick(AdapterView
<?
> parent
, View view
, int position
, long id
) {
247 if (showAccounts
&& position
> 0){
248 position
= position
- 1;
252 showAccounts
= !showAccounts
;
253 adapter
.setShowAccounts(showAccounts
);
254 adapter
.notifyDataSetChanged();
257 MainApp
.showOnlyFilesOnDevice(false
);
258 mDrawerLayout
.closeDrawers();
261 MainApp
.showOnlyFilesOnDevice(true
);
262 mDrawerLayout
.closeDrawers();
265 Intent settingsIntent
= new Intent(getApplicationContext(), Preferences
.class);
266 startActivity(settingsIntent
);
273 ImageView userIcon
= (ImageView
) notificatonDrawer
.findViewById(R
.id
.drawer_userIcon
);
274 userIcon
.setImageResource(DisplayUtils
.getSeasonalIconId());
277 TextView username
= (TextView
) notificatonDrawer
.findViewById(R
.id
.drawer_username
);
278 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getApplicationContext());
279 int lastAtPos
= account
.name
.lastIndexOf("@");
280 username
.setText(account
.name
.substring(0, lastAtPos
));
282 // Set the drawer toggle as the DrawerListener
283 mDrawerLayout
.setDrawerListener(mDrawerToggle
);
285 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
286 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
287 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
288 if (savedInstanceState
== null
) {
289 createMinFragments();
293 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
294 getSupportActionBar().setDisplayHomeAsUpEnabled(true
);
295 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
296 getSupportActionBar().setDisplayShowCustomEnabled(true
); // CRUCIAL - for displaying your custom actionbar
297 getSupportActionBar().setDisplayShowTitleEnabled(true
);
298 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
300 mDrawerToggle
.syncState();
304 Log_OC
.v(TAG
, "onCreate() end");
308 protected void onStart() {
309 Log_OC
.v(TAG
, "onStart() start");
311 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
312 Log_OC
.v(TAG
, "onStart() end");
316 protected void onPostCreate(Bundle savedInstanceState
) {
317 super.onPostCreate(savedInstanceState
);
318 // Sync the toggle state after onRestoreInstanceState has occurred.
319 mDrawerToggle
.syncState();
323 public void onConfigurationChanged(Configuration newConfig
) {
324 super.onConfigurationChanged(newConfig
);
325 mDrawerToggle
.onConfigurationChanged(newConfig
);
329 protected void onDestroy() {
330 Log_OC
.v(TAG
, "onDestroy() start");
332 Log_OC
.v(TAG
, "onDestroy() end");
336 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
339 protected void onAccountSet(boolean stateWasRecovered
) {
340 super.onAccountSet(stateWasRecovered
);
341 if (getAccount() != null
) {
342 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
343 OCFile file
= getFile();
344 // get parent from path
345 String parentPath
= "";
347 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
348 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
349 // get parent from path
350 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
351 if (getStorageManager().getFileByPath(parentPath
) == null
)
352 file
= null
; // not able to know the directory where the file is uploading
354 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
358 // fall back to root folder
359 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
362 setNavigationListWithFolder(file
);
364 if (!stateWasRecovered
) {
365 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
366 initFragmentsWithFile();
367 if (file
.isFolder()) {
368 startSyncFolderOperation(file
, false
);
372 updateFragmentsVisibility(!file
.isFolder());
373 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
379 private void setNavigationListWithFolder(OCFile file
) {
380 mDirectories
.clear();
381 OCFile fileIt
= file
;
383 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
384 if (fileIt
.isFolder()) {
385 mDirectories
.add(fileIt
.getFileName());
387 // get parent from path
388 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
389 fileIt
= getStorageManager().getFileByPath(parentPath
);
391 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
395 private void createMinFragments() {
396 OCFileListFragment listOfFiles
= new OCFileListFragment();
397 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
398 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
399 transaction
.commit();
402 private void initFragmentsWithFile() {
403 if (getAccount() != null
&& getFile() != null
) {
405 OCFileListFragment listOfFiles
= getListOfFilesFragment();
406 if (listOfFiles
!= null
) {
407 listOfFiles
.listDirectory(getCurrentDir(), MainApp
.getOnlyOnDevice());
409 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
413 OCFile file
= getFile();
414 Fragment secondFragment
= chooseInitialSecondFragment(file
);
415 if (secondFragment
!= null
) {
416 setSecondFragment(secondFragment
);
417 updateFragmentsVisibility(true
);
418 updateNavigationElementsInActionBar(file
);
421 cleanSecondFragment();
425 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
426 if (getAccount() == null
) {
427 Log_OC
.wtf(TAG
, "\t account is NULL");
429 if (getFile() == null
) {
430 Log_OC
.wtf(TAG
, "\t file is NULL");
435 private Fragment
chooseInitialSecondFragment(OCFile file
) {
436 Fragment secondFragment
= null
;
437 if (file
!= null
&& !file
.isFolder()) {
438 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
439 && file
.getLastSyncDateForProperties() > 0 // temporal fix
441 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
442 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
443 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
446 secondFragment
= new FileDetailFragment(file
, getAccount());
449 return secondFragment
;
454 * Replaces the second fragment managed by the activity with the received as
457 * Assumes never will be more than two fragments managed at the same time.
459 * @param fragment New second Fragment to set.
461 private void setSecondFragment(Fragment fragment
) {
462 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
463 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
464 transaction
.commit();
468 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
470 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
471 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
473 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
474 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
477 } else if (existsSecondFragment
) {
478 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
479 mLeftFragmentContainer
.setVisibility(View
.GONE
);
481 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
482 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
486 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
487 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
489 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
490 mRightFragmentContainer
.setVisibility(View
.GONE
);
496 private OCFileListFragment
getListOfFilesFragment() {
497 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
498 if (listOfFiles
!= null
) {
499 return (OCFileListFragment
)listOfFiles
;
501 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
505 public FileFragment
getSecondFragment() {
506 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
507 if (second
!= null
) {
508 return (FileFragment
)second
;
513 protected void cleanSecondFragment() {
514 Fragment second
= getSecondFragment();
515 if (second
!= null
) {
516 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
520 updateFragmentsVisibility(false
);
521 updateNavigationElementsInActionBar(null
);
524 protected void refreshListOfFilesFragment() {
525 OCFileListFragment fileListFragment
= getListOfFilesFragment();
526 if (fileListFragment
!= null
) {
527 fileListFragment
.listDirectory(MainApp
.getOnlyOnDevice());
531 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
532 FileFragment secondFragment
= getSecondFragment();
533 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
534 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
535 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
536 OCFile fileInFragment
= detailsFragment
.getFile();
537 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
538 // the user browsed to other file ; forget the automatic preview
539 mWaitingToPreview
= null
;
541 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
542 // grant that the right panel updates the progress bar
543 detailsFragment
.listenForTransferProgress();
544 detailsFragment
.updateFileDetails(true
, false
);
546 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
547 // update the right panel
548 boolean detailsFragmentChanged
= false
;
551 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
552 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
553 startMediaPreview(mWaitingToPreview
, 0, true
);
554 detailsFragmentChanged
= true
;
556 getFileOperationsHelper().openFile(mWaitingToPreview
);
559 mWaitingToPreview
= null
;
561 if (!detailsFragmentChanged
) {
562 detailsFragment
.updateFileDetails(false
, (success
));
569 public boolean onPrepareOptionsMenu(Menu menu
) {
570 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
571 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
572 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
573 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
575 return super.onPrepareOptionsMenu(menu
);
579 public boolean onCreateOptionsMenu(Menu menu
) {
580 MenuInflater inflater
= getSherlock().getMenuInflater();
581 inflater
.inflate(R
.menu
.main_menu
, menu
);
587 public boolean onOptionsItemSelected(MenuItem item
) {
588 boolean retval
= true
;
589 switch (item
.getItemId()) {
590 case R
.id
.action_create_dir
: {
591 CreateFolderDialogFragment dialog
= CreateFolderDialogFragment
.newInstance(getCurrentDir());
592 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
595 case R
.id
.action_upload
: {
596 UploadSourceDialogFragment dialog
= UploadSourceDialogFragment
.newInstance(getAccount());
597 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
601 case android
.R
.id
.home
: {
602 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
603 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
605 mDrawerLayout
.openDrawer(GravityCompat
.START
);
607 // TODO add hamburger to left of android.R.id.home
610 case R
.id
.action_sort
: {
611 SharedPreferences appPreferences
= PreferenceManager
612 .getDefaultSharedPreferences(this);
614 // Read sorting order, default to sort by name ascending
615 Integer sortOrder
= appPreferences
616 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
618 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
619 builder
.setTitle(R
.string
.actionbar_sort_title
)
620 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
621 public void onClick(DialogInterface dialog
, int which
) {
637 builder
.create().show();
641 retval
= super.onOptionsItemSelected(item
);
646 private void startSynchronization() {
647 Log_OC
.d(TAG
, "Got to start sync");
648 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
649 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
650 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
651 Bundle bundle
= new Bundle();
652 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
653 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
654 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
655 ContentResolver
.requestSync(
657 MainApp
.getAuthority(), bundle
);
659 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
660 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
661 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
662 builder
.setExpedited(true
);
663 builder
.setManual(true
);
666 // Fix bug in Android Lollipop when you click on refresh the whole account
667 Bundle extras
= new Bundle();
668 builder
.setExtras(extras
);
670 SyncRequest request
= builder
.build();
671 ContentResolver
.requestSync(request
);
677 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
678 if (itemPosition
!= 0) {
679 String targetPath
= "";
680 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
681 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
683 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
684 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
685 if (targetFolder
!= null
) {
686 browseTo(targetFolder
);
689 // the next operation triggers a new call to this method, but it's necessary to
690 // ensure that the name exposed in the action bar is the current directory when the
691 // user selected it in the navigation list
692 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
693 getSupportActionBar().setSelectedNavigationItem(0);
699 * Called, when the user selected something for uploading
702 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
704 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
706 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
707 //getClipData is only supported on api level 16+, Jelly Bean
708 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
709 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
710 Intent intent
= new Intent();
711 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
712 requestSimpleUpload(intent
, resultCode
);
715 requestSimpleUpload(data
, resultCode
);
717 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
718 requestMultipleUpload(data
, resultCode
);
720 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
722 final Intent fData
= data
;
723 final int fResultCode
= resultCode
;
724 getHandler().postDelayed(
728 requestMoveOperation(fData
, fResultCode
);
731 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
735 super.onActivityResult(requestCode
, resultCode
, data
);
740 private void requestMultipleUpload(Intent data
, int resultCode
) {
741 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
742 if (filePaths
!= null
) {
743 String
[] remotePaths
= new String
[filePaths
.length
];
744 String remotePathBase
= "";
746 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
747 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
749 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
750 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
751 for (int j
= 0; j
< remotePaths
.length
; j
++) {
752 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
755 Intent i
= new Intent(this, FileUploader
.class);
756 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
757 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
758 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
759 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
760 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
761 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
765 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
766 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
773 private void requestSimpleUpload(Intent data
, int resultCode
) {
774 String filePath
= null
;
775 String mimeType
= null
;
777 Uri selectedImageUri
= data
.getData();
780 mimeType
= getContentResolver().getType(selectedImageUri
);
782 String fileManagerString
= selectedImageUri
.getPath();
783 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
785 if (selectedImagePath
!= null
)
786 filePath
= selectedImagePath
;
788 filePath
= fileManagerString
;
790 } catch (Exception e
) {
791 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
794 if (filePath
== null
) {
795 Log_OC
.e(TAG
, "Couldn't resolve path to file");
796 Toast t
= Toast
.makeText(
797 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
804 Intent i
= new Intent(this, FileUploader
.class);
805 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
806 OCFile currentDir
= getCurrentDir();
807 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
809 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
810 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
812 if (cursor
!= null
&& cursor
.moveToFirst()) {
813 String displayName
= cursor
.getString(cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
814 Log_OC
.v(TAG
, "Display Name: " + displayName
);
816 displayName
.replace(File
.separatorChar
, '_');
817 displayName
.replace(File
.pathSeparatorChar
, '_');
818 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
821 // and what happens in case of error?; wrong target name for the upload
827 remotePath
+= new File(filePath
).getName();
830 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
831 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
832 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
833 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
834 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
835 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
840 * Request the operation for moving the file/folder from one path to another
842 * @param data Intent received
843 * @param resultCode Result code received
845 private void requestMoveOperation(Intent data
, int resultCode
) {
846 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
847 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
848 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
852 public void onBackPressed() {
853 OCFileListFragment listOfFiles
= getListOfFilesFragment();
854 if (mDualPane
|| getSecondFragment() == null
) {
855 if (listOfFiles
!= null
) { // should never be null, indeed
856 if (mDirectories
.getCount() <= 1) {
860 int levelsUp
= listOfFiles
.onBrowseUp();
861 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
866 if (listOfFiles
!= null
) { // should never be null, indeed
867 setFile(listOfFiles
.getCurrentFile());
869 cleanSecondFragment();
874 protected void onSaveInstanceState(Bundle outState
) {
875 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
876 Log_OC
.v(TAG
, "onSaveInstanceState() start");
877 super.onSaveInstanceState(outState
);
878 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
879 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
880 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
881 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
883 Log_OC
.v(TAG
, "onSaveInstanceState() end");
889 protected void onResume() {
890 Log_OC
.v(TAG
, "onResume() start");
893 // refresh list of files
894 refreshListOfFilesFragment();
896 // Listen for sync messages
897 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
898 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
899 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
900 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
901 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
902 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
903 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
904 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
906 // Listen for upload messages
907 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
908 mUploadFinishReceiver
= new UploadFinishReceiver();
909 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
911 // Listen for download messages
912 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
913 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
914 mDownloadFinishReceiver
= new DownloadFinishReceiver();
915 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
917 Log_OC
.v(TAG
, "onResume() end");
922 protected void onPause() {
923 Log_OC
.v(TAG
, "onPause() start");
924 if (mSyncBroadcastReceiver
!= null
) {
925 unregisterReceiver(mSyncBroadcastReceiver
);
926 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
927 mSyncBroadcastReceiver
= null
;
929 if (mUploadFinishReceiver
!= null
) {
930 unregisterReceiver(mUploadFinishReceiver
);
931 mUploadFinishReceiver
= null
;
933 if (mDownloadFinishReceiver
!= null
) {
934 unregisterReceiver(mDownloadFinishReceiver
);
935 mDownloadFinishReceiver
= null
;
939 Log_OC
.v(TAG
, "onPause() end");
943 * Pushes a directory to the drop down list
944 * @param directory to push
945 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
947 public void pushDirname(OCFile directory
) {
948 if(!directory
.isFolder()){
949 throw new IllegalArgumentException("Only directories may be pushed!");
951 mDirectories
.insert(directory
.getFileName(), 0);
956 * Pops a directory name from the drop down list
957 * @return True, unless the stack is empty
959 public boolean popDirname() {
960 mDirectories
.remove(mDirectories
.getItem(0));
961 return !mDirectories
.isEmpty();
964 // Custom array adapter to override text colors
965 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
967 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
971 public View
getView(int position
, View convertView
, ViewGroup parent
) {
972 View v
= super.getView(position
, convertView
, parent
);
974 ((TextView
) v
).setTextColor(getResources().getColorStateList(
975 android
.R
.color
.white
));
977 fixRoot((TextView
) v
);
981 public View
getDropDownView(int position
, View convertView
,
983 View v
= super.getDropDownView(position
, convertView
, parent
);
985 ((TextView
) v
).setTextColor(getResources().getColorStateList(
986 android
.R
.color
.white
));
988 fixRoot((TextView
) v
);
992 private void fixRoot(TextView v
) {
993 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
994 v
.setText(R
.string
.default_display_name_for_root_folder
);
1000 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
1003 * {@link BroadcastReceiver} to enable syncing feedback in UI
1006 public void onReceive(Context context
, Intent intent
) {
1008 String event
= intent
.getAction();
1009 Log_OC
.d(TAG
, "Received broadcast " + event
);
1010 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
1011 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
1012 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
1013 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
1017 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
1018 mSyncInProgress
= true
;
1021 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
1022 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1024 if (currentDir
== null
) {
1025 // current folder was removed from the server
1026 Toast
.makeText( FileDisplayActivity
.this,
1027 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
1033 if (currentFile
== null
&& !getFile().isFolder()) {
1034 // currently selected file was removed in the server, and now we know it
1035 cleanSecondFragment();
1036 currentFile
= currentDir
;
1039 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1040 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1041 if (fileListFragment
!= null
) {
1042 fileListFragment
.listDirectory(currentDir
, MainApp
.getOnlyOnDevice());
1045 setFile(currentFile
);
1048 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1050 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1052 /// TODO refactor and make common
1053 synchResult
!= null
&& !synchResult
.isSuccess() &&
1054 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1055 synchResult
.isIdPRedirection() ||
1056 (synchResult
.isException() && synchResult
.getException()
1057 instanceof AuthenticatorException
))) {
1061 OwnCloudClient client
;
1062 OwnCloudAccount ocAccount
=
1063 new OwnCloudAccount(getAccount(), context
);
1064 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1065 removeClientFor(ocAccount
));
1067 if (client
!= null
) {
1068 OwnCloudCredentials cred
= client
.getCredentials();
1070 AccountManager am
= AccountManager
.get(context
);
1071 if (cred
.authTokenExpires()) {
1072 am
.invalidateAuthToken(
1077 am
.clearPassword(getAccount());
1081 requestCredentialsUpdate();
1083 } catch (AccountNotFoundException e
) {
1084 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1089 removeStickyBroadcast(intent
);
1090 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1091 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1093 setBackgroundText();
1097 if (synchResult
!= null
) {
1098 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1099 mLastSslUntrustedServerResult
= synchResult
;
1102 } catch (RuntimeException e
) {
1103 // avoid app crashes after changing the serial id of RemoteOperationResult
1104 // in owncloud library with broadcast notifications pending to process
1105 removeStickyBroadcast(intent
);
1111 * Show a text message on screen view for notifying user if content is
1112 * loading or folder is empty
1114 private void setBackgroundText() {
1115 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1116 if (ocFileListFragment
!= null
) {
1117 int message
= R
.string
.file_list_loading
;
1118 if (!mSyncInProgress
) {
1119 // In case file list is empty
1120 message
= R
.string
.file_list_empty
;
1122 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1124 Log_OC
.e(TAG
, "OCFileListFragment is null");
1129 * Once the file upload has finished -> update view
1131 private class UploadFinishReceiver
extends BroadcastReceiver
{
1133 * Once the file upload has finished -> update view
1134 * @author David A. Velasco
1135 * {@link BroadcastReceiver} to enable upload feedback in UI
1138 public void onReceive(Context context
, Intent intent
) {
1140 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1141 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1142 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1143 OCFile currentDir
= getCurrentDir();
1144 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1145 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1147 if (sameAccount
&& isDescendant
) {
1148 refreshListOfFilesFragment();
1151 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1152 boolean renamedInUpload
= getFile().getRemotePath().
1153 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1154 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1156 FileFragment details
= getSecondFragment();
1157 boolean detailFragmentIsShown
= (details
!= null
&&
1158 details
instanceof FileDetailFragment
);
1160 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1161 if (uploadWasFine
) {
1162 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1164 if (renamedInUpload
) {
1165 String newName
= (new File(uploadedRemotePath
)).getName();
1166 Toast msg
= Toast
.makeText(
1169 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1174 if (uploadWasFine
|| getFile().fileExists()) {
1175 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1177 cleanSecondFragment();
1180 // Force the preview if the file is an image
1181 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1182 startImagePreview(getFile());
1183 } // TODO what about other kind of previews?
1187 if (intent
!= null
) {
1188 removeStickyBroadcast(intent
);
1198 * Class waiting for broadcast events from the {@link FileDownloader} service.
1200 * Updates the UI when a download is started or finished, provided that it is relevant for the
1203 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1205 //int refreshCounter = 0;
1207 public void onReceive(Context context
, Intent intent
) {
1209 boolean sameAccount
= isSameAccount(context
, intent
);
1210 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1211 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1213 if (sameAccount
&& isDescendant
) {
1214 String linkedToRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1215 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1216 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1217 refreshListOfFilesFragment();
1219 refreshSecondFragment(
1221 downloadedRemotePath
,
1222 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1226 if (mWaitingToSend
!= null
) {
1227 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1228 if (mWaitingToSend
.isDown()) {
1229 sendDownloadedFile();
1234 if (intent
!= null
) {
1235 removeStickyBroadcast(intent
);
1240 private boolean isDescendant(String downloadedRemotePath
) {
1241 OCFile currentDir
= getCurrentDir();
1243 currentDir
!= null
&&
1244 downloadedRemotePath
!= null
&&
1245 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1249 private boolean isAscendant(String linkedToRemotePath
) {
1250 OCFile currentDir
= getCurrentDir();
1252 currentDir
!= null
&&
1253 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1257 private boolean isSameAccount(Context context
, Intent intent
) {
1258 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1259 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1264 public void browseToRoot() {
1265 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1266 if (listOfFiles
!= null
) { // should never be null, indeed
1267 while (mDirectories
.getCount() > 1) {
1270 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1271 listOfFiles
.listDirectory(root
, MainApp
.getOnlyOnDevice());
1272 setFile(listOfFiles
.getCurrentFile());
1273 startSyncFolderOperation(root
, false
);
1275 cleanSecondFragment();
1279 public void browseTo(OCFile folder
) {
1280 if (folder
== null
|| !folder
.isFolder()) {
1281 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1283 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1284 if (listOfFiles
!= null
) {
1285 setNavigationListWithFolder(folder
);
1286 listOfFiles
.listDirectory(folder
, MainApp
.getOnlyOnDevice());
1287 setFile(listOfFiles
.getCurrentFile());
1288 startSyncFolderOperation(folder
, false
);
1290 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1292 cleanSecondFragment();
1299 * Updates action bar and second fragment, if in dual pane mode.
1302 public void onBrowsedDownTo(OCFile directory
) {
1303 pushDirname(directory
);
1304 cleanSecondFragment();
1307 startSyncFolderOperation(directory
, false
);
1312 * Shows the information of the {@link OCFile} received as a
1313 * parameter in the second fragment.
1315 * @param file {@link OCFile} whose details will be shown
1318 public void showDetails(OCFile file
) {
1319 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1320 setSecondFragment(detailFragment
);
1321 updateFragmentsVisibility(true
);
1322 updateNavigationElementsInActionBar(file
);
1330 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1331 ActionBar actionBar
= getSupportActionBar();
1333 // For adding content description tag to a title field in the action bar
1334 int actionBarTitleId
= getResources().getIdentifier("action_bar_title", "id", "android");
1336 if (chosenFile
== null
|| mDualPane
) {
1337 // only list of files - set for browsing through folders
1338 OCFile currentDir
= getCurrentDir();
1339 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1340 // actionBar.setDisplayHomeAsUpEnabled(noRoot);
1341 // actionBar.setDisplayShowTitleEnabled(!noRoot);
1342 actionBar
.setDisplayHomeAsUpEnabled(true
);
1343 actionBar
.setDisplayShowTitleEnabled(true
);
1345 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1346 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1347 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1348 actionBarTitleView
.setContentDescription(getString(R
.string
.default_display_name_for_root_folder
));
1351 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1352 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1355 actionBar
.setDisplayHomeAsUpEnabled(true
);
1356 actionBar
.setDisplayShowTitleEnabled(true
);
1357 actionBar
.setTitle(chosenFile
.getFileName());
1358 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1359 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1360 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1361 getWindow().getDecorView().findViewById(actionBarTitleId
).
1362 setContentDescription(chosenFile
.getFileName());
1369 protected ServiceConnection
newTransferenceServiceConnection() {
1370 return new ListServiceConnection();
1373 /** Defines callbacks for service binding, passed to bindService() */
1374 private class ListServiceConnection
implements ServiceConnection
{
1377 public void onServiceConnected(ComponentName component
, IBinder service
) {
1378 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1379 Log_OC
.d(TAG
, "Download service connected");
1380 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1381 if (mWaitingToPreview
!= null
)
1382 if (getStorageManager() != null
) {
1383 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1384 if (!mWaitingToPreview
.isDown()) {
1385 requestForDownload();
1389 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1390 Log_OC
.d(TAG
, "Upload service connected");
1391 mUploaderBinder
= (FileUploaderBinder
) service
;
1395 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1396 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1397 if (listOfFiles
!= null
) {
1398 listOfFiles
.listDirectory(MainApp
.getOnlyOnDevice());
1400 FileFragment secondFragment
= getSecondFragment();
1401 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1402 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1403 detailFragment
.listenForTransferProgress();
1404 detailFragment
.updateFileDetails(false
, false
);
1409 public void onServiceDisconnected(ComponentName component
) {
1410 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1411 Log_OC
.d(TAG
, "Download service disconnected");
1412 mDownloaderBinder
= null
;
1413 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1414 Log_OC
.d(TAG
, "Upload service disconnected");
1415 mUploaderBinder
= null
;
1421 public void onSavedCertificate() {
1422 startSyncFolderOperation(getCurrentDir(), false
);
1427 public void onFailedSavingCertificate() {
1428 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1429 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1431 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1435 public void onCancelCertificate() {
1440 * Updates the view associated to the activity after the finish of some operation over files
1441 * in the current account.
1443 * @param operation Removal operation performed.
1444 * @param result Result of the removal.
1447 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1448 super.onRemoteOperationFinish(operation
, result
);
1450 if (operation
instanceof RemoveFileOperation
) {
1451 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1453 } else if (operation
instanceof RenameFileOperation
) {
1454 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1456 } else if (operation
instanceof SynchronizeFileOperation
) {
1457 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1459 } else if (operation
instanceof CreateFolderOperation
) {
1460 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1462 } else if (operation
instanceof CreateShareOperation
) {
1463 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1465 } else if (operation
instanceof UnshareLinkOperation
) {
1466 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1468 } else if (operation
instanceof MoveFileOperation
) {
1469 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1475 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1476 if (result
.isSuccess()) {
1477 refreshShowDetails();
1478 refreshListOfFilesFragment();
1483 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1484 if (result
.isSuccess()) {
1485 refreshShowDetails();
1486 refreshListOfFilesFragment();
1488 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1489 cleanSecondFragment();
1490 refreshListOfFilesFragment();
1494 private void refreshShowDetails() {
1495 FileFragment details
= getSecondFragment();
1496 if (details
!= null
) {
1497 OCFile file
= details
.getFile();
1499 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1500 if (details
instanceof PreviewMediaFragment
) {
1501 // Refresh OCFile of the fragment
1502 ((PreviewMediaFragment
) details
).updateFile(file
);
1507 invalidateOptionsMenu();
1512 * Updates the view associated to the activity after the finish of an operation trying to remove a
1515 * @param operation Removal operation performed.
1516 * @param result Result of the removal.
1518 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1519 dismissLoadingDialog();
1521 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1525 if (result
.isSuccess()) {
1526 OCFile removedFile
= operation
.getFile();
1527 FileFragment second
= getSecondFragment();
1528 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1529 if (second
instanceof PreviewMediaFragment
) {
1530 ((PreviewMediaFragment
)second
).stopPreview(true
);
1532 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1533 cleanSecondFragment();
1535 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1536 refreshListOfFilesFragment();
1538 invalidateOptionsMenu();
1540 if (result
.isSslRecoverableException()) {
1541 mLastSslUntrustedServerResult
= result
;
1542 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1549 * Updates the view associated to the activity after the finish of an operation trying to move a
1552 * @param operation Move operation performed.
1553 * @param result Result of the move operation.
1555 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1556 if (result
.isSuccess()) {
1557 dismissLoadingDialog();
1558 refreshListOfFilesFragment();
1560 dismissLoadingDialog();
1562 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1563 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1567 } catch (NotFoundException e
) {
1568 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1575 * Updates the view associated to the activity after the finish of an operation trying to rename a
1578 * @param operation Renaming operation performed.
1579 * @param result Result of the renaming.
1581 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1582 dismissLoadingDialog();
1583 OCFile renamedFile
= operation
.getFile();
1584 if (result
.isSuccess()) {
1585 FileFragment details
= getSecondFragment();
1586 if (details
!= null
) {
1587 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1588 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1589 showDetails(renamedFile
);
1591 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1592 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1593 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1594 int position
= ((PreviewMediaFragment
)details
).getPosition();
1595 startMediaPreview(renamedFile
, position
, true
);
1597 getFileOperationsHelper().openFile(renamedFile
);
1602 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1603 refreshListOfFilesFragment();
1607 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1611 if (result
.isSslRecoverableException()) {
1612 mLastSslUntrustedServerResult
= result
;
1613 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1618 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1619 dismissLoadingDialog();
1620 OCFile syncedFile
= operation
.getLocalFile();
1621 if (!result
.isSuccess()) {
1622 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1623 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1624 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1625 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1631 if (operation
.transferWasRequested()) {
1632 onTransferStateChanged(syncedFile
, true
, true
);
1635 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1643 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1645 * @param operation Creation operation performed.
1646 * @param result Result of the creation.
1648 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1649 if (result
.isSuccess()) {
1650 dismissLoadingDialog();
1651 refreshListOfFilesFragment();
1653 dismissLoadingDialog();
1655 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1656 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1660 } catch (NotFoundException e
) {
1661 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1671 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1672 refreshListOfFilesFragment();
1673 FileFragment details
= getSecondFragment();
1674 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1675 if (downloading
|| uploading
) {
1676 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1678 if (!file
.fileExists()) {
1679 cleanSecondFragment();
1681 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1689 private void requestForDownload() {
1690 Account account
= getAccount();
1691 //if (!mWaitingToPreview.isDownloading()) {
1692 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1693 Intent i
= new Intent(this, FileDownloader
.class);
1694 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1695 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1701 private OCFile
getCurrentDir() {
1702 OCFile file
= getFile();
1704 if (file
.isFolder()) {
1706 } else if (getStorageManager() != null
) {
1707 String parentPath
= file
.getRemotePath().substring(0,
1708 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1709 return getStorageManager().getFileByPath(parentPath
);
1715 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1716 long currentSyncTime
= System
.currentTimeMillis();
1718 mSyncInProgress
= true
;
1720 // perform folder synchronization
1721 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1724 getFileOperationsHelper().isSharedSupported(),
1726 getStorageManager(),
1728 getApplicationContext()
1730 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1732 setSupportProgressBarIndeterminateVisibility(true
);
1734 setBackgroundText();
1738 * Show untrusted cert dialog
1740 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1741 // Show a dialog with the certificate info
1742 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1743 (CertificateCombinedException
) result
.getException());
1744 FragmentManager fm
= getSupportFragmentManager();
1745 FragmentTransaction ft
= fm
.beginTransaction();
1746 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1749 private void requestForDownload(OCFile file
) {
1750 Account account
= getAccount();
1751 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1752 Intent i
= new Intent(this, FileDownloader
.class);
1753 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1754 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1759 private void sendDownloadedFile(){
1760 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1761 mWaitingToSend
= null
;
1766 * Requests the download of the received {@link OCFile} , updates the UI
1767 * to monitor the download progress and prepares the activity to send the file
1768 * when the download finishes.
1770 * @param file {@link OCFile} to download and preview.
1772 public void startDownloadForSending(OCFile file
) {
1773 mWaitingToSend
= file
;
1774 requestForDownload(mWaitingToSend
);
1775 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1776 updateFragmentsVisibility(hasSecondFragment
);
1780 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1782 * @param file Image {@link OCFile} to show.
1784 public void startImagePreview(OCFile file
) {
1785 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1786 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1787 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1788 startActivity(showDetailsIntent
);
1793 * Stars the preview of an already down media {@link OCFile}.
1795 * @param file Media {@link OCFile} to preview.
1796 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1797 * @param autoplay When 'true', the playback will start without user interactions.
1799 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1800 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1801 setSecondFragment(mediaFragment
);
1802 updateFragmentsVisibility(true
);
1803 updateNavigationElementsInActionBar(file
);
1808 * Requests the download of the received {@link OCFile} , updates the UI
1809 * to monitor the download progress and prepares the activity to preview
1810 * or open the file when the download finishes.
1812 * @param file {@link OCFile} to download and preview.
1814 public void startDownloadForPreview(OCFile file
) {
1815 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1816 setSecondFragment(detailFragment
);
1817 mWaitingToPreview
= file
;
1818 requestForDownload();
1819 updateFragmentsVisibility(true
);
1820 updateNavigationElementsInActionBar(file
);
1825 public void cancelTransference(OCFile file
) {
1826 getFileOperationsHelper().cancelTransference(file
);
1827 if (mWaitingToPreview
!= null
&&
1828 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1829 mWaitingToPreview
= null
;
1831 if (mWaitingToSend
!= null
&&
1832 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1833 mWaitingToSend
= null
;
1835 onTransferStateChanged(file
, false
, false
);
1839 public void onRefresh(boolean ignoreETag
) {
1840 refreshList(ignoreETag
);
1844 public void onRefresh() {
1848 private void refreshList(boolean ignoreETag
) {
1849 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1850 if (listOfFiles
!= null
) {
1851 OCFile folder
= listOfFiles
.getCurrentFile();
1852 if (folder
!= null
) {
1853 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1854 listDirectory(mFile);*/
1855 startSyncFolderOperation(folder
, ignoreETag
);
1860 private void sortByDate(boolean ascending
){
1861 getListOfFilesFragment().sortByDate(ascending
);
1864 private void sortBySize(boolean ascending
){
1865 getListOfFilesFragment().sortBySize(ascending
);
1868 private void sortByName(boolean ascending
){
1869 getListOfFilesFragment().sortByName(ascending
);
1872 public void restart(){
1873 Intent i
= new Intent(this, FileDisplayActivity
.class);
1874 i
.addFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
1878 public void closeDrawer() {
1879 mDrawerLayout
.closeDrawers();