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
.annotation
.TargetApi
;
31 import android
.app
.AlertDialog
;
32 import android
.content
.BroadcastReceiver
;
33 import android
.content
.ComponentName
;
34 import android
.content
.ContentResolver
;
35 import android
.content
.Context
;
36 import android
.content
.DialogInterface
;
37 import android
.content
.Intent
;
38 import android
.content
.IntentFilter
;
39 import android
.content
.ServiceConnection
;
40 import android
.content
.SharedPreferences
;
41 import android
.content
.SyncRequest
;
42 import android
.content
.res
.Configuration
;
43 import android
.content
.res
.Resources
.NotFoundException
;
44 import android
.database
.Cursor
;
45 import android
.net
.Uri
;
46 import android
.os
.Build
;
47 import android
.os
.Bundle
;
48 import android
.os
.IBinder
;
49 import android
.preference
.PreferenceManager
;
50 import android
.provider
.OpenableColumns
;
51 import android
.support
.v4
.app
.ActionBarDrawerToggle
;
52 import android
.support
.v4
.app
.Fragment
;
53 import android
.support
.v4
.app
.FragmentManager
;
54 import android
.support
.v4
.app
.FragmentTransaction
;
55 import android
.support
.v4
.view
.GravityCompat
;
56 import android
.support
.v4
.widget
.DrawerLayout
;
57 import android
.view
.View
;
58 import android
.view
.ViewGroup
;
59 import android
.widget
.AdapterView
;
60 import android
.widget
.AdapterView
.OnItemClickListener
;
61 import android
.widget
.ArrayAdapter
;
62 import android
.widget
.ImageView
;
63 import android
.widget
.LinearLayout
;
64 import android
.widget
.ListView
;
65 import android
.widget
.TextView
;
66 import android
.widget
.Toast
;
68 import com
.actionbarsherlock
.app
.ActionBar
;
69 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
70 import com
.actionbarsherlock
.view
.Menu
;
71 import com
.actionbarsherlock
.view
.MenuInflater
;
72 import com
.actionbarsherlock
.view
.MenuItem
;
73 import com
.actionbarsherlock
.view
.Window
;
74 import com
.owncloud
.android
.MainApp
;
75 import com
.owncloud
.android
.R
;
76 import com
.owncloud
.android
.authentication
.AccountUtils
;
77 import com
.owncloud
.android
.datamodel
.OCFile
;
78 import com
.owncloud
.android
.files
.services
.FileDownloader
;
79 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
80 import com
.owncloud
.android
.files
.services
.FileUploader
;
81 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
82 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
83 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
84 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
85 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
86 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
87 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
88 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
89 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
90 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
91 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
92 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
93 import com
.owncloud
.android
.operations
.CreateShareOperation
;
94 import com
.owncloud
.android
.operations
.MoveFileOperation
;
95 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
96 import com
.owncloud
.android
.operations
.RenameFileOperation
;
97 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
98 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
99 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
100 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
101 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
102 import com
.owncloud
.android
.ui
.adapter
.NavigationDrawerListAdapter
;
103 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
104 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
105 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
106 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
107 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
108 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
109 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
110 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
111 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
112 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
113 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
114 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
115 import com
.owncloud
.android
.utils
.DisplayUtils
;
116 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
117 import com
.owncloud
.android
.utils
.FileStorageUtils
;
118 import com
.owncloud
.android
.utils
.UriUtils
;
122 * Displays, what files the user has available in his ownCloud.
125 public class FileDisplayActivity
extends HookActivity
implements
126 FileFragment
.ContainerActivity
, OnNavigationListener
,
127 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
129 private ArrayAdapter
<String
> mDirectories
;
131 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
132 private UploadFinishReceiver mUploadFinishReceiver
;
133 private DownloadFinishReceiver mDownloadFinishReceiver
;
134 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
136 private boolean mDualPane
;
137 private View mLeftFragmentContainer
;
138 private View mRightFragmentContainer
;
140 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
141 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
142 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
144 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
146 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
147 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
148 public static final int ACTION_MOVE_FILES
= 3;
150 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
152 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
153 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
155 private OCFile mWaitingToPreview
;
157 private boolean mSyncInProgress
= false
;
159 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
160 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
161 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
162 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
164 private NavigationDrawerListAdapter adapter
= null
;
166 private OCFile mWaitingToSend
;
168 private DrawerLayout mDrawerLayout
;
169 private ActionBarDrawerToggle mDrawerToggle
;
170 private boolean showAccounts
= false
;
173 protected void onCreate(Bundle savedInstanceState
) {
174 Log_OC
.v(TAG
, "onCreate() start");
175 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
177 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
179 /// grant that FileObserverService is watching favorite files
180 if (savedInstanceState
== null
) {
181 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
182 startService(initObserversIntent
);
185 /// Load of saved instance state
186 if(savedInstanceState
!= null
) {
187 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
188 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
189 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
192 mWaitingToPreview
= null
;
193 mSyncInProgress
= false
;
194 mWaitingToSend
= null
;
199 // Inflate and set the layout view
200 setContentView(R
.layout
.files
);
202 // TODO move to another place that all activity can use it
203 mDrawerLayout
= (DrawerLayout
) findViewById(R
.id
.drawer_layout
);
205 mDrawerToggle
= new ActionBarDrawerToggle(
208 R
.drawable
.ic_drawer
,
209 R
.string
.drawer_open
,
213 /** Called when a drawer has settled in a completely closed state. */
214 public void onDrawerClosed(View view
) {
215 super.onDrawerClosed(view
);
216 getSupportActionBar().setDisplayShowTitleEnabled(true
);
217 getSupportActionBar().setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
218 initFragmentsWithFile();
219 invalidateOptionsMenu();
222 /** Called when a drawer has settled in a completely open state. */
223 public void onDrawerOpened(View drawerView
) {
224 super.onDrawerOpened(drawerView
);
225 getSupportActionBar().setTitle(R
.string
.drawer_open
);
226 getSupportActionBar().setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
227 invalidateOptionsMenu();
231 mDrawerToggle
.setDrawerIndicatorEnabled(true
);
233 // Notification Drawer
234 LinearLayout notificatonDrawer
= (LinearLayout
) findViewById(R
.id
.left_drawer
);
237 ListView listView
= (ListView
) notificatonDrawer
.findViewById(R
.id
.drawer_list
);
238 adapter
= new NavigationDrawerListAdapter(getApplicationContext(), this);
240 listView
.setAdapter(adapter
);
242 listView
.setOnItemClickListener(new OnItemClickListener() {
244 public void onItemClick(AdapterView
<?
> parent
, View view
, int position
, long id
) {
245 if (showAccounts
&& position
> 0){
246 position
= position
- 1;
250 showAccounts
= !showAccounts
;
251 adapter
.setShowAccounts(showAccounts
);
252 adapter
.notifyDataSetChanged();
255 // TODO Enable when "On Device" is recovered ?
256 //MainApp.showOnlyFilesOnDevice(false);
257 mDrawerLayout
.closeDrawers();
259 // TODO Enable when "On Device" is recovered ?
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());
280 if (account
!= null
) {
281 int lastAtPos
= account
.name
.lastIndexOf("@");
282 username
.setText(account
.name
.substring(0, lastAtPos
));
285 // Set the drawer toggle as the DrawerListener
286 mDrawerLayout
.setDrawerListener(mDrawerToggle
);
288 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
289 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
290 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
291 if (savedInstanceState
== null
) {
292 createMinFragments();
296 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
297 getSupportActionBar().setDisplayHomeAsUpEnabled(true
);
298 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
299 getSupportActionBar().setDisplayShowCustomEnabled(true
); // CRUCIAL - for displaying your custom actionbar
300 getSupportActionBar().setDisplayShowTitleEnabled(true
);
301 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
303 mDrawerToggle
.syncState();
307 Log_OC
.v(TAG
, "onCreate() end");
311 protected void onStart() {
312 Log_OC
.v(TAG
, "onStart() start");
314 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
315 Log_OC
.v(TAG
, "onStart() end");
319 protected void onPostCreate(Bundle savedInstanceState
) {
320 super.onPostCreate(savedInstanceState
);
321 // Sync the toggle state after onRestoreInstanceState has occurred.
322 mDrawerToggle
.syncState();
326 public void onConfigurationChanged(Configuration newConfig
) {
327 super.onConfigurationChanged(newConfig
);
328 mDrawerToggle
.onConfigurationChanged(newConfig
);
332 protected void onDestroy() {
333 Log_OC
.v(TAG
, "onDestroy() start");
335 Log_OC
.v(TAG
, "onDestroy() end");
339 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
342 protected void onAccountSet(boolean stateWasRecovered
) {
343 super.onAccountSet(stateWasRecovered
);
344 if (getAccount() != null
) {
345 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
346 OCFile file
= getFile();
347 // get parent from path
348 String parentPath
= "";
350 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
351 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
352 // get parent from path
353 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
354 if (getStorageManager().getFileByPath(parentPath
) == null
)
355 file
= null
; // not able to know the directory where the file is uploading
357 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
361 // fall back to root folder
362 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
365 setNavigationListWithFolder(file
);
367 if (!stateWasRecovered
) {
368 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
369 initFragmentsWithFile();
370 if (file
.isFolder()) {
371 startSyncFolderOperation(file
, false
);
375 updateFragmentsVisibility(!file
.isFolder());
376 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
382 private void setNavigationListWithFolder(OCFile file
) {
383 mDirectories
.clear();
384 OCFile fileIt
= file
;
386 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
387 if (fileIt
.isFolder()) {
388 mDirectories
.add(fileIt
.getFileName());
390 // get parent from path
391 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
392 fileIt
= getStorageManager().getFileByPath(parentPath
);
394 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
398 private void createMinFragments() {
399 OCFileListFragment listOfFiles
= new OCFileListFragment();
400 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
401 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
402 transaction
.commit();
405 private void initFragmentsWithFile() {
406 if (getAccount() != null
&& getFile() != null
) {
408 OCFileListFragment listOfFiles
= getListOfFilesFragment();
409 if (listOfFiles
!= null
) {
410 listOfFiles
.listDirectory(getCurrentDir());
411 // TODO Enable when "On Device" is recovered
412 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
414 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
418 OCFile file
= getFile();
419 Fragment secondFragment
= chooseInitialSecondFragment(file
);
420 if (secondFragment
!= null
) {
421 setSecondFragment(secondFragment
);
422 updateFragmentsVisibility(true
);
423 updateNavigationElementsInActionBar(file
);
426 cleanSecondFragment();
430 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
431 if (getAccount() == null
) {
432 Log_OC
.wtf(TAG
, "\t account is NULL");
434 if (getFile() == null
) {
435 Log_OC
.wtf(TAG
, "\t file is NULL");
440 private Fragment
chooseInitialSecondFragment(OCFile file
) {
441 Fragment secondFragment
= null
;
442 if (file
!= null
&& !file
.isFolder()) {
443 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
444 && file
.getLastSyncDateForProperties() > 0 // temporal fix
446 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
447 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
448 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
451 secondFragment
= new FileDetailFragment(file
, getAccount());
454 return secondFragment
;
459 * Replaces the second fragment managed by the activity with the received as
462 * Assumes never will be more than two fragments managed at the same time.
464 * @param fragment New second Fragment to set.
466 private void setSecondFragment(Fragment fragment
) {
467 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
468 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
469 transaction
.commit();
473 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
475 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
476 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
478 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
479 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
482 } else if (existsSecondFragment
) {
483 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
484 mLeftFragmentContainer
.setVisibility(View
.GONE
);
486 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
487 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
491 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
492 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
494 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
495 mRightFragmentContainer
.setVisibility(View
.GONE
);
501 private OCFileListFragment
getListOfFilesFragment() {
502 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
503 if (listOfFiles
!= null
) {
504 return (OCFileListFragment
)listOfFiles
;
506 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
510 public FileFragment
getSecondFragment() {
511 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
512 if (second
!= null
) {
513 return (FileFragment
)second
;
518 protected void cleanSecondFragment() {
519 Fragment second
= getSecondFragment();
520 if (second
!= null
) {
521 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
525 updateFragmentsVisibility(false
);
526 updateNavigationElementsInActionBar(null
);
529 protected void refreshListOfFilesFragment() {
530 OCFileListFragment fileListFragment
= getListOfFilesFragment();
531 if (fileListFragment
!= null
) {
532 fileListFragment
.listDirectory();
533 // TODO Enable when "On Device" is recovered ?
534 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
538 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
539 FileFragment secondFragment
= getSecondFragment();
540 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
541 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
542 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
543 OCFile fileInFragment
= detailsFragment
.getFile();
544 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
545 // the user browsed to other file ; forget the automatic preview
546 mWaitingToPreview
= null
;
548 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
549 // grant that the right panel updates the progress bar
550 detailsFragment
.listenForTransferProgress();
551 detailsFragment
.updateFileDetails(true
, false
);
553 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
554 // update the right panel
555 boolean detailsFragmentChanged
= false
;
558 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
559 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
560 startMediaPreview(mWaitingToPreview
, 0, true
);
561 detailsFragmentChanged
= true
;
563 getFileOperationsHelper().openFile(mWaitingToPreview
);
566 mWaitingToPreview
= null
;
568 if (!detailsFragmentChanged
) {
569 detailsFragment
.updateFileDetails(false
, (success
));
576 public boolean onPrepareOptionsMenu(Menu menu
) {
577 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
578 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
579 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
580 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
582 return super.onPrepareOptionsMenu(menu
);
586 public boolean onCreateOptionsMenu(Menu menu
) {
587 MenuInflater inflater
= getSherlock().getMenuInflater();
588 inflater
.inflate(R
.menu
.main_menu
, menu
);
594 public boolean onOptionsItemSelected(MenuItem item
) {
595 boolean retval
= true
;
596 switch (item
.getItemId()) {
597 case R
.id
.action_create_dir
: {
598 CreateFolderDialogFragment dialog
= CreateFolderDialogFragment
.newInstance(getCurrentDir());
599 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
602 case R
.id
.action_upload
: {
603 UploadSourceDialogFragment dialog
= UploadSourceDialogFragment
.newInstance(getAccount());
604 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
608 case android
.R
.id
.home
: {
609 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
610 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
612 mDrawerLayout
.openDrawer(GravityCompat
.START
);
614 // TODO add hamburger to left of android.R.id.home
617 case R
.id
.action_sort
: {
618 SharedPreferences appPreferences
= PreferenceManager
619 .getDefaultSharedPreferences(this);
621 // Read sorting order, default to sort by name ascending
622 Integer sortOrder
= appPreferences
623 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
625 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
626 builder
.setTitle(R
.string
.actionbar_sort_title
)
627 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
628 public void onClick(DialogInterface dialog
, int which
) {
644 builder
.create().show();
648 retval
= super.onOptionsItemSelected(item
);
653 private void startSynchronization() {
654 Log_OC
.d(TAG
, "Got to start sync");
655 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
656 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
657 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
658 Bundle bundle
= new Bundle();
659 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
660 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
661 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
662 ContentResolver
.requestSync(
664 MainApp
.getAuthority(), bundle
);
666 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
667 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
668 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
669 builder
.setExpedited(true
);
670 builder
.setManual(true
);
673 // Fix bug in Android Lollipop when you click on refresh the whole account
674 Bundle extras
= new Bundle();
675 builder
.setExtras(extras
);
677 SyncRequest request
= builder
.build();
678 ContentResolver
.requestSync(request
);
684 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
685 if (itemPosition
!= 0) {
686 String targetPath
= "";
687 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
688 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
690 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
691 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
692 if (targetFolder
!= null
) {
693 browseTo(targetFolder
);
696 // the next operation triggers a new call to this method, but it's necessary to
697 // ensure that the name exposed in the action bar is the current directory when the
698 // user selected it in the navigation list
699 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
700 getSupportActionBar().setSelectedNavigationItem(0);
706 * Called, when the user selected something for uploading
709 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
711 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
713 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
714 //getClipData is only supported on api level 16+, Jelly Bean
715 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
716 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
717 Intent intent
= new Intent();
718 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
719 requestSimpleUpload(intent
, resultCode
);
722 requestSimpleUpload(data
, resultCode
);
724 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
725 requestMultipleUpload(data
, resultCode
);
727 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
729 final Intent fData
= data
;
730 final int fResultCode
= resultCode
;
731 getHandler().postDelayed(
735 requestMoveOperation(fData
, fResultCode
);
738 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
742 super.onActivityResult(requestCode
, resultCode
, data
);
747 private void requestMultipleUpload(Intent data
, int resultCode
) {
748 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
749 if (filePaths
!= null
) {
750 String
[] remotePaths
= new String
[filePaths
.length
];
751 String remotePathBase
= "";
753 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
754 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
756 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
757 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
758 for (int j
= 0; j
< remotePaths
.length
; j
++) {
759 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
762 Intent i
= new Intent(this, FileUploader
.class);
763 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
764 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
765 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
766 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
767 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
768 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
772 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
773 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
780 private void requestSimpleUpload(Intent data
, int resultCode
) {
781 String filePath
= null
;
782 String mimeType
= null
;
784 Uri selectedImageUri
= data
.getData();
787 mimeType
= getContentResolver().getType(selectedImageUri
);
789 String fileManagerString
= selectedImageUri
.getPath();
790 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
792 if (selectedImagePath
!= null
)
793 filePath
= selectedImagePath
;
795 filePath
= fileManagerString
;
797 } catch (Exception e
) {
798 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
801 if (filePath
== null
) {
802 Log_OC
.e(TAG
, "Couldn't resolve path to file");
803 Toast t
= Toast
.makeText(
804 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
811 Intent i
= new Intent(this, FileUploader
.class);
812 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
813 OCFile currentDir
= getCurrentDir();
814 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
816 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
817 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
819 if (cursor
!= null
&& cursor
.moveToFirst()) {
820 String displayName
= cursor
.getString(cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
821 Log_OC
.v(TAG
, "Display Name: " + displayName
);
823 displayName
.replace(File
.separatorChar
, '_');
824 displayName
.replace(File
.pathSeparatorChar
, '_');
825 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
828 // and what happens in case of error?; wrong target name for the upload
834 remotePath
+= new File(filePath
).getName();
837 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
838 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
839 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
840 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
841 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
842 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
847 * Request the operation for moving the file/folder from one path to another
849 * @param data Intent received
850 * @param resultCode Result code received
852 private void requestMoveOperation(Intent data
, int resultCode
) {
853 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
854 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
855 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
859 public void onBackPressed() {
860 OCFileListFragment listOfFiles
= getListOfFilesFragment();
861 if (mDualPane
|| getSecondFragment() == null
) {
862 if (listOfFiles
!= null
) { // should never be null, indeed
863 if (mDirectories
.getCount() <= 1) {
867 int levelsUp
= listOfFiles
.onBrowseUp();
868 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
873 if (listOfFiles
!= null
) { // should never be null, indeed
874 setFile(listOfFiles
.getCurrentFile());
876 cleanSecondFragment();
881 protected void onSaveInstanceState(Bundle outState
) {
882 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
883 Log_OC
.v(TAG
, "onSaveInstanceState() start");
884 super.onSaveInstanceState(outState
);
885 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
886 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
887 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
888 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
890 Log_OC
.v(TAG
, "onSaveInstanceState() end");
896 protected void onResume() {
897 Log_OC
.v(TAG
, "onResume() start");
900 // refresh Navigation Drawer account list
901 adapter
.updateAccountList();
903 // refresh list of files
904 refreshListOfFilesFragment();
906 // Listen for sync messages
907 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
908 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
909 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
910 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
911 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
912 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
913 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
914 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
916 // Listen for upload messages
917 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
918 mUploadFinishReceiver
= new UploadFinishReceiver();
919 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
921 // Listen for download messages
922 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
923 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
924 mDownloadFinishReceiver
= new DownloadFinishReceiver();
925 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
927 Log_OC
.v(TAG
, "onResume() end");
932 protected void onPause() {
933 Log_OC
.v(TAG
, "onPause() start");
934 if (mSyncBroadcastReceiver
!= null
) {
935 unregisterReceiver(mSyncBroadcastReceiver
);
936 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
937 mSyncBroadcastReceiver
= null
;
939 if (mUploadFinishReceiver
!= null
) {
940 unregisterReceiver(mUploadFinishReceiver
);
941 mUploadFinishReceiver
= null
;
943 if (mDownloadFinishReceiver
!= null
) {
944 unregisterReceiver(mDownloadFinishReceiver
);
945 mDownloadFinishReceiver
= null
;
949 Log_OC
.v(TAG
, "onPause() end");
953 * Pushes a directory to the drop down list
954 * @param directory to push
955 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
957 public void pushDirname(OCFile directory
) {
958 if(!directory
.isFolder()){
959 throw new IllegalArgumentException("Only directories may be pushed!");
961 mDirectories
.insert(directory
.getFileName(), 0);
966 * Pops a directory name from the drop down list
967 * @return True, unless the stack is empty
969 public boolean popDirname() {
970 mDirectories
.remove(mDirectories
.getItem(0));
971 return !mDirectories
.isEmpty();
974 // Custom array adapter to override text colors
975 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
977 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
981 public View
getView(int position
, View convertView
, ViewGroup parent
) {
982 View v
= super.getView(position
, convertView
, parent
);
984 ((TextView
) v
).setTextColor(getResources().getColorStateList(
985 android
.R
.color
.white
));
987 fixRoot((TextView
) v
);
991 public View
getDropDownView(int position
, View convertView
,
993 View v
= super.getDropDownView(position
, convertView
, parent
);
995 ((TextView
) v
).setTextColor(getResources().getColorStateList(
996 android
.R
.color
.white
));
998 fixRoot((TextView
) v
);
1002 private void fixRoot(TextView v
) {
1003 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
1004 v
.setText(R
.string
.default_display_name_for_root_folder
);
1010 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
1013 * {@link BroadcastReceiver} to enable syncing feedback in UI
1016 public void onReceive(Context context
, Intent intent
) {
1018 String event
= intent
.getAction();
1019 Log_OC
.d(TAG
, "Received broadcast " + event
);
1020 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
1021 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
1022 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
1023 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
1027 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
1028 mSyncInProgress
= true
;
1031 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
1032 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1034 if (currentDir
== null
) {
1035 // current folder was removed from the server
1036 Toast
.makeText( FileDisplayActivity
.this,
1037 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
1043 if (currentFile
== null
&& !getFile().isFolder()) {
1044 // currently selected file was removed in the server, and now we know it
1045 cleanSecondFragment();
1046 currentFile
= currentDir
;
1049 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1050 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1051 if (fileListFragment
!= null
) {
1052 fileListFragment
.listDirectory();
1053 // TODO Enable when "On Device" is recovered ?
1054 // fileListFragment.listDirectory(currentDir, MainApp.getOnlyOnDevice());
1057 setFile(currentFile
);
1060 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1062 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1064 /// TODO refactor and make common
1065 synchResult
!= null
&& !synchResult
.isSuccess() &&
1066 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1067 synchResult
.isIdPRedirection() ||
1068 (synchResult
.isException() && synchResult
.getException()
1069 instanceof AuthenticatorException
))) {
1073 OwnCloudClient client
;
1074 OwnCloudAccount ocAccount
=
1075 new OwnCloudAccount(getAccount(), context
);
1076 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1077 removeClientFor(ocAccount
));
1079 if (client
!= null
) {
1080 OwnCloudCredentials cred
= client
.getCredentials();
1082 AccountManager am
= AccountManager
.get(context
);
1083 if (cred
.authTokenExpires()) {
1084 am
.invalidateAuthToken(
1089 am
.clearPassword(getAccount());
1093 requestCredentialsUpdate();
1095 } catch (AccountNotFoundException e
) {
1096 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1101 removeStickyBroadcast(intent
);
1102 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1103 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1105 setBackgroundText();
1109 if (synchResult
!= null
) {
1110 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1111 mLastSslUntrustedServerResult
= synchResult
;
1114 } catch (RuntimeException e
) {
1115 // avoid app crashes after changing the serial id of RemoteOperationResult
1116 // in owncloud library with broadcast notifications pending to process
1117 removeStickyBroadcast(intent
);
1123 * Show a text message on screen view for notifying user if content is
1124 * loading or folder is empty
1126 private void setBackgroundText() {
1127 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1128 if (ocFileListFragment
!= null
) {
1129 int message
= R
.string
.file_list_loading
;
1130 if (!mSyncInProgress
) {
1131 // In case file list is empty
1132 message
= R
.string
.file_list_empty
;
1134 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1136 Log_OC
.e(TAG
, "OCFileListFragment is null");
1141 * Once the file upload has finished -> update view
1143 private class UploadFinishReceiver
extends BroadcastReceiver
{
1145 * Once the file upload has finished -> update view
1146 * @author David A. Velasco
1147 * {@link BroadcastReceiver} to enable upload feedback in UI
1150 public void onReceive(Context context
, Intent intent
) {
1152 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1153 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1154 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1155 OCFile currentDir
= getCurrentDir();
1156 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1157 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1159 if (sameAccount
&& isDescendant
) {
1160 refreshListOfFilesFragment();
1163 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1164 boolean renamedInUpload
= getFile().getRemotePath().
1165 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1166 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1168 FileFragment details
= getSecondFragment();
1169 boolean detailFragmentIsShown
= (details
!= null
&&
1170 details
instanceof FileDetailFragment
);
1172 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1173 if (uploadWasFine
) {
1174 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1176 if (renamedInUpload
) {
1177 String newName
= (new File(uploadedRemotePath
)).getName();
1178 Toast msg
= Toast
.makeText(
1181 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1186 if (uploadWasFine
|| getFile().fileExists()) {
1187 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1189 cleanSecondFragment();
1192 // Force the preview if the file is an image
1193 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1194 startImagePreview(getFile());
1195 } // TODO what about other kind of previews?
1199 if (intent
!= null
) {
1200 removeStickyBroadcast(intent
);
1210 * Class waiting for broadcast events from the {@link FileDownloader} service.
1212 * Updates the UI when a download is started or finished, provided that it is relevant for the
1215 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1217 //int refreshCounter = 0;
1219 public void onReceive(Context context
, Intent intent
) {
1221 boolean sameAccount
= isSameAccount(context
, intent
);
1222 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1223 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1225 if (sameAccount
&& isDescendant
) {
1226 String linkedToRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1227 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1228 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1229 refreshListOfFilesFragment();
1231 refreshSecondFragment(
1233 downloadedRemotePath
,
1234 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1238 if (mWaitingToSend
!= null
) {
1239 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1240 if (mWaitingToSend
.isDown()) {
1241 sendDownloadedFile();
1246 if (intent
!= null
) {
1247 removeStickyBroadcast(intent
);
1252 private boolean isDescendant(String downloadedRemotePath
) {
1253 OCFile currentDir
= getCurrentDir();
1255 currentDir
!= null
&&
1256 downloadedRemotePath
!= null
&&
1257 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1261 private boolean isAscendant(String linkedToRemotePath
) {
1262 OCFile currentDir
= getCurrentDir();
1264 currentDir
!= null
&&
1265 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1269 private boolean isSameAccount(Context context
, Intent intent
) {
1270 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1271 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1276 public void browseToRoot() {
1277 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1278 if (listOfFiles
!= null
) { // should never be null, indeed
1279 while (mDirectories
.getCount() > 1) {
1282 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1283 listOfFiles
.listDirectory(root
);
1284 // TODO Enable when "On Device" is recovered ?
1285 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1286 setFile(listOfFiles
.getCurrentFile());
1287 startSyncFolderOperation(root
, false
);
1289 cleanSecondFragment();
1293 public void browseTo(OCFile folder
) {
1294 if (folder
== null
|| !folder
.isFolder()) {
1295 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1297 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1298 if (listOfFiles
!= null
) {
1299 setNavigationListWithFolder(folder
);
1300 listOfFiles
.listDirectory(folder
);
1301 // TODO Enable when "On Device" is recovered ?
1302 // listOfFiles.listDirectory(folder, MainApp.getOnlyOnDevice());
1303 setFile(listOfFiles
.getCurrentFile());
1304 startSyncFolderOperation(folder
, false
);
1306 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1308 cleanSecondFragment();
1315 * Updates action bar and second fragment, if in dual pane mode.
1318 public void onBrowsedDownTo(OCFile directory
) {
1319 pushDirname(directory
);
1320 cleanSecondFragment();
1323 startSyncFolderOperation(directory
, false
);
1328 * Shows the information of the {@link OCFile} received as a
1329 * parameter in the second fragment.
1331 * @param file {@link OCFile} whose details will be shown
1334 public void showDetails(OCFile file
) {
1335 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1336 setSecondFragment(detailFragment
);
1337 updateFragmentsVisibility(true
);
1338 updateNavigationElementsInActionBar(file
);
1346 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1347 ActionBar actionBar
= getSupportActionBar();
1349 // For adding content description tag to a title field in the action bar
1350 int actionBarTitleId
= getResources().getIdentifier("action_bar_title", "id", "android");
1352 if (chosenFile
== null
|| mDualPane
) {
1353 // only list of files - set for browsing through folders
1354 OCFile currentDir
= getCurrentDir();
1355 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1356 // actionBar.setDisplayHomeAsUpEnabled(noRoot);
1357 // actionBar.setDisplayShowTitleEnabled(!noRoot);
1358 actionBar
.setDisplayHomeAsUpEnabled(true
);
1359 actionBar
.setDisplayShowTitleEnabled(true
);
1361 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1362 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1363 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1364 actionBarTitleView
.setContentDescription(getString(R
.string
.default_display_name_for_root_folder
));
1367 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1368 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1371 actionBar
.setDisplayHomeAsUpEnabled(true
);
1372 actionBar
.setDisplayShowTitleEnabled(true
);
1373 actionBar
.setTitle(chosenFile
.getFileName());
1374 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1375 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1376 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1377 getWindow().getDecorView().findViewById(actionBarTitleId
).
1378 setContentDescription(chosenFile
.getFileName());
1385 protected ServiceConnection
newTransferenceServiceConnection() {
1386 return new ListServiceConnection();
1389 /** Defines callbacks for service binding, passed to bindService() */
1390 private class ListServiceConnection
implements ServiceConnection
{
1393 public void onServiceConnected(ComponentName component
, IBinder service
) {
1394 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1395 Log_OC
.d(TAG
, "Download service connected");
1396 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1397 if (mWaitingToPreview
!= null
)
1398 if (getStorageManager() != null
) {
1399 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1400 if (!mWaitingToPreview
.isDown()) {
1401 requestForDownload();
1405 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1406 Log_OC
.d(TAG
, "Upload service connected");
1407 mUploaderBinder
= (FileUploaderBinder
) service
;
1411 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1412 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1413 if (listOfFiles
!= null
) {
1414 listOfFiles
.listDirectory();
1415 // TODO Enable when "On Device" is recovered ?
1416 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1418 FileFragment secondFragment
= getSecondFragment();
1419 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1420 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1421 detailFragment
.listenForTransferProgress();
1422 detailFragment
.updateFileDetails(false
, false
);
1427 public void onServiceDisconnected(ComponentName component
) {
1428 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1429 Log_OC
.d(TAG
, "Download service disconnected");
1430 mDownloaderBinder
= null
;
1431 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1432 Log_OC
.d(TAG
, "Upload service disconnected");
1433 mUploaderBinder
= null
;
1439 public void onSavedCertificate() {
1440 startSyncFolderOperation(getCurrentDir(), false
);
1445 public void onFailedSavingCertificate() {
1446 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1447 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1449 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1453 public void onCancelCertificate() {
1458 * Updates the view associated to the activity after the finish of some operation over files
1459 * in the current account.
1461 * @param operation Removal operation performed.
1462 * @param result Result of the removal.
1465 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1466 super.onRemoteOperationFinish(operation
, result
);
1468 if (operation
instanceof RemoveFileOperation
) {
1469 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1471 } else if (operation
instanceof RenameFileOperation
) {
1472 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1474 } else if (operation
instanceof SynchronizeFileOperation
) {
1475 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1477 } else if (operation
instanceof CreateFolderOperation
) {
1478 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1480 } else if (operation
instanceof CreateShareOperation
) {
1481 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1483 } else if (operation
instanceof UnshareLinkOperation
) {
1484 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1486 } else if (operation
instanceof MoveFileOperation
) {
1487 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1493 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1494 if (result
.isSuccess()) {
1495 refreshShowDetails();
1496 refreshListOfFilesFragment();
1501 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1502 if (result
.isSuccess()) {
1503 refreshShowDetails();
1504 refreshListOfFilesFragment();
1506 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1507 cleanSecondFragment();
1508 refreshListOfFilesFragment();
1512 private void refreshShowDetails() {
1513 FileFragment details
= getSecondFragment();
1514 if (details
!= null
) {
1515 OCFile file
= details
.getFile();
1517 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1518 if (details
instanceof PreviewMediaFragment
) {
1519 // Refresh OCFile of the fragment
1520 ((PreviewMediaFragment
) details
).updateFile(file
);
1525 invalidateOptionsMenu();
1530 * Updates the view associated to the activity after the finish of an operation trying to remove a
1533 * @param operation Removal operation performed.
1534 * @param result Result of the removal.
1536 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1537 dismissLoadingDialog();
1539 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1543 if (result
.isSuccess()) {
1544 OCFile removedFile
= operation
.getFile();
1545 FileFragment second
= getSecondFragment();
1546 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1547 if (second
instanceof PreviewMediaFragment
) {
1548 ((PreviewMediaFragment
)second
).stopPreview(true
);
1550 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1551 cleanSecondFragment();
1553 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1554 refreshListOfFilesFragment();
1556 invalidateOptionsMenu();
1558 if (result
.isSslRecoverableException()) {
1559 mLastSslUntrustedServerResult
= result
;
1560 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1567 * Updates the view associated to the activity after the finish of an operation trying to move a
1570 * @param operation Move operation performed.
1571 * @param result Result of the move operation.
1573 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1574 if (result
.isSuccess()) {
1575 dismissLoadingDialog();
1576 refreshListOfFilesFragment();
1578 dismissLoadingDialog();
1580 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1581 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1585 } catch (NotFoundException e
) {
1586 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1593 * Updates the view associated to the activity after the finish of an operation trying to rename a
1596 * @param operation Renaming operation performed.
1597 * @param result Result of the renaming.
1599 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1600 dismissLoadingDialog();
1601 OCFile renamedFile
= operation
.getFile();
1602 if (result
.isSuccess()) {
1603 FileFragment details
= getSecondFragment();
1604 if (details
!= null
) {
1605 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1606 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1607 showDetails(renamedFile
);
1609 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1610 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1611 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1612 int position
= ((PreviewMediaFragment
)details
).getPosition();
1613 startMediaPreview(renamedFile
, position
, true
);
1615 getFileOperationsHelper().openFile(renamedFile
);
1620 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1621 refreshListOfFilesFragment();
1625 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1629 if (result
.isSslRecoverableException()) {
1630 mLastSslUntrustedServerResult
= result
;
1631 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1636 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1637 dismissLoadingDialog();
1638 OCFile syncedFile
= operation
.getLocalFile();
1639 if (!result
.isSuccess()) {
1640 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1641 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1642 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1643 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1649 if (operation
.transferWasRequested()) {
1650 onTransferStateChanged(syncedFile
, true
, true
);
1653 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1661 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1663 * @param operation Creation operation performed.
1664 * @param result Result of the creation.
1666 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1667 if (result
.isSuccess()) {
1668 dismissLoadingDialog();
1669 refreshListOfFilesFragment();
1671 dismissLoadingDialog();
1673 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1674 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1678 } catch (NotFoundException e
) {
1679 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1689 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1690 refreshListOfFilesFragment();
1691 FileFragment details
= getSecondFragment();
1692 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1693 if (downloading
|| uploading
) {
1694 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1696 if (!file
.fileExists()) {
1697 cleanSecondFragment();
1699 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1707 private void requestForDownload() {
1708 Account account
= getAccount();
1709 //if (!mWaitingToPreview.isDownloading()) {
1710 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1711 Intent i
= new Intent(this, FileDownloader
.class);
1712 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1713 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1719 private OCFile
getCurrentDir() {
1720 OCFile file
= getFile();
1722 if (file
.isFolder()) {
1724 } else if (getStorageManager() != null
) {
1725 String parentPath
= file
.getRemotePath().substring(0,
1726 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1727 return getStorageManager().getFileByPath(parentPath
);
1733 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1734 long currentSyncTime
= System
.currentTimeMillis();
1736 mSyncInProgress
= true
;
1738 // perform folder synchronization
1739 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1742 getFileOperationsHelper().isSharedSupported(),
1744 getStorageManager(),
1746 getApplicationContext()
1748 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1750 setSupportProgressBarIndeterminateVisibility(true
);
1752 setBackgroundText();
1756 * Show untrusted cert dialog
1758 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1759 // Show a dialog with the certificate info
1760 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1761 (CertificateCombinedException
) result
.getException());
1762 FragmentManager fm
= getSupportFragmentManager();
1763 FragmentTransaction ft
= fm
.beginTransaction();
1764 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1767 private void requestForDownload(OCFile file
) {
1768 Account account
= getAccount();
1769 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1770 Intent i
= new Intent(this, FileDownloader
.class);
1771 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1772 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1777 private void sendDownloadedFile(){
1778 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1779 mWaitingToSend
= null
;
1784 * Requests the download of the received {@link OCFile} , updates the UI
1785 * to monitor the download progress and prepares the activity to send the file
1786 * when the download finishes.
1788 * @param file {@link OCFile} to download and preview.
1790 public void startDownloadForSending(OCFile file
) {
1791 mWaitingToSend
= file
;
1792 requestForDownload(mWaitingToSend
);
1793 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1794 updateFragmentsVisibility(hasSecondFragment
);
1798 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1800 * @param file Image {@link OCFile} to show.
1802 public void startImagePreview(OCFile file
) {
1803 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1804 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1805 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1806 startActivity(showDetailsIntent
);
1811 * Stars the preview of an already down media {@link OCFile}.
1813 * @param file Media {@link OCFile} to preview.
1814 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1815 * @param autoplay When 'true', the playback will start without user interactions.
1817 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1818 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1819 setSecondFragment(mediaFragment
);
1820 updateFragmentsVisibility(true
);
1821 updateNavigationElementsInActionBar(file
);
1826 * Requests the download of the received {@link OCFile} , updates the UI
1827 * to monitor the download progress and prepares the activity to preview
1828 * or open the file when the download finishes.
1830 * @param file {@link OCFile} to download and preview.
1832 public void startDownloadForPreview(OCFile file
) {
1833 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1834 setSecondFragment(detailFragment
);
1835 mWaitingToPreview
= file
;
1836 requestForDownload();
1837 updateFragmentsVisibility(true
);
1838 updateNavigationElementsInActionBar(file
);
1843 public void cancelTransference(OCFile file
) {
1844 getFileOperationsHelper().cancelTransference(file
);
1845 if (mWaitingToPreview
!= null
&&
1846 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1847 mWaitingToPreview
= null
;
1849 if (mWaitingToSend
!= null
&&
1850 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1851 mWaitingToSend
= null
;
1853 onTransferStateChanged(file
, false
, false
);
1857 public void onRefresh(boolean ignoreETag
) {
1858 refreshList(ignoreETag
);
1862 public void onRefresh() {
1866 private void refreshList(boolean ignoreETag
) {
1867 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1868 if (listOfFiles
!= null
) {
1869 OCFile folder
= listOfFiles
.getCurrentFile();
1870 if (folder
!= null
) {
1871 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1872 listDirectory(mFile);*/
1873 startSyncFolderOperation(folder
, ignoreETag
);
1878 private void sortByDate(boolean ascending
){
1879 getListOfFilesFragment().sortByDate(ascending
);
1882 private void sortBySize(boolean ascending
){
1883 getListOfFilesFragment().sortBySize(ascending
);
1886 private void sortByName(boolean ascending
){
1887 getListOfFilesFragment().sortByName(ascending
);
1890 public void restart(){
1891 Intent i
= new Intent(this, FileDisplayActivity
.class);
1892 i
.addFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
1896 public void closeDrawer() {
1897 mDrawerLayout
.closeDrawers();