1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
22 import java
.io
.IOException
;
24 import android
.accounts
.Account
;
25 import android
.accounts
.AccountManager
;
26 import android
.accounts
.AuthenticatorException
;
27 import android
.accounts
.OperationCanceledException
;
28 import android
.app
.AlertDialog
;
29 import android
.app
.Dialog
;
30 import android
.app
.ProgressDialog
;
31 import android
.content
.BroadcastReceiver
;
32 import android
.content
.ComponentName
;
33 import android
.content
.ContentResolver
;
34 import android
.content
.Context
;
35 import android
.content
.DialogInterface
;
36 import android
.content
.Intent
;
37 import android
.content
.IntentFilter
;
38 import android
.content
.ServiceConnection
;
39 import android
.content
.SharedPreferences
;
40 import android
.content
.SyncRequest
;
41 import android
.content
.res
.Resources
.NotFoundException
;
42 import android
.database
.Cursor
;
43 import android
.net
.Uri
;
44 import android
.os
.Bundle
;
45 import android
.os
.IBinder
;
46 import android
.preference
.PreferenceManager
;
47 import android
.provider
.MediaStore
;
48 import android
.support
.v4
.app
.Fragment
;
49 import android
.support
.v4
.app
.FragmentManager
;
50 import android
.support
.v4
.app
.FragmentTransaction
;
51 import android
.view
.View
;
52 import android
.view
.ViewGroup
;
53 import android
.widget
.ArrayAdapter
;
54 import android
.widget
.TextView
;
55 import android
.widget
.Toast
;
57 import com
.actionbarsherlock
.app
.ActionBar
;
58 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
59 import com
.actionbarsherlock
.view
.Menu
;
60 import com
.actionbarsherlock
.view
.MenuInflater
;
61 import com
.actionbarsherlock
.view
.MenuItem
;
62 import com
.actionbarsherlock
.view
.Window
;
63 import com
.owncloud
.android
.BuildConfig
;
64 import com
.owncloud
.android
.MainApp
;
65 import com
.owncloud
.android
.R
;
66 import com
.owncloud
.android
.datamodel
.OCFile
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
;
68 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
69 import com
.owncloud
.android
.files
.services
.FileUploader
;
70 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
74 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
75 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
76 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
80 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
81 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
82 import com
.owncloud
.android
.operations
.CreateShareOperation
;
83 import com
.owncloud
.android
.operations
.MoveFileOperation
;
84 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
85 import com
.owncloud
.android
.operations
.RenameFileOperation
;
86 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
87 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
88 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
89 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
90 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
91 import com
.owncloud
.android
.ui
.adapter
.FileListListAdapter
;
92 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
95 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
96 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
97 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
102 import com
.owncloud
.android
.utils
.DisplayUtils
;
103 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
107 * Displays, what files the user has available in his ownCloud.
109 * @author Bartek Przybylski
110 * @author David A. Velasco
113 public class FileDisplayActivity
extends HookActivity
implements
114 FileFragment
.ContainerActivity
, OnNavigationListener
,
115 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
117 private ArrayAdapter
<String
> mDirectories
;
119 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
120 private UploadFinishReceiver mUploadFinishReceiver
;
121 private DownloadFinishReceiver mDownloadFinishReceiver
;
122 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
124 private boolean mDualPane
;
125 private View mLeftFragmentContainer
;
126 private View mRightFragmentContainer
;
128 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
129 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
130 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
132 public static final int DIALOG_SHORT_WAIT
= 0;
133 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
134 private static final int DIALOG_CERT_NOT_SAVED
= 2;
136 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
138 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
139 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
140 public static final int ACTION_MOVE_FILES
= 3;
142 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
144 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
145 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
147 private OCFile mWaitingToPreview
;
149 private boolean mSyncInProgress
= false
;
151 private String DIALOG_UNTRUSTED_CERT
;
153 private OCFile mWaitingToSend
;
156 protected void onCreate(Bundle savedInstanceState
) {
157 Log_OC
.d(TAG
, "onCreate() start");
158 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
160 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
162 // PIN CODE request ; best location is to decide, let's try this first
163 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
165 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
169 /// grant that FileObserverService is watching favourite files
170 if (savedInstanceState
== null
) {
171 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
172 startService(initObserversIntent
);
175 /// Load of saved instance state
176 if(savedInstanceState
!= null
) {
177 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
178 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
179 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
182 mWaitingToPreview
= null
;
183 mSyncInProgress
= false
;
184 mWaitingToSend
= null
;
189 // Inflate and set the layout view
190 setContentView(R
.layout
.files
);
191 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
192 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
193 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
194 if (savedInstanceState
== null
) {
195 createMinFragments();
199 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
200 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
201 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
205 Log_OC
.d(TAG
, "onCreate() end");
209 protected void onStart() {
211 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
215 protected void onDestroy() {
220 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
223 protected void onAccountSet(boolean stateWasRecovered
) {
224 super.onAccountSet(stateWasRecovered
);
225 if (getAccount() != null
) {
226 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
227 OCFile file
= getFile();
228 // get parent from path
229 String parentPath
= "";
231 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
232 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
233 // get parent from path
234 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
235 if (getStorageManager().getFileByPath(parentPath
) == null
)
236 file
= null
; // not able to know the directory where the file is uploading
238 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
242 // fall back to root folder
243 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
246 setNavigationListWithFolder(file
);
248 if (!stateWasRecovered
) {
249 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
250 initFragmentsWithFile();
251 if (file
.isFolder()) {
252 startSyncFolderOperation(file
, false
);
256 updateFragmentsVisibility(!file
.isFolder());
257 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
263 private void setNavigationListWithFolder(OCFile file
) {
264 mDirectories
.clear();
265 OCFile fileIt
= file
;
267 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
268 if (fileIt
.isFolder()) {
269 mDirectories
.add(fileIt
.getFileName());
271 // get parent from path
272 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
273 fileIt
= getStorageManager().getFileByPath(parentPath
);
275 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
279 private void createMinFragments() {
280 OCFileListFragment listOfFiles
= new OCFileListFragment();
281 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
282 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
283 transaction
.commit();
286 private void initFragmentsWithFile() {
287 if (getAccount() != null
&& getFile() != null
) {
289 OCFileListFragment listOfFiles
= getListOfFilesFragment();
290 if (listOfFiles
!= null
) {
291 listOfFiles
.listDirectory(getCurrentDir());
293 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
297 OCFile file
= getFile();
298 Fragment secondFragment
= chooseInitialSecondFragment(file
);
299 if (secondFragment
!= null
) {
300 setSecondFragment(secondFragment
);
301 updateFragmentsVisibility(true
);
302 updateNavigationElementsInActionBar(file
);
305 cleanSecondFragment();
309 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
310 if (getAccount() == null
) {
311 Log_OC
.wtf(TAG
, "\t account is NULL");
313 if (getFile() == null
) {
314 Log_OC
.wtf(TAG
, "\t file is NULL");
319 private Fragment
chooseInitialSecondFragment(OCFile file
) {
320 Fragment secondFragment
= null
;
321 if (file
!= null
&& !file
.isFolder()) {
322 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
323 && file
.getLastSyncDateForProperties() > 0 // temporal fix
325 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
326 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
327 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
330 secondFragment
= new FileDetailFragment(file
, getAccount());
333 return secondFragment
;
338 * Replaces the second fragment managed by the activity with the received as
341 * Assumes never will be more than two fragments managed at the same time.
343 * @param fragment New second Fragment to set.
345 private void setSecondFragment(Fragment fragment
) {
346 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
347 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
348 transaction
.commit();
352 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
354 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
355 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
357 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
358 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
361 } else if (existsSecondFragment
) {
362 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
363 mLeftFragmentContainer
.setVisibility(View
.GONE
);
365 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
366 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
370 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
371 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
373 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
374 mRightFragmentContainer
.setVisibility(View
.GONE
);
380 private OCFileListFragment
getListOfFilesFragment() {
381 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
382 if (listOfFiles
!= null
) {
383 return (OCFileListFragment
)listOfFiles
;
385 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
389 public FileFragment
getSecondFragment() {
390 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
391 if (second
!= null
) {
392 return (FileFragment
)second
;
397 protected void cleanSecondFragment() {
398 Fragment second
= getSecondFragment();
399 if (second
!= null
) {
400 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
404 updateFragmentsVisibility(false
);
405 updateNavigationElementsInActionBar(null
);
408 protected void refreshListOfFilesFragment() {
409 OCFileListFragment fileListFragment
= getListOfFilesFragment();
410 if (fileListFragment
!= null
) {
411 fileListFragment
.listDirectory();
415 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
416 FileFragment secondFragment
= getSecondFragment();
417 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
418 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
419 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
420 OCFile fileInFragment
= detailsFragment
.getFile();
421 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
422 // the user browsed to other file ; forget the automatic preview
423 mWaitingToPreview
= null
;
425 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
426 // grant that the right panel updates the progress bar
427 detailsFragment
.listenForTransferProgress();
428 detailsFragment
.updateFileDetails(true
, false
);
430 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
431 // update the right panel
432 boolean detailsFragmentChanged
= false
;
435 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
436 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
437 startMediaPreview(mWaitingToPreview
, 0, true
);
438 detailsFragmentChanged
= true
;
440 getFileOperationsHelper().openFile(mWaitingToPreview
);
443 mWaitingToPreview
= null
;
445 if (!detailsFragmentChanged
) {
446 detailsFragment
.updateFileDetails(false
, (success
));
453 public boolean onPrepareOptionsMenu(Menu menu
) {
454 if (BuildConfig
.DEBUG
) {
455 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
457 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
459 return super.onPrepareOptionsMenu(menu
);
463 public boolean onCreateOptionsMenu(Menu menu
) {
464 MenuInflater inflater
= getSherlock().getMenuInflater();
465 inflater
.inflate(R
.menu
.main_menu
, menu
);
470 public boolean onOptionsItemSelected(MenuItem item
) {
471 boolean retval
= true
;
472 switch (item
.getItemId()) {
473 case R
.id
.action_create_dir
: {
474 CreateFolderDialogFragment dialog
=
475 CreateFolderDialogFragment
.newInstance(getCurrentDir());
476 dialog
.show(getSupportFragmentManager(), "createdirdialog");
479 case R
.id
.action_sync_account
: {
480 startSynchronization();
483 case R
.id
.action_upload
: {
484 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
487 case R
.id
.action_settings
: {
488 Intent settingsIntent
= new Intent(this, Preferences
.class);
489 startActivity(settingsIntent
);
492 case R
.id
.action_logger
: {
493 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
494 startActivity(loggerIntent
);
497 case android
.R
.id
.home
: {
498 FileFragment second
= getSecondFragment();
499 OCFile currentDir
= getCurrentDir();
500 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
501 (second
!= null
&& second
.getFile() != null
)) {
507 case R
.id
.action_sort
: {
508 SharedPreferences appPreferences
= PreferenceManager
509 .getDefaultSharedPreferences(this);
511 // Read sorting order, default to sort by name ascending
512 Integer sortOrder
= appPreferences
513 .getInt("sortOrder", FileListListAdapter
.SORT_NAME
);
515 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
516 builder
.setTitle(R
.string
.actionbar_sort_title
)
517 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
518 public void onClick(DialogInterface dialog
, int which
) {
528 // TODO re-enable when server-side folder size calculation is available
530 // sortBySize(false);
538 builder
.create().show();
542 retval
= super.onOptionsItemSelected(item
);
547 private void startSynchronization() {
548 Log_OC
.e(TAG
, "Got to start sync");
549 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
550 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
551 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
552 Bundle bundle
= new Bundle();
553 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
554 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
555 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
556 ContentResolver
.requestSync(
558 MainApp
.getAuthority(), bundle
);
560 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
561 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
562 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
563 builder
.setExpedited(true
);
564 builder
.setManual(true
);
567 // Fix bug in Android Lollipop when you click on refresh the whole account
568 Bundle extras
= new Bundle();
569 builder
.setExtras(extras
);
571 SyncRequest request
= builder
.build();
572 ContentResolver
.requestSync(request
);
578 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
579 if (itemPosition
!= 0) {
580 String targetPath
= "";
581 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
582 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
584 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
585 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
586 if (targetFolder
!= null
) {
587 browseTo(targetFolder
);
590 // the next operation triggers a new call to this method, but it's necessary to
591 // ensure that the name exposed in the action bar is the current directory when the
592 // user selected it in the navigation list
593 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
594 getSupportActionBar().setSelectedNavigationItem(0);
600 * Called, when the user selected something for uploading
602 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
603 super.onActivityResult(requestCode
, resultCode
, data
);
605 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
606 requestSimpleUpload(data
, resultCode
);
608 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
609 requestMultipleUpload(data
, resultCode
);
611 } else if (requestCode
== ACTION_MOVE_FILES
&& (resultCode
== RESULT_OK
||
612 resultCode
== MoveActivity
.RESULT_OK_AND_MOVE
)){
614 final Intent fData
= data
;
615 final int fResultCode
= resultCode
;
616 getHandler().postDelayed(
620 requestMoveOperation(fData
, fResultCode
);
623 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
628 private void requestMultipleUpload(Intent data
, int resultCode
) {
629 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
630 if (filePaths
!= null
) {
631 String
[] remotePaths
= new String
[filePaths
.length
];
632 String remotePathBase
= "";
633 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
634 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
636 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
637 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
638 for (int j
= 0; j
< remotePaths
.length
; j
++) {
639 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
642 Intent i
= new Intent(this, FileUploader
.class);
643 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
644 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
645 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
646 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
647 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
648 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
652 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
653 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
660 private void requestSimpleUpload(Intent data
, int resultCode
) {
661 String filepath
= null
;
663 Uri selectedImageUri
= data
.getData();
665 String filemanagerstring
= selectedImageUri
.getPath();
666 String selectedImagePath
= getPath(selectedImageUri
);
668 if (selectedImagePath
!= null
)
669 filepath
= selectedImagePath
;
671 filepath
= filemanagerstring
;
673 } catch (Exception e
) {
674 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
678 if (filepath
== null
) {
679 Log_OC
.e(TAG
, "Couldnt resolve path to file");
680 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
686 Intent i
= new Intent(this, FileUploader
.class);
687 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
689 String remotepath
= new String();
690 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
691 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
693 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
694 remotepath
+= OCFile
.PATH_SEPARATOR
;
695 remotepath
+= new File(filepath
).getName();
697 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
698 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
699 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
700 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
701 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
706 * Request the operation for moving the file/folder from one path to another
708 * @param data Intent received
709 * @param resultCode Result code received
711 private void requestMoveOperation(Intent data
, int resultCode
) {
712 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
713 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
);
714 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
718 public void onBackPressed() {
719 OCFileListFragment listOfFiles
= getListOfFilesFragment();
720 if (mDualPane
|| getSecondFragment() == null
) {
721 if (listOfFiles
!= null
) { // should never be null, indeed
722 if (mDirectories
.getCount() <= 1) {
726 int levelsUp
= listOfFiles
.onBrowseUp();
727 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
732 if (listOfFiles
!= null
) { // should never be null, indeed
733 setFile(listOfFiles
.getCurrentFile());
735 cleanSecondFragment();
740 protected void onSaveInstanceState(Bundle outState
) {
741 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
742 Log_OC
.e(TAG
, "onSaveInstanceState() start");
743 super.onSaveInstanceState(outState
);
744 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
745 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
746 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
747 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
749 Log_OC
.d(TAG
, "onSaveInstanceState() end");
755 protected void onResume() {
757 Log_OC
.e(TAG
, "onResume() start");
759 // refresh list of files
760 refreshListOfFilesFragment();
762 // Listen for sync messages
763 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
764 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
765 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
766 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
767 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
768 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
769 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
770 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
772 // Listen for upload messages
773 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
774 mUploadFinishReceiver
= new UploadFinishReceiver();
775 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
777 // Listen for download messages
778 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
779 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
780 mDownloadFinishReceiver
= new DownloadFinishReceiver();
781 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
783 Log_OC
.d(TAG
, "onResume() end");
788 protected void onPause() {
789 Log_OC
.e(TAG
, "onPause() start");
790 if (mSyncBroadcastReceiver
!= null
) {
791 unregisterReceiver(mSyncBroadcastReceiver
);
792 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
793 mSyncBroadcastReceiver
= null
;
795 if (mUploadFinishReceiver
!= null
) {
796 unregisterReceiver(mUploadFinishReceiver
);
797 mUploadFinishReceiver
= null
;
799 if (mDownloadFinishReceiver
!= null
) {
800 unregisterReceiver(mDownloadFinishReceiver
);
801 mDownloadFinishReceiver
= null
;
805 Log_OC
.d(TAG
, "onPause() end");
811 protected Dialog
onCreateDialog(int id
) {
812 Dialog dialog
= null
;
813 AlertDialog
.Builder builder
;
815 case DIALOG_SHORT_WAIT
: {
816 ProgressDialog working_dialog
= new ProgressDialog(this);
817 working_dialog
.setMessage(getResources().getString(
818 R
.string
.wait_a_moment
));
819 working_dialog
.setIndeterminate(true
);
820 working_dialog
.setCancelable(false
);
821 dialog
= working_dialog
;
824 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
827 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
828 getString(R
.string
.actionbar_upload_from_apps
) };
830 builder
= new AlertDialog
.Builder(this);
831 builder
.setTitle(R
.string
.actionbar_upload
);
832 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
833 public void onClick(DialogInterface dialog
, int item
) {
836 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
837 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
838 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
840 // TODO create and handle new fragment
841 // LocalFileListFragment
843 } else if (item
== 1) {
844 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
845 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
846 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
847 ACTION_SELECT_CONTENT_FROM_APPS
);
851 dialog
= builder
.create();
854 case DIALOG_CERT_NOT_SAVED
: {
855 builder
= new AlertDialog
.Builder(this);
856 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
857 builder
.setCancelable(false
);
858 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
860 public void onClick(DialogInterface dialog
, int which
) {
864 dialog
= builder
.create();
876 * Translates a content URI of an image to a physical path
878 * @param uri The URI to resolve
879 * @return The path to the image or null if it could not be found
881 public String
getPath(Uri uri
) {
882 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
883 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
884 if (cursor
!= null
) {
885 int column_index
= cursor
886 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
887 cursor
.moveToFirst();
888 return cursor
.getString(column_index
);
894 * Pushes a directory to the drop down list
895 * @param directory to push
896 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
898 public void pushDirname(OCFile directory
) {
899 if(!directory
.isFolder()){
900 throw new IllegalArgumentException("Only directories may be pushed!");
902 mDirectories
.insert(directory
.getFileName(), 0);
907 * Pops a directory name from the drop down list
908 * @return True, unless the stack is empty
910 public boolean popDirname() {
911 mDirectories
.remove(mDirectories
.getItem(0));
912 return !mDirectories
.isEmpty();
915 // Custom array adapter to override text colors
916 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
918 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
922 public View
getView(int position
, View convertView
, ViewGroup parent
) {
923 View v
= super.getView(position
, convertView
, parent
);
925 ((TextView
) v
).setTextColor(getResources().getColorStateList(
926 android
.R
.color
.white
));
928 fixRoot((TextView
) v
);
932 public View
getDropDownView(int position
, View convertView
,
934 View v
= super.getDropDownView(position
, convertView
, parent
);
936 ((TextView
) v
).setTextColor(getResources().getColorStateList(
937 android
.R
.color
.white
));
939 fixRoot((TextView
) v
);
943 private void fixRoot(TextView v
) {
944 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
945 v
.setText(R
.string
.default_display_name_for_root_folder
);
951 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
954 * {@link BroadcastReceiver} to enable syncing feedback in UI
957 public void onReceive(Context context
, Intent intent
) {
959 String event
= intent
.getAction();
960 Log_OC
.d(TAG
, "Received broadcast " + event
);
961 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
962 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
963 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
964 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
968 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
969 mSyncInProgress
= true
;
972 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
973 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
975 if (currentDir
== null
) {
976 // current folder was removed from the server
977 Toast
.makeText( FileDisplayActivity
.this,
978 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
984 if (currentFile
== null
&& !getFile().isFolder()) {
985 // currently selected file was removed in the server, and now we know it
986 cleanSecondFragment();
987 currentFile
= currentDir
;
990 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
991 OCFileListFragment fileListFragment
= getListOfFilesFragment();
992 if (fileListFragment
!= null
) {
993 fileListFragment
.listDirectory(currentDir
);
996 setFile(currentFile
);
999 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1001 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1003 /// TODO refactor and make common
1004 synchResult
!= null
&& !synchResult
.isSuccess() &&
1005 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1006 synchResult
.isIdPRedirection() ||
1007 (synchResult
.isException() && synchResult
.getException()
1008 instanceof AuthenticatorException
))) {
1010 OwnCloudClient client
= null
;
1012 OwnCloudAccount ocAccount
=
1013 new OwnCloudAccount(getAccount(), context
);
1014 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1015 removeClientFor(ocAccount
));
1016 // TODO get rid of these exceptions
1017 } catch (AccountNotFoundException e
) {
1018 e
.printStackTrace();
1019 } catch (AuthenticatorException e
) {
1020 e
.printStackTrace();
1021 } catch (OperationCanceledException e
) {
1022 e
.printStackTrace();
1023 } catch (IOException e
) {
1024 e
.printStackTrace();
1027 if (client
!= null
) {
1028 OwnCloudCredentials cred
= client
.getCredentials();
1030 AccountManager am
= AccountManager
.get(context
);
1031 if (cred
.authTokenExpires()) {
1032 am
.invalidateAuthToken(
1037 am
.clearPassword(getAccount());
1042 requestCredentialsUpdate();
1046 removeStickyBroadcast(intent
);
1047 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1048 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1050 setBackgroundText();
1054 if (synchResult
!= null
) {
1055 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1056 mLastSslUntrustedServerResult
= synchResult
;
1059 } catch (RuntimeException e
) {
1060 // avoid app crashes after changing the serial id of RemoteOperationResult
1061 // in owncloud library with broadcast notifications pending to process
1062 removeStickyBroadcast(intent
);
1068 * Show a text message on screen view for notifying user if content is
1069 * loading or folder is empty
1071 private void setBackgroundText() {
1072 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1073 if (ocFileListFragment
!= null
) {
1074 int message
= R
.string
.file_list_loading
;
1075 if (!mSyncInProgress
) {
1076 // In case file list is empty
1077 message
= R
.string
.file_list_empty
;
1079 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1081 Log_OC
.e(TAG
, "OCFileListFragment is null");
1086 * Once the file upload has finished -> update view
1088 private class UploadFinishReceiver
extends BroadcastReceiver
{
1090 * Once the file upload has finished -> update view
1091 * @author David A. Velasco
1092 * {@link BroadcastReceiver} to enable upload feedback in UI
1095 public void onReceive(Context context
, Intent intent
) {
1097 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1098 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1099 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1100 OCFile currentDir
= getCurrentDir();
1101 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1102 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1104 if (sameAccount
&& isDescendant
) {
1105 refreshListOfFilesFragment();
1108 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1109 boolean renamedInUpload
= getFile().getRemotePath().
1110 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1111 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1113 FileFragment details
= getSecondFragment();
1114 boolean detailFragmentIsShown
= (details
!= null
&&
1115 details
instanceof FileDetailFragment
);
1117 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1118 if (uploadWasFine
) {
1119 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1121 if (renamedInUpload
) {
1122 String newName
= (new File(uploadedRemotePath
)).getName();
1123 Toast msg
= Toast
.makeText(
1126 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1131 if (uploadWasFine
|| getFile().fileExists()) {
1132 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1134 cleanSecondFragment();
1137 // Force the preview if the file is an image
1138 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1139 startImagePreview(getFile());
1140 } // TODO what about other kind of previews?
1144 if (intent
!= null
) {
1145 removeStickyBroadcast(intent
);
1155 * Class waiting for broadcast events from the {@link FielDownloader} service.
1157 * Updates the UI when a download is started or finished, provided that it is relevant for the
1160 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1162 public void onReceive(Context context
, Intent intent
) {
1164 boolean sameAccount
= isSameAccount(context
, intent
);
1165 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1166 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1168 if (sameAccount
&& isDescendant
) {
1169 refreshListOfFilesFragment();
1170 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1173 if (mWaitingToSend
!= null
) {
1174 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1175 if (mWaitingToSend
.isDown()) {
1176 sendDownloadedFile();
1181 if (intent
!= null
) {
1182 removeStickyBroadcast(intent
);
1187 private boolean isDescendant(String downloadedRemotePath
) {
1188 OCFile currentDir
= getCurrentDir();
1189 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1192 private boolean isSameAccount(Context context
, Intent intent
) {
1193 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1194 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1199 public void browseToRoot() {
1200 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1201 if (listOfFiles
!= null
) { // should never be null, indeed
1202 while (mDirectories
.getCount() > 1) {
1205 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1206 listOfFiles
.listDirectory(root
);
1207 setFile(listOfFiles
.getCurrentFile());
1208 startSyncFolderOperation(root
, false
);
1210 cleanSecondFragment();
1214 public void browseTo(OCFile folder
) {
1215 if (folder
== null
|| !folder
.isFolder()) {
1216 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1218 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1219 if (listOfFiles
!= null
) {
1220 setNavigationListWithFolder(folder
);
1221 listOfFiles
.listDirectory(folder
);
1222 setFile(listOfFiles
.getCurrentFile());
1223 startSyncFolderOperation(folder
, false
);
1225 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1227 cleanSecondFragment();
1234 * Updates action bar and second fragment, if in dual pane mode.
1237 public void onBrowsedDownTo(OCFile directory
) {
1238 pushDirname(directory
);
1239 cleanSecondFragment();
1242 startSyncFolderOperation(directory
, false
);
1247 * Shows the information of the {@link OCFile} received as a
1248 * parameter in the second fragment.
1250 * @param file {@link OCFile} whose details will be shown
1253 public void showDetails(OCFile file
) {
1254 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1255 setSecondFragment(detailFragment
);
1256 updateFragmentsVisibility(true
);
1257 updateNavigationElementsInActionBar(file
);
1265 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1266 ActionBar actionBar
= getSupportActionBar();
1267 if (chosenFile
== null
|| mDualPane
) {
1268 // only list of files - set for browsing through folders
1269 OCFile currentDir
= getCurrentDir();
1270 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1271 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1272 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1274 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1276 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1277 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1280 actionBar
.setDisplayHomeAsUpEnabled(true
);
1281 actionBar
.setDisplayShowTitleEnabled(true
);
1282 actionBar
.setTitle(chosenFile
.getFileName());
1283 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1289 protected ServiceConnection
newTransferenceServiceConnection() {
1290 return new ListServiceConnection();
1293 /** Defines callbacks for service binding, passed to bindService() */
1294 private class ListServiceConnection
implements ServiceConnection
{
1297 public void onServiceConnected(ComponentName component
, IBinder service
) {
1298 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1299 Log_OC
.d(TAG
, "Download service connected");
1300 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1301 if (mWaitingToPreview
!= null
)
1302 if (getStorageManager() != null
) {
1303 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1304 if (!mWaitingToPreview
.isDown()) {
1305 requestForDownload();
1309 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1310 Log_OC
.d(TAG
, "Upload service connected");
1311 mUploaderBinder
= (FileUploaderBinder
) service
;
1315 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1316 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1317 if (listOfFiles
!= null
) {
1318 listOfFiles
.listDirectory();
1320 FileFragment secondFragment
= getSecondFragment();
1321 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1322 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1323 detailFragment
.listenForTransferProgress();
1324 detailFragment
.updateFileDetails(false
, false
);
1329 public void onServiceDisconnected(ComponentName component
) {
1330 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1331 Log_OC
.d(TAG
, "Download service disconnected");
1332 mDownloaderBinder
= null
;
1333 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1334 Log_OC
.d(TAG
, "Upload service disconnected");
1335 mUploaderBinder
= null
;
1343 * Launch an intent to request the PIN code to the user before letting him use the app
1345 private void requestPinCode() {
1346 boolean pinStart
= false
;
1347 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1348 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1350 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1351 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1358 public void onSavedCertificate() {
1359 startSyncFolderOperation(getCurrentDir(), false
);
1364 public void onFailedSavingCertificate() {
1365 showDialog(DIALOG_CERT_NOT_SAVED
);
1369 public void onCancelCertificate() {
1374 * Updates the view associated to the activity after the finish of some operation over files
1375 * in the current account.
1377 * @param operation Removal operation performed.
1378 * @param result Result of the removal.
1381 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1382 super.onRemoteOperationFinish(operation
, result
);
1384 if (operation
instanceof RemoveFileOperation
) {
1385 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1387 } else if (operation
instanceof RenameFileOperation
) {
1388 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1390 } else if (operation
instanceof SynchronizeFileOperation
) {
1391 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1393 } else if (operation
instanceof CreateFolderOperation
) {
1394 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1396 } else if (operation
instanceof CreateShareOperation
) {
1397 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1399 } else if (operation
instanceof UnshareLinkOperation
) {
1400 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1402 } else if (operation
instanceof MoveFileOperation
) {
1403 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1409 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1410 if (result
.isSuccess()) {
1411 refreshShowDetails();
1412 refreshListOfFilesFragment();
1417 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1418 if (result
.isSuccess()) {
1419 refreshShowDetails();
1420 refreshListOfFilesFragment();
1422 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1423 cleanSecondFragment();
1424 refreshListOfFilesFragment();
1428 private void refreshShowDetails() {
1429 FileFragment details
= getSecondFragment();
1430 if (details
!= null
) {
1431 OCFile file
= details
.getFile();
1433 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1434 if (details
instanceof PreviewMediaFragment
) {
1435 // Refresh OCFile of the fragment
1436 ((PreviewMediaFragment
) details
).updateFile(file
);
1441 invalidateOptionsMenu();
1446 * Updates the view associated to the activity after the finish of an operation trying to remove a
1449 * @param operation Removal operation performed.
1450 * @param result Result of the removal.
1452 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1453 dismissLoadingDialog();
1455 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1459 if (result
.isSuccess()) {
1460 OCFile removedFile
= operation
.getFile();
1461 FileFragment second
= getSecondFragment();
1462 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1463 if (second
instanceof PreviewMediaFragment
) {
1464 ((PreviewMediaFragment
)second
).stopPreview(true
);
1466 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1467 cleanSecondFragment();
1469 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1470 refreshListOfFilesFragment();
1472 invalidateOptionsMenu();
1474 if (result
.isSslRecoverableException()) {
1475 mLastSslUntrustedServerResult
= result
;
1476 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1483 * Updates the view associated to the activity after the finish of an operation trying to move a
1486 * @param operation Move operation performed.
1487 * @param result Result of the move operation.
1489 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1490 if (result
.isSuccess()) {
1491 dismissLoadingDialog();
1492 refreshListOfFilesFragment();
1494 dismissLoadingDialog();
1496 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1497 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1501 } catch (NotFoundException e
) {
1502 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1509 * Updates the view associated to the activity after the finish of an operation trying to rename a
1512 * @param operation Renaming operation performed.
1513 * @param result Result of the renaming.
1515 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1516 dismissLoadingDialog();
1517 OCFile renamedFile
= operation
.getFile();
1518 if (result
.isSuccess()) {
1519 FileFragment details
= getSecondFragment();
1520 if (details
!= null
) {
1521 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1522 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1523 showDetails(renamedFile
);
1525 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1526 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1527 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1528 int position
= ((PreviewMediaFragment
)details
).getPosition();
1529 startMediaPreview(renamedFile
, position
, true
);
1531 getFileOperationsHelper().openFile(renamedFile
);
1536 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1537 refreshListOfFilesFragment();
1541 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1545 if (result
.isSslRecoverableException()) {
1546 mLastSslUntrustedServerResult
= result
;
1547 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1552 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1553 dismissLoadingDialog();
1554 OCFile syncedFile
= operation
.getLocalFile();
1555 if (!result
.isSuccess()) {
1556 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1557 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1558 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1559 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1565 if (operation
.transferWasRequested()) {
1566 onTransferStateChanged(syncedFile
, true
, true
);
1569 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1577 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1579 * @param operation Creation operation performed.
1580 * @param result Result of the creation.
1582 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1583 if (result
.isSuccess()) {
1584 dismissLoadingDialog();
1585 refreshListOfFilesFragment();
1587 dismissLoadingDialog();
1589 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1590 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1594 } catch (NotFoundException e
) {
1595 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1605 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1606 refreshListOfFilesFragment();
1607 FileFragment details
= getSecondFragment();
1608 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1609 if (downloading
|| uploading
) {
1610 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1612 if (!file
.fileExists()) {
1613 cleanSecondFragment();
1615 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1623 private void requestForDownload() {
1624 Account account
= getAccount();
1625 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1626 Intent i
= new Intent(this, FileDownloader
.class);
1627 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1628 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1634 private OCFile
getCurrentDir() {
1635 OCFile file
= getFile();
1637 if (file
.isFolder()) {
1639 } else if (getStorageManager() != null
) {
1640 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1641 return getStorageManager().getFileByPath(parentPath
);
1647 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1648 long currentSyncTime
= System
.currentTimeMillis();
1650 mSyncInProgress
= true
;
1652 // perform folder synchronization
1653 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1656 getFileOperationsHelper().isSharedSupported(),
1658 getStorageManager(),
1660 getApplicationContext()
1662 synchFolderOp
.execute(getAccount(), this, null
, null
);
1664 setSupportProgressBarIndeterminateVisibility(true
);
1666 setBackgroundText();
1670 * Show untrusted cert dialog
1672 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1673 // Show a dialog with the certificate info
1674 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1675 FragmentManager fm
= getSupportFragmentManager();
1676 FragmentTransaction ft
= fm
.beginTransaction();
1677 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1680 private void requestForDownload(OCFile file
) {
1681 Account account
= getAccount();
1682 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1683 Intent i
= new Intent(this, FileDownloader
.class);
1684 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1685 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1690 private void sendDownloadedFile(){
1691 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1692 mWaitingToSend
= null
;
1697 * Requests the download of the received {@link OCFile} , updates the UI
1698 * to monitor the download progress and prepares the activity to send the file
1699 * when the download finishes.
1701 * @param file {@link OCFile} to download and preview.
1703 public void startDownloadForSending(OCFile file
) {
1704 mWaitingToSend
= file
;
1705 requestForDownload(mWaitingToSend
);
1706 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1707 updateFragmentsVisibility(hasSecondFragment
);
1711 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1713 * @param file Image {@link OCFile} to show.
1715 public void startImagePreview(OCFile file
) {
1716 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1717 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1718 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1719 startActivity(showDetailsIntent
);
1724 * Stars the preview of an already down media {@link OCFile}.
1726 * @param file Media {@link OCFile} to preview.
1727 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1728 * @param autoplay When 'true', the playback will start without user interactions.
1730 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1731 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1732 setSecondFragment(mediaFragment
);
1733 updateFragmentsVisibility(true
);
1734 updateNavigationElementsInActionBar(file
);
1739 * Requests the download of the received {@link OCFile} , updates the UI
1740 * to monitor the download progress and prepares the activity to preview
1741 * or open the file when the download finishes.
1743 * @param file {@link OCFile} to download and preview.
1745 public void startDownloadForPreview(OCFile file
) {
1746 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1747 setSecondFragment(detailFragment
);
1748 mWaitingToPreview
= file
;
1749 requestForDownload();
1750 updateFragmentsVisibility(true
);
1751 updateNavigationElementsInActionBar(file
);
1756 public void cancelTransference(OCFile file
) {
1757 getFileOperationsHelper().cancelTransference(file
);
1758 if (mWaitingToPreview
!= null
&&
1759 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1760 mWaitingToPreview
= null
;
1762 if (mWaitingToSend
!= null
&&
1763 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1764 mWaitingToSend
= null
;
1766 onTransferStateChanged(file
, false
, false
);
1770 public void onRefresh(boolean ignoreETag
) {
1771 refreshList(ignoreETag
);
1775 public void onRefresh() {
1779 private void refreshList(boolean ignoreETag
) {
1780 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1781 if (listOfFiles
!= null
) {
1782 OCFile folder
= listOfFiles
.getCurrentFile();
1783 if (folder
!= null
) {
1784 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1785 listDirectory(mFile);*/
1786 startSyncFolderOperation(folder
, ignoreETag
);
1791 private void sortByDate(boolean ascending
){
1792 getListOfFilesFragment().sortByDate(ascending
);
1795 private void sortBySize(boolean ascending
){
1796 getListOfFilesFragment().sortBySize(ascending
);
1799 private void sortByName(boolean ascending
){
1800 getListOfFilesFragment().sortByName(ascending
);