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 refreshListOfFilesFragment();
1054 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1056 boolean renamedInUpload
= getFile().getRemotePath().
1057 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1058 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1060 FileFragment details
= getSecondFragment();
1061 boolean detailFragmentIsShown
= (details
!= null
&&
1062 details
instanceof FileDetailFragment
);
1064 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1065 if (uploadWasFine
) {
1066 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1068 if (renamedInUpload
) {
1069 String newName
= (new File(uploadedRemotePath
)).getName();
1070 Toast msg
= Toast
.makeText(
1073 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1078 if (uploadWasFine
|| getFile().fileExists()) {
1079 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1081 cleanSecondFragment();
1084 // Force the preview if the file is an image or text file
1085 if (uploadWasFine
) {
1086 OCFile ocFile
= getFile();
1087 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1088 startImagePreview(getFile());
1089 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1090 startTextPreview(ocFile
);
1091 // TODO what about other kind of previews?
1095 mProgressBar
.setIndeterminate(false
);
1097 if (intent
!= null
) {
1098 removeStickyBroadcast(intent
);
1108 * Class waiting for broadcast events from the {@link FileDownloader} service.
1110 * Updates the UI when a download is started or finished, provided that it is relevant for the
1113 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1115 //int refreshCounter = 0;
1117 public void onReceive(Context context
, Intent intent
) {
1119 boolean sameAccount
= isSameAccount(context
, intent
);
1120 String downloadedRemotePath
=
1121 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1122 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1124 if (sameAccount
&& isDescendant
) {
1125 String linkedToRemotePath
=
1126 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1127 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1128 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1129 refreshListOfFilesFragment();
1131 refreshSecondFragment(
1133 downloadedRemotePath
,
1134 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1138 if (mWaitingToSend
!= null
) {
1140 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1141 if (mWaitingToSend
.isDown()) {
1142 sendDownloadedFile();
1147 if (intent
!= null
) {
1148 removeStickyBroadcast(intent
);
1153 private boolean isDescendant(String downloadedRemotePath
) {
1154 OCFile currentDir
= getCurrentDir();
1156 currentDir
!= null
&&
1157 downloadedRemotePath
!= null
&&
1158 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1162 private boolean isAscendant(String linkedToRemotePath
) {
1163 OCFile currentDir
= getCurrentDir();
1165 currentDir
!= null
&&
1166 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1170 private boolean isSameAccount(Context context
, Intent intent
) {
1171 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1172 return (accountName
!= null
&& getAccount() != null
&&
1173 accountName
.equals(getAccount().name
));
1178 public void browseToRoot() {
1179 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1180 if (listOfFiles
!= null
) { // should never be null, indeed
1181 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1182 listOfFiles
.listDirectory(root
);
1183 // TODO Enable when "On Device" is recovered ?
1184 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1185 setFile(listOfFiles
.getCurrentFile());
1186 startSyncFolderOperation(root
, false
);
1188 cleanSecondFragment();
1195 * Updates action bar and second fragment, if in dual pane mode.
1198 public void onBrowsedDownTo(OCFile directory
) {
1200 cleanSecondFragment();
1202 startSyncFolderOperation(directory
, false
);
1206 * Shows the information of the {@link OCFile} received as a
1207 * parameter in the second fragment.
1209 * @param file {@link OCFile} whose details will be shown
1212 public void showDetails(OCFile file
) {
1213 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1214 setSecondFragment(detailFragment
);
1215 updateFragmentsVisibility(true
);
1216 updateActionBarTitleAndHomeButton(file
);
1221 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1223 // in dual pane mode, keep the focus of title an action bar in the current folder
1224 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1227 super.updateActionBarTitleAndHomeButton(chosenFile
);
1233 protected ServiceConnection
newTransferenceServiceConnection() {
1234 return new ListServiceConnection();
1238 * Defines callbacks for service binding, passed to bindService()
1240 private class ListServiceConnection
implements ServiceConnection
{
1243 public void onServiceConnected(ComponentName component
, IBinder service
) {
1244 if (component
.equals(new ComponentName(
1245 FileDisplayActivity
.this, FileDownloader
.class))) {
1246 Log_OC
.d(TAG
, "Download service connected");
1247 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1248 if (mWaitingToPreview
!= null
)
1249 if (getStorageManager() != null
) {
1252 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1253 if (!mWaitingToPreview
.isDown()) {
1254 requestForDownload();
1258 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1259 FileUploader
.class))) {
1260 Log_OC
.d(TAG
, "Upload service connected");
1261 mUploaderBinder
= (FileUploaderBinder
) service
;
1265 // a new chance to get the mDownloadBinder through
1266 // getFileDownloadBinder() - THIS IS A MESS
1267 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1268 if (listOfFiles
!= null
) {
1269 listOfFiles
.listDirectory();
1270 // TODO Enable when "On Device" is recovered ?
1271 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1273 FileFragment secondFragment
= getSecondFragment();
1274 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1275 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1276 detailFragment
.listenForTransferProgress();
1277 detailFragment
.updateFileDetails(false
, false
);
1282 public void onServiceDisconnected(ComponentName component
) {
1283 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1284 FileDownloader
.class))) {
1285 Log_OC
.d(TAG
, "Download service disconnected");
1286 mDownloaderBinder
= null
;
1287 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1288 FileUploader
.class))) {
1289 Log_OC
.d(TAG
, "Upload service disconnected");
1290 mUploaderBinder
= null
;
1296 public void onSavedCertificate() {
1297 startSyncFolderOperation(getCurrentDir(), false
);
1302 public void onFailedSavingCertificate() {
1303 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1304 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1306 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1310 public void onCancelCertificate() {
1315 * Updates the view associated to the activity after the finish of some operation over files
1316 * in the current account.
1318 * @param operation Removal operation performed.
1319 * @param result Result of the removal.
1322 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1323 super.onRemoteOperationFinish(operation
, result
);
1325 if (operation
instanceof RemoveFileOperation
) {
1326 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1328 } else if (operation
instanceof RenameFileOperation
) {
1329 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1331 } else if (operation
instanceof SynchronizeFileOperation
) {
1332 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1334 } else if (operation
instanceof CreateFolderOperation
) {
1335 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1337 } else if (operation
instanceof CreateShareOperation
) {
1338 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1340 } else if (operation
instanceof UnshareLinkOperation
) {
1341 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
1343 } else if (operation
instanceof MoveFileOperation
) {
1344 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1346 } else if (operation
instanceof CopyFileOperation
) {
1347 onCopyFileOperationFinish((CopyFileOperation
) operation
, result
);
1351 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1352 RemoteOperationResult result
) {
1353 if (result
.isSuccess()) {
1354 refreshShowDetails();
1355 refreshListOfFilesFragment();
1359 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1360 RemoteOperationResult result
) {
1361 if (result
.isSuccess()) {
1362 refreshShowDetails();
1363 refreshListOfFilesFragment();
1365 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1366 cleanSecondFragment();
1367 refreshListOfFilesFragment();
1371 private void refreshShowDetails() {
1372 FileFragment details
= getSecondFragment();
1373 if (details
!= null
) {
1374 OCFile file
= details
.getFile();
1376 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1377 if (details
instanceof PreviewMediaFragment
) {
1378 // Refresh OCFile of the fragment
1379 ((PreviewMediaFragment
) details
).updateFile(file
);
1380 } else if (details
instanceof PreviewTextFragment
) {
1381 // Refresh OCFile of the fragment
1382 ((PreviewTextFragment
) details
).updateFile(file
);
1387 invalidateOptionsMenu();
1392 * Updates the view associated to the activity after the finish of an operation trying to
1395 * @param operation Removal operation performed.
1396 * @param result Result of the removal.
1398 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1399 RemoteOperationResult result
) {
1400 dismissLoadingDialog();
1402 Toast msg
= Toast
.makeText(this,
1403 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1407 if (result
.isSuccess()) {
1408 OCFile removedFile
= operation
.getFile();
1409 FileFragment second
= getSecondFragment();
1410 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1411 if (second
instanceof PreviewMediaFragment
) {
1412 ((PreviewMediaFragment
) second
).stopPreview(true
);
1414 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1415 cleanSecondFragment();
1417 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){
1418 refreshListOfFilesFragment();
1420 invalidateOptionsMenu();
1422 if (result
.isSslRecoverableException()) {
1423 mLastSslUntrustedServerResult
= result
;
1424 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1431 * Updates the view associated to the activity after the finish of an operation trying to move a
1434 * @param operation Move operation performed.
1435 * @param result Result of the move operation.
1437 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1438 RemoteOperationResult result
) {
1439 if (result
.isSuccess()) {
1440 dismissLoadingDialog();
1441 refreshListOfFilesFragment();
1443 dismissLoadingDialog();
1445 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1446 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1450 } catch (NotFoundException e
) {
1451 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1457 * Updates the view associated to the activity after the finish of an operation trying to copy a
1460 * @param operation Copy operation performed.
1461 * @param result Result of the copy operation.
1463 private void onCopyFileOperationFinish(CopyFileOperation operation
, RemoteOperationResult result
) {
1464 if (result
.isSuccess()) {
1465 dismissLoadingDialog();
1466 refreshListOfFilesFragment();
1468 dismissLoadingDialog();
1470 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1471 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1475 } catch (NotFoundException e
) {
1476 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1482 * Updates the view associated to the activity after the finish of an operation trying to rename
1485 * @param operation Renaming operation performed.
1486 * @param result Result of the renaming.
1488 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1489 RemoteOperationResult result
) {
1490 dismissLoadingDialog();
1491 OCFile renamedFile
= operation
.getFile();
1492 if (result
.isSuccess()) {
1493 FileFragment details
= getSecondFragment();
1494 if (details
!= null
) {
1495 if (details
instanceof FileDetailFragment
&&
1496 renamedFile
.equals(details
.getFile()) ) {
1497 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1498 showDetails(renamedFile
);
1500 } else if (details
instanceof PreviewMediaFragment
&&
1501 renamedFile
.equals(details
.getFile())) {
1502 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1503 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1504 int position
= ((PreviewMediaFragment
) details
).getPosition();
1505 startMediaPreview(renamedFile
, position
, true
);
1507 getFileOperationsHelper().openFile(renamedFile
);
1509 } else if (details
instanceof PreviewTextFragment
&&
1510 renamedFile
.equals(details
.getFile())) {
1511 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1512 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1513 startTextPreview(renamedFile
);
1515 getFileOperationsHelper().openFile(renamedFile
);
1520 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1521 refreshListOfFilesFragment();
1525 Toast msg
= Toast
.makeText(this,
1526 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1530 if (result
.isSslRecoverableException()) {
1531 mLastSslUntrustedServerResult
= result
;
1532 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1537 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1538 RemoteOperationResult result
) {
1539 if (result
.isSuccess()) {
1540 if (operation
.transferWasRequested()) {
1541 OCFile syncedFile
= operation
.getLocalFile();
1542 onTransferStateChanged(syncedFile
, true
, true
);
1543 invalidateOptionsMenu();
1544 refreshShowDetails();
1550 * Updates the view associated to the activity after the finish of an operation trying create a
1553 * @param operation Creation operation performed.
1554 * @param result Result of the creation.
1556 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1557 RemoteOperationResult result
) {
1558 if (result
.isSuccess()) {
1559 dismissLoadingDialog();
1560 refreshListOfFilesFragment();
1562 dismissLoadingDialog();
1564 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1565 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1569 } catch (NotFoundException e
) {
1570 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1580 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1581 refreshListOfFilesFragment();
1582 FileFragment details
= getSecondFragment();
1583 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1584 file
.equals(details
.getFile()) ) {
1585 if (downloading
|| uploading
) {
1586 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1588 if (!file
.fileExists()) {
1589 cleanSecondFragment();
1591 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1599 private void requestForDownload() {
1600 Account account
= getAccount();
1601 //if (!mWaitingToPreview.isDownloading()) {
1602 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1603 Intent i
= new Intent(this, FileDownloader
.class);
1604 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1605 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1611 private OCFile
getCurrentDir() {
1612 OCFile file
= getFile();
1614 if (file
.isFolder()) {
1616 } else if (getStorageManager() != null
) {
1617 String parentPath
= file
.getRemotePath().substring(0,
1618 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1619 return getStorageManager().getFileByPath(parentPath
);
1625 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1626 long currentSyncTime
= System
.currentTimeMillis();
1628 mSyncInProgress
= true
;
1630 // perform folder synchronization
1631 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1634 getFileOperationsHelper().isSharedSupported(),
1636 getStorageManager(),
1638 getApplicationContext()
1640 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1642 mProgressBar
.setIndeterminate(true
);
1644 setBackgroundText();
1648 * Show untrusted cert dialog
1650 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1651 // Show a dialog with the certificate info
1652 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1653 (CertificateCombinedException
) result
.getException());
1654 FragmentManager fm
= getSupportFragmentManager();
1655 FragmentTransaction ft
= fm
.beginTransaction();
1656 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1659 private void requestForDownload(OCFile file
) {
1660 Account account
= getAccount();
1661 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1662 Intent i
= new Intent(this, FileDownloader
.class);
1663 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1664 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1669 private void sendDownloadedFile() {
1670 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1671 mWaitingToSend
= null
;
1676 * Requests the download of the received {@link OCFile} , updates the UI
1677 * to monitor the download progress and prepares the activity to send the file
1678 * when the download finishes.
1680 * @param file {@link OCFile} to download and preview.
1682 public void startDownloadForSending(OCFile file
) {
1683 mWaitingToSend
= file
;
1684 requestForDownload(mWaitingToSend
);
1685 boolean hasSecondFragment
= (getSecondFragment() != null
);
1686 updateFragmentsVisibility(hasSecondFragment
);
1690 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1692 * @param file Image {@link OCFile} to show.
1694 public void startImagePreview(OCFile file
) {
1695 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1696 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1697 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1698 startActivity(showDetailsIntent
);
1702 * Stars the preview of an already down media {@link OCFile}.
1704 * @param file Media {@link OCFile} to preview.
1705 * @param startPlaybackPosition Media position where the playback will be started,
1707 * @param autoplay When 'true', the playback will start without user
1710 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1711 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1713 setSecondFragment(mediaFragment
);
1714 updateFragmentsVisibility(true
);
1715 updateActionBarTitleAndHomeButton(file
);
1720 * Stars the preview of a text file {@link OCFile}.
1722 * @param file Text {@link OCFile} to preview.
1724 public void startTextPreview(OCFile file
) {
1725 Bundle args
= new Bundle();
1726 args
.putParcelable(EXTRA_FILE
, file
);
1727 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1728 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(),
1729 PreviewTextFragment
.class.getName(), args
);
1730 setSecondFragment(textPreviewFragment
);
1731 updateFragmentsVisibility(true
);
1732 //updateNavigationElementsInActionBar(file);
1737 * Requests the download of the received {@link OCFile} , updates the UI
1738 * to monitor the download progress and prepares the activity to preview
1739 * or open the file when the download finishes.
1741 * @param file {@link OCFile} to download and preview.
1743 public void startDownloadForPreview(OCFile file
) {
1744 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1745 setSecondFragment(detailFragment
);
1746 mWaitingToPreview
= file
;
1747 requestForDownload();
1748 updateFragmentsVisibility(true
);
1749 updateActionBarTitleAndHomeButton(file
);
1754 public void cancelTransference(OCFile file
) {
1755 getFileOperationsHelper().cancelTransference(file
);
1756 if (mWaitingToPreview
!= null
&&
1757 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1758 mWaitingToPreview
= null
;
1760 if (mWaitingToSend
!= null
&&
1761 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1762 mWaitingToSend
= null
;
1764 onTransferStateChanged(file
, false
, false
);
1768 public void onRefresh(boolean ignoreETag
) {
1769 refreshList(ignoreETag
);
1773 public void onRefresh() {
1777 private void refreshList(boolean ignoreETag
) {
1778 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1779 if (listOfFiles
!= null
) {
1780 OCFile folder
= listOfFiles
.getCurrentFile();
1781 if (folder
!= null
) {
1782 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1783 listDirectory(mFile);*/
1784 startSyncFolderOperation(folder
, ignoreETag
);
1789 private void sortByDate(boolean ascending
) {
1790 getListOfFilesFragment().sortByDate(ascending
);
1793 private void sortBySize(boolean ascending
) {
1794 getListOfFilesFragment().sortBySize(ascending
);
1797 private void sortByName(boolean ascending
) {
1798 getListOfFilesFragment().sortByName(ascending
);
1801 public void allFilesOption() {