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
.view
.Window
;
57 import android
.widget
.Toast
;
59 import com
.owncloud
.android
.MainApp
;
60 import com
.owncloud
.android
.R
;
61 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
62 import com
.owncloud
.android
.datamodel
.OCFile
;
63 import com
.owncloud
.android
.files
.services
.FileDownloader
;
64 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
65 import com
.owncloud
.android
.files
.services
.FileUploader
;
66 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
67 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
68 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
69 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
70 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
71 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
72 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
73 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
74 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
75 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
76 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
77 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
78 import com
.owncloud
.android
.operations
.CreateShareOperation
;
79 import com
.owncloud
.android
.operations
.MoveFileOperation
;
80 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
81 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
82 import com
.owncloud
.android
.operations
.RenameFileOperation
;
83 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
84 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
85 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
86 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
87 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
88 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
89 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
90 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
91 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
92 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
93 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
94 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
95 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
96 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
97 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewTextFragment
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
100 import com
.owncloud
.android
.utils
.DisplayUtils
;
101 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
102 import com
.owncloud
.android
.utils
.FileStorageUtils
;
103 import com
.owncloud
.android
.utils
.UriUtils
;
107 import java
.io
.IOException
;
112 * Displays, what files the user has available in his ownCloud.
115 public class FileDisplayActivity
extends HookActivity
116 implements FileFragment
.ContainerActivity
,
117 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
121 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
122 private UploadFinishReceiver mUploadFinishReceiver
;
123 private DownloadFinishReceiver mDownloadFinishReceiver
;
124 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
126 private boolean mDualPane
;
127 private View mLeftFragmentContainer
;
128 private View mRightFragmentContainer
;
130 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
131 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
132 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
134 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
136 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
137 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
138 public static final int ACTION_MOVE_FILES
= 3;
140 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
142 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
143 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
145 private OCFile mWaitingToPreview
;
147 private boolean mSyncInProgress
= false
;
149 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
150 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
151 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
152 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
154 private OCFile mWaitingToSend
;
158 protected void onCreate(Bundle savedInstanceState
) {
159 Log_OC
.v(TAG
, "onCreate() start");
160 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
162 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
165 /// grant that FileObserverService is watching favorite files
166 if (savedInstanceState
== null
) {
167 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
168 startService(initObserversIntent
);
171 /// Load of saved instance state
172 if(savedInstanceState
!= null
) {
173 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
174 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
175 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
176 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
177 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
179 mWaitingToPreview
= null
;
180 mSyncInProgress
= false
;
181 mWaitingToSend
= null
;
186 // Inflate and set the layout view
187 setContentView(R
.layout
.files
);
191 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
192 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
193 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
194 if (savedInstanceState
== null
) {
195 createMinFragments();
199 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
200 // according to the official
203 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
204 /*|| mRefreshSharesInProgress*/);
205 // always AFTER setContentView(...) ; to work around bug in its implementation
209 Log_OC
.v(TAG
, "onCreate() end");
213 protected void onStart() {
214 Log_OC
.v(TAG
, "onStart() start");
216 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
217 Log_OC
.v(TAG
, "onStart() end");
221 protected void onDestroy() {
222 Log_OC
.v(TAG
, "onDestroy() start");
224 Log_OC
.v(TAG
, "onDestroy() end");
228 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
231 protected void onAccountSet(boolean stateWasRecovered
) {
232 super.onAccountSet(stateWasRecovered
);
233 if (getAccount() != null
) {
234 /// Check whether the 'main' OCFile handled by the Activity is contained in the
236 OCFile file
= getFile();
237 // get parent from path
238 String parentPath
= "";
240 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
241 // upload in progress - right now, files are not inserted in the local
242 // cache until the upload is successful get parent from path
243 parentPath
= file
.getRemotePath().substring(0,
244 file
.getRemotePath().lastIndexOf(file
.getFileName()));
245 if (getStorageManager().getFileByPath(parentPath
) == null
)
246 file
= null
; // not able to know the directory where the file is uploading
248 file
= getStorageManager().getFileByPath(file
.getRemotePath());
249 // currentDir = null if not in the current Account
253 // fall back to root folder
254 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
258 if (!stateWasRecovered
) {
259 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
260 initFragmentsWithFile();
261 if (file
.isFolder()) {
262 startSyncFolderOperation(file
, false
);
266 updateFragmentsVisibility(!file
.isFolder());
267 updateActionBarTitleAndHomeButton(file
.isFolder() ? null
: file
);
272 private void createMinFragments() {
273 OCFileListFragment listOfFiles
= new OCFileListFragment();
274 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
275 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
276 transaction
.commit();
279 private void initFragmentsWithFile() {
280 if (getAccount() != null
&& getFile() != null
) {
282 OCFileListFragment listOfFiles
= getListOfFilesFragment();
283 if (listOfFiles
!= null
) {
284 listOfFiles
.listDirectory(getCurrentDir());
285 // TODO Enable when "On Device" is recovered
286 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
289 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
293 OCFile file
= getFile();
294 Fragment secondFragment
= chooseInitialSecondFragment(file
);
295 if (secondFragment
!= null
) {
296 setSecondFragment(secondFragment
);
297 updateFragmentsVisibility(true
);
298 updateActionBarTitleAndHomeButton(file
);
301 cleanSecondFragment();
302 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
))
303 startTextPreview(file
);
307 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
308 if (getAccount() == null
) {
309 Log_OC
.wtf(TAG
, "\t account is NULL");
311 if (getFile() == null
) {
312 Log_OC
.wtf(TAG
, "\t file is NULL");
317 private Fragment
chooseInitialSecondFragment(OCFile file
) {
318 Fragment secondFragment
= null
;
319 if (file
!= null
&& !file
.isFolder()) {
320 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
321 && file
.getLastSyncDateForProperties() > 0 // temporal fix
323 int startPlaybackPosition
=
324 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
326 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
327 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
328 startPlaybackPosition
, autoplay
);
330 } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) {
331 secondFragment
= null
;
333 secondFragment
= FileDetailFragment
.newInstance(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(
385 FileDisplayActivity
.TAG_LIST_OF_FILES
);
386 if (listOfFiles
!= null
) {
387 return (OCFileListFragment
) listOfFiles
;
389 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
393 public FileFragment
getSecondFragment() {
394 Fragment second
= getSupportFragmentManager().findFragmentByTag(
395 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
396 if (second
!= null
) {
397 return (FileFragment
) second
;
402 protected void cleanSecondFragment() {
403 Fragment second
= getSecondFragment();
404 if (second
!= null
) {
405 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
409 updateFragmentsVisibility(false
);
410 updateActionBarTitleAndHomeButton(null
);
413 protected void refreshListOfFilesFragment() {
414 OCFileListFragment fileListFragment
= getListOfFilesFragment();
415 if (fileListFragment
!= null
) {
416 fileListFragment
.listDirectory();
417 // TODO Enable when "On Device" is recovered ?
418 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
422 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
424 FileFragment secondFragment
= getSecondFragment();
425 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
426 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
427 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
428 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
429 OCFile fileInFragment
= detailsFragment
.getFile();
430 if (fileInFragment
!= null
&&
431 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
432 // the user browsed to other file ; forget the automatic preview
433 mWaitingToPreview
= null
;
435 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
436 // grant that the right panel updates the progress bar
437 detailsFragment
.listenForTransferProgress();
438 detailsFragment
.updateFileDetails(true
, false
);
440 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
441 // update the right panel
442 boolean detailsFragmentChanged
= false
;
445 mWaitingToPreview
= getStorageManager().getFileById(
446 mWaitingToPreview
.getFileId()); // update the file from database,
447 // for the local storage path
448 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
449 startMediaPreview(mWaitingToPreview
, 0, true
);
450 detailsFragmentChanged
= true
;
451 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
452 startTextPreview(mWaitingToPreview
);
453 detailsFragmentChanged
= true
;
455 getFileOperationsHelper().openFile(mWaitingToPreview
);
458 mWaitingToPreview
= null
;
460 if (!detailsFragmentChanged
) {
461 detailsFragment
.updateFileDetails(false
, (success
));
468 public boolean onPrepareOptionsMenu(Menu menu
) {
469 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
470 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
471 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
472 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
473 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
475 return super.onPrepareOptionsMenu(menu
);
479 public boolean onCreateOptionsMenu(Menu menu
) {
480 MenuInflater inflater
= getMenuInflater();
481 inflater
.inflate(R
.menu
.main_menu
, menu
);
487 public boolean onOptionsItemSelected(MenuItem item
) {
488 boolean retval
= true
;
489 switch (item
.getItemId()) {
490 case R
.id
.action_create_dir
: {
491 CreateFolderDialogFragment dialog
=
492 CreateFolderDialogFragment
.newInstance(getCurrentDir());
493 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
497 case R
.id
.action_sync_account
: {
498 startSynchronization();
501 case R
.id
.action_upload
: {
502 UploadSourceDialogFragment dialog
=
503 UploadSourceDialogFragment
.newInstance(getAccount());
504 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
507 case android
.R
.id
.home
: {
508 FileFragment second
= getSecondFragment();
509 OCFile currentDir
= getCurrentDir();
510 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
511 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
512 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
513 (second
!= null
&& second
.getFile() != null
)) {
517 mDrawerLayout
.openDrawer(GravityCompat
.START
);
521 case R
.id
.action_sort
: {
522 SharedPreferences appPreferences
= PreferenceManager
523 .getDefaultSharedPreferences(this);
525 // Read sorting order, default to sort by name ascending
526 Integer sortOrder
= appPreferences
527 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
529 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
530 builder
.setTitle(R
.string
.actionbar_sort_title
)
531 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
532 new DialogInterface
.OnClickListener() {
533 public void onClick(DialogInterface dialog
, int which
) {
546 builder
.create().show();
550 retval
= super.onOptionsItemSelected(item
);
555 private void startSynchronization() {
556 Log_OC
.d(TAG
, "Got to start sync");
557 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
558 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
559 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
560 // cancel the current synchronizations of any ownCloud account
561 Bundle bundle
= new Bundle();
562 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
563 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
564 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
565 MainApp
.getAuthority());
566 ContentResolver
.requestSync(
568 MainApp
.getAuthority(), bundle
);
570 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
571 MainApp
.getAuthority() + " with new API");
572 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
573 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
574 builder
.setExpedited(true
);
575 builder
.setManual(true
);
578 // Fix bug in Android Lollipop when you click on refresh the whole account
579 Bundle extras
= new Bundle();
580 builder
.setExtras(extras
);
582 SyncRequest request
= builder
.build();
583 ContentResolver
.requestSync(request
);
588 * Called, when the user selected something for uploading
591 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
593 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
595 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
596 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
597 //getClipData is only supported on api level 16+, Jelly Bean
598 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
599 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
600 Intent intent
= new Intent();
601 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
602 requestSimpleUpload(intent
, resultCode
);
605 requestSimpleUpload(data
, resultCode
);
607 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
608 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
609 requestMultipleUpload(data
, resultCode
);
611 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
) {
613 final Intent fData
= data
;
614 final int fResultCode
= resultCode
;
615 getHandler().postDelayed(
619 requestMoveOperation(fData
, fResultCode
);
622 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
626 super.onActivityResult(requestCode
, resultCode
, data
);
631 private void requestMultipleUpload(Intent data
, int resultCode
) {
632 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
633 if (filePaths
!= null
) {
634 String
[] remotePaths
= new String
[filePaths
.length
];
635 String remotePathBase
= getCurrentDir().getRemotePath();
636 for (int j
= 0; j
< remotePaths
.length
; j
++) {
637 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
640 Intent i
= new Intent(this, FileUploader
.class);
641 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
642 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
643 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
644 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
645 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
646 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
650 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
651 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
659 private void requestSimpleUpload(Intent data
, int resultCode
) {
660 String filePath
= null
;
661 String mimeType
= null
;
663 Uri selectedImageUri
= data
.getData();
666 mimeType
= getContentResolver().getType(selectedImageUri
);
668 String fileManagerString
= selectedImageUri
.getPath();
669 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
671 if (selectedImagePath
!= null
)
672 filePath
= selectedImagePath
;
674 filePath
= fileManagerString
;
676 } catch (Exception e
) {
677 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
678 "Intent.ACTION_GET_CONTENT", e
);
681 if (filePath
== null
) {
682 Log_OC
.e(TAG
, "Couldn't resolve path to file");
683 Toast t
= Toast
.makeText(
684 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
692 Intent i
= new Intent(this, FileUploader
.class);
693 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
694 OCFile currentDir
= getCurrentDir();
695 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
697 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
698 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
700 if (cursor
!= null
&& cursor
.moveToFirst()) {
701 String displayName
= cursor
.getString(cursor
.getColumnIndex(
702 OpenableColumns
.DISPLAY_NAME
));
703 Log_OC
.v(TAG
, "Display Name: " + displayName
);
705 displayName
.replace(File
.separatorChar
, '_');
706 displayName
.replace(File
.pathSeparatorChar
, '_');
707 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
710 // and what happens in case of error?; wrong target name for the upload
716 remotePath
+= new File(filePath
).getName();
719 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
720 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
721 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
722 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
723 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
724 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
729 * Request the operation for moving the file/folder from one path to another
731 * @param data Intent received
732 * @param resultCode Result code received
734 private void requestMoveOperation(Intent data
, int resultCode
) {
735 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
736 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
737 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
741 public void onBackPressed() {
742 OCFileListFragment listOfFiles
= getListOfFilesFragment();
743 if (mDualPane
|| getSecondFragment() == null
) {
744 OCFile currentDir
= getCurrentDir();
745 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
749 if (listOfFiles
!= null
) { // should never be null, indeed
750 listOfFiles
.onBrowseUp();
753 if (listOfFiles
!= null
) { // should never be null, indeed
754 setFile(listOfFiles
.getCurrentFile());
756 cleanSecondFragment();
761 protected void onSaveInstanceState(Bundle outState
) {
762 // responsibility of restore is preferred in onCreate() before than in
763 // onRestoreInstanceState when there are Fragments involved
764 Log_OC
.v(TAG
, "onSaveInstanceState() start");
765 super.onSaveInstanceState(outState
);
766 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
767 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
768 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
769 // mRefreshSharesInProgress);
770 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
772 Log_OC
.v(TAG
, "onSaveInstanceState() end");
777 protected void onResume() {
778 Log_OC
.v(TAG
, "onResume() start");
780 // refresh Navigation Drawer account list
781 mNavigationDrawerAdapter
.updateAccountList();
783 // refresh list of files
784 refreshListOfFilesFragment();
786 // Listen for sync messages
787 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
788 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
789 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
790 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
791 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
792 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
793 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
794 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
795 // syncIntentFilter);
797 // Listen for upload messages
798 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
799 mUploadFinishReceiver
= new UploadFinishReceiver();
800 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
802 // Listen for download messages
803 IntentFilter downloadIntentFilter
= new IntentFilter(
804 FileDownloader
.getDownloadAddedMessage());
805 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
806 mDownloadFinishReceiver
= new DownloadFinishReceiver();
807 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
808 Log_OC
.v(TAG
, "onResume() end");
814 protected void onPause() {
815 Log_OC
.v(TAG
, "onPause() start");
816 if (mSyncBroadcastReceiver
!= null
) {
817 unregisterReceiver(mSyncBroadcastReceiver
);
818 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
819 mSyncBroadcastReceiver
= null
;
821 if (mUploadFinishReceiver
!= null
) {
822 unregisterReceiver(mUploadFinishReceiver
);
823 mUploadFinishReceiver
= null
;
825 if (mDownloadFinishReceiver
!= null
) {
826 unregisterReceiver(mDownloadFinishReceiver
);
827 mDownloadFinishReceiver
= null
;
831 Log_OC
.v(TAG
, "onPause() end");
835 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
838 * {@link BroadcastReceiver} to enable syncing feedback in UI
841 public void onReceive(Context context
, Intent intent
) {
843 String event
= intent
.getAction();
844 Log_OC
.d(TAG
, "Received broadcast " + event
);
845 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
846 String synchFolderRemotePath
=
847 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
848 RemoteOperationResult synchResult
=
849 (RemoteOperationResult
)intent
.getSerializableExtra(
850 FileSyncAdapter
.EXTRA_RESULT
);
851 boolean sameAccount
= (getAccount() != null
&&
852 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
856 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
857 mSyncInProgress
= true
;
860 OCFile currentFile
= (getFile() == null
) ? null
:
861 getStorageManager().getFileByPath(getFile().getRemotePath());
862 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
863 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
865 if (currentDir
== null
) {
866 // current folder was removed from the server
867 Toast
.makeText( FileDisplayActivity
.this,
870 sync_current_folder_was_removed
),
871 synchFolderRemotePath
),
878 if (currentFile
== null
&& !getFile().isFolder()) {
879 // currently selected file was removed in the server, and now we
881 cleanSecondFragment();
882 currentFile
= currentDir
;
885 if (synchFolderRemotePath
!= null
&&
886 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
887 OCFileListFragment fileListFragment
= getListOfFilesFragment();
888 if (fileListFragment
!= null
) {
889 fileListFragment
.listDirectory();
890 // TODO Enable when "On Device" is recovered ?
891 // fileListFragment.listDirectory(currentDir,
892 // MainApp.getOnlyOnDevice());
895 setFile(currentFile
);
898 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
899 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
902 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
903 equals(event
) &&/// TODO refactor and make common
904 synchResult
!= null
&& !synchResult
.isSuccess() &&
905 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
906 synchResult
.isIdPRedirection() ||
907 (synchResult
.isException() && synchResult
.getException()
908 instanceof AuthenticatorException
))) {
912 OwnCloudClient client
;
913 OwnCloudAccount ocAccount
=
914 new OwnCloudAccount(getAccount(), context
);
915 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
916 removeClientFor(ocAccount
));
917 if (client
!= null
) {
918 OwnCloudCredentials cred
= client
.getCredentials();
920 AccountManager am
= AccountManager
.get(context
);
921 if (cred
.authTokenExpires()) {
922 am
.invalidateAuthToken(
927 am
.clearPassword(getAccount());
931 requestCredentialsUpdate();
933 } catch (AccountNotFoundException e
) {
934 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
939 removeStickyBroadcast(intent
);
940 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
941 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
942 /*|| mRefreshSharesInProgress*/);
948 if (synchResult
!= null
) {
949 if (synchResult
.getCode().equals(
950 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
951 mLastSslUntrustedServerResult
= synchResult
;
954 } catch (RuntimeException e
) {
955 // avoid app crashes after changing the serial id of RemoteOperationResult
956 // in owncloud library with broadcast notifications pending to process
957 removeStickyBroadcast(intent
);
963 * Show a text message on screen view for notifying user if content is
964 * loading or folder is empty
966 private void setBackgroundText() {
967 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
968 if (ocFileListFragment
!= null
) {
969 int message
= R
.string
.file_list_loading
;
970 if (!mSyncInProgress
) {
971 // In case file list is empty
972 message
= R
.string
.file_list_empty
;
974 ocFileListFragment
.setMessageForEmptyList(getString(message
));
976 Log_OC
.e(TAG
, "OCFileListFragment is null");
981 * Once the file upload has finished -> update view
983 private class UploadFinishReceiver
extends BroadcastReceiver
{
985 * Once the file upload has finished -> update view
987 * @author David A. Velasco
988 * {@link BroadcastReceiver} to enable upload feedback in UI
991 public void onReceive(Context context
, Intent intent
) {
993 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
994 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
995 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
996 OCFile currentDir
= getCurrentDir();
997 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
998 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1000 if (sameAccount
&& isDescendant
) {
1001 refreshListOfFilesFragment();
1003 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1005 boolean renamedInUpload
= getFile().getRemotePath().
1006 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1007 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1009 FileFragment details
= getSecondFragment();
1010 boolean detailFragmentIsShown
= (details
!= null
&&
1011 details
instanceof FileDetailFragment
);
1013 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1014 if (uploadWasFine
) {
1015 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1017 if (renamedInUpload
) {
1018 String newName
= (new File(uploadedRemotePath
)).getName();
1019 Toast msg
= Toast
.makeText(
1022 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1027 if (uploadWasFine
|| getFile().fileExists()) {
1028 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1030 cleanSecondFragment();
1033 // Force the preview if the file is an image or text file
1034 if (uploadWasFine
) {
1035 OCFile ocFile
= getFile();
1036 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1037 startImagePreview(getFile());
1038 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1039 startTextPreview(ocFile
);
1040 // TODO what about other kind of previews?
1045 if (intent
!= null
) {
1046 removeStickyBroadcast(intent
);
1056 * Class waiting for broadcast events from the {@link FileDownloader} service.
1058 * Updates the UI when a download is started or finished, provided that it is relevant for the
1061 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1063 //int refreshCounter = 0;
1065 public void onReceive(Context context
, Intent intent
) {
1067 boolean sameAccount
= isSameAccount(context
, intent
);
1068 String downloadedRemotePath
=
1069 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1070 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1072 if (sameAccount
&& isDescendant
) {
1073 String linkedToRemotePath
=
1074 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1075 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1076 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1077 refreshListOfFilesFragment();
1079 refreshSecondFragment(
1081 downloadedRemotePath
,
1082 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1086 if (mWaitingToSend
!= null
) {
1088 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1089 if (mWaitingToSend
.isDown()) {
1090 sendDownloadedFile();
1095 if (intent
!= null
) {
1096 removeStickyBroadcast(intent
);
1101 private boolean isDescendant(String downloadedRemotePath
) {
1102 OCFile currentDir
= getCurrentDir();
1104 currentDir
!= null
&&
1105 downloadedRemotePath
!= null
&&
1106 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1110 private boolean isAscendant(String linkedToRemotePath
) {
1111 OCFile currentDir
= getCurrentDir();
1113 currentDir
!= null
&&
1114 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1118 private boolean isSameAccount(Context context
, Intent intent
) {
1119 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1120 return (accountName
!= null
&& getAccount() != null
&&
1121 accountName
.equals(getAccount().name
));
1126 public void browseToRoot() {
1127 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1128 if (listOfFiles
!= null
) { // should never be null, indeed
1129 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1130 listOfFiles
.listDirectory(root
);
1131 // TODO Enable when "On Device" is recovered ?
1132 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1133 setFile(listOfFiles
.getCurrentFile());
1134 startSyncFolderOperation(root
, false
);
1136 cleanSecondFragment();
1143 * Updates action bar and second fragment, if in dual pane mode.
1146 public void onBrowsedDownTo(OCFile directory
) {
1148 cleanSecondFragment();
1150 startSyncFolderOperation(directory
, false
);
1154 * Shows the information of the {@link OCFile} received as a
1155 * parameter in the second fragment.
1157 * @param file {@link OCFile} whose details will be shown
1160 public void showDetails(OCFile file
) {
1161 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1162 setSecondFragment(detailFragment
);
1163 updateFragmentsVisibility(true
);
1164 updateActionBarTitleAndHomeButton(file
);
1169 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1171 // in dual pane mode, keep the focus of title an action bar in the current folder
1172 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1175 super.updateActionBarTitleAndHomeButton(chosenFile
);
1182 protected ServiceConnection
newTransferenceServiceConnection() {
1183 return new ListServiceConnection();
1187 * Defines callbacks for service binding, passed to bindService()
1189 private class ListServiceConnection
implements ServiceConnection
{
1192 public void onServiceConnected(ComponentName component
, IBinder service
) {
1193 if (component
.equals(new ComponentName(
1194 FileDisplayActivity
.this, FileDownloader
.class))) {
1195 Log_OC
.d(TAG
, "Download service connected");
1196 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1197 if (mWaitingToPreview
!= null
)
1198 if (getStorageManager() != null
) {
1201 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1202 if (!mWaitingToPreview
.isDown()) {
1203 requestForDownload();
1207 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1208 FileUploader
.class))) {
1209 Log_OC
.d(TAG
, "Upload service connected");
1210 mUploaderBinder
= (FileUploaderBinder
) service
;
1214 // a new chance to get the mDownloadBinder through
1215 // getFileDownloadBinder() - THIS IS A MESS
1216 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1217 if (listOfFiles
!= null
) {
1218 listOfFiles
.listDirectory();
1219 // TODO Enable when "On Device" is recovered ?
1220 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1222 FileFragment secondFragment
= getSecondFragment();
1223 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1224 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1225 detailFragment
.listenForTransferProgress();
1226 detailFragment
.updateFileDetails(false
, false
);
1231 public void onServiceDisconnected(ComponentName component
) {
1232 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1233 FileDownloader
.class))) {
1234 Log_OC
.d(TAG
, "Download service disconnected");
1235 mDownloaderBinder
= null
;
1236 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1237 FileUploader
.class))) {
1238 Log_OC
.d(TAG
, "Upload service disconnected");
1239 mUploaderBinder
= null
;
1245 public void onSavedCertificate() {
1246 startSyncFolderOperation(getCurrentDir(), false
);
1251 public void onFailedSavingCertificate() {
1252 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1253 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1255 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1259 public void onCancelCertificate() {
1264 * Updates the view associated to the activity after the finish of some operation over files
1265 * in the current account.
1267 * @param operation Removal operation performed.
1268 * @param result Result of the removal.
1271 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1272 super.onRemoteOperationFinish(operation
, result
);
1274 if (operation
instanceof RemoveFileOperation
) {
1275 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1277 } else if (operation
instanceof RenameFileOperation
) {
1278 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1280 } else if (operation
instanceof SynchronizeFileOperation
) {
1281 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1283 } else if (operation
instanceof CreateFolderOperation
) {
1284 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1286 } else if (operation
instanceof CreateShareOperation
) {
1287 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1289 } else if (operation
instanceof UnshareLinkOperation
) {
1290 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
1292 } else if (operation
instanceof MoveFileOperation
) {
1293 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1298 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1299 RemoteOperationResult result
) {
1300 if (result
.isSuccess()) {
1301 refreshShowDetails();
1302 refreshListOfFilesFragment();
1306 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1307 RemoteOperationResult result
) {
1308 if (result
.isSuccess()) {
1309 refreshShowDetails();
1310 refreshListOfFilesFragment();
1312 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1313 cleanSecondFragment();
1314 refreshListOfFilesFragment();
1318 private void refreshShowDetails() {
1319 FileFragment details
= getSecondFragment();
1320 if (details
!= null
) {
1321 OCFile file
= details
.getFile();
1323 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1324 if (details
instanceof PreviewMediaFragment
) {
1325 // Refresh OCFile of the fragment
1326 ((PreviewMediaFragment
) details
).updateFile(file
);
1327 } else if (details
instanceof PreviewTextFragment
) {
1328 // Refresh OCFile of the fragment
1329 ((PreviewTextFragment
) details
).updateFile(file
);
1333 invalidateOptionsMenu();
1338 * Updates the view associated to the activity after the finish of an operation trying to
1341 * @param operation Removal operation performed.
1342 * @param result Result of the removal.
1344 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1345 RemoteOperationResult result
) {
1346 dismissLoadingDialog();
1347 Toast msg
= Toast
.makeText(this,
1348 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1352 if (result
.isSuccess()) {
1353 OCFile removedFile
= operation
.getFile();
1354 FileFragment second
= getSecondFragment();
1355 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1356 if (second
instanceof PreviewMediaFragment
) {
1357 ((PreviewMediaFragment
) second
).stopPreview(true
);
1359 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1360 cleanSecondFragment();
1362 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){
1363 refreshListOfFilesFragment();
1365 invalidateOptionsMenu();
1367 if (result
.isSslRecoverableException()) {
1368 mLastSslUntrustedServerResult
= result
;
1369 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1376 * Updates the view associated to the activity after the finish of an operation trying to move a
1379 * @param operation Move operation performed.
1380 * @param result Result of the move operation.
1382 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1383 RemoteOperationResult result
) {
1384 if (result
.isSuccess()) {
1385 dismissLoadingDialog();
1386 refreshListOfFilesFragment();
1388 dismissLoadingDialog();
1390 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1391 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1395 } catch (NotFoundException e
) {
1396 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1403 * Updates the view associated to the activity after the finish of an operation trying to rename
1406 * @param operation Renaming operation performed.
1407 * @param result Result of the renaming.
1409 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1410 RemoteOperationResult result
) {
1411 dismissLoadingDialog();
1412 OCFile renamedFile
= operation
.getFile();
1413 if (result
.isSuccess()) {
1414 FileFragment details
= getSecondFragment();
1415 if (details
!= null
) {
1416 if (details
instanceof FileDetailFragment
&&
1417 renamedFile
.equals(details
.getFile()) ) {
1418 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1419 showDetails(renamedFile
);
1421 } else if (details
instanceof PreviewMediaFragment
&&
1422 renamedFile
.equals(details
.getFile())) {
1423 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1424 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1425 int position
= ((PreviewMediaFragment
) details
).getPosition();
1426 startMediaPreview(renamedFile
, position
, true
);
1428 getFileOperationsHelper().openFile(renamedFile
);
1430 } else if (details
instanceof PreviewTextFragment
&&
1431 renamedFile
.equals(details
.getFile())) {
1432 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1433 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1434 startTextPreview(renamedFile
);
1436 getFileOperationsHelper().openFile(renamedFile
);
1441 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1442 refreshListOfFilesFragment();
1446 Toast msg
= Toast
.makeText(this,
1447 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1451 if (result
.isSslRecoverableException()) {
1452 mLastSslUntrustedServerResult
= result
;
1453 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1458 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1459 RemoteOperationResult result
) {
1460 if (result
.isSuccess()) {
1461 if (operation
.transferWasRequested()) {
1462 OCFile syncedFile
= operation
.getLocalFile();
1463 onTransferStateChanged(syncedFile
, true
, true
);
1464 invalidateOptionsMenu();
1470 * Updates the view associated to the activity after the finish of an operation trying create a
1473 * @param operation Creation operation performed.
1474 * @param result Result of the creation.
1476 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1477 RemoteOperationResult result
) {
1478 if (result
.isSuccess()) {
1479 dismissLoadingDialog();
1480 refreshListOfFilesFragment();
1482 dismissLoadingDialog();
1484 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1485 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1489 } catch (NotFoundException e
) {
1490 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1500 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1501 refreshListOfFilesFragment();
1502 FileFragment details
= getSecondFragment();
1503 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1504 file
.equals(details
.getFile()) ) {
1505 if (downloading
|| uploading
) {
1506 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1508 if (!file
.fileExists()) {
1509 cleanSecondFragment();
1511 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1519 private void requestForDownload() {
1520 Account account
= getAccount();
1521 //if (!mWaitingToPreview.isDownloading()) {
1522 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1523 Intent i
= new Intent(this, FileDownloader
.class);
1524 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1525 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1531 private OCFile
getCurrentDir() {
1532 OCFile file
= getFile();
1534 if (file
.isFolder()) {
1536 } else if (getStorageManager() != null
) {
1537 String parentPath
= file
.getRemotePath().substring(0,
1538 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1539 return getStorageManager().getFileByPath(parentPath
);
1545 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1546 long currentSyncTime
= System
.currentTimeMillis();
1548 mSyncInProgress
= true
;
1550 // perform folder synchronization
1551 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1554 getFileOperationsHelper().isSharedSupported(),
1556 getStorageManager(),
1558 getApplicationContext()
1560 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1562 setSupportProgressBarIndeterminateVisibility(true
);
1564 setBackgroundText();
1568 * Show untrusted cert dialog
1570 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1571 // Show a dialog with the certificate info
1572 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1573 (CertificateCombinedException
) result
.getException());
1574 FragmentManager fm
= getSupportFragmentManager();
1575 FragmentTransaction ft
= fm
.beginTransaction();
1576 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1579 private void requestForDownload(OCFile file
) {
1580 Account account
= getAccount();
1581 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1582 Intent i
= new Intent(this, FileDownloader
.class);
1583 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1584 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1589 private void sendDownloadedFile() {
1590 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1591 mWaitingToSend
= null
;
1596 * Requests the download of the received {@link OCFile} , updates the UI
1597 * to monitor the download progress and prepares the activity to send the file
1598 * when the download finishes.
1600 * @param file {@link OCFile} to download and preview.
1602 public void startDownloadForSending(OCFile file
) {
1603 mWaitingToSend
= file
;
1604 requestForDownload(mWaitingToSend
);
1605 boolean hasSecondFragment
= (getSecondFragment() != null
);
1606 updateFragmentsVisibility(hasSecondFragment
);
1610 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1612 * @param file Image {@link OCFile} to show.
1614 public void startImagePreview(OCFile file
) {
1615 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1616 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1617 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1618 startActivity(showDetailsIntent
);
1622 * Stars the preview of an already down media {@link OCFile}.
1624 * @param file Media {@link OCFile} to preview.
1625 * @param startPlaybackPosition Media position where the playback will be started,
1627 * @param autoplay When 'true', the playback will start without user
1630 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1631 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1633 setSecondFragment(mediaFragment
);
1634 updateFragmentsVisibility(true
);
1635 updateActionBarTitleAndHomeButton(file
);
1640 * Stars the preview of a text file {@link OCFile}.
1642 * @param file Text {@link OCFile} to preview.
1644 public void startTextPreview(OCFile file
) {
1645 Bundle args
= new Bundle();
1646 args
.putParcelable(EXTRA_FILE
, file
);
1647 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1648 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(),
1649 PreviewTextFragment
.class.getName(), args
);
1650 setSecondFragment(textPreviewFragment
);
1651 updateFragmentsVisibility(true
);
1652 //updateNavigationElementsInActionBar(file);
1657 * Requests the download of the received {@link OCFile} , updates the UI
1658 * to monitor the download progress and prepares the activity to preview
1659 * or open the file when the download finishes.
1661 * @param file {@link OCFile} to download and preview.
1663 public void startDownloadForPreview(OCFile file
) {
1664 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1665 setSecondFragment(detailFragment
);
1666 mWaitingToPreview
= file
;
1667 requestForDownload();
1668 updateFragmentsVisibility(true
);
1669 updateActionBarTitleAndHomeButton(file
);
1674 public void cancelTransference(OCFile file
) {
1675 getFileOperationsHelper().cancelTransference(file
);
1676 if (mWaitingToPreview
!= null
&&
1677 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1678 mWaitingToPreview
= null
;
1680 if (mWaitingToSend
!= null
&&
1681 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1682 mWaitingToSend
= null
;
1684 onTransferStateChanged(file
, false
, false
);
1688 public void onRefresh(boolean ignoreETag
) {
1689 refreshList(ignoreETag
);
1693 public void onRefresh() {
1697 private void refreshList(boolean ignoreETag
) {
1698 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1699 if (listOfFiles
!= null
) {
1700 OCFile folder
= listOfFiles
.getCurrentFile();
1701 if (folder
!= null
) {
1702 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1703 listDirectory(mFile);*/
1704 startSyncFolderOperation(folder
, ignoreETag
);
1709 private void sortByDate(boolean ascending
) {
1710 getListOfFilesFragment().sortByDate(ascending
);
1713 private void sortBySize(boolean ascending
) {
1714 getListOfFilesFragment().sortBySize(ascending
);
1717 private void sortByName(boolean ascending
) {
1718 getListOfFilesFragment().sortByName(ascending
);
1721 public void allFilesOption() {