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";
167 private NavigationDrawerListAdapter adapter
= null
;
169 private OCFile mWaitingToSend
;
171 private DrawerLayout mDrawerLayout
;
172 private ActionBarDrawerToggle mDrawerToggle
;
173 private boolean showAccounts
= false
;
176 protected void onCreate(Bundle savedInstanceState
) {
177 Log_OC
.v(TAG
, "onCreate() start");
178 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
180 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
182 /// grant that FileObserverService is watching favorite files
183 if (savedInstanceState
== null
) {
184 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
185 startService(initObserversIntent
);
188 /// Load of saved instance state
189 if(savedInstanceState
!= null
) {
190 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
191 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
192 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
195 mWaitingToPreview
= null
;
196 mSyncInProgress
= false
;
197 mWaitingToSend
= null
;
202 // Inflate and set the layout view
203 setContentView(R
.layout
.files
);
205 // TODO move to another place that all activity can use it
206 mDrawerLayout
= (DrawerLayout
) findViewById(R
.id
.drawer_layout
);
208 mDrawerToggle
= new ActionBarDrawerToggle(
211 R
.drawable
.ic_drawer
,
212 R
.string
.drawer_open
,
216 /** Called when a drawer has settled in a completely closed state. */
217 public void onDrawerClosed(View view
) {
218 super.onDrawerClosed(view
);
219 getSupportActionBar().setDisplayShowTitleEnabled(true
);
220 getSupportActionBar().setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
221 initFragmentsWithFile();
222 invalidateOptionsMenu();
225 /** Called when a drawer has settled in a completely open state. */
226 public void onDrawerOpened(View drawerView
) {
227 super.onDrawerOpened(drawerView
);
228 getSupportActionBar().setTitle(R
.string
.drawer_open
);
229 getSupportActionBar().setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
230 invalidateOptionsMenu();
234 mDrawerToggle
.setDrawerIndicatorEnabled(true
);
236 // Notification Drawer
237 LinearLayout notificatonDrawer
= (LinearLayout
) findViewById(R
.id
.left_drawer
);
240 ListView listView
= (ListView
) notificatonDrawer
.findViewById(R
.id
.drawer_list
);
241 adapter
= new NavigationDrawerListAdapter(getApplicationContext(), this);
243 listView
.setAdapter(adapter
);
245 listView
.setOnItemClickListener(new OnItemClickListener() {
247 public void onItemClick(AdapterView
<?
> parent
, View view
, int position
, long id
) {
248 if (showAccounts
&& position
> 0){
249 position
= position
- 1;
253 showAccounts
= !showAccounts
;
254 adapter
.setShowAccounts(showAccounts
);
255 adapter
.notifyDataSetChanged();
258 MainApp
.showOnlyFilesOnDevice(false
);
259 mDrawerLayout
.closeDrawers();
262 MainApp
.showOnlyFilesOnDevice(true
);
263 mDrawerLayout
.closeDrawers();
266 Intent settingsIntent
= new Intent(getApplicationContext(), Preferences
.class);
267 startActivity(settingsIntent
);
274 ImageView userIcon
= (ImageView
) notificatonDrawer
.findViewById(R
.id
.drawer_userIcon
);
275 userIcon
.setImageResource(DisplayUtils
.getSeasonalIconId());
278 TextView username
= (TextView
) notificatonDrawer
.findViewById(R
.id
.drawer_username
);
279 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getApplicationContext());
281 if (account
!= null
) {
282 int lastAtPos
= account
.name
.lastIndexOf("@");
283 username
.setText(account
.name
.substring(0, lastAtPos
));
286 // Set the drawer toggle as the DrawerListener
287 mDrawerLayout
.setDrawerListener(mDrawerToggle
);
289 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
290 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
291 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
292 if (savedInstanceState
== null
) {
293 createMinFragments();
297 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
298 getSupportActionBar().setDisplayHomeAsUpEnabled(true
);
299 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
300 getSupportActionBar().setDisplayShowCustomEnabled(true
); // CRUCIAL - for displaying your custom actionbar
301 getSupportActionBar().setDisplayShowTitleEnabled(true
);
302 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
304 mDrawerToggle
.syncState();
308 Log_OC
.v(TAG
, "onCreate() end");
312 protected void onStart() {
313 Log_OC
.v(TAG
, "onStart() start");
315 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
316 Log_OC
.v(TAG
, "onStart() end");
320 protected void onPostCreate(Bundle savedInstanceState
) {
321 super.onPostCreate(savedInstanceState
);
322 // Sync the toggle state after onRestoreInstanceState has occurred.
323 mDrawerToggle
.syncState();
327 public void onConfigurationChanged(Configuration newConfig
) {
328 super.onConfigurationChanged(newConfig
);
329 mDrawerToggle
.onConfigurationChanged(newConfig
);
333 protected void onDestroy() {
334 Log_OC
.v(TAG
, "onDestroy() start");
336 Log_OC
.v(TAG
, "onDestroy() end");
340 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
343 protected void onAccountSet(boolean stateWasRecovered
) {
344 super.onAccountSet(stateWasRecovered
);
345 if (getAccount() != null
) {
346 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
347 OCFile file
= getFile();
348 // get parent from path
349 String parentPath
= "";
351 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
352 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
353 // get parent from path
354 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
355 if (getStorageManager().getFileByPath(parentPath
) == null
)
356 file
= null
; // not able to know the directory where the file is uploading
358 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
362 // fall back to root folder
363 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
366 setNavigationListWithFolder(file
);
368 if (!stateWasRecovered
) {
369 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
370 initFragmentsWithFile();
371 if (file
.isFolder()) {
372 startSyncFolderOperation(file
, false
);
376 updateFragmentsVisibility(!file
.isFolder());
377 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
383 private void setNavigationListWithFolder(OCFile file
) {
384 mDirectories
.clear();
385 OCFile fileIt
= file
;
387 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
388 if (fileIt
.isFolder()) {
389 mDirectories
.add(fileIt
.getFileName());
391 // get parent from path
392 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
393 fileIt
= getStorageManager().getFileByPath(parentPath
);
395 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
399 private void createMinFragments() {
400 OCFileListFragment listOfFiles
= new OCFileListFragment();
401 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
402 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
403 transaction
.commit();
406 private void initFragmentsWithFile() {
407 if (getAccount() != null
&& getFile() != null
) {
409 OCFileListFragment listOfFiles
= getListOfFilesFragment();
410 if (listOfFiles
!= null
) {
411 listOfFiles
.listDirectory(getCurrentDir(), MainApp
.getOnlyOnDevice());
413 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
417 OCFile file
= getFile();
418 Fragment secondFragment
= chooseInitialSecondFragment(file
);
419 if (secondFragment
!= null
) {
420 setSecondFragment(secondFragment
);
421 updateFragmentsVisibility(true
);
422 updateNavigationElementsInActionBar(file
);
425 cleanSecondFragment();
429 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
430 if (getAccount() == null
) {
431 Log_OC
.wtf(TAG
, "\t account is NULL");
433 if (getFile() == null
) {
434 Log_OC
.wtf(TAG
, "\t file is NULL");
439 private Fragment
chooseInitialSecondFragment(OCFile file
) {
440 Fragment secondFragment
= null
;
441 if (file
!= null
&& !file
.isFolder()) {
442 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
443 && file
.getLastSyncDateForProperties() > 0 // temporal fix
445 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
446 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
447 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
450 secondFragment
= new FileDetailFragment(file
, getAccount());
453 return secondFragment
;
458 * Replaces the second fragment managed by the activity with the received as
461 * Assumes never will be more than two fragments managed at the same time.
463 * @param fragment New second Fragment to set.
465 private void setSecondFragment(Fragment fragment
) {
466 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
467 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
468 transaction
.commit();
472 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
474 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
475 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
477 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
478 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
481 } else if (existsSecondFragment
) {
482 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
483 mLeftFragmentContainer
.setVisibility(View
.GONE
);
485 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
486 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
490 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
491 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
493 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
494 mRightFragmentContainer
.setVisibility(View
.GONE
);
500 private OCFileListFragment
getListOfFilesFragment() {
501 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
502 if (listOfFiles
!= null
) {
503 return (OCFileListFragment
)listOfFiles
;
505 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
509 public FileFragment
getSecondFragment() {
510 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
511 if (second
!= null
) {
512 return (FileFragment
)second
;
517 protected void cleanSecondFragment() {
518 Fragment second
= getSecondFragment();
519 if (second
!= null
) {
520 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
524 updateFragmentsVisibility(false
);
525 updateNavigationElementsInActionBar(null
);
528 protected void refreshListOfFilesFragment() {
529 OCFileListFragment fileListFragment
= getListOfFilesFragment();
530 if (fileListFragment
!= null
) {
531 fileListFragment
.listDirectory(MainApp
.getOnlyOnDevice());
535 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
536 FileFragment secondFragment
= getSecondFragment();
537 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
538 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
539 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
540 OCFile fileInFragment
= detailsFragment
.getFile();
541 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
542 // the user browsed to other file ; forget the automatic preview
543 mWaitingToPreview
= null
;
545 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
546 // grant that the right panel updates the progress bar
547 detailsFragment
.listenForTransferProgress();
548 detailsFragment
.updateFileDetails(true
, false
);
550 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
551 // update the right panel
552 boolean detailsFragmentChanged
= false
;
555 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
556 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
557 startMediaPreview(mWaitingToPreview
, 0, true
);
558 detailsFragmentChanged
= true
;
560 getFileOperationsHelper().openFile(mWaitingToPreview
);
563 mWaitingToPreview
= null
;
565 if (!detailsFragmentChanged
) {
566 detailsFragment
.updateFileDetails(false
, (success
));
573 public boolean onPrepareOptionsMenu(Menu menu
) {
574 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
575 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
576 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
577 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
579 return super.onPrepareOptionsMenu(menu
);
583 public boolean onCreateOptionsMenu(Menu menu
) {
584 MenuInflater inflater
= getSherlock().getMenuInflater();
585 inflater
.inflate(R
.menu
.main_menu
, menu
);
591 public boolean onOptionsItemSelected(MenuItem item
) {
592 boolean retval
= true
;
593 switch (item
.getItemId()) {
594 case R
.id
.action_create_dir
: {
595 CreateFolderDialogFragment dialog
= CreateFolderDialogFragment
.newInstance(getCurrentDir());
596 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
599 case R
.id
.action_upload
: {
600 UploadSourceDialogFragment dialog
= UploadSourceDialogFragment
.newInstance(getAccount());
601 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
605 case android
.R
.id
.home
: {
606 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
607 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
609 mDrawerLayout
.openDrawer(GravityCompat
.START
);
611 // TODO add hamburger to left of android.R.id.home
614 case R
.id
.action_sort
: {
615 SharedPreferences appPreferences
= PreferenceManager
616 .getDefaultSharedPreferences(this);
618 // Read sorting order, default to sort by name ascending
619 Integer sortOrder
= appPreferences
620 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
622 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
623 builder
.setTitle(R
.string
.actionbar_sort_title
)
624 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
625 public void onClick(DialogInterface dialog
, int which
) {
641 builder
.create().show();
645 retval
= super.onOptionsItemSelected(item
);
650 private void startSynchronization() {
651 Log_OC
.d(TAG
, "Got to start sync");
652 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
653 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
654 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
655 Bundle bundle
= new Bundle();
656 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
657 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
658 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
659 ContentResolver
.requestSync(
661 MainApp
.getAuthority(), bundle
);
663 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
664 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
665 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
666 builder
.setExpedited(true
);
667 builder
.setManual(true
);
670 // Fix bug in Android Lollipop when you click on refresh the whole account
671 Bundle extras
= new Bundle();
672 builder
.setExtras(extras
);
674 SyncRequest request
= builder
.build();
675 ContentResolver
.requestSync(request
);
681 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
682 if (itemPosition
!= 0) {
683 String targetPath
= "";
684 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
685 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
687 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
688 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
689 if (targetFolder
!= null
) {
690 browseTo(targetFolder
);
693 // the next operation triggers a new call to this method, but it's necessary to
694 // ensure that the name exposed in the action bar is the current directory when the
695 // user selected it in the navigation list
696 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
697 getSupportActionBar().setSelectedNavigationItem(0);
703 * Called, when the user selected something for uploading
706 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
708 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
710 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
711 //getClipData is only supported on api level 16+, Jelly Bean
712 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
713 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
714 Intent intent
= new Intent();
715 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
716 requestSimpleUpload(intent
, resultCode
);
719 requestSimpleUpload(data
, resultCode
);
721 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
722 requestMultipleUpload(data
, resultCode
);
724 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
726 final Intent fData
= data
;
727 final int fResultCode
= resultCode
;
728 getHandler().postDelayed(
732 requestMoveOperation(fData
, fResultCode
);
735 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
739 super.onActivityResult(requestCode
, resultCode
, data
);
744 private void requestMultipleUpload(Intent data
, int resultCode
) {
745 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
746 if (filePaths
!= null
) {
747 String
[] remotePaths
= new String
[filePaths
.length
];
748 String remotePathBase
= "";
750 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
751 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
753 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
754 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
755 for (int j
= 0; j
< remotePaths
.length
; j
++) {
756 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
759 Intent i
= new Intent(this, FileUploader
.class);
760 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
761 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
762 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
763 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
764 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
765 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
769 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
770 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
777 private void requestSimpleUpload(Intent data
, int resultCode
) {
778 String filePath
= null
;
779 String mimeType
= null
;
781 Uri selectedImageUri
= data
.getData();
784 mimeType
= getContentResolver().getType(selectedImageUri
);
786 String fileManagerString
= selectedImageUri
.getPath();
787 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
789 if (selectedImagePath
!= null
)
790 filePath
= selectedImagePath
;
792 filePath
= fileManagerString
;
794 } catch (Exception e
) {
795 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
798 if (filePath
== null
) {
799 Log_OC
.e(TAG
, "Couldn't resolve path to file");
800 Toast t
= Toast
.makeText(
801 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
808 Intent i
= new Intent(this, FileUploader
.class);
809 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
810 OCFile currentDir
= getCurrentDir();
811 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
813 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
814 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
816 if (cursor
!= null
&& cursor
.moveToFirst()) {
817 String displayName
= cursor
.getString(cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
818 Log_OC
.v(TAG
, "Display Name: " + displayName
);
820 displayName
.replace(File
.separatorChar
, '_');
821 displayName
.replace(File
.pathSeparatorChar
, '_');
822 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
825 // and what happens in case of error?; wrong target name for the upload
831 remotePath
+= new File(filePath
).getName();
834 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
835 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
836 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
837 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
838 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
839 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
844 * Request the operation for moving the file/folder from one path to another
846 * @param data Intent received
847 * @param resultCode Result code received
849 private void requestMoveOperation(Intent data
, int resultCode
) {
850 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
851 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
852 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
856 public void onBackPressed() {
857 OCFileListFragment listOfFiles
= getListOfFilesFragment();
858 if (mDualPane
|| getSecondFragment() == null
) {
859 if (listOfFiles
!= null
) { // should never be null, indeed
860 if (mDirectories
.getCount() <= 1) {
864 int levelsUp
= listOfFiles
.onBrowseUp();
865 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
870 if (listOfFiles
!= null
) { // should never be null, indeed
871 setFile(listOfFiles
.getCurrentFile());
873 cleanSecondFragment();
878 protected void onSaveInstanceState(Bundle outState
) {
879 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
880 Log_OC
.v(TAG
, "onSaveInstanceState() start");
881 super.onSaveInstanceState(outState
);
882 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
883 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
884 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
885 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
887 Log_OC
.v(TAG
, "onSaveInstanceState() end");
893 protected void onResume() {
894 Log_OC
.v(TAG
, "onResume() start");
897 // refresh Navigation Drawer account list
898 adapter
.updateAccountList();
900 // refresh list of files
901 refreshListOfFilesFragment();
903 // Listen for sync messages
904 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
905 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
906 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
907 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
908 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
909 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
910 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
911 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
913 // Listen for upload messages
914 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
915 mUploadFinishReceiver
= new UploadFinishReceiver();
916 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
918 // Listen for download messages
919 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
920 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
921 mDownloadFinishReceiver
= new DownloadFinishReceiver();
922 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
924 Log_OC
.v(TAG
, "onResume() end");
929 protected void onPause() {
930 Log_OC
.v(TAG
, "onPause() start");
931 if (mSyncBroadcastReceiver
!= null
) {
932 unregisterReceiver(mSyncBroadcastReceiver
);
933 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
934 mSyncBroadcastReceiver
= null
;
936 if (mUploadFinishReceiver
!= null
) {
937 unregisterReceiver(mUploadFinishReceiver
);
938 mUploadFinishReceiver
= null
;
940 if (mDownloadFinishReceiver
!= null
) {
941 unregisterReceiver(mDownloadFinishReceiver
);
942 mDownloadFinishReceiver
= null
;
946 Log_OC
.v(TAG
, "onPause() end");
950 * Pushes a directory to the drop down list
951 * @param directory to push
952 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
954 public void pushDirname(OCFile directory
) {
955 if(!directory
.isFolder()){
956 throw new IllegalArgumentException("Only directories may be pushed!");
958 mDirectories
.insert(directory
.getFileName(), 0);
963 * Pops a directory name from the drop down list
964 * @return True, unless the stack is empty
966 public boolean popDirname() {
967 mDirectories
.remove(mDirectories
.getItem(0));
968 return !mDirectories
.isEmpty();
971 // Custom array adapter to override text colors
972 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
974 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
978 public View
getView(int position
, View convertView
, ViewGroup parent
) {
979 View v
= super.getView(position
, convertView
, parent
);
981 ((TextView
) v
).setTextColor(getResources().getColorStateList(
982 android
.R
.color
.white
));
984 fixRoot((TextView
) v
);
988 public View
getDropDownView(int position
, View convertView
,
990 View v
= super.getDropDownView(position
, convertView
, parent
);
992 ((TextView
) v
).setTextColor(getResources().getColorStateList(
993 android
.R
.color
.white
));
995 fixRoot((TextView
) v
);
999 private void fixRoot(TextView v
) {
1000 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
1001 v
.setText(R
.string
.default_display_name_for_root_folder
);
1007 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
1010 * {@link BroadcastReceiver} to enable syncing feedback in UI
1013 public void onReceive(Context context
, Intent intent
) {
1015 String event
= intent
.getAction();
1016 Log_OC
.d(TAG
, "Received broadcast " + event
);
1017 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
1018 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
1019 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
1020 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
1024 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
1025 mSyncInProgress
= true
;
1028 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
1029 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1031 if (currentDir
== null
) {
1032 // current folder was removed from the server
1033 Toast
.makeText( FileDisplayActivity
.this,
1034 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
1040 if (currentFile
== null
&& !getFile().isFolder()) {
1041 // currently selected file was removed in the server, and now we know it
1042 cleanSecondFragment();
1043 currentFile
= currentDir
;
1046 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1047 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1048 if (fileListFragment
!= null
) {
1049 fileListFragment
.listDirectory(currentDir
, MainApp
.getOnlyOnDevice());
1052 setFile(currentFile
);
1055 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1057 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1059 /// TODO refactor and make common
1060 synchResult
!= null
&& !synchResult
.isSuccess() &&
1061 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1062 synchResult
.isIdPRedirection() ||
1063 (synchResult
.isException() && synchResult
.getException()
1064 instanceof AuthenticatorException
))) {
1068 OwnCloudClient client
;
1069 OwnCloudAccount ocAccount
=
1070 new OwnCloudAccount(getAccount(), context
);
1071 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1072 removeClientFor(ocAccount
));
1074 if (client
!= null
) {
1075 OwnCloudCredentials cred
= client
.getCredentials();
1077 AccountManager am
= AccountManager
.get(context
);
1078 if (cred
.authTokenExpires()) {
1079 am
.invalidateAuthToken(
1084 am
.clearPassword(getAccount());
1088 requestCredentialsUpdate();
1090 } catch (AccountNotFoundException e
) {
1091 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1096 removeStickyBroadcast(intent
);
1097 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1098 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1100 setBackgroundText();
1104 if (synchResult
!= null
) {
1105 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1106 mLastSslUntrustedServerResult
= synchResult
;
1109 } catch (RuntimeException e
) {
1110 // avoid app crashes after changing the serial id of RemoteOperationResult
1111 // in owncloud library with broadcast notifications pending to process
1112 removeStickyBroadcast(intent
);
1118 * Show a text message on screen view for notifying user if content is
1119 * loading or folder is empty
1121 private void setBackgroundText() {
1122 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1123 if (ocFileListFragment
!= null
) {
1124 int message
= R
.string
.file_list_loading
;
1125 if (!mSyncInProgress
) {
1126 // In case file list is empty
1127 message
= R
.string
.file_list_empty
;
1129 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1131 Log_OC
.e(TAG
, "OCFileListFragment is null");
1136 * Once the file upload has finished -> update view
1138 private class UploadFinishReceiver
extends BroadcastReceiver
{
1140 * Once the file upload has finished -> update view
1141 * @author David A. Velasco
1142 * {@link BroadcastReceiver} to enable upload feedback in UI
1145 public void onReceive(Context context
, Intent intent
) {
1147 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1148 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1149 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1150 OCFile currentDir
= getCurrentDir();
1151 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1152 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1154 if (sameAccount
&& isDescendant
) {
1155 refreshListOfFilesFragment();
1158 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1159 boolean renamedInUpload
= getFile().getRemotePath().
1160 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1161 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1163 FileFragment details
= getSecondFragment();
1164 boolean detailFragmentIsShown
= (details
!= null
&&
1165 details
instanceof FileDetailFragment
);
1167 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1168 if (uploadWasFine
) {
1169 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1171 if (renamedInUpload
) {
1172 String newName
= (new File(uploadedRemotePath
)).getName();
1173 Toast msg
= Toast
.makeText(
1176 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1181 if (uploadWasFine
|| getFile().fileExists()) {
1182 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1184 cleanSecondFragment();
1187 // Force the preview if the file is an image
1188 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1189 startImagePreview(getFile());
1190 } // TODO what about other kind of previews?
1194 if (intent
!= null
) {
1195 removeStickyBroadcast(intent
);
1205 * Class waiting for broadcast events from the {@link FileDownloader} service.
1207 * Updates the UI when a download is started or finished, provided that it is relevant for the
1210 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1212 //int refreshCounter = 0;
1214 public void onReceive(Context context
, Intent intent
) {
1216 boolean sameAccount
= isSameAccount(context
, intent
);
1217 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1218 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1220 if (sameAccount
&& isDescendant
) {
1221 String linkedToRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1222 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1223 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1224 refreshListOfFilesFragment();
1226 refreshSecondFragment(
1228 downloadedRemotePath
,
1229 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1233 if (mWaitingToSend
!= null
) {
1234 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1235 if (mWaitingToSend
.isDown()) {
1236 sendDownloadedFile();
1241 if (intent
!= null
) {
1242 removeStickyBroadcast(intent
);
1247 private boolean isDescendant(String downloadedRemotePath
) {
1248 OCFile currentDir
= getCurrentDir();
1250 currentDir
!= null
&&
1251 downloadedRemotePath
!= null
&&
1252 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1256 private boolean isAscendant(String linkedToRemotePath
) {
1257 OCFile currentDir
= getCurrentDir();
1259 currentDir
!= null
&&
1260 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1264 private boolean isSameAccount(Context context
, Intent intent
) {
1265 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1266 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1271 public void browseToRoot() {
1272 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1273 if (listOfFiles
!= null
) { // should never be null, indeed
1274 while (mDirectories
.getCount() > 1) {
1277 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1278 listOfFiles
.listDirectory(root
, MainApp
.getOnlyOnDevice());
1279 setFile(listOfFiles
.getCurrentFile());
1280 startSyncFolderOperation(root
, false
);
1282 cleanSecondFragment();
1286 public void browseTo(OCFile folder
) {
1287 if (folder
== null
|| !folder
.isFolder()) {
1288 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1290 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1291 if (listOfFiles
!= null
) {
1292 setNavigationListWithFolder(folder
);
1293 listOfFiles
.listDirectory(folder
, MainApp
.getOnlyOnDevice());
1294 setFile(listOfFiles
.getCurrentFile());
1295 startSyncFolderOperation(folder
, false
);
1297 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1299 cleanSecondFragment();
1306 * Updates action bar and second fragment, if in dual pane mode.
1309 public void onBrowsedDownTo(OCFile directory
) {
1310 pushDirname(directory
);
1311 cleanSecondFragment();
1314 startSyncFolderOperation(directory
, false
);
1319 * Shows the information of the {@link OCFile} received as a
1320 * parameter in the second fragment.
1322 * @param file {@link OCFile} whose details will be shown
1325 public void showDetails(OCFile file
) {
1326 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1327 setSecondFragment(detailFragment
);
1328 updateFragmentsVisibility(true
);
1329 updateNavigationElementsInActionBar(file
);
1337 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1338 ActionBar actionBar
= getSupportActionBar();
1340 // For adding content description tag to a title field in the action bar
1341 int actionBarTitleId
= getResources().getIdentifier("action_bar_title", "id", "android");
1343 if (chosenFile
== null
|| mDualPane
) {
1344 // only list of files - set for browsing through folders
1345 OCFile currentDir
= getCurrentDir();
1346 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1347 // actionBar.setDisplayHomeAsUpEnabled(noRoot);
1348 // actionBar.setDisplayShowTitleEnabled(!noRoot);
1349 actionBar
.setDisplayHomeAsUpEnabled(true
);
1350 actionBar
.setDisplayShowTitleEnabled(true
);
1352 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1353 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1354 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1355 actionBarTitleView
.setContentDescription(getString(R
.string
.default_display_name_for_root_folder
));
1358 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1359 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1362 actionBar
.setDisplayHomeAsUpEnabled(true
);
1363 actionBar
.setDisplayShowTitleEnabled(true
);
1364 actionBar
.setTitle(chosenFile
.getFileName());
1365 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1366 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1367 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1368 getWindow().getDecorView().findViewById(actionBarTitleId
).
1369 setContentDescription(chosenFile
.getFileName());
1376 protected ServiceConnection
newTransferenceServiceConnection() {
1377 return new ListServiceConnection();
1380 /** Defines callbacks for service binding, passed to bindService() */
1381 private class ListServiceConnection
implements ServiceConnection
{
1384 public void onServiceConnected(ComponentName component
, IBinder service
) {
1385 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1386 Log_OC
.d(TAG
, "Download service connected");
1387 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1388 if (mWaitingToPreview
!= null
)
1389 if (getStorageManager() != null
) {
1390 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1391 if (!mWaitingToPreview
.isDown()) {
1392 requestForDownload();
1396 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1397 Log_OC
.d(TAG
, "Upload service connected");
1398 mUploaderBinder
= (FileUploaderBinder
) service
;
1402 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1403 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1404 if (listOfFiles
!= null
) {
1405 listOfFiles
.listDirectory(MainApp
.getOnlyOnDevice());
1407 FileFragment secondFragment
= getSecondFragment();
1408 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1409 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1410 detailFragment
.listenForTransferProgress();
1411 detailFragment
.updateFileDetails(false
, false
);
1416 public void onServiceDisconnected(ComponentName component
) {
1417 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1418 Log_OC
.d(TAG
, "Download service disconnected");
1419 mDownloaderBinder
= null
;
1420 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1421 Log_OC
.d(TAG
, "Upload service disconnected");
1422 mUploaderBinder
= null
;
1428 public void onSavedCertificate() {
1429 startSyncFolderOperation(getCurrentDir(), false
);
1434 public void onFailedSavingCertificate() {
1435 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1436 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1438 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1442 public void onCancelCertificate() {
1447 * Updates the view associated to the activity after the finish of some operation over files
1448 * in the current account.
1450 * @param operation Removal operation performed.
1451 * @param result Result of the removal.
1454 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1455 super.onRemoteOperationFinish(operation
, result
);
1457 if (operation
instanceof RemoveFileOperation
) {
1458 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1460 } else if (operation
instanceof RenameFileOperation
) {
1461 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1463 } else if (operation
instanceof SynchronizeFileOperation
) {
1464 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1466 } else if (operation
instanceof CreateFolderOperation
) {
1467 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1469 } else if (operation
instanceof CreateShareOperation
) {
1470 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1472 } else if (operation
instanceof UnshareLinkOperation
) {
1473 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1475 } else if (operation
instanceof MoveFileOperation
) {
1476 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1482 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1483 if (result
.isSuccess()) {
1484 refreshShowDetails();
1485 refreshListOfFilesFragment();
1490 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1491 if (result
.isSuccess()) {
1492 refreshShowDetails();
1493 refreshListOfFilesFragment();
1495 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1496 cleanSecondFragment();
1497 refreshListOfFilesFragment();
1501 private void refreshShowDetails() {
1502 FileFragment details
= getSecondFragment();
1503 if (details
!= null
) {
1504 OCFile file
= details
.getFile();
1506 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1507 if (details
instanceof PreviewMediaFragment
) {
1508 // Refresh OCFile of the fragment
1509 ((PreviewMediaFragment
) details
).updateFile(file
);
1514 invalidateOptionsMenu();
1519 * Updates the view associated to the activity after the finish of an operation trying to remove a
1522 * @param operation Removal operation performed.
1523 * @param result Result of the removal.
1525 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1526 dismissLoadingDialog();
1528 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1532 if (result
.isSuccess()) {
1533 OCFile removedFile
= operation
.getFile();
1534 FileFragment second
= getSecondFragment();
1535 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1536 if (second
instanceof PreviewMediaFragment
) {
1537 ((PreviewMediaFragment
)second
).stopPreview(true
);
1539 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1540 cleanSecondFragment();
1542 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1543 refreshListOfFilesFragment();
1545 invalidateOptionsMenu();
1547 if (result
.isSslRecoverableException()) {
1548 mLastSslUntrustedServerResult
= result
;
1549 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1556 * Updates the view associated to the activity after the finish of an operation trying to move a
1559 * @param operation Move operation performed.
1560 * @param result Result of the move operation.
1562 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1563 if (result
.isSuccess()) {
1564 dismissLoadingDialog();
1565 refreshListOfFilesFragment();
1567 dismissLoadingDialog();
1569 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1570 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1574 } catch (NotFoundException e
) {
1575 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1582 * Updates the view associated to the activity after the finish of an operation trying to rename a
1585 * @param operation Renaming operation performed.
1586 * @param result Result of the renaming.
1588 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1589 dismissLoadingDialog();
1590 OCFile renamedFile
= operation
.getFile();
1591 if (result
.isSuccess()) {
1592 FileFragment details
= getSecondFragment();
1593 if (details
!= null
) {
1594 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1595 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1596 showDetails(renamedFile
);
1598 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1599 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1600 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1601 int position
= ((PreviewMediaFragment
)details
).getPosition();
1602 startMediaPreview(renamedFile
, position
, true
);
1604 getFileOperationsHelper().openFile(renamedFile
);
1609 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1610 refreshListOfFilesFragment();
1614 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1618 if (result
.isSslRecoverableException()) {
1619 mLastSslUntrustedServerResult
= result
;
1620 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1625 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1626 dismissLoadingDialog();
1627 OCFile syncedFile
= operation
.getLocalFile();
1628 if (!result
.isSuccess()) {
1629 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1630 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1631 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1632 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1638 if (operation
.transferWasRequested()) {
1639 onTransferStateChanged(syncedFile
, true
, true
);
1642 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1650 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1652 * @param operation Creation operation performed.
1653 * @param result Result of the creation.
1655 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1656 if (result
.isSuccess()) {
1657 dismissLoadingDialog();
1658 refreshListOfFilesFragment();
1660 dismissLoadingDialog();
1662 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1663 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1667 } catch (NotFoundException e
) {
1668 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1678 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1679 refreshListOfFilesFragment();
1680 FileFragment details
= getSecondFragment();
1681 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1682 if (downloading
|| uploading
) {
1683 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1685 if (!file
.fileExists()) {
1686 cleanSecondFragment();
1688 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1696 private void requestForDownload() {
1697 Account account
= getAccount();
1698 //if (!mWaitingToPreview.isDownloading()) {
1699 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1700 Intent i
= new Intent(this, FileDownloader
.class);
1701 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1702 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1708 private OCFile
getCurrentDir() {
1709 OCFile file
= getFile();
1711 if (file
.isFolder()) {
1713 } else if (getStorageManager() != null
) {
1714 String parentPath
= file
.getRemotePath().substring(0,
1715 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1716 return getStorageManager().getFileByPath(parentPath
);
1722 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1723 long currentSyncTime
= System
.currentTimeMillis();
1725 mSyncInProgress
= true
;
1727 // perform folder synchronization
1728 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1731 getFileOperationsHelper().isSharedSupported(),
1733 getStorageManager(),
1735 getApplicationContext()
1737 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1739 setSupportProgressBarIndeterminateVisibility(true
);
1741 setBackgroundText();
1745 * Show untrusted cert dialog
1747 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1748 // Show a dialog with the certificate info
1749 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1750 (CertificateCombinedException
) result
.getException());
1751 FragmentManager fm
= getSupportFragmentManager();
1752 FragmentTransaction ft
= fm
.beginTransaction();
1753 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1756 private void requestForDownload(OCFile file
) {
1757 Account account
= getAccount();
1758 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1759 Intent i
= new Intent(this, FileDownloader
.class);
1760 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1761 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1766 private void sendDownloadedFile(){
1767 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1768 mWaitingToSend
= null
;
1773 * Requests the download of the received {@link OCFile} , updates the UI
1774 * to monitor the download progress and prepares the activity to send the file
1775 * when the download finishes.
1777 * @param file {@link OCFile} to download and preview.
1779 public void startDownloadForSending(OCFile file
) {
1780 mWaitingToSend
= file
;
1781 requestForDownload(mWaitingToSend
);
1782 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1783 updateFragmentsVisibility(hasSecondFragment
);
1787 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1789 * @param file Image {@link OCFile} to show.
1791 public void startImagePreview(OCFile file
) {
1792 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1793 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1794 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1795 startActivity(showDetailsIntent
);
1800 * Stars the preview of an already down media {@link OCFile}.
1802 * @param file Media {@link OCFile} to preview.
1803 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1804 * @param autoplay When 'true', the playback will start without user interactions.
1806 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1807 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1808 setSecondFragment(mediaFragment
);
1809 updateFragmentsVisibility(true
);
1810 updateNavigationElementsInActionBar(file
);
1815 * Requests the download of the received {@link OCFile} , updates the UI
1816 * to monitor the download progress and prepares the activity to preview
1817 * or open the file when the download finishes.
1819 * @param file {@link OCFile} to download and preview.
1821 public void startDownloadForPreview(OCFile file
) {
1822 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1823 setSecondFragment(detailFragment
);
1824 mWaitingToPreview
= file
;
1825 requestForDownload();
1826 updateFragmentsVisibility(true
);
1827 updateNavigationElementsInActionBar(file
);
1832 public void cancelTransference(OCFile file
) {
1833 getFileOperationsHelper().cancelTransference(file
);
1834 if (mWaitingToPreview
!= null
&&
1835 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1836 mWaitingToPreview
= null
;
1838 if (mWaitingToSend
!= null
&&
1839 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1840 mWaitingToSend
= null
;
1842 onTransferStateChanged(file
, false
, false
);
1846 public void onRefresh(boolean ignoreETag
) {
1847 refreshList(ignoreETag
);
1851 public void onRefresh() {
1855 private void refreshList(boolean ignoreETag
) {
1856 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1857 if (listOfFiles
!= null
) {
1858 OCFile folder
= listOfFiles
.getCurrentFile();
1859 if (folder
!= null
) {
1860 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1861 listDirectory(mFile);*/
1862 startSyncFolderOperation(folder
, ignoreETag
);
1867 private void sortByDate(boolean ascending
){
1868 getListOfFilesFragment().sortByDate(ascending
);
1871 private void sortBySize(boolean ascending
){
1872 getListOfFilesFragment().sortBySize(ascending
);
1875 private void sortByName(boolean ascending
){
1876 getListOfFilesFragment().sortByName(ascending
);
1879 public void restart(){
1880 Intent i
= new Intent(this, FileDisplayActivity
.class);
1881 i
.addFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
1885 public void closeDrawer() {
1886 mDrawerLayout
.closeDrawers();