2 * ownCloud Android client application
4 * @author Bartek Przybylski
5 * @author David A. Velasco
6 * Copyright (C) 2011 Bartek Przybylski
7 * Copyright (C) 2015 ownCloud Inc.
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2,
11 * as published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 package com
.owncloud
.android
.ui
.activity
;
25 import android
.accounts
.Account
;
26 import android
.accounts
.AccountManager
;
27 import android
.accounts
.AuthenticatorException
;
28 import android
.annotation
.TargetApi
;
29 import android
.app
.AlertDialog
;
30 import android
.content
.BroadcastReceiver
;
31 import android
.content
.ComponentName
;
32 import android
.content
.ContentResolver
;
33 import android
.content
.Context
;
34 import android
.content
.DialogInterface
;
35 import android
.content
.Intent
;
36 import android
.content
.IntentFilter
;
37 import android
.content
.ServiceConnection
;
38 import android
.content
.SharedPreferences
;
39 import android
.content
.SyncRequest
;
40 import android
.content
.res
.Resources
.NotFoundException
;
41 import android
.database
.Cursor
;
42 import android
.net
.Uri
;
43 import android
.os
.Build
;
44 import android
.os
.Bundle
;
45 import android
.os
.IBinder
;
46 import android
.preference
.PreferenceManager
;
47 import android
.provider
.OpenableColumns
;
48 import android
.support
.v4
.app
.Fragment
;
49 import android
.support
.v4
.app
.FragmentManager
;
50 import android
.support
.v4
.app
.FragmentTransaction
;
51 import android
.support
.v4
.view
.GravityCompat
;
52 import android
.view
.Menu
;
53 import android
.view
.MenuInflater
;
54 import android
.view
.MenuItem
;
55 import android
.view
.View
;
56 import android
.widget
.ProgressBar
;
57 import android
.widget
.RelativeLayout
;
58 import android
.widget
.TextView
;
59 import android
.widget
.Toast
;
61 import com
.owncloud
.android
.MainApp
;
62 import com
.owncloud
.android
.R
;
63 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
64 import com
.owncloud
.android
.datamodel
.OCFile
;
65 import com
.owncloud
.android
.files
.services
.FileDownloader
;
66 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
67 import com
.owncloud
.android
.files
.services
.FileUploader
;
68 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
69 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
70 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
73 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
74 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
75 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
76 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
78 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
79 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
80 import com
.owncloud
.android
.operations
.CreateShareOperation
;
81 import com
.owncloud
.android
.operations
.MoveFileOperation
;
82 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
83 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
84 import com
.owncloud
.android
.operations
.RenameFileOperation
;
85 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
86 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
87 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
88 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
89 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
90 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
91 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
92 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
93 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
94 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
95 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
96 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
97 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
101 import com
.owncloud
.android
.utils
.DisplayUtils
;
102 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
103 import com
.owncloud
.android
.utils
.FileStorageUtils
;
104 import com
.owncloud
.android
.utils
.UriUtils
;
110 * Displays, what files the user has available in his ownCloud.
113 public class FileDisplayActivity
extends HookActivity
114 implements FileFragment
.ContainerActivity
,
115 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
117 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
118 private UploadFinishReceiver mUploadFinishReceiver
;
119 private DownloadFinishReceiver mDownloadFinishReceiver
;
120 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
122 private boolean mDualPane
;
123 private View mLeftFragmentContainer
;
124 private View mRightFragmentContainer
;
125 private ProgressBar mProgressBar
;
127 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
128 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
129 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
131 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
133 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
134 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
135 public static final int ACTION_MOVE_FILES
= 3;
137 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
139 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
140 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
142 private OCFile mWaitingToPreview
;
144 private boolean mSyncInProgress
= false
;
146 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
147 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
148 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
149 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
151 private OCFile mWaitingToSend
;
155 protected void onCreate(Bundle savedInstanceState
) {
156 Log_OC
.v(TAG
, "onCreate() start");
157 //requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
159 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
162 /// grant that FileObserverService is watching favorite files
163 if (savedInstanceState
== null
) {
164 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
165 startService(initObserversIntent
);
168 /// Load of saved instance state
169 if(savedInstanceState
!= null
) {
170 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
171 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
172 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
173 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
174 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
177 mWaitingToPreview
= null
;
178 mSyncInProgress
= false
;
179 mWaitingToSend
= null
;
184 // Inflate and set the layout view
185 setContentView(R
.layout
.files
);
190 mProgressBar
= (ProgressBar
) findViewById(R
.id
.progressBar
);
192 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
193 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
194 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
195 if (savedInstanceState
== null
) {
196 createMinFragments();
200 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
201 // according to the official
204 // enable ActionBar app icon to behave as action to toggle nav drawer
205 //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
206 getSupportActionBar().setHomeButtonEnabled(true
);
208 mProgressBar
.setVisibility((mSyncInProgress
) ? View
.VISIBLE
: View
.INVISIBLE
);
209 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
210 /*|| mRefreshSharesInProgress*/ //);
211 // always AFTER setContentView(...) ; to work around bug in its implementation
217 Log_OC
.v(TAG
, "onCreate() end");
221 protected void onStart() {
222 Log_OC
.v(TAG
, "onStart() start");
224 Log_OC
.v(TAG
, "onStart() end");
228 protected void onDestroy() {
229 Log_OC
.v(TAG
, "onDestroy() start");
231 Log_OC
.v(TAG
, "onDestroy() end");
235 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
238 protected void onAccountSet(boolean stateWasRecovered
) {
239 super.onAccountSet(stateWasRecovered
);
240 if (getAccount() != null
) {
241 /// Check whether the 'main' OCFile handled by the Activity is contained in the
243 OCFile file
= getFile();
244 // get parent from path
245 String parentPath
= "";
247 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
248 // upload in progress - right now, files are not inserted in the local
249 // cache until the upload is successful get parent from path
250 parentPath
= file
.getRemotePath().substring(0,
251 file
.getRemotePath().lastIndexOf(file
.getFileName()));
252 if (getStorageManager().getFileByPath(parentPath
) == null
)
253 file
= null
; // not able to know the directory where the file is uploading
255 file
= getStorageManager().getFileByPath(file
.getRemotePath());
256 // currentDir = null if not in the current Account
260 // fall back to root folder
261 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
265 if (mAccountWasSet
) {
266 RelativeLayout navigationDrawerLayout
= (RelativeLayout
) findViewById(R
.id
.left_drawer
);
267 if (navigationDrawerLayout
!= null
&& getAccount() != null
) {
268 TextView username
= (TextView
) navigationDrawerLayout
.findViewById(R
.id
.drawer_username
);
269 int lastAtPos
= getAccount().name
.lastIndexOf("@");
270 username
.setText(getAccount().name
.substring(0, lastAtPos
));
274 if (!stateWasRecovered
) {
275 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
276 initFragmentsWithFile();
277 if (file
.isFolder()) {
278 startSyncFolderOperation(file
, false
);
282 updateFragmentsVisibility(!file
.isFolder());
283 updateActionBarTitleAndHomeButton(file
.isFolder() ? null
: file
);
289 private void createMinFragments() {
290 OCFileListFragment listOfFiles
= new OCFileListFragment();
291 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
292 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
293 transaction
.commit();
296 private void initFragmentsWithFile() {
297 if (getAccount() != null
&& getFile() != null
) {
299 OCFileListFragment listOfFiles
= getListOfFilesFragment();
300 if (listOfFiles
!= null
) {
301 listOfFiles
.listDirectory(getCurrentDir());
302 // TODO Enable when "On Device" is recovered
303 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
305 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
309 OCFile file
= getFile();
310 Fragment secondFragment
= chooseInitialSecondFragment(file
);
311 if (secondFragment
!= null
) {
312 setSecondFragment(secondFragment
);
313 updateFragmentsVisibility(true
);
314 updateActionBarTitleAndHomeButton(file
);
317 cleanSecondFragment();
321 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
322 if (getAccount() == null
) {
323 Log_OC
.wtf(TAG
, "\t account is NULL");
325 if (getFile() == null
) {
326 Log_OC
.wtf(TAG
, "\t file is NULL");
331 private Fragment
chooseInitialSecondFragment(OCFile file
) {
332 Fragment secondFragment
= null
;
333 if (file
!= null
&& !file
.isFolder()) {
334 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
335 && file
.getLastSyncDateForProperties() > 0 // temporal fix
337 int startPlaybackPosition
=
338 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
340 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
341 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
342 startPlaybackPosition
, autoplay
);
345 secondFragment
= FileDetailFragment
.newInstance(file
, getAccount());
348 return secondFragment
;
353 * Replaces the second fragment managed by the activity with the received as
356 * Assumes never will be more than two fragments managed at the same time.
358 * @param fragment New second Fragment to set.
360 private void setSecondFragment(Fragment fragment
) {
361 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
362 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
363 transaction
.commit();
367 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
369 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
370 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
372 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
373 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
376 } else if (existsSecondFragment
) {
377 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
378 mLeftFragmentContainer
.setVisibility(View
.GONE
);
380 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
381 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
385 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
386 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
388 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
389 mRightFragmentContainer
.setVisibility(View
.GONE
);
395 private OCFileListFragment
getListOfFilesFragment() {
396 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
397 FileDisplayActivity
.TAG_LIST_OF_FILES
);
398 if (listOfFiles
!= null
) {
399 return (OCFileListFragment
)listOfFiles
;
401 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
405 public FileFragment
getSecondFragment() {
406 Fragment second
= getSupportFragmentManager().findFragmentByTag(
407 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
408 if (second
!= null
) {
409 return (FileFragment
)second
;
414 protected void cleanSecondFragment() {
415 Fragment second
= getSecondFragment();
416 if (second
!= null
) {
417 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
421 updateFragmentsVisibility(false
);
422 updateActionBarTitleAndHomeButton(null
);
425 protected void refreshListOfFilesFragment() {
426 OCFileListFragment fileListFragment
= getListOfFilesFragment();
427 if (fileListFragment
!= null
) {
428 fileListFragment
.listDirectory();
429 // TODO Enable when "On Device" is recovered ?
430 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
434 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
436 FileFragment secondFragment
= getSecondFragment();
437 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
438 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
439 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
440 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
441 OCFile fileInFragment
= detailsFragment
.getFile();
442 if (fileInFragment
!= null
&&
443 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
444 // the user browsed to other file ; forget the automatic preview
445 mWaitingToPreview
= null
;
447 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
448 // grant that the right panel updates the progress bar
449 detailsFragment
.listenForTransferProgress();
450 detailsFragment
.updateFileDetails(true
, false
);
452 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
453 // update the right panel
454 boolean detailsFragmentChanged
= false
;
457 mWaitingToPreview
= getStorageManager().getFileById(
458 mWaitingToPreview
.getFileId()); // update the file from database,
459 // for the local storage path
460 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
461 startMediaPreview(mWaitingToPreview
, 0, true
);
462 detailsFragmentChanged
= true
;
464 getFileOperationsHelper().openFile(mWaitingToPreview
);
467 mWaitingToPreview
= null
;
469 if (!detailsFragmentChanged
) {
470 detailsFragment
.updateFileDetails(false
, (success
));
477 public boolean onPrepareOptionsMenu(Menu menu
) {
478 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
479 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
480 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
481 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
482 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
484 return super.onPrepareOptionsMenu(menu
);
488 public boolean onCreateOptionsMenu(Menu menu
) {
489 MenuInflater inflater
= getMenuInflater();
490 inflater
.inflate(R
.menu
.main_menu
, menu
);
496 public boolean onOptionsItemSelected(MenuItem item
) {
497 boolean retval
= true
;
498 switch (item
.getItemId()) {
499 case R
.id
.action_create_dir
: {
500 CreateFolderDialogFragment dialog
=
501 CreateFolderDialogFragment
.newInstance(getCurrentDir());
502 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
505 case R
.id
.action_sync_account
: {
506 startSynchronization();
509 case R
.id
.action_upload
: {
510 UploadSourceDialogFragment dialog
=
511 UploadSourceDialogFragment
.newInstance(getAccount());
512 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
516 case android
.R
.id
.home
: {
517 FileFragment second
= getSecondFragment();
518 OCFile currentDir
= getCurrentDir();
519 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
520 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
521 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
522 (second
!= null
&& second
.getFile() != null
)) {
526 mDrawerLayout
.openDrawer(GravityCompat
.START
);
530 case R
.id
.action_sort
: {
531 SharedPreferences appPreferences
= PreferenceManager
532 .getDefaultSharedPreferences(this);
534 // Read sorting order, default to sort by name ascending
535 Integer sortOrder
= appPreferences
536 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
538 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
539 builder
.setTitle(R
.string
.actionbar_sort_title
)
540 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
541 new DialogInterface
.OnClickListener() {
542 public void onClick(DialogInterface dialog
, int which
) {
555 builder
.create().show();
559 retval
= super.onOptionsItemSelected(item
);
564 private void startSynchronization() {
565 Log_OC
.d(TAG
, "Got to start sync");
566 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
567 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
568 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
569 // cancel the current synchronizations of any ownCloud account
570 Bundle bundle
= new Bundle();
571 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
572 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
573 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
574 MainApp
.getAuthority());
575 ContentResolver
.requestSync(
577 MainApp
.getAuthority(), bundle
);
579 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
580 MainApp
.getAuthority() + " with new API");
581 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
582 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
583 builder
.setExpedited(true
);
584 builder
.setManual(true
);
587 // Fix bug in Android Lollipop when you click on refresh the whole account
588 Bundle extras
= new Bundle();
589 builder
.setExtras(extras
);
591 SyncRequest request
= builder
.build();
592 ContentResolver
.requestSync(request
);
597 * Called, when the user selected something for uploading
600 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
602 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
604 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
605 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
606 //getClipData is only supported on api level 16+, Jelly Bean
607 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
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
||
617 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
618 requestMultipleUpload(data
, resultCode
);
620 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
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
635 super.onActivityResult(requestCode
, resultCode
, data
);
640 private void requestMultipleUpload(Intent data
, int resultCode
) {
641 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
642 if (filePaths
!= null
) {
643 String
[] remotePaths
= new String
[filePaths
.length
];
644 String remotePathBase
= getCurrentDir().getRemotePath();
645 for (int j
= 0; j
< remotePaths
.length
; j
++) {
646 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
649 Intent i
= new Intent(this, FileUploader
.class);
650 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
651 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
652 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
653 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
654 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
655 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
659 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
660 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
668 private void requestSimpleUpload(Intent data
, int resultCode
) {
669 String filePath
= null
;
670 String mimeType
= null
;
672 Uri selectedImageUri
= data
.getData();
675 mimeType
= getContentResolver().getType(selectedImageUri
);
677 String fileManagerString
= selectedImageUri
.getPath();
678 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
680 if (selectedImagePath
!= null
)
681 filePath
= selectedImagePath
;
683 filePath
= fileManagerString
;
685 } catch (Exception e
) {
686 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
687 "Intent.ACTION_GET_CONTENT", e
);
690 if (filePath
== null
) {
691 Log_OC
.e(TAG
, "Couldn't resolve path to file");
692 Toast t
= Toast
.makeText(
693 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
701 Intent i
= new Intent(this, FileUploader
.class);
702 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
703 OCFile currentDir
= getCurrentDir();
704 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
706 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
707 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
709 if (cursor
!= null
&& cursor
.moveToFirst()) {
710 String displayName
= cursor
.getString(cursor
.getColumnIndex(
711 OpenableColumns
.DISPLAY_NAME
));
712 Log_OC
.v(TAG
, "Display Name: " + displayName
);
714 displayName
.replace(File
.separatorChar
, '_');
715 displayName
.replace(File
.pathSeparatorChar
, '_');
716 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
719 // and what happens in case of error?; wrong target name for the upload
725 remotePath
+= new File(filePath
).getName();
728 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
729 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
730 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
731 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
732 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
733 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
738 * Request the operation for moving the file/folder from one path to another
740 * @param data Intent received
741 * @param resultCode Result code received
743 private void requestMoveOperation(Intent data
, int resultCode
) {
744 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
745 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
746 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
750 public void onBackPressed() {
751 if (!isDrawerOpen()){
752 OCFileListFragment listOfFiles
= getListOfFilesFragment();
753 if (mDualPane
|| getSecondFragment() == null
) {
754 OCFile currentDir
= getCurrentDir();
755 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
759 if (listOfFiles
!= null
) { // should never be null, indeed
760 listOfFiles
.onBrowseUp();
763 if (listOfFiles
!= null
) { // should never be null, indeed
764 setFile(listOfFiles
.getCurrentFile());
766 cleanSecondFragment();
768 super.onBackPressed();
773 protected void onSaveInstanceState(Bundle outState
) {
774 // responsibility of restore is preferred in onCreate() before than in
775 // onRestoreInstanceState when there are Fragments involved
776 Log_OC
.v(TAG
, "onSaveInstanceState() start");
777 super.onSaveInstanceState(outState
);
778 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
779 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
780 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
781 // mRefreshSharesInProgress);
782 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
784 Log_OC
.v(TAG
, "onSaveInstanceState() end");
790 protected void onResume() {
791 Log_OC
.v(TAG
, "onResume() start");
794 // refresh Navigation Drawer account list
795 mNavigationDrawerAdapter
.updateAccountList();
798 // refresh list of files
799 refreshListOfFilesFragment();
801 // Listen for sync messages
802 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
803 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
804 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
805 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
806 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
807 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
808 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
809 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
810 // syncIntentFilter);
812 // Listen for upload messages
813 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
814 mUploadFinishReceiver
= new UploadFinishReceiver();
815 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
817 // Listen for download messages
818 IntentFilter downloadIntentFilter
= new IntentFilter(
819 FileDownloader
.getDownloadAddedMessage());
820 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
821 mDownloadFinishReceiver
= new DownloadFinishReceiver();
822 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
824 Log_OC
.v(TAG
, "onResume() end");
829 protected void onPause() {
830 Log_OC
.v(TAG
, "onPause() start");
831 if (mSyncBroadcastReceiver
!= null
) {
832 unregisterReceiver(mSyncBroadcastReceiver
);
833 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
834 mSyncBroadcastReceiver
= null
;
836 if (mUploadFinishReceiver
!= null
) {
837 unregisterReceiver(mUploadFinishReceiver
);
838 mUploadFinishReceiver
= null
;
840 if (mDownloadFinishReceiver
!= null
) {
841 unregisterReceiver(mDownloadFinishReceiver
);
842 mDownloadFinishReceiver
= null
;
846 Log_OC
.v(TAG
, "onPause() end");
850 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
853 * {@link BroadcastReceiver} to enable syncing feedback in UI
856 public void onReceive(Context context
, Intent intent
) {
858 String event
= intent
.getAction();
859 Log_OC
.d(TAG
, "Received broadcast " + event
);
860 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
861 String synchFolderRemotePath
=
862 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
863 RemoteOperationResult synchResult
=
864 (RemoteOperationResult
)intent
.getSerializableExtra(
865 FileSyncAdapter
.EXTRA_RESULT
);
866 boolean sameAccount
= (getAccount() != null
&&
867 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
871 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
872 mSyncInProgress
= true
;
875 OCFile currentFile
= (getFile() == null
) ? null
:
876 getStorageManager().getFileByPath(getFile().getRemotePath());
877 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
878 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
880 if (currentDir
== null
) {
881 // current folder was removed from the server
882 Toast
.makeText( FileDisplayActivity
.this,
885 sync_current_folder_was_removed
),
886 synchFolderRemotePath
),
892 if (currentFile
== null
&& !getFile().isFolder()) {
893 // currently selected file was removed in the server, and now we
895 cleanSecondFragment();
896 currentFile
= currentDir
;
899 if (synchFolderRemotePath
!= null
&&
900 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
901 OCFileListFragment fileListFragment
= getListOfFilesFragment();
902 if (fileListFragment
!= null
) {
903 fileListFragment
.listDirectory();
904 // TODO Enable when "On Device" is recovered ?
905 // fileListFragment.listDirectory(currentDir,
906 // MainApp.getOnlyOnDevice());
909 setFile(currentFile
);
912 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
913 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
916 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
918 /// TODO refactor and make common
919 synchResult
!= null
&& !synchResult
.isSuccess() &&
920 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
921 synchResult
.isIdPRedirection() ||
922 (synchResult
.isException() && synchResult
.getException()
923 instanceof AuthenticatorException
))) {
927 OwnCloudClient client
;
928 OwnCloudAccount ocAccount
=
929 new OwnCloudAccount(getAccount(), context
);
930 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
931 removeClientFor(ocAccount
));
933 if (client
!= null
) {
934 OwnCloudCredentials cred
= client
.getCredentials();
936 AccountManager am
= AccountManager
.get(context
);
937 if (cred
.authTokenExpires()) {
938 am
.invalidateAuthToken(
943 am
.clearPassword(getAccount());
947 requestCredentialsUpdate();
949 } catch (AccountNotFoundException e
) {
950 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
955 removeStickyBroadcast(intent
);
956 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
957 mProgressBar
.setVisibility((mSyncInProgress
) ? View
.VISIBLE
: View
.INVISIBLE
);
958 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
959 /*|| mRefreshSharesInProgress*/ //);
965 if (synchResult
!= null
) {
966 if (synchResult
.getCode().equals(
967 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
968 mLastSslUntrustedServerResult
= synchResult
;
971 } catch (RuntimeException e
) {
972 // avoid app crashes after changing the serial id of RemoteOperationResult
973 // in owncloud library with broadcast notifications pending to process
974 removeStickyBroadcast(intent
);
980 * Show a text message on screen view for notifying user if content is
981 * loading or folder is empty
983 private void setBackgroundText() {
984 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
985 if (ocFileListFragment
!= null
) {
986 int message
= R
.string
.file_list_loading
;
987 if (!mSyncInProgress
) {
988 // In case file list is empty
989 message
= R
.string
.file_list_empty
;
991 ocFileListFragment
.setMessageForEmptyList(getString(message
));
993 Log_OC
.e(TAG
, "OCFileListFragment is null");
998 * Once the file upload has finished -> update view
1000 private class UploadFinishReceiver
extends BroadcastReceiver
{
1002 * Once the file upload has finished -> update view
1003 * @author David A. Velasco
1004 * {@link BroadcastReceiver} to enable upload feedback in UI
1007 public void onReceive(Context context
, Intent intent
) {
1009 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1010 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1011 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1012 OCFile currentDir
= getCurrentDir();
1013 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1014 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1016 if (sameAccount
&& isDescendant
) {
1017 refreshListOfFilesFragment();
1020 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1022 boolean renamedInUpload
= getFile().getRemotePath().
1023 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1024 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1026 FileFragment details
= getSecondFragment();
1027 boolean detailFragmentIsShown
= (details
!= null
&&
1028 details
instanceof FileDetailFragment
);
1030 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1031 if (uploadWasFine
) {
1032 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1034 if (renamedInUpload
) {
1035 String newName
= (new File(uploadedRemotePath
)).getName();
1036 Toast msg
= Toast
.makeText(
1039 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1044 if (uploadWasFine
|| getFile().fileExists()) {
1045 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1047 cleanSecondFragment();
1050 // Force the preview if the file is an image
1051 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1052 startImagePreview(getFile());
1053 } // TODO what about other kind of previews?
1056 //setSupportProgressBarIndeterminate(false);
1057 mProgressBar
.setVisibility(View
.INVISIBLE
);
1060 if (intent
!= null
) {
1061 removeStickyBroadcast(intent
);
1071 * Class waiting for broadcast events from the {@link FileDownloader} service.
1073 * Updates the UI when a download is started or finished, provided that it is relevant for the
1076 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1078 //int refreshCounter = 0;
1080 public void onReceive(Context context
, Intent intent
) {
1082 boolean sameAccount
= isSameAccount(context
, intent
);
1083 String downloadedRemotePath
=
1084 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1085 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1087 if (sameAccount
&& isDescendant
) {
1088 String linkedToRemotePath
=
1089 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1090 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1091 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1092 refreshListOfFilesFragment();
1094 refreshSecondFragment(
1096 downloadedRemotePath
,
1097 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1101 if (mWaitingToSend
!= null
) {
1103 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1104 if (mWaitingToSend
.isDown()) {
1105 sendDownloadedFile();
1110 if (intent
!= null
) {
1111 removeStickyBroadcast(intent
);
1116 private boolean isDescendant(String downloadedRemotePath
) {
1117 OCFile currentDir
= getCurrentDir();
1119 currentDir
!= null
&&
1120 downloadedRemotePath
!= null
&&
1121 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1125 private boolean isAscendant(String linkedToRemotePath
) {
1126 OCFile currentDir
= getCurrentDir();
1128 currentDir
!= null
&&
1129 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1133 private boolean isSameAccount(Context context
, Intent intent
) {
1134 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1135 return (accountName
!= null
&& getAccount() != null
&&
1136 accountName
.equals(getAccount().name
));
1141 public void browseToRoot() {
1142 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1143 if (listOfFiles
!= null
) { // should never be null, indeed
1144 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1145 listOfFiles
.listDirectory(root
);
1146 // TODO Enable when "On Device" is recovered ?
1147 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1148 setFile(listOfFiles
.getCurrentFile());
1149 startSyncFolderOperation(root
, false
);
1151 cleanSecondFragment();
1159 * Updates action bar and second fragment, if in dual pane mode.
1162 public void onBrowsedDownTo(OCFile directory
) {
1164 cleanSecondFragment();
1166 startSyncFolderOperation(directory
, false
);
1170 * Shows the information of the {@link OCFile} received as a
1171 * parameter in the second fragment.
1173 * @param file {@link OCFile} whose details will be shown
1176 public void showDetails(OCFile file
) {
1177 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1178 setSecondFragment(detailFragment
);
1179 updateFragmentsVisibility(true
);
1180 updateActionBarTitleAndHomeButton(file
);
1185 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1187 // in dual pane mode, keep the focus of title an action bar in the current folder
1188 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1191 super.updateActionBarTitleAndHomeButton(chosenFile
);
1197 protected ServiceConnection
newTransferenceServiceConnection() {
1198 return new ListServiceConnection();
1201 /** Defines callbacks for service binding, passed to bindService() */
1202 private class ListServiceConnection
implements ServiceConnection
{
1205 public void onServiceConnected(ComponentName component
, IBinder service
) {
1206 if (component
.equals(new ComponentName(
1207 FileDisplayActivity
.this, FileDownloader
.class))) {
1208 Log_OC
.d(TAG
, "Download service connected");
1209 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1210 if (mWaitingToPreview
!= null
)
1211 if (getStorageManager() != null
) {
1214 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1215 if (!mWaitingToPreview
.isDown()) {
1216 requestForDownload();
1220 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1221 FileUploader
.class))) {
1222 Log_OC
.d(TAG
, "Upload service connected");
1223 mUploaderBinder
= (FileUploaderBinder
) service
;
1227 // a new chance to get the mDownloadBinder through
1228 // getFileDownloadBinder() - THIS IS A MESS
1229 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1230 if (listOfFiles
!= null
) {
1231 listOfFiles
.listDirectory();
1232 // TODO Enable when "On Device" is recovered ?
1233 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1235 FileFragment secondFragment
= getSecondFragment();
1236 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1237 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1238 detailFragment
.listenForTransferProgress();
1239 detailFragment
.updateFileDetails(false
, false
);
1244 public void onServiceDisconnected(ComponentName component
) {
1245 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1246 FileDownloader
.class))) {
1247 Log_OC
.d(TAG
, "Download service disconnected");
1248 mDownloaderBinder
= null
;
1249 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1250 FileUploader
.class))) {
1251 Log_OC
.d(TAG
, "Upload service disconnected");
1252 mUploaderBinder
= null
;
1258 public void onSavedCertificate() {
1259 startSyncFolderOperation(getCurrentDir(), false
);
1264 public void onFailedSavingCertificate() {
1265 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1266 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1268 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1272 public void onCancelCertificate() {
1277 * Updates the view associated to the activity after the finish of some operation over files
1278 * in the current account.
1280 * @param operation Removal operation performed.
1281 * @param result Result of the removal.
1284 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1285 super.onRemoteOperationFinish(operation
, result
);
1287 if (operation
instanceof RemoveFileOperation
) {
1288 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1290 } else if (operation
instanceof RenameFileOperation
) {
1291 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1293 } else if (operation
instanceof SynchronizeFileOperation
) {
1294 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1296 } else if (operation
instanceof CreateFolderOperation
) {
1297 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1299 } else if (operation
instanceof CreateShareOperation
) {
1300 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1302 } else if (operation
instanceof UnshareLinkOperation
) {
1303 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1305 } else if (operation
instanceof MoveFileOperation
) {
1306 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1312 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1313 RemoteOperationResult result
) {
1314 if (result
.isSuccess()) {
1315 refreshShowDetails();
1316 refreshListOfFilesFragment();
1321 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1322 RemoteOperationResult result
) {
1323 if (result
.isSuccess()) {
1324 refreshShowDetails();
1325 refreshListOfFilesFragment();
1327 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1328 cleanSecondFragment();
1329 refreshListOfFilesFragment();
1333 private void refreshShowDetails() {
1334 FileFragment details
= getSecondFragment();
1335 if (details
!= null
) {
1336 OCFile file
= details
.getFile();
1338 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1339 if (details
instanceof PreviewMediaFragment
) {
1340 // Refresh OCFile of the fragment
1341 ((PreviewMediaFragment
) details
).updateFile(file
);
1346 invalidateOptionsMenu();
1351 * Updates the view associated to the activity after the finish of an operation trying to
1354 * @param operation Removal operation performed.
1355 * @param result Result of the removal.
1357 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1358 RemoteOperationResult result
) {
1359 dismissLoadingDialog();
1361 Toast msg
= Toast
.makeText(this,
1362 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1366 if (result
.isSuccess()) {
1367 OCFile removedFile
= operation
.getFile();
1368 FileFragment second
= getSecondFragment();
1369 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1370 if (second
instanceof PreviewMediaFragment
) {
1371 ((PreviewMediaFragment
)second
).stopPreview(true
);
1373 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1374 cleanSecondFragment();
1376 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1377 refreshListOfFilesFragment();
1379 invalidateOptionsMenu();
1381 if (result
.isSslRecoverableException()) {
1382 mLastSslUntrustedServerResult
= result
;
1383 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1390 * Updates the view associated to the activity after the finish of an operation trying to move a
1393 * @param operation Move operation performed.
1394 * @param result Result of the move operation.
1396 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1397 RemoteOperationResult result
) {
1398 if (result
.isSuccess()) {
1399 dismissLoadingDialog();
1400 refreshListOfFilesFragment();
1402 dismissLoadingDialog();
1404 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1405 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1409 } catch (NotFoundException e
) {
1410 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1417 * Updates the view associated to the activity after the finish of an operation trying to rename
1420 * @param operation Renaming operation performed.
1421 * @param result Result of the renaming.
1423 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1424 RemoteOperationResult result
) {
1425 dismissLoadingDialog();
1426 OCFile renamedFile
= operation
.getFile();
1427 if (result
.isSuccess()) {
1428 FileFragment details
= getSecondFragment();
1429 if (details
!= null
) {
1430 if (details
instanceof FileDetailFragment
&&
1431 renamedFile
.equals(details
.getFile()) ) {
1432 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1433 showDetails(renamedFile
);
1435 } else if (details
instanceof PreviewMediaFragment
&&
1436 renamedFile
.equals(details
.getFile())) {
1437 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1438 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1439 int position
= ((PreviewMediaFragment
)details
).getPosition();
1440 startMediaPreview(renamedFile
, position
, true
);
1442 getFileOperationsHelper().openFile(renamedFile
);
1447 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1448 refreshListOfFilesFragment();
1452 Toast msg
= Toast
.makeText(this,
1453 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1457 if (result
.isSslRecoverableException()) {
1458 mLastSslUntrustedServerResult
= result
;
1459 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1464 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1465 RemoteOperationResult result
) {
1466 dismissLoadingDialog();
1467 OCFile syncedFile
= operation
.getLocalFile();
1468 if (!result
.isSuccess()) {
1469 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1470 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1471 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1472 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1478 if (operation
.transferWasRequested()) {
1479 onTransferStateChanged(syncedFile
, true
, true
);
1482 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
,
1483 operation
, getResources()), Toast
.LENGTH_LONG
);
1486 invalidateOptionsMenu();
1491 * Updates the view associated to the activity after the finish of an operation trying create a
1494 * @param operation Creation operation performed.
1495 * @param result Result of the creation.
1497 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1498 RemoteOperationResult result
) {
1499 if (result
.isSuccess()) {
1500 dismissLoadingDialog();
1501 refreshListOfFilesFragment();
1503 dismissLoadingDialog();
1505 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1506 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1510 } catch (NotFoundException e
) {
1511 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1521 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1522 refreshListOfFilesFragment();
1523 FileFragment details
= getSecondFragment();
1524 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1525 file
.equals(details
.getFile()) ) {
1526 if (downloading
|| uploading
) {
1527 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1529 if (!file
.fileExists()) {
1530 cleanSecondFragment();
1532 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1540 private void requestForDownload() {
1541 Account account
= getAccount();
1542 //if (!mWaitingToPreview.isDownloading()) {
1543 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1544 Intent i
= new Intent(this, FileDownloader
.class);
1545 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1546 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1552 private OCFile
getCurrentDir() {
1553 OCFile file
= getFile();
1555 if (file
.isFolder()) {
1557 } else if (getStorageManager() != null
) {
1558 String parentPath
= file
.getRemotePath().substring(0,
1559 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1560 return getStorageManager().getFileByPath(parentPath
);
1566 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1567 long currentSyncTime
= System
.currentTimeMillis();
1569 mSyncInProgress
= true
;
1571 // perform folder synchronization
1572 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1575 getFileOperationsHelper().isSharedSupported(),
1577 getStorageManager(),
1579 getApplicationContext()
1581 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1583 mProgressBar
.setVisibility(View
.VISIBLE
);
1584 //setSupportProgressBarIndeterminateVisibility(true);
1586 setBackgroundText();
1590 * Show untrusted cert dialog
1592 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1593 // Show a dialog with the certificate info
1594 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1595 (CertificateCombinedException
) result
.getException());
1596 FragmentManager fm
= getSupportFragmentManager();
1597 FragmentTransaction ft
= fm
.beginTransaction();
1598 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1601 private void requestForDownload(OCFile file
) {
1602 Account account
= getAccount();
1603 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1604 Intent i
= new Intent(this, FileDownloader
.class);
1605 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1606 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1611 private void sendDownloadedFile(){
1612 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1613 mWaitingToSend
= null
;
1618 * Requests the download of the received {@link OCFile} , updates the UI
1619 * to monitor the download progress and prepares the activity to send the file
1620 * when the download finishes.
1622 * @param file {@link OCFile} to download and preview.
1624 public void startDownloadForSending(OCFile file
) {
1625 mWaitingToSend
= file
;
1626 requestForDownload(mWaitingToSend
);
1627 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1628 updateFragmentsVisibility(hasSecondFragment
);
1632 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1634 * @param file Image {@link OCFile} to show.
1636 public void startImagePreview(OCFile file
) {
1637 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1638 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1639 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1640 startActivity(showDetailsIntent
);
1645 * Stars the preview of an already down media {@link OCFile}.
1647 * @param file Media {@link OCFile} to preview.
1648 * @param startPlaybackPosition Media position where the playback will be started,
1650 * @param autoplay When 'true', the playback will start without user
1653 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1654 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1656 setSecondFragment(mediaFragment
);
1657 updateFragmentsVisibility(true
);
1658 updateActionBarTitleAndHomeButton(file
);
1663 * Requests the download of the received {@link OCFile} , updates the UI
1664 * to monitor the download progress and prepares the activity to preview
1665 * or open the file when the download finishes.
1667 * @param file {@link OCFile} to download and preview.
1669 public void startDownloadForPreview(OCFile file
) {
1670 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1671 setSecondFragment(detailFragment
);
1672 mWaitingToPreview
= file
;
1673 requestForDownload();
1674 updateFragmentsVisibility(true
);
1675 updateActionBarTitleAndHomeButton(file
);
1680 public void cancelTransference(OCFile file
) {
1681 getFileOperationsHelper().cancelTransference(file
);
1682 if (mWaitingToPreview
!= null
&&
1683 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1684 mWaitingToPreview
= null
;
1686 if (mWaitingToSend
!= null
&&
1687 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1688 mWaitingToSend
= null
;
1690 onTransferStateChanged(file
, false
, false
);
1694 public void onRefresh(boolean ignoreETag
) {
1695 refreshList(ignoreETag
);
1699 public void onRefresh() {
1703 private void refreshList(boolean ignoreETag
) {
1704 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1705 if (listOfFiles
!= null
) {
1706 OCFile folder
= listOfFiles
.getCurrentFile();
1707 if (folder
!= null
) {
1708 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1709 listDirectory(mFile);*/
1710 startSyncFolderOperation(folder
, ignoreETag
);
1715 private void sortByDate(boolean ascending
){
1716 getListOfFilesFragment().sortByDate(ascending
);
1719 private void sortBySize(boolean ascending
){
1720 getListOfFilesFragment().sortBySize(ascending
);
1723 private void sortByName(boolean ascending
){
1724 getListOfFilesFragment().sortByName(ascending
);
1727 public void allFilesOption() {