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
.support
.v7
.app
.ActionBar
;
53 import android
.view
.Menu
;
54 import android
.view
.MenuInflater
;
55 import android
.view
.MenuItem
;
56 import android
.view
.View
;
57 import android
.view
.Window
;
58 import android
.widget
.Toast
;
60 import com
.owncloud
.android
.MainApp
;
61 import com
.owncloud
.android
.R
;
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
.PreviewVideoActivity
;
99 import com
.owncloud
.android
.utils
.DisplayUtils
;
100 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
101 import com
.owncloud
.android
.utils
.FileStorageUtils
;
102 import com
.owncloud
.android
.utils
.UriUtils
;
108 * Displays, what files the user has available in his ownCloud.
111 public class FileDisplayActivity
extends HookActivity
112 implements FileFragment
.ContainerActivity
,
113 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
115 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
116 private UploadFinishReceiver mUploadFinishReceiver
;
117 private DownloadFinishReceiver mDownloadFinishReceiver
;
118 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
120 private boolean mDualPane
;
121 private View mLeftFragmentContainer
;
122 private View mRightFragmentContainer
;
124 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
125 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
126 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
128 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
130 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
131 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
132 public static final int ACTION_MOVE_FILES
= 3;
134 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
136 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
137 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
139 private OCFile mWaitingToPreview
;
141 private boolean mSyncInProgress
= false
;
143 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
144 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
145 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
146 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
148 private OCFile mWaitingToSend
;
152 protected void onCreate(Bundle savedInstanceState
) {
153 Log_OC
.v(TAG
, "onCreate() start");
154 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
156 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
159 /// grant that FileObserverService is watching favorite files
160 if (savedInstanceState
== null
) {
161 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
162 startService(initObserversIntent
);
165 /// Load of saved instance state
166 if(savedInstanceState
!= null
) {
167 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
168 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
169 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
170 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
171 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
174 mWaitingToPreview
= null
;
175 mSyncInProgress
= false
;
176 mWaitingToSend
= null
;
181 // Inflate and set the layout view
182 setContentView(R
.layout
.files
);
187 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
188 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
189 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
190 if (savedInstanceState
== null
) {
191 createMinFragments();
195 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
196 // according to the official
198 if (getFile() != null
) {
199 updateActionBarTitle();
202 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
203 /*|| mRefreshSharesInProgress*/);
204 // always AFTER setContentView(...) ; to work around bug in its implementation
208 Log_OC
.v(TAG
, "onCreate() end");
212 protected void onStart() {
213 Log_OC
.v(TAG
, "onStart() start");
215 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
216 Log_OC
.v(TAG
, "onStart() end");
220 protected void onDestroy() {
221 Log_OC
.v(TAG
, "onDestroy() start");
223 Log_OC
.v(TAG
, "onDestroy() end");
227 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
230 protected void onAccountSet(boolean stateWasRecovered
) {
231 super.onAccountSet(stateWasRecovered
);
232 if (getAccount() != null
) {
233 /// Check whether the 'main' OCFile handled by the Activity is contained in the
235 OCFile file
= getFile();
236 // get parent from path
237 String parentPath
= "";
239 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
240 // upload in progress - right now, files are not inserted in the local
241 // cache until the upload is successful get parent from path
242 parentPath
= file
.getRemotePath().substring(0,
243 file
.getRemotePath().lastIndexOf(file
.getFileName()));
244 if (getStorageManager().getFileByPath(parentPath
) == null
)
245 file
= null
; // not able to know the directory where the file is uploading
247 file
= getStorageManager().getFileByPath(file
.getRemotePath());
248 // currentDir = null if not in the current Account
252 // fall back to root folder
253 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
257 if (!stateWasRecovered
) {
258 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
259 initFragmentsWithFile();
260 if (file
.isFolder()) {
261 startSyncFolderOperation(file
, false
);
265 updateFragmentsVisibility(!file
.isFolder());
266 updateNavigationElementsInActionBar(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());
288 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
292 OCFile file
= getFile();
293 Fragment secondFragment
= chooseInitialSecondFragment(file
);
294 if (secondFragment
!= null
) {
295 setSecondFragment(secondFragment
);
296 updateFragmentsVisibility(true
);
297 updateNavigationElementsInActionBar(file
);
300 cleanSecondFragment();
304 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
305 if (getAccount() == null
) {
306 Log_OC
.wtf(TAG
, "\t account is NULL");
308 if (getFile() == null
) {
309 Log_OC
.wtf(TAG
, "\t file is NULL");
314 private Fragment
chooseInitialSecondFragment(OCFile file
) {
315 Fragment secondFragment
= null
;
316 if (file
!= null
&& !file
.isFolder()) {
317 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
318 && file
.getLastSyncDateForProperties() > 0 // temporal fix
320 int startPlaybackPosition
=
321 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
323 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
324 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
325 startPlaybackPosition
, autoplay
);
328 secondFragment
= new FileDetailFragment(file
, getAccount());
331 return secondFragment
;
336 * Replaces the second fragment managed by the activity with the received as
339 * Assumes never will be more than two fragments managed at the same time.
341 * @param fragment New second Fragment to set.
343 private void setSecondFragment(Fragment fragment
) {
344 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
345 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
346 transaction
.commit();
350 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
352 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
353 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
355 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
356 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
359 } else if (existsSecondFragment
) {
360 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
361 mLeftFragmentContainer
.setVisibility(View
.GONE
);
363 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
364 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
368 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
369 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
371 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
372 mRightFragmentContainer
.setVisibility(View
.GONE
);
378 private OCFileListFragment
getListOfFilesFragment() {
379 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
380 FileDisplayActivity
.TAG_LIST_OF_FILES
);
381 if (listOfFiles
!= null
) {
382 return (OCFileListFragment
)listOfFiles
;
384 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
388 public FileFragment
getSecondFragment() {
389 Fragment second
= getSupportFragmentManager().findFragmentByTag(
390 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
391 if (second
!= null
) {
392 return (FileFragment
)second
;
397 protected void cleanSecondFragment() {
398 Fragment second
= getSecondFragment();
399 if (second
!= null
) {
400 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
404 updateFragmentsVisibility(false
);
405 updateNavigationElementsInActionBar(null
);
408 protected void refreshListOfFilesFragment() {
409 OCFileListFragment fileListFragment
= getListOfFilesFragment();
410 if (fileListFragment
!= null
) {
411 fileListFragment
.listDirectory();
412 // TODO Enable when "On Device" is recovered ?
413 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
417 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
419 FileFragment secondFragment
= getSecondFragment();
420 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
421 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
422 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
423 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
424 OCFile fileInFragment
= detailsFragment
.getFile();
425 if (fileInFragment
!= null
&&
426 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
427 // the user browsed to other file ; forget the automatic preview
428 mWaitingToPreview
= null
;
430 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
431 // grant that the right panel updates the progress bar
432 detailsFragment
.listenForTransferProgress();
433 detailsFragment
.updateFileDetails(true
, false
);
435 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
436 // update the right panel
437 boolean detailsFragmentChanged
= false
;
440 mWaitingToPreview
= getStorageManager().getFileById(
441 mWaitingToPreview
.getFileId()); // update the file from database,
442 // for the local storage path
443 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
444 startMediaPreview(mWaitingToPreview
, 0, true
);
445 detailsFragmentChanged
= true
;
447 getFileOperationsHelper().openFile(mWaitingToPreview
);
450 mWaitingToPreview
= null
;
452 if (!detailsFragmentChanged
) {
453 detailsFragment
.updateFileDetails(false
, (success
));
460 public boolean onPrepareOptionsMenu(Menu menu
) {
461 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
462 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
463 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
464 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
465 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
467 return super.onPrepareOptionsMenu(menu
);
471 public boolean onCreateOptionsMenu(Menu menu
) {
472 MenuInflater inflater
= getMenuInflater();
473 inflater
.inflate(R
.menu
.main_menu
, menu
);
479 public boolean onOptionsItemSelected(MenuItem item
) {
480 boolean retval
= true
;
481 switch (item
.getItemId()) {
482 case R
.id
.action_create_dir
: {
483 CreateFolderDialogFragment dialog
=
484 CreateFolderDialogFragment
.newInstance(getCurrentDir());
485 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
488 case R
.id
.action_sync_account
: {
489 startSynchronization();
492 case R
.id
.action_upload
: {
493 UploadSourceDialogFragment dialog
=
494 UploadSourceDialogFragment
.newInstance(getAccount());
495 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
499 case android
.R
.id
.home
: {
500 FileFragment second
= getSecondFragment();
501 OCFile currentDir
= getCurrentDir();
502 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
503 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
504 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
505 (second
!= null
&& second
.getFile() != null
)) {
509 mDrawerLayout
.openDrawer(GravityCompat
.START
);
513 case R
.id
.action_sort
: {
514 SharedPreferences appPreferences
= PreferenceManager
515 .getDefaultSharedPreferences(this);
517 // Read sorting order, default to sort by name ascending
518 Integer sortOrder
= appPreferences
519 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
521 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
522 builder
.setTitle(R
.string
.actionbar_sort_title
)
523 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
524 new DialogInterface
.OnClickListener() {
525 public void onClick(DialogInterface dialog
, int which
) {
538 builder
.create().show();
542 retval
= super.onOptionsItemSelected(item
);
547 private void startSynchronization() {
548 Log_OC
.d(TAG
, "Got to start sync");
549 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
550 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
551 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
552 // cancel the current synchronizations of any ownCloud account
553 Bundle bundle
= new Bundle();
554 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
555 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
556 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
557 MainApp
.getAuthority());
558 ContentResolver
.requestSync(
560 MainApp
.getAuthority(), bundle
);
562 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
563 MainApp
.getAuthority() + " with new API");
564 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
565 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
566 builder
.setExpedited(true
);
567 builder
.setManual(true
);
570 // Fix bug in Android Lollipop when you click on refresh the whole account
571 Bundle extras
= new Bundle();
572 builder
.setExtras(extras
);
574 SyncRequest request
= builder
.build();
575 ContentResolver
.requestSync(request
);
580 * Called, when the user selected something for uploading
583 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
585 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
587 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
588 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
589 //getClipData is only supported on api level 16+, Jelly Bean
590 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
591 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
592 Intent intent
= new Intent();
593 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
594 requestSimpleUpload(intent
, resultCode
);
597 requestSimpleUpload(data
, resultCode
);
599 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
600 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
601 requestMultipleUpload(data
, resultCode
);
603 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
605 final Intent fData
= data
;
606 final int fResultCode
= resultCode
;
607 getHandler().postDelayed(
611 requestMoveOperation(fData
, fResultCode
);
614 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
618 super.onActivityResult(requestCode
, resultCode
, data
);
623 private void requestMultipleUpload(Intent data
, int resultCode
) {
624 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
625 if (filePaths
!= null
) {
626 String
[] remotePaths
= new String
[filePaths
.length
];
627 String remotePathBase
= "";
629 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
630 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
631 for (int j
= 0; j
< remotePaths
.length
; j
++) {
632 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
635 Intent i
= new Intent(this, FileUploader
.class);
636 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
637 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
638 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
639 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
640 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
641 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
645 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
646 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
654 private void requestSimpleUpload(Intent data
, int resultCode
) {
655 String filePath
= null
;
656 String mimeType
= null
;
658 Uri selectedImageUri
= data
.getData();
661 mimeType
= getContentResolver().getType(selectedImageUri
);
663 String fileManagerString
= selectedImageUri
.getPath();
664 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
666 if (selectedImagePath
!= null
)
667 filePath
= selectedImagePath
;
669 filePath
= fileManagerString
;
671 } catch (Exception e
) {
672 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
673 "Intent.ACTION_GET_CONTENT", e
);
676 if (filePath
== null
) {
677 Log_OC
.e(TAG
, "Couldn't resolve path to file");
678 Toast t
= Toast
.makeText(
679 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
687 Intent i
= new Intent(this, FileUploader
.class);
688 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
689 OCFile currentDir
= getCurrentDir();
690 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
692 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
693 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
695 if (cursor
!= null
&& cursor
.moveToFirst()) {
696 String displayName
= cursor
.getString(cursor
.getColumnIndex(
697 OpenableColumns
.DISPLAY_NAME
));
698 Log_OC
.v(TAG
, "Display Name: " + displayName
);
700 displayName
.replace(File
.separatorChar
, '_');
701 displayName
.replace(File
.pathSeparatorChar
, '_');
702 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
705 // and what happens in case of error?; wrong target name for the upload
711 remotePath
+= new File(filePath
).getName();
714 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
715 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
716 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
717 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
718 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
719 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
724 * Request the operation for moving the file/folder from one path to another
726 * @param data Intent received
727 * @param resultCode Result code received
729 private void requestMoveOperation(Intent data
, int resultCode
) {
730 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
731 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
732 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
736 public void onBackPressed() {
737 OCFileListFragment listOfFiles
= getListOfFilesFragment();
738 if (mDualPane
|| getSecondFragment() == null
) {
739 if (listOfFiles
!= null
) { // should never be null, indeed
740 listOfFiles
.onBrowseUp();
743 if (listOfFiles
!= null
) { // should never be null, indeed
744 setFile(listOfFiles
.getCurrentFile());
746 updateActionBarTitle();
747 cleanSecondFragment();
752 protected void onSaveInstanceState(Bundle outState
) {
753 // responsibility of restore is preferred in onCreate() before than in
754 // onRestoreInstanceState when there are Fragments involved
755 Log_OC
.v(TAG
, "onSaveInstanceState() start");
756 super.onSaveInstanceState(outState
);
757 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
758 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
759 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
760 // mRefreshSharesInProgress);
761 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
763 Log_OC
.v(TAG
, "onSaveInstanceState() end");
769 protected void onResume() {
770 Log_OC
.v(TAG
, "onResume() start");
773 // refresh Navigation Drawer account list
774 mNavigationDrawerAdapter
.updateAccountList();
777 // refresh list of files
778 refreshListOfFilesFragment();
780 // Listen for sync messages
781 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
782 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
783 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
784 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
785 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
786 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
787 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
788 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
789 // syncIntentFilter);
791 // Listen for upload messages
792 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
793 mUploadFinishReceiver
= new UploadFinishReceiver();
794 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
796 // Listen for download messages
797 IntentFilter downloadIntentFilter
= new IntentFilter(
798 FileDownloader
.getDownloadAddedMessage());
799 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
800 mDownloadFinishReceiver
= new DownloadFinishReceiver();
801 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
803 Log_OC
.v(TAG
, "onResume() end");
808 protected void onPause() {
809 Log_OC
.v(TAG
, "onPause() start");
810 if (mSyncBroadcastReceiver
!= null
) {
811 unregisterReceiver(mSyncBroadcastReceiver
);
812 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
813 mSyncBroadcastReceiver
= null
;
815 if (mUploadFinishReceiver
!= null
) {
816 unregisterReceiver(mUploadFinishReceiver
);
817 mUploadFinishReceiver
= null
;
819 if (mDownloadFinishReceiver
!= null
) {
820 unregisterReceiver(mDownloadFinishReceiver
);
821 mDownloadFinishReceiver
= null
;
825 Log_OC
.v(TAG
, "onPause() end");
829 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
832 * {@link BroadcastReceiver} to enable syncing feedback in UI
835 public void onReceive(Context context
, Intent intent
) {
837 String event
= intent
.getAction();
838 Log_OC
.d(TAG
, "Received broadcast " + event
);
839 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
840 String synchFolderRemotePath
=
841 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
842 RemoteOperationResult synchResult
=
843 (RemoteOperationResult
)intent
.getSerializableExtra(
844 FileSyncAdapter
.EXTRA_RESULT
);
845 boolean sameAccount
= (getAccount() != null
&&
846 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
850 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
851 mSyncInProgress
= true
;
854 OCFile currentFile
= (getFile() == null
) ? null
:
855 getStorageManager().getFileByPath(getFile().getRemotePath());
856 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
857 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
859 if (currentDir
== null
) {
860 // current folder was removed from the server
861 Toast
.makeText( FileDisplayActivity
.this,
864 sync_current_folder_was_removed
),
865 synchFolderRemotePath
),
871 if (currentFile
== null
&& !getFile().isFolder()) {
872 // currently selected file was removed in the server, and now we
874 cleanSecondFragment();
875 currentFile
= currentDir
;
878 if (synchFolderRemotePath
!= null
&&
879 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
880 OCFileListFragment fileListFragment
= getListOfFilesFragment();
881 if (fileListFragment
!= null
) {
882 fileListFragment
.listDirectory();
883 // TODO Enable when "On Device" is recovered ?
884 // fileListFragment.listDirectory(currentDir,
885 // MainApp.getOnlyOnDevice());
888 setFile(currentFile
);
891 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
892 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
895 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
897 /// TODO refactor and make common
898 synchResult
!= null
&& !synchResult
.isSuccess() &&
899 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
900 synchResult
.isIdPRedirection() ||
901 (synchResult
.isException() && synchResult
.getException()
902 instanceof AuthenticatorException
))) {
906 OwnCloudClient client
;
907 OwnCloudAccount ocAccount
=
908 new OwnCloudAccount(getAccount(), context
);
909 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
910 removeClientFor(ocAccount
));
912 if (client
!= null
) {
913 OwnCloudCredentials cred
= client
.getCredentials();
915 AccountManager am
= AccountManager
.get(context
);
916 if (cred
.authTokenExpires()) {
917 am
.invalidateAuthToken(
922 am
.clearPassword(getAccount());
926 requestCredentialsUpdate();
928 } catch (AccountNotFoundException e
) {
929 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
934 removeStickyBroadcast(intent
);
935 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
936 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
937 /*|| mRefreshSharesInProgress*/);
943 if (synchResult
!= null
) {
944 if (synchResult
.getCode().equals(
945 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
946 mLastSslUntrustedServerResult
= synchResult
;
949 } catch (RuntimeException e
) {
950 // avoid app crashes after changing the serial id of RemoteOperationResult
951 // in owncloud library with broadcast notifications pending to process
952 removeStickyBroadcast(intent
);
958 * Show a text message on screen view for notifying user if content is
959 * loading or folder is empty
961 private void setBackgroundText() {
962 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
963 if (ocFileListFragment
!= null
) {
964 int message
= R
.string
.file_list_loading
;
965 if (!mSyncInProgress
) {
966 // In case file list is empty
967 message
= R
.string
.file_list_empty
;
969 ocFileListFragment
.setMessageForEmptyList(getString(message
));
971 Log_OC
.e(TAG
, "OCFileListFragment is null");
976 * Once the file upload has finished -> update view
978 private class UploadFinishReceiver
extends BroadcastReceiver
{
980 * Once the file upload has finished -> update view
981 * @author David A. Velasco
982 * {@link BroadcastReceiver} to enable upload feedback in UI
985 public void onReceive(Context context
, Intent intent
) {
987 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
988 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
989 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
990 OCFile currentDir
= getCurrentDir();
991 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
992 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
994 if (sameAccount
&& isDescendant
) {
995 refreshListOfFilesFragment();
998 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1000 boolean renamedInUpload
= getFile().getRemotePath().
1001 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1002 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1004 FileFragment details
= getSecondFragment();
1005 boolean detailFragmentIsShown
= (details
!= null
&&
1006 details
instanceof FileDetailFragment
);
1008 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1009 if (uploadWasFine
) {
1010 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1012 if (renamedInUpload
) {
1013 String newName
= (new File(uploadedRemotePath
)).getName();
1014 Toast msg
= Toast
.makeText(
1017 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1022 if (uploadWasFine
|| getFile().fileExists()) {
1023 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1025 cleanSecondFragment();
1028 // Force the preview if the file is an image
1029 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1030 startImagePreview(getFile());
1031 } // TODO what about other kind of previews?
1035 if (intent
!= null
) {
1036 removeStickyBroadcast(intent
);
1046 * Class waiting for broadcast events from the {@link FileDownloader} service.
1048 * Updates the UI when a download is started or finished, provided that it is relevant for the
1051 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1053 //int refreshCounter = 0;
1055 public void onReceive(Context context
, Intent intent
) {
1057 boolean sameAccount
= isSameAccount(context
, intent
);
1058 String downloadedRemotePath
=
1059 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1060 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1062 if (sameAccount
&& isDescendant
) {
1063 String linkedToRemotePath
=
1064 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1065 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1066 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1067 refreshListOfFilesFragment();
1069 refreshSecondFragment(
1071 downloadedRemotePath
,
1072 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1076 if (mWaitingToSend
!= null
) {
1078 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1079 if (mWaitingToSend
.isDown()) {
1080 sendDownloadedFile();
1085 if (intent
!= null
) {
1086 removeStickyBroadcast(intent
);
1091 private boolean isDescendant(String downloadedRemotePath
) {
1092 OCFile currentDir
= getCurrentDir();
1094 currentDir
!= null
&&
1095 downloadedRemotePath
!= null
&&
1096 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1100 private boolean isAscendant(String linkedToRemotePath
) {
1101 OCFile currentDir
= getCurrentDir();
1103 currentDir
!= null
&&
1104 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1108 private boolean isSameAccount(Context context
, Intent intent
) {
1109 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1110 return (accountName
!= null
&& getAccount() != null
&&
1111 accountName
.equals(getAccount().name
));
1116 public void browseToRoot() {
1117 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1118 if (listOfFiles
!= null
) { // should never be null, indeed
1119 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1120 listOfFiles
.listDirectory(root
);
1121 // TODO Enable when "On Device" is recovered ?
1122 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1123 setFile(listOfFiles
.getCurrentFile());
1124 startSyncFolderOperation(root
, false
);
1125 updateActionBarTitle();
1127 cleanSecondFragment();
1135 * Updates action bar and second fragment, if in dual pane mode.
1138 public void onBrowsedDownTo(OCFile directory
) {
1139 cleanSecondFragment();
1141 updateActionBarTitle();
1143 startSyncFolderOperation(directory
, false
);
1148 * Shows the information of the {@link OCFile} received as a
1149 * parameter in the second fragment.
1151 * @param file {@link OCFile} whose details will be shown
1154 public void showDetails(OCFile file
) {
1155 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1156 setSecondFragment(detailFragment
);
1157 updateFragmentsVisibility(true
);
1158 updateNavigationElementsInActionBar(file
);
1166 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1167 ActionBar actionBar
= getSupportActionBar();
1169 // For adding content description tag to a title field in the action bar
1170 int actionBarTitleId
= getResources().getIdentifier("action_bar_title", "id", "android");
1172 if (chosenFile
== null
|| mDualPane
) {
1173 // only list of files - set for browsing through folders
1174 OCFile currentDir
= getCurrentDir();
1175 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1176 // actionBar.setDisplayHomeAsUpEnabled(noRoot);
1177 // actionBar.setDisplayShowTitleEnabled(!noRoot);
1178 actionBar
.setDisplayHomeAsUpEnabled(true
);
1179 actionBar
.setDisplayShowTitleEnabled(true
);
1181 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1182 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1183 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1184 actionBarTitleView
.setContentDescription(
1185 getString(R
.string
.default_display_name_for_root_folder
));
1188 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1191 actionBar
.setDisplayHomeAsUpEnabled(true
);
1192 actionBar
.setDisplayShowTitleEnabled(true
);
1193 actionBar
.setTitle(chosenFile
.getFileName());
1194 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1195 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1196 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1197 getWindow().getDecorView().findViewById(actionBarTitleId
).
1198 setContentDescription(chosenFile
.getFileName());
1205 protected ServiceConnection
newTransferenceServiceConnection() {
1206 return new ListServiceConnection();
1209 /** Defines callbacks for service binding, passed to bindService() */
1210 private class ListServiceConnection
implements ServiceConnection
{
1213 public void onServiceConnected(ComponentName component
, IBinder service
) {
1214 if (component
.equals(new ComponentName(
1215 FileDisplayActivity
.this, FileDownloader
.class))) {
1216 Log_OC
.d(TAG
, "Download service connected");
1217 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1218 if (mWaitingToPreview
!= null
)
1219 if (getStorageManager() != null
) {
1222 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1223 if (!mWaitingToPreview
.isDown()) {
1224 requestForDownload();
1228 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1229 FileUploader
.class))) {
1230 Log_OC
.d(TAG
, "Upload service connected");
1231 mUploaderBinder
= (FileUploaderBinder
) service
;
1235 // a new chance to get the mDownloadBinder through
1236 // getFileDownloadBinder() - THIS IS A MESS
1237 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1238 if (listOfFiles
!= null
) {
1239 listOfFiles
.listDirectory();
1240 // TODO Enable when "On Device" is recovered ?
1241 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1243 FileFragment secondFragment
= getSecondFragment();
1244 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1245 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1246 detailFragment
.listenForTransferProgress();
1247 detailFragment
.updateFileDetails(false
, false
);
1252 public void onServiceDisconnected(ComponentName component
) {
1253 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1254 FileDownloader
.class))) {
1255 Log_OC
.d(TAG
, "Download service disconnected");
1256 mDownloaderBinder
= null
;
1257 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1258 FileUploader
.class))) {
1259 Log_OC
.d(TAG
, "Upload service disconnected");
1260 mUploaderBinder
= null
;
1266 public void onSavedCertificate() {
1267 startSyncFolderOperation(getCurrentDir(), false
);
1272 public void onFailedSavingCertificate() {
1273 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1274 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1276 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1280 public void onCancelCertificate() {
1285 * Updates the view associated to the activity after the finish of some operation over files
1286 * in the current account.
1288 * @param operation Removal operation performed.
1289 * @param result Result of the removal.
1292 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1293 super.onRemoteOperationFinish(operation
, result
);
1295 if (operation
instanceof RemoveFileOperation
) {
1296 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1298 } else if (operation
instanceof RenameFileOperation
) {
1299 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1301 } else if (operation
instanceof SynchronizeFileOperation
) {
1302 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1304 } else if (operation
instanceof CreateFolderOperation
) {
1305 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1307 } else if (operation
instanceof CreateShareOperation
) {
1308 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1310 } else if (operation
instanceof UnshareLinkOperation
) {
1311 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1313 } else if (operation
instanceof MoveFileOperation
) {
1314 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1320 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1321 RemoteOperationResult result
) {
1322 if (result
.isSuccess()) {
1323 refreshShowDetails();
1324 refreshListOfFilesFragment();
1329 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1330 RemoteOperationResult result
) {
1331 if (result
.isSuccess()) {
1332 refreshShowDetails();
1333 refreshListOfFilesFragment();
1335 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1336 cleanSecondFragment();
1337 refreshListOfFilesFragment();
1341 private void refreshShowDetails() {
1342 FileFragment details
= getSecondFragment();
1343 if (details
!= null
) {
1344 OCFile file
= details
.getFile();
1346 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1347 if (details
instanceof PreviewMediaFragment
) {
1348 // Refresh OCFile of the fragment
1349 ((PreviewMediaFragment
) details
).updateFile(file
);
1354 invalidateOptionsMenu();
1359 * Updates the view associated to the activity after the finish of an operation trying to
1362 * @param operation Removal operation performed.
1363 * @param result Result of the removal.
1365 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1366 RemoteOperationResult result
) {
1367 dismissLoadingDialog();
1369 Toast msg
= Toast
.makeText(this,
1370 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1374 if (result
.isSuccess()) {
1375 OCFile removedFile
= operation
.getFile();
1376 FileFragment second
= getSecondFragment();
1377 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1378 if (second
instanceof PreviewMediaFragment
) {
1379 ((PreviewMediaFragment
)second
).stopPreview(true
);
1381 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1382 cleanSecondFragment();
1384 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1385 refreshListOfFilesFragment();
1387 invalidateOptionsMenu();
1389 if (result
.isSslRecoverableException()) {
1390 mLastSslUntrustedServerResult
= result
;
1391 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1398 * Updates the view associated to the activity after the finish of an operation trying to move a
1401 * @param operation Move operation performed.
1402 * @param result Result of the move operation.
1404 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1405 RemoteOperationResult result
) {
1406 if (result
.isSuccess()) {
1407 dismissLoadingDialog();
1408 refreshListOfFilesFragment();
1410 dismissLoadingDialog();
1412 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1413 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1417 } catch (NotFoundException e
) {
1418 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1425 * Updates the view associated to the activity after the finish of an operation trying to rename
1428 * @param operation Renaming operation performed.
1429 * @param result Result of the renaming.
1431 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1432 RemoteOperationResult result
) {
1433 dismissLoadingDialog();
1434 OCFile renamedFile
= operation
.getFile();
1435 if (result
.isSuccess()) {
1436 FileFragment details
= getSecondFragment();
1437 if (details
!= null
) {
1438 if (details
instanceof FileDetailFragment
&&
1439 renamedFile
.equals(details
.getFile()) ) {
1440 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1441 showDetails(renamedFile
);
1443 } else if (details
instanceof PreviewMediaFragment
&&
1444 renamedFile
.equals(details
.getFile())) {
1445 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1446 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1447 int position
= ((PreviewMediaFragment
)details
).getPosition();
1448 startMediaPreview(renamedFile
, position
, true
);
1450 getFileOperationsHelper().openFile(renamedFile
);
1455 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1456 refreshListOfFilesFragment();
1460 Toast msg
= Toast
.makeText(this,
1461 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1465 if (result
.isSslRecoverableException()) {
1466 mLastSslUntrustedServerResult
= result
;
1467 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1472 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1473 RemoteOperationResult result
) {
1474 dismissLoadingDialog();
1475 OCFile syncedFile
= operation
.getLocalFile();
1476 if (!result
.isSuccess()) {
1477 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1478 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1479 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1480 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1486 if (operation
.transferWasRequested()) {
1487 onTransferStateChanged(syncedFile
, true
, true
);
1490 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
,
1491 operation
, getResources()), Toast
.LENGTH_LONG
);
1498 * Updates the view associated to the activity after the finish of an operation trying create a
1501 * @param operation Creation operation performed.
1502 * @param result Result of the creation.
1504 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1505 RemoteOperationResult result
) {
1506 if (result
.isSuccess()) {
1507 dismissLoadingDialog();
1508 refreshListOfFilesFragment();
1510 dismissLoadingDialog();
1512 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1513 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1517 } catch (NotFoundException e
) {
1518 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1528 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1529 refreshListOfFilesFragment();
1530 FileFragment details
= getSecondFragment();
1531 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1532 file
.equals(details
.getFile()) ) {
1533 if (downloading
|| uploading
) {
1534 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1536 if (!file
.fileExists()) {
1537 cleanSecondFragment();
1539 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1547 private void requestForDownload() {
1548 Account account
= getAccount();
1549 //if (!mWaitingToPreview.isDownloading()) {
1550 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1551 Intent i
= new Intent(this, FileDownloader
.class);
1552 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1553 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1559 private OCFile
getCurrentDir() {
1560 OCFile file
= getFile();
1562 if (file
.isFolder()) {
1564 } else if (getStorageManager() != null
) {
1565 String parentPath
= file
.getRemotePath().substring(0,
1566 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1567 return getStorageManager().getFileByPath(parentPath
);
1573 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1574 long currentSyncTime
= System
.currentTimeMillis();
1576 mSyncInProgress
= true
;
1578 // perform folder synchronization
1579 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1582 getFileOperationsHelper().isSharedSupported(),
1584 getStorageManager(),
1586 getApplicationContext()
1588 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1590 setSupportProgressBarIndeterminateVisibility(true
);
1592 setBackgroundText();
1596 * Show untrusted cert dialog
1598 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1599 // Show a dialog with the certificate info
1600 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1601 (CertificateCombinedException
) result
.getException());
1602 FragmentManager fm
= getSupportFragmentManager();
1603 FragmentTransaction ft
= fm
.beginTransaction();
1604 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1607 private void requestForDownload(OCFile file
) {
1608 Account account
= getAccount();
1609 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1610 Intent i
= new Intent(this, FileDownloader
.class);
1611 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1612 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1617 private void sendDownloadedFile(){
1618 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1619 mWaitingToSend
= null
;
1624 * Requests the download of the received {@link OCFile} , updates the UI
1625 * to monitor the download progress and prepares the activity to send the file
1626 * when the download finishes.
1628 * @param file {@link OCFile} to download and preview.
1630 public void startDownloadForSending(OCFile file
) {
1631 mWaitingToSend
= file
;
1632 requestForDownload(mWaitingToSend
);
1633 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1634 updateFragmentsVisibility(hasSecondFragment
);
1638 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1640 * @param file Image {@link OCFile} to show.
1642 public void startImagePreview(OCFile file
) {
1643 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1644 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1645 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1646 startActivity(showDetailsIntent
);
1651 * Stars the preview of an already down media {@link OCFile}.
1653 * @param file Media {@link OCFile} to preview.
1654 * @param startPlaybackPosition Media position where the playback will be started,
1656 * @param autoplay When 'true', the playback will start without user
1659 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1660 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1662 setSecondFragment(mediaFragment
);
1663 updateFragmentsVisibility(true
);
1664 updateNavigationElementsInActionBar(file
);
1669 * Requests the download of the received {@link OCFile} , updates the UI
1670 * to monitor the download progress and prepares the activity to preview
1671 * or open the file when the download finishes.
1673 * @param file {@link OCFile} to download and preview.
1675 public void startDownloadForPreview(OCFile file
) {
1676 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1677 setSecondFragment(detailFragment
);
1678 mWaitingToPreview
= file
;
1679 requestForDownload();
1680 updateFragmentsVisibility(true
);
1681 updateNavigationElementsInActionBar(file
);
1686 public void cancelTransference(OCFile file
) {
1687 getFileOperationsHelper().cancelTransference(file
);
1688 if (mWaitingToPreview
!= null
&&
1689 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1690 mWaitingToPreview
= null
;
1692 if (mWaitingToSend
!= null
&&
1693 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1694 mWaitingToSend
= null
;
1696 onTransferStateChanged(file
, false
, false
);
1700 public void onRefresh(boolean ignoreETag
) {
1701 refreshList(ignoreETag
);
1705 public void onRefresh() {
1709 private void refreshList(boolean ignoreETag
) {
1710 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1711 if (listOfFiles
!= null
) {
1712 OCFile folder
= listOfFiles
.getCurrentFile();
1713 if (folder
!= null
) {
1714 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1715 listDirectory(mFile);*/
1716 startSyncFolderOperation(folder
, ignoreETag
);
1721 private void sortByDate(boolean ascending
){
1722 getListOfFilesFragment().sortByDate(ascending
);
1725 private void sortBySize(boolean ascending
){
1726 getListOfFilesFragment().sortBySize(ascending
);
1729 private void sortByName(boolean ascending
){
1730 getListOfFilesFragment().sortByName(ascending
);
1733 public void allFilesOption() {