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
.annotation
.SuppressLint
;
29 import android
.annotation
.TargetApi
;
30 import android
.app
.AlertDialog
;
31 import android
.app
.Dialog
;
32 import android
.app
.ProgressDialog
;
33 import android
.content
.BroadcastReceiver
;
34 import android
.content
.ComponentName
;
35 import android
.content
.ContentResolver
;
36 import android
.content
.Context
;
37 import android
.content
.DialogInterface
;
38 import android
.content
.Intent
;
39 import android
.content
.IntentFilter
;
40 import android
.content
.ServiceConnection
;
41 import android
.content
.SharedPreferences
;
42 import android
.content
.SyncRequest
;
43 import android
.content
.res
.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
.MediaStore
;
51 import android
.support
.v4
.app
.Fragment
;
52 import android
.support
.v4
.app
.FragmentManager
;
53 import android
.support
.v4
.app
.FragmentTransaction
;
54 import android
.view
.View
;
55 import android
.view
.ViewGroup
;
56 import android
.widget
.ArrayAdapter
;
57 import android
.widget
.TextView
;
58 import android
.widget
.Toast
;
60 import com
.actionbarsherlock
.app
.ActionBar
;
61 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
62 import com
.actionbarsherlock
.view
.Menu
;
63 import com
.actionbarsherlock
.view
.MenuInflater
;
64 import com
.actionbarsherlock
.view
.MenuItem
;
65 import com
.actionbarsherlock
.view
.Window
;
66 import com
.owncloud
.android
.BuildConfig
;
67 import com
.owncloud
.android
.MainApp
;
68 import com
.owncloud
.android
.R
;
69 import com
.owncloud
.android
.datamodel
.OCFile
;
70 import com
.owncloud
.android
.files
.services
.FileDownloader
;
71 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
72 import com
.owncloud
.android
.files
.services
.FileUploader
;
73 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
74 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
75 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
76 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
77 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
78 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
79 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
80 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
81 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
82 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
83 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
84 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
85 import com
.owncloud
.android
.operations
.CreateShareOperation
;
86 import com
.owncloud
.android
.operations
.MoveFileOperation
;
87 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
88 import com
.owncloud
.android
.operations
.RenameFileOperation
;
89 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
90 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
91 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
92 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
93 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
94 import com
.owncloud
.android
.ui
.adapter
.FileListListAdapter
;
95 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
96 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
97 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
98 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
99 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
100 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
104 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
105 import com
.owncloud
.android
.utils
.DisplayUtils
;
106 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
110 * Displays, what files the user has available in his ownCloud.
112 * @author Bartek Przybylski
113 * @author David A. Velasco
116 public class FileDisplayActivity
extends HookActivity
implements
117 FileFragment
.ContainerActivity
, OnNavigationListener
,
118 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
120 private ArrayAdapter
<String
> mDirectories
;
122 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
123 private UploadFinishReceiver mUploadFinishReceiver
;
124 private DownloadFinishReceiver mDownloadFinishReceiver
;
125 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
127 private boolean mDualPane
;
128 private View mLeftFragmentContainer
;
129 private View mRightFragmentContainer
;
131 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
132 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
133 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
135 public static final int DIALOG_SHORT_WAIT
= 0;
136 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
137 private static final int DIALOG_CERT_NOT_SAVED
= 2;
139 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
141 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
142 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
143 public static final int ACTION_MOVE_FILES
= 3;
145 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
147 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
148 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
150 private OCFile mWaitingToPreview
;
152 private boolean mSyncInProgress
= false
;
154 private String DIALOG_UNTRUSTED_CERT
;
156 private OCFile mWaitingToSend
;
159 protected void onCreate(Bundle savedInstanceState
) {
160 Log_OC
.d(TAG
, "onCreate() start");
161 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
163 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
165 // PIN CODE request ; best location is to decide, let's try this first
166 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
168 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
172 /// grant that FileObserverService is watching favourite files
173 if (savedInstanceState
== null
) {
174 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
175 startService(initObserversIntent
);
178 /// Load of saved instance state
179 if(savedInstanceState
!= null
) {
180 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
181 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
182 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
185 mWaitingToPreview
= null
;
186 mSyncInProgress
= false
;
187 mWaitingToSend
= null
;
192 // Inflate and set the layout view
193 setContentView(R
.layout
.files
);
194 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
195 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
196 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
197 if (savedInstanceState
== null
) {
198 createMinFragments();
202 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
203 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
204 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
208 Log_OC
.d(TAG
, "onCreate() end");
212 protected void onStart() {
214 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
218 protected void onDestroy() {
223 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
226 protected void onAccountSet(boolean stateWasRecovered
) {
227 super.onAccountSet(stateWasRecovered
);
228 if (getAccount() != null
) {
229 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
230 OCFile file
= getFile();
231 // get parent from path
232 String parentPath
= "";
234 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
235 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
236 // get parent from path
237 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
238 if (getStorageManager().getFileByPath(parentPath
) == null
)
239 file
= null
; // not able to know the directory where the file is uploading
241 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
245 // fall back to root folder
246 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
249 setNavigationListWithFolder(file
);
251 if (!stateWasRecovered
) {
252 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
253 initFragmentsWithFile();
254 if (file
.isFolder()) {
255 startSyncFolderOperation(file
, false
);
259 updateFragmentsVisibility(!file
.isFolder());
260 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
266 private void setNavigationListWithFolder(OCFile file
) {
267 mDirectories
.clear();
268 OCFile fileIt
= file
;
270 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
271 if (fileIt
.isFolder()) {
272 mDirectories
.add(fileIt
.getFileName());
274 // get parent from path
275 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
276 fileIt
= getStorageManager().getFileByPath(parentPath
);
278 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
282 private void createMinFragments() {
283 OCFileListFragment listOfFiles
= new OCFileListFragment();
284 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
285 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
286 transaction
.commit();
289 private void initFragmentsWithFile() {
290 if (getAccount() != null
&& getFile() != null
) {
292 OCFileListFragment listOfFiles
= getListOfFilesFragment();
293 if (listOfFiles
!= null
) {
294 listOfFiles
.listDirectory(getCurrentDir());
296 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
300 OCFile file
= getFile();
301 Fragment secondFragment
= chooseInitialSecondFragment(file
);
302 if (secondFragment
!= null
) {
303 setSecondFragment(secondFragment
);
304 updateFragmentsVisibility(true
);
305 updateNavigationElementsInActionBar(file
);
308 cleanSecondFragment();
312 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
313 if (getAccount() == null
) {
314 Log_OC
.wtf(TAG
, "\t account is NULL");
316 if (getFile() == null
) {
317 Log_OC
.wtf(TAG
, "\t file is NULL");
322 private Fragment
chooseInitialSecondFragment(OCFile file
) {
323 Fragment secondFragment
= null
;
324 if (file
!= null
&& !file
.isFolder()) {
325 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
326 && file
.getLastSyncDateForProperties() > 0 // temporal fix
328 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
329 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
330 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
333 secondFragment
= new FileDetailFragment(file
, getAccount());
336 return secondFragment
;
341 * Replaces the second fragment managed by the activity with the received as
344 * Assumes never will be more than two fragments managed at the same time.
346 * @param fragment New second Fragment to set.
348 private void setSecondFragment(Fragment fragment
) {
349 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
350 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
351 transaction
.commit();
355 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
357 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
358 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
360 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
361 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
364 } else if (existsSecondFragment
) {
365 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
366 mLeftFragmentContainer
.setVisibility(View
.GONE
);
368 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
369 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
373 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
374 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
376 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
377 mRightFragmentContainer
.setVisibility(View
.GONE
);
383 private OCFileListFragment
getListOfFilesFragment() {
384 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
385 if (listOfFiles
!= null
) {
386 return (OCFileListFragment
)listOfFiles
;
388 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
392 public FileFragment
getSecondFragment() {
393 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
394 if (second
!= null
) {
395 return (FileFragment
)second
;
400 protected void cleanSecondFragment() {
401 Fragment second
= getSecondFragment();
402 if (second
!= null
) {
403 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
407 updateFragmentsVisibility(false
);
408 updateNavigationElementsInActionBar(null
);
411 protected void refreshListOfFilesFragment() {
412 OCFileListFragment fileListFragment
= getListOfFilesFragment();
413 if (fileListFragment
!= null
) {
414 fileListFragment
.listDirectory();
418 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
419 FileFragment secondFragment
= getSecondFragment();
420 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
421 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
422 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
423 OCFile fileInFragment
= detailsFragment
.getFile();
424 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
425 // the user browsed to other file ; forget the automatic preview
426 mWaitingToPreview
= null
;
428 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
429 // grant that the right panel updates the progress bar
430 detailsFragment
.listenForTransferProgress();
431 detailsFragment
.updateFileDetails(true
, false
);
433 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
434 // update the right panel
435 boolean detailsFragmentChanged
= false
;
438 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
439 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
440 startMediaPreview(mWaitingToPreview
, 0, true
);
441 detailsFragmentChanged
= true
;
443 getFileOperationsHelper().openFile(mWaitingToPreview
);
446 mWaitingToPreview
= null
;
448 if (!detailsFragmentChanged
) {
449 detailsFragment
.updateFileDetails(false
, (success
));
456 public boolean onPrepareOptionsMenu(Menu menu
) {
457 if (BuildConfig
.DEBUG
) {
458 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
460 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
462 return super.onPrepareOptionsMenu(menu
);
466 public boolean onCreateOptionsMenu(Menu menu
) {
467 MenuInflater inflater
= getSherlock().getMenuInflater();
468 inflater
.inflate(R
.menu
.main_menu
, menu
);
473 public boolean onOptionsItemSelected(MenuItem item
) {
474 boolean retval
= true
;
475 switch (item
.getItemId()) {
476 case R
.id
.action_create_dir
: {
477 CreateFolderDialogFragment dialog
=
478 CreateFolderDialogFragment
.newInstance(getCurrentDir());
479 dialog
.show(getSupportFragmentManager(), "createdirdialog");
482 case R
.id
.action_sync_account
: {
483 startSynchronization();
486 case R
.id
.action_upload
: {
487 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
490 case R
.id
.action_settings
: {
491 Intent settingsIntent
= new Intent(this, Preferences
.class);
492 startActivity(settingsIntent
);
495 case R
.id
.action_logger
: {
496 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
497 startActivity(loggerIntent
);
500 case android
.R
.id
.home
: {
501 FileFragment second
= getSecondFragment();
502 OCFile currentDir
= getCurrentDir();
503 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
504 (second
!= null
&& second
.getFile() != null
)) {
510 case R
.id
.action_sort
: {
511 SharedPreferences appPreferences
= PreferenceManager
512 .getDefaultSharedPreferences(this);
514 // Read sorting order, default to sort by name ascending
515 Integer sortOrder
= appPreferences
516 .getInt("sortOrder", FileListListAdapter
.SORT_NAME
);
518 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
519 builder
.setTitle(R
.string
.actionbar_sort_title
)
520 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
521 public void onClick(DialogInterface dialog
, int which
) {
531 // TODO re-enable when server-side folder size calculation is available
533 // sortBySize(false);
541 builder
.create().show();
545 retval
= super.onOptionsItemSelected(item
);
550 private void startSynchronization() {
551 Log_OC
.e(TAG
, "Got to start sync");
552 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
553 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
554 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
555 Bundle bundle
= new Bundle();
556 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
557 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
558 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
559 ContentResolver
.requestSync(
561 MainApp
.getAuthority(), bundle
);
563 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
564 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
565 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
566 builder
.setExpedited(true
);
567 builder
.setManual(true
);
569 SyncRequest request
= builder
.build();
570 ContentResolver
.requestSync(request
);
576 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
577 if (itemPosition
!= 0) {
578 String targetPath
= "";
579 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
580 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
582 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
583 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
584 if (targetFolder
!= null
) {
585 browseTo(targetFolder
);
588 // the next operation triggers a new call to this method, but it's necessary to
589 // ensure that the name exposed in the action bar is the current directory when the
590 // user selected it in the navigation list
591 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
592 getSupportActionBar().setSelectedNavigationItem(0);
598 * Called, when the user selected something for uploading
601 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
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 //getClipData is only supported on api level 16+
607 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= 16){
608 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
609 Intent intent
= new Intent();
610 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
611 requestSimpleUpload(intent
, resultCode
);
614 requestSimpleUpload(data
, resultCode
);
616 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
617 requestMultipleUpload(data
, resultCode
);
619 } else if (requestCode
== ACTION_MOVE_FILES
&& (resultCode
== RESULT_OK
||
620 resultCode
== MoveActivity
.RESULT_OK_AND_MOVE
)){
622 final Intent fData
= data
;
623 final int fResultCode
= resultCode
;
624 getHandler().postDelayed(
628 requestMoveOperation(fData
, fResultCode
);
631 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
636 private void requestMultipleUpload(Intent data
, int resultCode
) {
637 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
638 if (filePaths
!= null
) {
639 String
[] remotePaths
= new String
[filePaths
.length
];
640 String remotePathBase
= "";
641 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
642 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
644 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
645 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
646 for (int j
= 0; j
< remotePaths
.length
; j
++) {
647 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
650 Intent i
= new Intent(this, FileUploader
.class);
651 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
652 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
653 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
654 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
655 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
656 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
660 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
661 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
668 private void requestSimpleUpload(Intent data
, int resultCode
) {
669 String filepath
= null
;
671 Uri selectedImageUri
= data
.getData();
673 String filemanagerstring
= selectedImageUri
.getPath();
674 String selectedImagePath
= getPath(selectedImageUri
);
676 if (selectedImagePath
!= null
)
677 filepath
= selectedImagePath
;
679 filepath
= filemanagerstring
;
681 } catch (Exception e
) {
682 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
686 if (filepath
== null
) {
687 Log_OC
.e(TAG
, "Couldnt resolve path to file");
688 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
694 Intent i
= new Intent(this, FileUploader
.class);
695 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
697 String remotepath
= new String();
698 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
699 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
701 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
702 remotepath
+= OCFile
.PATH_SEPARATOR
;
703 remotepath
+= new File(filepath
).getName();
705 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
706 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
707 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
708 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
709 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
714 * Request the operation for moving the file/folder from one path to another
716 * @param data Intent received
717 * @param resultCode Result code received
719 private void requestMoveOperation(Intent data
, int resultCode
) {
720 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
721 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
);
722 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
726 public void onBackPressed() {
727 OCFileListFragment listOfFiles
= getListOfFilesFragment();
728 if (mDualPane
|| getSecondFragment() == null
) {
729 if (listOfFiles
!= null
) { // should never be null, indeed
730 if (mDirectories
.getCount() <= 1) {
734 int levelsUp
= listOfFiles
.onBrowseUp();
735 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
740 if (listOfFiles
!= null
) { // should never be null, indeed
741 setFile(listOfFiles
.getCurrentFile());
743 cleanSecondFragment();
748 protected void onSaveInstanceState(Bundle outState
) {
749 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
750 Log_OC
.e(TAG
, "onSaveInstanceState() start");
751 super.onSaveInstanceState(outState
);
752 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
753 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
754 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
755 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
757 Log_OC
.d(TAG
, "onSaveInstanceState() end");
763 protected void onResume() {
765 Log_OC
.e(TAG
, "onResume() start");
767 // refresh list of files
768 refreshListOfFilesFragment();
770 // Listen for sync messages
771 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
772 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
773 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
774 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
775 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
776 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
777 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
778 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
780 // Listen for upload messages
781 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
782 mUploadFinishReceiver
= new UploadFinishReceiver();
783 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
785 // Listen for download messages
786 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
787 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
788 mDownloadFinishReceiver
= new DownloadFinishReceiver();
789 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
791 Log_OC
.d(TAG
, "onResume() end");
796 protected void onPause() {
797 Log_OC
.e(TAG
, "onPause() start");
798 if (mSyncBroadcastReceiver
!= null
) {
799 unregisterReceiver(mSyncBroadcastReceiver
);
800 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
801 mSyncBroadcastReceiver
= null
;
803 if (mUploadFinishReceiver
!= null
) {
804 unregisterReceiver(mUploadFinishReceiver
);
805 mUploadFinishReceiver
= null
;
807 if (mDownloadFinishReceiver
!= null
) {
808 unregisterReceiver(mDownloadFinishReceiver
);
809 mDownloadFinishReceiver
= null
;
813 Log_OC
.d(TAG
, "onPause() end");
819 protected Dialog
onCreateDialog(int id
) {
820 Dialog dialog
= null
;
821 AlertDialog
.Builder builder
;
823 case DIALOG_SHORT_WAIT
: {
824 ProgressDialog working_dialog
= new ProgressDialog(this);
825 working_dialog
.setMessage(getResources().getString(
826 R
.string
.wait_a_moment
));
827 working_dialog
.setIndeterminate(true
);
828 working_dialog
.setCancelable(false
);
829 dialog
= working_dialog
;
832 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
835 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
836 getString(R
.string
.actionbar_upload_from_apps
) };
838 builder
= new AlertDialog
.Builder(this);
839 builder
.setTitle(R
.string
.actionbar_upload
);
840 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
841 public void onClick(DialogInterface dialog
, int item
) {
844 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
845 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
846 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
848 // TODO create and handle new fragment
849 // LocalFileListFragment
851 } else if (item
== 1) {
852 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
853 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
854 //putExtra is only supported on api level 18+
855 if(Build
.VERSION
.SDK_INT
>= 18) {
856 action
.putExtra(Intent
.EXTRA_ALLOW_MULTIPLE
, true
);
858 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
859 ACTION_SELECT_CONTENT_FROM_APPS
);
863 dialog
= builder
.create();
866 case DIALOG_CERT_NOT_SAVED
: {
867 builder
= new AlertDialog
.Builder(this);
868 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
869 builder
.setCancelable(false
);
870 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
872 public void onClick(DialogInterface dialog
, int which
) {
876 dialog
= builder
.create();
888 * Translates a content URI of an image to a physical path
890 * @param uri The URI to resolve
891 * @return The path to the image or null if it could not be found
893 public String
getPath(Uri uri
) {
894 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
895 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
896 if (cursor
!= null
) {
897 int column_index
= cursor
898 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
899 cursor
.moveToFirst();
900 return cursor
.getString(column_index
);
906 * Pushes a directory to the drop down list
907 * @param directory to push
908 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
910 public void pushDirname(OCFile directory
) {
911 if(!directory
.isFolder()){
912 throw new IllegalArgumentException("Only directories may be pushed!");
914 mDirectories
.insert(directory
.getFileName(), 0);
919 * Pops a directory name from the drop down list
920 * @return True, unless the stack is empty
922 public boolean popDirname() {
923 mDirectories
.remove(mDirectories
.getItem(0));
924 return !mDirectories
.isEmpty();
927 // Custom array adapter to override text colors
928 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
930 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
934 public View
getView(int position
, View convertView
, ViewGroup parent
) {
935 View v
= super.getView(position
, convertView
, parent
);
937 ((TextView
) v
).setTextColor(getResources().getColorStateList(
938 android
.R
.color
.white
));
940 fixRoot((TextView
) v
);
944 public View
getDropDownView(int position
, View convertView
,
946 View v
= super.getDropDownView(position
, convertView
, parent
);
948 ((TextView
) v
).setTextColor(getResources().getColorStateList(
949 android
.R
.color
.white
));
951 fixRoot((TextView
) v
);
955 private void fixRoot(TextView v
) {
956 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
957 v
.setText(R
.string
.default_display_name_for_root_folder
);
963 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
966 * {@link BroadcastReceiver} to enable syncing feedback in UI
969 public void onReceive(Context context
, Intent intent
) {
971 String event
= intent
.getAction();
972 Log_OC
.d(TAG
, "Received broadcast " + event
);
973 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
974 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
975 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
976 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
980 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
981 mSyncInProgress
= true
;
984 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
985 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
987 if (currentDir
== null
) {
988 // current folder was removed from the server
989 Toast
.makeText( FileDisplayActivity
.this,
990 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
996 if (currentFile
== null
&& !getFile().isFolder()) {
997 // currently selected file was removed in the server, and now we know it
998 cleanSecondFragment();
999 currentFile
= currentDir
;
1002 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1003 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1004 if (fileListFragment
!= null
) {
1005 fileListFragment
.listDirectory(currentDir
);
1008 setFile(currentFile
);
1011 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1013 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1015 /// TODO refactor and make common
1016 synchResult
!= null
&& !synchResult
.isSuccess() &&
1017 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1018 synchResult
.isIdPRedirection() ||
1019 (synchResult
.isException() && synchResult
.getException()
1020 instanceof AuthenticatorException
))) {
1022 OwnCloudClient client
= null
;
1024 OwnCloudAccount ocAccount
=
1025 new OwnCloudAccount(getAccount(), context
);
1026 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1027 removeClientFor(ocAccount
));
1028 // TODO get rid of these exceptions
1029 } catch (AccountNotFoundException e
) {
1030 e
.printStackTrace();
1031 } catch (AuthenticatorException e
) {
1032 e
.printStackTrace();
1033 } catch (OperationCanceledException e
) {
1034 e
.printStackTrace();
1035 } catch (IOException e
) {
1036 e
.printStackTrace();
1039 if (client
!= null
) {
1040 OwnCloudCredentials cred
= client
.getCredentials();
1042 AccountManager am
= AccountManager
.get(context
);
1043 if (cred
.authTokenExpires()) {
1044 am
.invalidateAuthToken(
1049 am
.clearPassword(getAccount());
1054 requestCredentialsUpdate();
1058 removeStickyBroadcast(intent
);
1059 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1060 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1062 setBackgroundText();
1066 if (synchResult
!= null
) {
1067 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1068 mLastSslUntrustedServerResult
= synchResult
;
1071 } catch (RuntimeException e
) {
1072 // avoid app crashes after changing the serial id of RemoteOperationResult
1073 // in owncloud library with broadcast notifications pending to process
1074 removeStickyBroadcast(intent
);
1080 * Show a text message on screen view for notifying user if content is
1081 * loading or folder is empty
1083 private void setBackgroundText() {
1084 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1085 if (ocFileListFragment
!= null
) {
1086 int message
= R
.string
.file_list_loading
;
1087 if (!mSyncInProgress
) {
1088 // In case file list is empty
1089 message
= R
.string
.file_list_empty
;
1091 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1093 Log_OC
.e(TAG
, "OCFileListFragment is null");
1098 * Once the file upload has finished -> update view
1100 private class UploadFinishReceiver
extends BroadcastReceiver
{
1102 * Once the file upload has finished -> update view
1103 * @author David A. Velasco
1104 * {@link BroadcastReceiver} to enable upload feedback in UI
1107 public void onReceive(Context context
, Intent intent
) {
1109 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1110 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1111 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1112 OCFile currentDir
= getCurrentDir();
1113 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1114 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1116 if (sameAccount
&& isDescendant
) {
1117 refreshListOfFilesFragment();
1120 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1121 boolean renamedInUpload
= getFile().getRemotePath().
1122 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1123 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1125 FileFragment details
= getSecondFragment();
1126 boolean detailFragmentIsShown
= (details
!= null
&&
1127 details
instanceof FileDetailFragment
);
1129 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1130 if (uploadWasFine
) {
1131 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1133 if (renamedInUpload
) {
1134 String newName
= (new File(uploadedRemotePath
)).getName();
1135 Toast msg
= Toast
.makeText(
1138 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1143 if (uploadWasFine
|| getFile().fileExists()) {
1144 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1146 cleanSecondFragment();
1149 // Force the preview if the file is an image
1150 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1151 startImagePreview(getFile());
1152 } // TODO what about other kind of previews?
1156 if (intent
!= null
) {
1157 removeStickyBroadcast(intent
);
1167 * Class waiting for broadcast events from the {@link FielDownloader} service.
1169 * Updates the UI when a download is started or finished, provided that it is relevant for the
1172 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1174 public void onReceive(Context context
, Intent intent
) {
1176 boolean sameAccount
= isSameAccount(context
, intent
);
1177 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1178 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1180 if (sameAccount
&& isDescendant
) {
1181 refreshListOfFilesFragment();
1182 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1185 if (mWaitingToSend
!= null
) {
1186 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1187 if (mWaitingToSend
.isDown()) {
1188 sendDownloadedFile();
1193 if (intent
!= null
) {
1194 removeStickyBroadcast(intent
);
1199 private boolean isDescendant(String downloadedRemotePath
) {
1200 OCFile currentDir
= getCurrentDir();
1201 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1204 private boolean isSameAccount(Context context
, Intent intent
) {
1205 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1206 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1211 public void browseToRoot() {
1212 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1213 if (listOfFiles
!= null
) { // should never be null, indeed
1214 while (mDirectories
.getCount() > 1) {
1217 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1218 listOfFiles
.listDirectory(root
);
1219 setFile(listOfFiles
.getCurrentFile());
1220 startSyncFolderOperation(root
, false
);
1222 cleanSecondFragment();
1226 public void browseTo(OCFile folder
) {
1227 if (folder
== null
|| !folder
.isFolder()) {
1228 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1230 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1231 if (listOfFiles
!= null
) {
1232 setNavigationListWithFolder(folder
);
1233 listOfFiles
.listDirectory(folder
);
1234 setFile(listOfFiles
.getCurrentFile());
1235 startSyncFolderOperation(folder
, false
);
1237 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1239 cleanSecondFragment();
1246 * Updates action bar and second fragment, if in dual pane mode.
1249 public void onBrowsedDownTo(OCFile directory
) {
1250 pushDirname(directory
);
1251 cleanSecondFragment();
1254 startSyncFolderOperation(directory
, false
);
1259 * Shows the information of the {@link OCFile} received as a
1260 * parameter in the second fragment.
1262 * @param file {@link OCFile} whose details will be shown
1265 public void showDetails(OCFile file
) {
1266 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1267 setSecondFragment(detailFragment
);
1268 updateFragmentsVisibility(true
);
1269 updateNavigationElementsInActionBar(file
);
1277 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1278 ActionBar actionBar
= getSupportActionBar();
1279 if (chosenFile
== null
|| mDualPane
) {
1280 // only list of files - set for browsing through folders
1281 OCFile currentDir
= getCurrentDir();
1282 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1283 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1284 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1286 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1288 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1289 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1292 actionBar
.setDisplayHomeAsUpEnabled(true
);
1293 actionBar
.setDisplayShowTitleEnabled(true
);
1294 actionBar
.setTitle(chosenFile
.getFileName());
1295 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1301 protected ServiceConnection
newTransferenceServiceConnection() {
1302 return new ListServiceConnection();
1305 /** Defines callbacks for service binding, passed to bindService() */
1306 private class ListServiceConnection
implements ServiceConnection
{
1309 public void onServiceConnected(ComponentName component
, IBinder service
) {
1310 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1311 Log_OC
.d(TAG
, "Download service connected");
1312 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1313 if (mWaitingToPreview
!= null
)
1314 if (getStorageManager() != null
) {
1315 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1316 if (!mWaitingToPreview
.isDown()) {
1317 requestForDownload();
1321 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1322 Log_OC
.d(TAG
, "Upload service connected");
1323 mUploaderBinder
= (FileUploaderBinder
) service
;
1327 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1328 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1329 if (listOfFiles
!= null
) {
1330 listOfFiles
.listDirectory();
1332 FileFragment secondFragment
= getSecondFragment();
1333 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1334 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1335 detailFragment
.listenForTransferProgress();
1336 detailFragment
.updateFileDetails(false
, false
);
1341 public void onServiceDisconnected(ComponentName component
) {
1342 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1343 Log_OC
.d(TAG
, "Download service disconnected");
1344 mDownloaderBinder
= null
;
1345 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1346 Log_OC
.d(TAG
, "Upload service disconnected");
1347 mUploaderBinder
= null
;
1355 * Launch an intent to request the PIN code to the user before letting him use the app
1357 private void requestPinCode() {
1358 boolean pinStart
= false
;
1359 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1360 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1362 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1363 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1370 public void onSavedCertificate() {
1371 startSyncFolderOperation(getCurrentDir(), false
);
1376 public void onFailedSavingCertificate() {
1377 showDialog(DIALOG_CERT_NOT_SAVED
);
1381 public void onCancelCertificate() {
1386 * Updates the view associated to the activity after the finish of some operation over files
1387 * in the current account.
1389 * @param operation Removal operation performed.
1390 * @param result Result of the removal.
1393 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1394 super.onRemoteOperationFinish(operation
, result
);
1396 if (operation
instanceof RemoveFileOperation
) {
1397 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1399 } else if (operation
instanceof RenameFileOperation
) {
1400 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1402 } else if (operation
instanceof SynchronizeFileOperation
) {
1403 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1405 } else if (operation
instanceof CreateFolderOperation
) {
1406 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1408 } else if (operation
instanceof CreateShareOperation
) {
1409 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1411 } else if (operation
instanceof UnshareLinkOperation
) {
1412 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1414 } else if (operation
instanceof MoveFileOperation
) {
1415 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1421 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1422 if (result
.isSuccess()) {
1423 refreshShowDetails();
1424 refreshListOfFilesFragment();
1429 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1430 if (result
.isSuccess()) {
1431 refreshShowDetails();
1432 refreshListOfFilesFragment();
1434 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1435 cleanSecondFragment();
1436 refreshListOfFilesFragment();
1440 private void refreshShowDetails() {
1441 FileFragment details
= getSecondFragment();
1442 if (details
!= null
) {
1443 OCFile file
= details
.getFile();
1445 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1446 if (details
instanceof PreviewMediaFragment
) {
1447 // Refresh OCFile of the fragment
1448 ((PreviewMediaFragment
) details
).updateFile(file
);
1453 invalidateOptionsMenu();
1458 * Updates the view associated to the activity after the finish of an operation trying to remove a
1461 * @param operation Removal operation performed.
1462 * @param result Result of the removal.
1464 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1465 dismissLoadingDialog();
1467 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1471 if (result
.isSuccess()) {
1472 OCFile removedFile
= operation
.getFile();
1473 FileFragment second
= getSecondFragment();
1474 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1475 if (second
instanceof PreviewMediaFragment
) {
1476 ((PreviewMediaFragment
)second
).stopPreview(true
);
1478 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1479 cleanSecondFragment();
1481 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1482 refreshListOfFilesFragment();
1484 invalidateOptionsMenu();
1486 if (result
.isSslRecoverableException()) {
1487 mLastSslUntrustedServerResult
= result
;
1488 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1495 * Updates the view associated to the activity after the finish of an operation trying to move a
1498 * @param operation Move operation performed.
1499 * @param result Result of the move operation.
1501 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1502 if (result
.isSuccess()) {
1503 dismissLoadingDialog();
1504 refreshListOfFilesFragment();
1506 dismissLoadingDialog();
1508 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1509 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1513 } catch (NotFoundException e
) {
1514 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1521 * Updates the view associated to the activity after the finish of an operation trying to rename a
1524 * @param operation Renaming operation performed.
1525 * @param result Result of the renaming.
1527 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1528 dismissLoadingDialog();
1529 OCFile renamedFile
= operation
.getFile();
1530 if (result
.isSuccess()) {
1531 FileFragment details
= getSecondFragment();
1532 if (details
!= null
) {
1533 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1534 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1535 showDetails(renamedFile
);
1537 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1538 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1539 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1540 int position
= ((PreviewMediaFragment
)details
).getPosition();
1541 startMediaPreview(renamedFile
, position
, true
);
1543 getFileOperationsHelper().openFile(renamedFile
);
1548 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1549 refreshListOfFilesFragment();
1553 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1557 if (result
.isSslRecoverableException()) {
1558 mLastSslUntrustedServerResult
= result
;
1559 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1564 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1565 dismissLoadingDialog();
1566 OCFile syncedFile
= operation
.getLocalFile();
1567 if (!result
.isSuccess()) {
1568 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1569 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1570 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1571 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1577 if (operation
.transferWasRequested()) {
1578 onTransferStateChanged(syncedFile
, true
, true
);
1581 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1589 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1591 * @param operation Creation operation performed.
1592 * @param result Result of the creation.
1594 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1595 if (result
.isSuccess()) {
1596 dismissLoadingDialog();
1597 refreshListOfFilesFragment();
1599 dismissLoadingDialog();
1601 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1602 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1606 } catch (NotFoundException e
) {
1607 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1617 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1618 refreshListOfFilesFragment();
1619 FileFragment details
= getSecondFragment();
1620 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1621 if (downloading
|| uploading
) {
1622 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1624 if (!file
.fileExists()) {
1625 cleanSecondFragment();
1627 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1635 private void requestForDownload() {
1636 Account account
= getAccount();
1637 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1638 Intent i
= new Intent(this, FileDownloader
.class);
1639 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1640 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1646 private OCFile
getCurrentDir() {
1647 OCFile file
= getFile();
1649 if (file
.isFolder()) {
1651 } else if (getStorageManager() != null
) {
1652 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1653 return getStorageManager().getFileByPath(parentPath
);
1659 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1660 long currentSyncTime
= System
.currentTimeMillis();
1662 mSyncInProgress
= true
;
1664 // perform folder synchronization
1665 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1668 getFileOperationsHelper().isSharedSupported(),
1670 getStorageManager(),
1672 getApplicationContext()
1674 synchFolderOp
.execute(getAccount(), this, null
, null
);
1676 setSupportProgressBarIndeterminateVisibility(true
);
1678 setBackgroundText();
1682 * Show untrusted cert dialog
1684 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1685 // Show a dialog with the certificate info
1686 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1687 FragmentManager fm
= getSupportFragmentManager();
1688 FragmentTransaction ft
= fm
.beginTransaction();
1689 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1692 private void requestForDownload(OCFile file
) {
1693 Account account
= getAccount();
1694 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1695 Intent i
= new Intent(this, FileDownloader
.class);
1696 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1697 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1702 private void sendDownloadedFile(){
1703 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1704 mWaitingToSend
= null
;
1709 * Requests the download of the received {@link OCFile} , updates the UI
1710 * to monitor the download progress and prepares the activity to send the file
1711 * when the download finishes.
1713 * @param file {@link OCFile} to download and preview.
1715 public void startDownloadForSending(OCFile file
) {
1716 mWaitingToSend
= file
;
1717 requestForDownload(mWaitingToSend
);
1718 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1719 updateFragmentsVisibility(hasSecondFragment
);
1723 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1725 * @param file Image {@link OCFile} to show.
1727 public void startImagePreview(OCFile file
) {
1728 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1729 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1730 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1731 startActivity(showDetailsIntent
);
1736 * Stars the preview of an already down media {@link OCFile}.
1738 * @param file Media {@link OCFile} to preview.
1739 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1740 * @param autoplay When 'true', the playback will start without user interactions.
1742 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1743 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1744 setSecondFragment(mediaFragment
);
1745 updateFragmentsVisibility(true
);
1746 updateNavigationElementsInActionBar(file
);
1751 * Requests the download of the received {@link OCFile} , updates the UI
1752 * to monitor the download progress and prepares the activity to preview
1753 * or open the file when the download finishes.
1755 * @param file {@link OCFile} to download and preview.
1757 public void startDownloadForPreview(OCFile file
) {
1758 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1759 setSecondFragment(detailFragment
);
1760 mWaitingToPreview
= file
;
1761 requestForDownload();
1762 updateFragmentsVisibility(true
);
1763 updateNavigationElementsInActionBar(file
);
1768 public void cancelTransference(OCFile file
) {
1769 getFileOperationsHelper().cancelTransference(file
);
1770 if (mWaitingToPreview
!= null
&&
1771 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1772 mWaitingToPreview
= null
;
1774 if (mWaitingToSend
!= null
&&
1775 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1776 mWaitingToSend
= null
;
1778 onTransferStateChanged(file
, false
, false
);
1782 public void onRefresh(boolean ignoreETag
) {
1783 refreshList(ignoreETag
);
1787 public void onRefresh() {
1791 private void refreshList(boolean ignoreETag
) {
1792 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1793 if (listOfFiles
!= null
) {
1794 OCFile folder
= listOfFiles
.getCurrentFile();
1795 if (folder
!= null
) {
1796 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1797 listDirectory(mFile);*/
1798 startSyncFolderOperation(folder
, ignoreETag
);
1803 private void sortByDate(boolean ascending
){
1804 getListOfFilesFragment().sortByDate(ascending
);
1807 private void sortBySize(boolean ascending
){
1808 getListOfFilesFragment().sortBySize(ascending
);
1811 private void sortByName(boolean ascending
){
1812 getListOfFilesFragment().sortByName(ascending
);