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
.support
.v7
.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
.content
.ContextCompat
;
52 import android
.support
.v4
.view
.GravityCompat
;
53 import android
.view
.Menu
;
54 import android
.view
.MenuInflater
;
55 import android
.view
.MenuItem
;
56 import android
.view
.View
;
57 import android
.widget
.ProgressBar
;
58 import android
.widget
.RelativeLayout
;
59 import android
.widget
.TextView
;
60 import android
.widget
.Toast
;
62 import com
.owncloud
.android
.MainApp
;
63 import com
.owncloud
.android
.R
;
64 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
65 import com
.owncloud
.android
.datamodel
.OCFile
;
66 import com
.owncloud
.android
.files
.services
.FileDownloader
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
68 import com
.owncloud
.android
.files
.services
.FileUploader
;
69 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
70 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
74 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
75 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
76 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
79 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
80 import com
.owncloud
.android
.operations
.CopyFileOperation
;
81 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
82 import com
.owncloud
.android
.operations
.CreateShareOperation
;
83 import com
.owncloud
.android
.operations
.MoveFileOperation
;
84 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
85 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
86 import com
.owncloud
.android
.operations
.RenameFileOperation
;
87 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
88 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
89 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
90 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
91 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
92 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
95 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
96 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
97 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
98 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewTextFragment
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
104 import com
.owncloud
.android
.utils
.DisplayUtils
;
105 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
106 import com
.owncloud
.android
.utils
.FileStorageUtils
;
107 import com
.owncloud
.android
.utils
.UriUtils
;
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
;
129 private ProgressBar mProgressBar
;
131 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
132 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
133 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
135 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
137 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
138 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
139 public static final int ACTION_MOVE_FILES
= 3;
140 public static final int ACTION_COPY_FILES
= 4;
142 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
144 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
145 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
147 private OCFile mWaitingToPreview
;
149 private boolean mSyncInProgress
= false
;
151 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
152 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
153 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
154 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
156 private OCFile mWaitingToSend
;
160 protected void onCreate(Bundle savedInstanceState
) {
161 Log_OC
.v(TAG
, "onCreate() start");
163 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
166 /// grant that FileObserverService is watching favorite files
167 if (savedInstanceState
== null
) {
168 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
169 startService(initObserversIntent
);
172 /// Load of saved instance state
173 if(savedInstanceState
!= null
) {
174 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
175 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
176 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
177 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
178 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
180 mWaitingToPreview
= null
;
181 mSyncInProgress
= false
;
182 mWaitingToSend
= null
;
187 // Inflate and set the layout view
188 setContentView(R
.layout
.files
);
193 mProgressBar
= (ProgressBar
) findViewById(R
.id
.progressBar
);
194 mProgressBar
.setIndeterminateDrawable(
195 ContextCompat
.getDrawable(this,
196 R
.drawable
.actionbar_progress_indeterminate_horizontal
));
198 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
199 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
200 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
201 if (savedInstanceState
== null
) {
202 createMinFragments();
206 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
207 // according to the official
210 // enable ActionBar app icon to behave as action to toggle nav drawer
211 //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
212 getSupportActionBar().setHomeButtonEnabled(true
);
214 mProgressBar
.setIndeterminate(mSyncInProgress
);
215 // always AFTER setContentView(...) ; to work around bug in its implementation
219 Log_OC
.v(TAG
, "onCreate() end");
223 protected void onStart() {
224 Log_OC
.v(TAG
, "onStart() start");
226 Log_OC
.v(TAG
, "onStart() end");
230 protected void onDestroy() {
231 Log_OC
.v(TAG
, "onDestroy() start");
233 Log_OC
.v(TAG
, "onDestroy() end");
237 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
240 protected void onAccountSet(boolean stateWasRecovered
) {
241 super.onAccountSet(stateWasRecovered
);
242 if (getAccount() != null
) {
243 /// Check whether the 'main' OCFile handled by the Activity is contained in the
245 OCFile file
= getFile();
246 // get parent from path
247 String parentPath
= "";
249 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
250 // upload in progress - right now, files are not inserted in the local
251 // cache until the upload is successful get parent from path
252 parentPath
= file
.getRemotePath().substring(0,
253 file
.getRemotePath().lastIndexOf(file
.getFileName()));
254 if (getStorageManager().getFileByPath(parentPath
) == null
)
255 file
= null
; // not able to know the directory where the file is uploading
257 file
= getStorageManager().getFileByPath(file
.getRemotePath());
258 // currentDir = null if not in the current Account
262 // fall back to root folder
263 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
267 if (mAccountWasSet
) {
268 RelativeLayout navigationDrawerLayout
= (RelativeLayout
) findViewById(R
.id
.left_drawer
);
269 if (navigationDrawerLayout
!= null
&& getAccount() != null
) {
270 TextView username
= (TextView
) navigationDrawerLayout
.findViewById(R
.id
.drawer_username
);
271 int lastAtPos
= getAccount().name
.lastIndexOf("@");
272 username
.setText(getAccount().name
.substring(0, lastAtPos
));
276 if (!stateWasRecovered
) {
277 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
278 initFragmentsWithFile();
279 if (file
.isFolder()) {
280 startSyncFolderOperation(file
, false
);
284 updateFragmentsVisibility(!file
.isFolder());
285 updateActionBarTitleAndHomeButton(file
.isFolder() ? null
: file
);
290 private void createMinFragments() {
291 OCFileListFragment listOfFiles
= new OCFileListFragment();
292 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
293 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
294 transaction
.commit();
297 private void initFragmentsWithFile() {
298 if (getAccount() != null
&& getFile() != null
) {
300 OCFileListFragment listOfFiles
= getListOfFilesFragment();
301 if (listOfFiles
!= null
) {
302 listOfFiles
.listDirectory(getCurrentDir());
303 // TODO Enable when "On Device" is recovered
304 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
307 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
311 OCFile file
= getFile();
312 Fragment secondFragment
= chooseInitialSecondFragment(file
);
313 if (secondFragment
!= null
) {
314 setSecondFragment(secondFragment
);
315 updateFragmentsVisibility(true
);
316 updateActionBarTitleAndHomeButton(file
);
319 cleanSecondFragment();
320 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
))
321 startTextPreview(file
);
325 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
326 if (getAccount() == null
) {
327 Log_OC
.wtf(TAG
, "\t account is NULL");
329 if (getFile() == null
) {
330 Log_OC
.wtf(TAG
, "\t file is NULL");
335 private Fragment
chooseInitialSecondFragment(OCFile file
) {
336 Fragment secondFragment
= null
;
337 if (file
!= null
&& !file
.isFolder()) {
338 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
339 && file
.getLastSyncDateForProperties() > 0 // temporal fix
341 int startPlaybackPosition
=
342 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
344 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
345 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
346 startPlaybackPosition
, autoplay
);
348 } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) {
349 secondFragment
= null
;
351 secondFragment
= FileDetailFragment
.newInstance(file
, getAccount());
354 return secondFragment
;
359 * Replaces the second fragment managed by the activity with the received as
362 * Assumes never will be more than two fragments managed at the same time.
364 * @param fragment New second Fragment to set.
366 private void setSecondFragment(Fragment fragment
) {
367 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
368 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
369 transaction
.commit();
373 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
375 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
376 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
378 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
379 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
382 } else if (existsSecondFragment
) {
383 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
384 mLeftFragmentContainer
.setVisibility(View
.GONE
);
386 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
387 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
391 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
392 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
394 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
395 mRightFragmentContainer
.setVisibility(View
.GONE
);
401 private OCFileListFragment
getListOfFilesFragment() {
402 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
403 FileDisplayActivity
.TAG_LIST_OF_FILES
);
404 if (listOfFiles
!= null
) {
405 return (OCFileListFragment
) listOfFiles
;
407 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
411 public FileFragment
getSecondFragment() {
412 Fragment second
= getSupportFragmentManager().findFragmentByTag(
413 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
414 if (second
!= null
) {
415 return (FileFragment
) second
;
420 protected void cleanSecondFragment() {
421 Fragment second
= getSecondFragment();
422 if (second
!= null
) {
423 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
427 updateFragmentsVisibility(false
);
428 updateActionBarTitleAndHomeButton(null
);
431 protected void refreshListOfFilesFragment() {
432 OCFileListFragment fileListFragment
= getListOfFilesFragment();
433 if (fileListFragment
!= null
) {
434 fileListFragment
.listDirectory();
435 // TODO Enable when "On Device" is recovered ?
436 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
440 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
442 FileFragment secondFragment
= getSecondFragment();
443 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
444 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
445 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
446 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
447 OCFile fileInFragment
= detailsFragment
.getFile();
448 if (fileInFragment
!= null
&&
449 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
450 // the user browsed to other file ; forget the automatic preview
451 mWaitingToPreview
= null
;
453 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
454 // grant that the right panel updates the progress bar
455 detailsFragment
.listenForTransferProgress();
456 detailsFragment
.updateFileDetails(true
, false
);
458 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
459 // update the right panel
460 boolean detailsFragmentChanged
= false
;
463 mWaitingToPreview
= getStorageManager().getFileById(
464 mWaitingToPreview
.getFileId()); // update the file from database,
465 // for the local storage path
466 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
467 startMediaPreview(mWaitingToPreview
, 0, true
);
468 detailsFragmentChanged
= true
;
469 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
470 startTextPreview(mWaitingToPreview
);
471 detailsFragmentChanged
= true
;
473 getFileOperationsHelper().openFile(mWaitingToPreview
);
476 mWaitingToPreview
= null
;
478 if (!detailsFragmentChanged
) {
479 detailsFragment
.updateFileDetails(false
, (success
));
486 public boolean onPrepareOptionsMenu(Menu menu
) {
487 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
488 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
489 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
490 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
491 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
493 return super.onPrepareOptionsMenu(menu
);
497 public boolean onCreateOptionsMenu(Menu menu
) {
498 MenuInflater inflater
= getMenuInflater();
499 inflater
.inflate(R
.menu
.main_menu
, menu
);
505 public boolean onOptionsItemSelected(MenuItem item
) {
506 boolean retval
= true
;
507 switch (item
.getItemId()) {
508 case R
.id
.action_create_dir
: {
509 CreateFolderDialogFragment dialog
=
510 CreateFolderDialogFragment
.newInstance(getCurrentDir());
511 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
515 case R
.id
.action_sync_account
: {
516 startSynchronization();
519 case R
.id
.action_upload
: {
520 UploadSourceDialogFragment dialog
=
521 UploadSourceDialogFragment
.newInstance(getAccount());
522 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
525 case android
.R
.id
.home
: {
526 FileFragment second
= getSecondFragment();
527 OCFile currentDir
= getCurrentDir();
528 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
529 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
530 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
531 (second
!= null
&& second
.getFile() != null
)) {
535 mDrawerLayout
.openDrawer(GravityCompat
.START
);
539 case R
.id
.action_sort
: {
540 SharedPreferences appPreferences
= PreferenceManager
541 .getDefaultSharedPreferences(this);
543 // Read sorting order, default to sort by name ascending
544 Integer sortOrder
= appPreferences
545 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
547 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
548 builder
.setTitle(R
.string
.actionbar_sort_title
)
549 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
550 new DialogInterface
.OnClickListener() {
551 public void onClick(DialogInterface dialog
, int which
) {
564 builder
.create().show();
568 retval
= super.onOptionsItemSelected(item
);
573 private void startSynchronization() {
574 Log_OC
.d(TAG
, "Got to start sync");
575 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
576 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
577 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
578 // cancel the current synchronizations of any ownCloud account
579 Bundle bundle
= new Bundle();
580 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
581 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
582 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
583 MainApp
.getAuthority());
584 ContentResolver
.requestSync(
586 MainApp
.getAuthority(), bundle
);
588 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
589 MainApp
.getAuthority() + " with new API");
590 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
591 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
592 builder
.setExpedited(true
);
593 builder
.setManual(true
);
596 // Fix bug in Android Lollipop when you click on refresh the whole account
597 Bundle extras
= new Bundle();
598 builder
.setExtras(extras
);
600 SyncRequest request
= builder
.build();
601 ContentResolver
.requestSync(request
);
606 * Called, when the user selected something for uploading
609 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
611 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
613 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
614 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
615 //getClipData is only supported on api level 16+, Jelly Bean
616 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
617 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
618 Intent intent
= new Intent();
619 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
620 requestSimpleUpload(intent
, resultCode
);
623 requestSimpleUpload(data
, resultCode
);
625 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
626 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
627 requestMultipleUpload(data
, resultCode
);
629 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
630 final Intent fData
= data
;
631 final int fResultCode
= resultCode
;
632 getHandler().postDelayed(
636 requestMoveOperation(fData
, fResultCode
);
639 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
642 } else if (requestCode
== ACTION_COPY_FILES
&& resultCode
== RESULT_OK
) {
644 final Intent fData
= data
;
645 final int fResultCode
= resultCode
;
646 getHandler().postDelayed(
650 requestCopyOperation(fData
, fResultCode
);
653 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
657 super.onActivityResult(requestCode
, resultCode
, data
);
662 private void requestMultipleUpload(Intent data
, int resultCode
) {
663 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
664 if (filePaths
!= null
) {
665 String
[] remotePaths
= new String
[filePaths
.length
];
666 String remotePathBase
= getCurrentDir().getRemotePath();
667 for (int j
= 0; j
< remotePaths
.length
; j
++) {
668 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
671 Intent i
= new Intent(this, FileUploader
.class);
672 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
673 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
674 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
675 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
676 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
677 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
681 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
682 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
690 private void requestSimpleUpload(Intent data
, int resultCode
) {
691 String filePath
= null
;
692 String mimeType
= null
;
694 Uri selectedImageUri
= data
.getData();
697 mimeType
= getContentResolver().getType(selectedImageUri
);
699 String fileManagerString
= selectedImageUri
.getPath();
700 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
702 if (selectedImagePath
!= null
)
703 filePath
= selectedImagePath
;
705 filePath
= fileManagerString
;
707 } catch (Exception e
) {
708 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
709 "Intent.ACTION_GET_CONTENT", e
);
712 if (filePath
== null
) {
713 Log_OC
.e(TAG
, "Couldn't resolve path to file");
714 Toast t
= Toast
.makeText(
715 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
723 Intent i
= new Intent(this, FileUploader
.class);
724 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
725 OCFile currentDir
= getCurrentDir();
726 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
728 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
729 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
731 if (cursor
!= null
&& cursor
.moveToFirst()) {
732 String displayName
= cursor
.getString(cursor
.getColumnIndex(
733 OpenableColumns
.DISPLAY_NAME
));
734 Log_OC
.v(TAG
, "Display Name: " + displayName
);
736 displayName
.replace(File
.separatorChar
, '_');
737 displayName
.replace(File
.pathSeparatorChar
, '_');
738 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
741 // and what happens in case of error?; wrong target name for the upload
747 remotePath
+= new File(filePath
).getName();
750 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
751 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
752 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
753 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
754 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
755 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
760 * Request the operation for moving the file/folder from one path to another
762 * @param data Intent received
763 * @param resultCode Result code received
765 private void requestMoveOperation(Intent data
, int resultCode
) {
766 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
767 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
768 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
772 * Request the operation for copying the file/folder from one path to another
774 * @param data Intent received
775 * @param resultCode Result code received
777 private void requestCopyOperation(Intent data
, int resultCode
) {
778 OCFile folderToMoveAt
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
779 OCFile targetFile
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
780 getFileOperationsHelper().copyFile(folderToMoveAt
, targetFile
);
784 public void onBackPressed() {
785 if (!isDrawerOpen()){
786 OCFileListFragment listOfFiles
= getListOfFilesFragment();
787 if (mDualPane
|| getSecondFragment() == null
) {
788 OCFile currentDir
= getCurrentDir();
789 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
793 if (listOfFiles
!= null
) { // should never be null, indeed
794 listOfFiles
.onBrowseUp();
797 if (listOfFiles
!= null
) { // should never be null, indeed
798 setFile(listOfFiles
.getCurrentFile());
800 cleanSecondFragment();
802 super.onBackPressed();
807 protected void onSaveInstanceState(Bundle outState
) {
808 // responsibility of restore is preferred in onCreate() before than in
809 // onRestoreInstanceState when there are Fragments involved
810 Log_OC
.v(TAG
, "onSaveInstanceState() start");
811 super.onSaveInstanceState(outState
);
812 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
813 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
814 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
815 // mRefreshSharesInProgress);
816 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
818 Log_OC
.v(TAG
, "onSaveInstanceState() end");
823 protected void onResume() {
824 Log_OC
.v(TAG
, "onResume() start");
826 // refresh Navigation Drawer account list
827 mNavigationDrawerAdapter
.updateAccountList();
829 // refresh list of files
830 refreshListOfFilesFragment();
832 // Listen for sync messages
833 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
834 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
835 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
836 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
837 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
838 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
839 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
840 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
841 // syncIntentFilter);
843 // Listen for upload messages
844 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
845 mUploadFinishReceiver
= new UploadFinishReceiver();
846 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
848 // Listen for download messages
849 IntentFilter downloadIntentFilter
= new IntentFilter(
850 FileDownloader
.getDownloadAddedMessage());
851 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
852 mDownloadFinishReceiver
= new DownloadFinishReceiver();
853 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
855 Log_OC
.v(TAG
, "onResume() end");
861 protected void onPause() {
862 Log_OC
.v(TAG
, "onPause() start");
863 if (mSyncBroadcastReceiver
!= null
) {
864 unregisterReceiver(mSyncBroadcastReceiver
);
865 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
866 mSyncBroadcastReceiver
= null
;
868 if (mUploadFinishReceiver
!= null
) {
869 unregisterReceiver(mUploadFinishReceiver
);
870 mUploadFinishReceiver
= null
;
872 if (mDownloadFinishReceiver
!= null
) {
873 unregisterReceiver(mDownloadFinishReceiver
);
874 mDownloadFinishReceiver
= null
;
878 Log_OC
.v(TAG
, "onPause() end");
882 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
885 * {@link BroadcastReceiver} to enable syncing feedback in UI
888 public void onReceive(Context context
, Intent intent
) {
890 String event
= intent
.getAction();
891 Log_OC
.d(TAG
, "Received broadcast " + event
);
892 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
893 String synchFolderRemotePath
=
894 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
895 RemoteOperationResult synchResult
=
896 (RemoteOperationResult
)intent
.getSerializableExtra(
897 FileSyncAdapter
.EXTRA_RESULT
);
898 boolean sameAccount
= (getAccount() != null
&&
899 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
903 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
904 mSyncInProgress
= true
;
907 OCFile currentFile
= (getFile() == null
) ? null
:
908 getStorageManager().getFileByPath(getFile().getRemotePath());
909 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
910 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
912 if (currentDir
== null
) {
913 // current folder was removed from the server
914 Toast
.makeText( FileDisplayActivity
.this,
917 sync_current_folder_was_removed
),
918 synchFolderRemotePath
),
925 if (currentFile
== null
&& !getFile().isFolder()) {
926 // currently selected file was removed in the server, and now we
928 cleanSecondFragment();
929 currentFile
= currentDir
;
932 if (synchFolderRemotePath
!= null
&&
933 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
934 OCFileListFragment fileListFragment
= getListOfFilesFragment();
935 if (fileListFragment
!= null
) {
936 fileListFragment
.listDirectory();
937 // TODO Enable when "On Device" is recovered ?
938 // fileListFragment.listDirectory(currentDir,
939 // MainApp.getOnlyOnDevice());
942 setFile(currentFile
);
945 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
946 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
949 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
950 equals(event
) &&/// TODO refactor and make common
952 synchResult
!= null
&& !synchResult
.isSuccess() &&
953 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
954 synchResult
.isIdPRedirection() ||
955 (synchResult
.isException() && synchResult
.getException()
956 instanceof AuthenticatorException
))) {
960 OwnCloudClient client
;
961 OwnCloudAccount ocAccount
=
962 new OwnCloudAccount(getAccount(), context
);
963 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
964 removeClientFor(ocAccount
));
965 if (client
!= null
) {
966 OwnCloudCredentials cred
= client
.getCredentials();
968 AccountManager am
= AccountManager
.get(context
);
969 if (cred
.authTokenExpires()) {
970 am
.invalidateAuthToken(
975 am
.clearPassword(getAccount());
979 requestCredentialsUpdate();
981 } catch (AccountNotFoundException e
) {
982 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
987 removeStickyBroadcast(intent
);
988 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
989 mProgressBar
.setIndeterminate(mSyncInProgress
);
990 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
991 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
992 /*|| mRefreshSharesInProgress*/ //);
998 if (synchResult
!= null
) {
999 if (synchResult
.getCode().equals(
1000 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1001 mLastSslUntrustedServerResult
= synchResult
;
1004 } catch (RuntimeException e
) {
1005 // avoid app crashes after changing the serial id of RemoteOperationResult
1006 // in owncloud library with broadcast notifications pending to process
1007 removeStickyBroadcast(intent
);
1013 * Show a text message on screen view for notifying user if content is
1014 * loading or folder is empty
1016 private void setBackgroundText() {
1017 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1018 if (ocFileListFragment
!= null
) {
1019 int message
= R
.string
.file_list_loading
;
1020 if (!mSyncInProgress
) {
1021 // In case file list is empty
1022 message
= R
.string
.file_list_empty
;
1024 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1026 Log_OC
.e(TAG
, "OCFileListFragment is null");
1031 * Once the file upload has finished -> update view
1033 private class UploadFinishReceiver
extends BroadcastReceiver
{
1035 * Once the file upload has finished -> update view
1037 * @author David A. Velasco
1038 * {@link BroadcastReceiver} to enable upload feedback in UI
1041 public void onReceive(Context context
, Intent intent
) {
1043 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1044 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1045 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1046 OCFile currentDir
= getCurrentDir();
1047 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1048 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1050 if (sameAccount
&& isDescendant
) {
1051 String linkedToRemotePath
=
1052 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1053 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1054 refreshListOfFilesFragment();
1058 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1060 boolean renamedInUpload
= getFile().getRemotePath().
1061 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1062 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1064 FileFragment details
= getSecondFragment();
1065 boolean detailFragmentIsShown
= (details
!= null
&&
1066 details
instanceof FileDetailFragment
);
1068 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1069 if (uploadWasFine
) {
1070 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1072 if (renamedInUpload
) {
1073 String newName
= (new File(uploadedRemotePath
)).getName();
1074 Toast msg
= Toast
.makeText(
1077 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1082 if (uploadWasFine
|| getFile().fileExists()) {
1083 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1085 cleanSecondFragment();
1088 // Force the preview if the file is an image or text file
1089 if (uploadWasFine
) {
1090 OCFile ocFile
= getFile();
1091 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1092 startImagePreview(getFile());
1093 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1094 startTextPreview(ocFile
);
1095 // TODO what about other kind of previews?
1099 mProgressBar
.setIndeterminate(false
);
1101 if (intent
!= null
) {
1102 removeStickyBroadcast(intent
);
1108 // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
1109 private boolean isAscendant(String linkedToRemotePath
) {
1110 OCFile currentDir
= getCurrentDir();
1112 currentDir
!= null
&&
1113 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1122 * Class waiting for broadcast events from the {@link FileDownloader} service.
1124 * Updates the UI when a download is started or finished, provided that it is relevant for the
1127 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1130 public void onReceive(Context context
, Intent intent
) {
1132 boolean sameAccount
= isSameAccount(intent
);
1133 String downloadedRemotePath
=
1134 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1135 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1137 if (sameAccount
&& isDescendant
) {
1138 String linkedToRemotePath
=
1139 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1140 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1141 refreshListOfFilesFragment();
1143 refreshSecondFragment(
1145 downloadedRemotePath
,
1146 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1150 if (mWaitingToSend
!= null
) {
1152 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1153 if (mWaitingToSend
.isDown()) {
1154 sendDownloadedFile();
1159 if (intent
!= null
) {
1160 removeStickyBroadcast(intent
);
1165 private boolean isDescendant(String downloadedRemotePath
) {
1166 OCFile currentDir
= getCurrentDir();
1168 currentDir
!= null
&&
1169 downloadedRemotePath
!= null
&&
1170 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1174 private boolean isAscendant(String linkedToRemotePath
) {
1175 OCFile currentDir
= getCurrentDir();
1177 currentDir
!= null
&&
1178 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1182 private boolean isSameAccount(Intent intent
) {
1183 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1184 return (accountName
!= null
&& getAccount() != null
&&
1185 accountName
.equals(getAccount().name
));
1190 public void browseToRoot() {
1191 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1192 if (listOfFiles
!= null
) { // should never be null, indeed
1193 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1194 listOfFiles
.listDirectory(root
);
1195 // TODO Enable when "On Device" is recovered ?
1196 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1197 setFile(listOfFiles
.getCurrentFile());
1198 startSyncFolderOperation(root
, false
);
1200 cleanSecondFragment();
1207 * Updates action bar and second fragment, if in dual pane mode.
1210 public void onBrowsedDownTo(OCFile directory
) {
1212 cleanSecondFragment();
1214 startSyncFolderOperation(directory
, false
);
1218 * Shows the information of the {@link OCFile} received as a
1219 * parameter in the second fragment.
1221 * @param file {@link OCFile} whose details will be shown
1224 public void showDetails(OCFile file
) {
1225 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1226 setSecondFragment(detailFragment
);
1227 updateFragmentsVisibility(true
);
1228 updateActionBarTitleAndHomeButton(file
);
1233 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1235 // in dual pane mode, keep the focus of title an action bar in the current folder
1236 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1239 super.updateActionBarTitleAndHomeButton(chosenFile
);
1245 protected ServiceConnection
newTransferenceServiceConnection() {
1246 return new ListServiceConnection();
1250 * Defines callbacks for service binding, passed to bindService()
1252 private class ListServiceConnection
implements ServiceConnection
{
1255 public void onServiceConnected(ComponentName component
, IBinder service
) {
1256 if (component
.equals(new ComponentName(
1257 FileDisplayActivity
.this, FileDownloader
.class))) {
1258 Log_OC
.d(TAG
, "Download service connected");
1259 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1260 if (mWaitingToPreview
!= null
)
1261 if (getStorageManager() != null
) {
1264 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1265 if (!mWaitingToPreview
.isDown()) {
1266 requestForDownload();
1270 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1271 FileUploader
.class))) {
1272 Log_OC
.d(TAG
, "Upload service connected");
1273 mUploaderBinder
= (FileUploaderBinder
) service
;
1277 // a new chance to get the mDownloadBinder through
1278 // getFileDownloadBinder() - THIS IS A MESS
1279 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1280 if (listOfFiles
!= null
) {
1281 listOfFiles
.listDirectory();
1282 // TODO Enable when "On Device" is recovered ?
1283 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1285 FileFragment secondFragment
= getSecondFragment();
1286 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1287 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1288 detailFragment
.listenForTransferProgress();
1289 detailFragment
.updateFileDetails(false
, false
);
1294 public void onServiceDisconnected(ComponentName component
) {
1295 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1296 FileDownloader
.class))) {
1297 Log_OC
.d(TAG
, "Download service disconnected");
1298 mDownloaderBinder
= null
;
1299 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1300 FileUploader
.class))) {
1301 Log_OC
.d(TAG
, "Upload service disconnected");
1302 mUploaderBinder
= null
;
1308 public void onSavedCertificate() {
1309 startSyncFolderOperation(getCurrentDir(), false
);
1314 public void onFailedSavingCertificate() {
1315 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1316 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1318 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1322 public void onCancelCertificate() {
1327 * Updates the view associated to the activity after the finish of some operation over files
1328 * in the current account.
1330 * @param operation Removal operation performed.
1331 * @param result Result of the removal.
1334 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1335 super.onRemoteOperationFinish(operation
, result
);
1337 if (operation
instanceof RemoveFileOperation
) {
1338 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1340 } else if (operation
instanceof RenameFileOperation
) {
1341 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1343 } else if (operation
instanceof SynchronizeFileOperation
) {
1344 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1346 } else if (operation
instanceof CreateFolderOperation
) {
1347 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1349 } else if (operation
instanceof CreateShareOperation
) {
1350 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1352 } else if (operation
instanceof UnshareLinkOperation
) {
1353 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
1355 } else if (operation
instanceof MoveFileOperation
) {
1356 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1358 } else if (operation
instanceof CopyFileOperation
) {
1359 onCopyFileOperationFinish((CopyFileOperation
) operation
, result
);
1363 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1364 RemoteOperationResult result
) {
1365 if (result
.isSuccess()) {
1366 refreshShowDetails();
1367 refreshListOfFilesFragment();
1371 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1372 RemoteOperationResult result
) {
1373 if (result
.isSuccess()) {
1374 refreshShowDetails();
1375 refreshListOfFilesFragment();
1377 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1378 cleanSecondFragment();
1379 refreshListOfFilesFragment();
1383 private void refreshShowDetails() {
1384 FileFragment details
= getSecondFragment();
1385 if (details
!= null
) {
1386 OCFile file
= details
.getFile();
1388 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1389 if (details
instanceof PreviewMediaFragment
) {
1390 // Refresh OCFile of the fragment
1391 ((PreviewMediaFragment
) details
).updateFile(file
);
1392 } else if (details
instanceof PreviewTextFragment
) {
1393 // Refresh OCFile of the fragment
1394 ((PreviewTextFragment
) details
).updateFile(file
);
1399 invalidateOptionsMenu();
1404 * Updates the view associated to the activity after the finish of an operation trying to
1407 * @param operation Removal operation performed.
1408 * @param result Result of the removal.
1410 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1411 RemoteOperationResult result
) {
1412 dismissLoadingDialog();
1414 Toast msg
= Toast
.makeText(this,
1415 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1419 if (result
.isSuccess()) {
1420 OCFile removedFile
= operation
.getFile();
1421 FileFragment second
= getSecondFragment();
1422 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1423 if (second
instanceof PreviewMediaFragment
) {
1424 ((PreviewMediaFragment
) second
).stopPreview(true
);
1426 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1427 cleanSecondFragment();
1429 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){
1430 refreshListOfFilesFragment();
1432 invalidateOptionsMenu();
1434 if (result
.isSslRecoverableException()) {
1435 mLastSslUntrustedServerResult
= result
;
1436 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1443 * Updates the view associated to the activity after the finish of an operation trying to move a
1446 * @param operation Move operation performed.
1447 * @param result Result of the move operation.
1449 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1450 RemoteOperationResult result
) {
1451 if (result
.isSuccess()) {
1452 dismissLoadingDialog();
1453 refreshListOfFilesFragment();
1455 dismissLoadingDialog();
1457 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1458 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1462 } catch (NotFoundException e
) {
1463 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1469 * Updates the view associated to the activity after the finish of an operation trying to copy a
1472 * @param operation Copy operation performed.
1473 * @param result Result of the copy operation.
1475 private void onCopyFileOperationFinish(CopyFileOperation operation
, RemoteOperationResult result
) {
1476 if (result
.isSuccess()) {
1477 dismissLoadingDialog();
1478 refreshListOfFilesFragment();
1480 dismissLoadingDialog();
1482 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1483 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1487 } catch (NotFoundException e
) {
1488 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1494 * Updates the view associated to the activity after the finish of an operation trying to rename
1497 * @param operation Renaming operation performed.
1498 * @param result Result of the renaming.
1500 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1501 RemoteOperationResult result
) {
1502 dismissLoadingDialog();
1503 OCFile renamedFile
= operation
.getFile();
1504 if (result
.isSuccess()) {
1505 FileFragment details
= getSecondFragment();
1506 if (details
!= null
) {
1507 if (details
instanceof FileDetailFragment
&&
1508 renamedFile
.equals(details
.getFile()) ) {
1509 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1510 showDetails(renamedFile
);
1512 } else if (details
instanceof PreviewMediaFragment
&&
1513 renamedFile
.equals(details
.getFile())) {
1514 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1515 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1516 int position
= ((PreviewMediaFragment
) details
).getPosition();
1517 startMediaPreview(renamedFile
, position
, true
);
1519 getFileOperationsHelper().openFile(renamedFile
);
1521 } else if (details
instanceof PreviewTextFragment
&&
1522 renamedFile
.equals(details
.getFile())) {
1523 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1524 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1525 startTextPreview(renamedFile
);
1527 getFileOperationsHelper().openFile(renamedFile
);
1532 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1533 refreshListOfFilesFragment();
1537 Toast msg
= Toast
.makeText(this,
1538 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1542 if (result
.isSslRecoverableException()) {
1543 mLastSslUntrustedServerResult
= result
;
1544 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1549 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1550 RemoteOperationResult result
) {
1551 if (result
.isSuccess()) {
1552 if (operation
.transferWasRequested()) {
1553 OCFile syncedFile
= operation
.getLocalFile();
1554 onTransferStateChanged(syncedFile
, true
, true
);
1555 invalidateOptionsMenu();
1556 refreshShowDetails();
1562 * Updates the view associated to the activity after the finish of an operation trying create a
1565 * @param operation Creation operation performed.
1566 * @param result Result of the creation.
1568 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1569 RemoteOperationResult result
) {
1570 if (result
.isSuccess()) {
1571 dismissLoadingDialog();
1572 refreshListOfFilesFragment();
1574 dismissLoadingDialog();
1576 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1577 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1581 } catch (NotFoundException e
) {
1582 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1592 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1593 refreshListOfFilesFragment();
1594 FileFragment details
= getSecondFragment();
1595 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1596 file
.equals(details
.getFile()) ) {
1597 if (downloading
|| uploading
) {
1598 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1600 if (!file
.fileExists()) {
1601 cleanSecondFragment();
1603 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1611 private void requestForDownload() {
1612 Account account
= getAccount();
1613 //if (!mWaitingToPreview.isDownloading()) {
1614 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1615 Intent i
= new Intent(this, FileDownloader
.class);
1616 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1617 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1623 private OCFile
getCurrentDir() {
1624 OCFile file
= getFile();
1626 if (file
.isFolder()) {
1628 } else if (getStorageManager() != null
) {
1629 String parentPath
= file
.getRemotePath().substring(0,
1630 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1631 return getStorageManager().getFileByPath(parentPath
);
1637 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1638 long currentSyncTime
= System
.currentTimeMillis();
1640 mSyncInProgress
= true
;
1642 // perform folder synchronization
1643 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1646 getFileOperationsHelper().isSharedSupported(),
1648 getStorageManager(),
1650 getApplicationContext()
1652 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1654 mProgressBar
.setIndeterminate(true
);
1656 setBackgroundText();
1660 * Show untrusted cert dialog
1662 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1663 // Show a dialog with the certificate info
1664 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1665 (CertificateCombinedException
) result
.getException());
1666 FragmentManager fm
= getSupportFragmentManager();
1667 FragmentTransaction ft
= fm
.beginTransaction();
1668 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1671 private void requestForDownload(OCFile file
) {
1672 Account account
= getAccount();
1673 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1674 Intent i
= new Intent(this, FileDownloader
.class);
1675 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1676 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1681 private void sendDownloadedFile() {
1682 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1683 mWaitingToSend
= null
;
1688 * Requests the download of the received {@link OCFile} , updates the UI
1689 * to monitor the download progress and prepares the activity to send the file
1690 * when the download finishes.
1692 * @param file {@link OCFile} to download and preview.
1694 public void startDownloadForSending(OCFile file
) {
1695 mWaitingToSend
= file
;
1696 requestForDownload(mWaitingToSend
);
1697 boolean hasSecondFragment
= (getSecondFragment() != null
);
1698 updateFragmentsVisibility(hasSecondFragment
);
1702 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1704 * @param file Image {@link OCFile} to show.
1706 public void startImagePreview(OCFile file
) {
1707 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1708 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1709 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1710 startActivity(showDetailsIntent
);
1714 * Stars the preview of an already down media {@link OCFile}.
1716 * @param file Media {@link OCFile} to preview.
1717 * @param startPlaybackPosition Media position where the playback will be started,
1719 * @param autoplay When 'true', the playback will start without user
1722 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1723 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1725 setSecondFragment(mediaFragment
);
1726 updateFragmentsVisibility(true
);
1727 updateActionBarTitleAndHomeButton(file
);
1732 * Stars the preview of a text file {@link OCFile}.
1734 * @param file Text {@link OCFile} to preview.
1736 public void startTextPreview(OCFile file
) {
1737 Bundle args
= new Bundle();
1738 args
.putParcelable(EXTRA_FILE
, file
);
1739 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1740 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(),
1741 PreviewTextFragment
.class.getName(), args
);
1742 setSecondFragment(textPreviewFragment
);
1743 updateFragmentsVisibility(true
);
1744 //updateNavigationElementsInActionBar(file);
1749 * Requests the download of the received {@link OCFile} , updates the UI
1750 * to monitor the download progress and prepares the activity to preview
1751 * or open the file when the download finishes.
1753 * @param file {@link OCFile} to download and preview.
1755 public void startDownloadForPreview(OCFile file
) {
1756 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1757 setSecondFragment(detailFragment
);
1758 mWaitingToPreview
= file
;
1759 requestForDownload();
1760 updateFragmentsVisibility(true
);
1761 updateActionBarTitleAndHomeButton(file
);
1766 public void cancelTransference(OCFile file
) {
1767 getFileOperationsHelper().cancelTransference(file
);
1768 if (mWaitingToPreview
!= null
&&
1769 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1770 mWaitingToPreview
= null
;
1772 if (mWaitingToSend
!= null
&&
1773 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1774 mWaitingToSend
= null
;
1776 onTransferStateChanged(file
, false
, false
);
1780 public void onRefresh(boolean ignoreETag
) {
1781 refreshList(ignoreETag
);
1785 public void onRefresh() {
1789 private void refreshList(boolean ignoreETag
) {
1790 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1791 if (listOfFiles
!= null
) {
1792 OCFile folder
= listOfFiles
.getCurrentFile();
1793 if (folder
!= null
) {
1794 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1795 listDirectory(mFile);*/
1796 startSyncFolderOperation(folder
, ignoreETag
);
1801 private void sortByDate(boolean ascending
) {
1802 getListOfFilesFragment().sortByDate(ascending
);
1805 private void sortBySize(boolean ascending
) {
1806 getListOfFilesFragment().sortBySize(ascending
);
1809 private void sortByName(boolean ascending
) {
1810 getListOfFilesFragment().sortByName(ascending
);
1813 public void allFilesOption() {