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
.CreateFolderOperation
;
81 import com
.owncloud
.android
.operations
.CreateShareOperation
;
82 import com
.owncloud
.android
.operations
.MoveFileOperation
;
83 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
84 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
85 import com
.owncloud
.android
.operations
.RenameFileOperation
;
86 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
87 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
88 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
89 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
90 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
91 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
92 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
94 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
95 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
96 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
97 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
102 import com
.owncloud
.android
.utils
.DisplayUtils
;
103 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
104 import com
.owncloud
.android
.utils
.FileStorageUtils
;
105 import com
.owncloud
.android
.utils
.UriUtils
;
111 * Displays, what files the user has available in his ownCloud.
114 public class FileDisplayActivity
extends HookActivity
115 implements FileFragment
.ContainerActivity
,
116 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
118 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
119 private UploadFinishReceiver mUploadFinishReceiver
;
120 private DownloadFinishReceiver mDownloadFinishReceiver
;
121 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
123 private boolean mDualPane
;
124 private View mLeftFragmentContainer
;
125 private View mRightFragmentContainer
;
126 private ProgressBar mProgressBar
;
128 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
129 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
130 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
132 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
134 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
135 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
136 public static final int ACTION_MOVE_FILES
= 3;
138 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
140 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
141 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
143 private OCFile mWaitingToPreview
;
145 private boolean mSyncInProgress
= false
;
147 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
148 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
149 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
150 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
152 private OCFile mWaitingToSend
;
156 protected void onCreate(Bundle savedInstanceState
) {
157 Log_OC
.v(TAG
, "onCreate() start");
159 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
162 /// grant that FileObserverService is watching favorite files
163 if (savedInstanceState
== null
) {
164 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
165 startService(initObserversIntent
);
168 /// Load of saved instance state
169 if(savedInstanceState
!= null
) {
170 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
171 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
172 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
173 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
174 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
177 mWaitingToPreview
= null
;
178 mSyncInProgress
= false
;
179 mWaitingToSend
= null
;
184 // Inflate and set the layout view
185 setContentView(R
.layout
.files
);
190 mProgressBar
= (ProgressBar
) findViewById(R
.id
.progressBar
);
191 mProgressBar
.setIndeterminateDrawable(
192 ContextCompat
.getDrawable(this,
193 R
.drawable
.actionbar_progress_indeterminate_horizontal
));
195 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
196 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
197 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
198 if (savedInstanceState
== null
) {
199 createMinFragments();
203 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
204 // according to the official
207 // enable ActionBar app icon to behave as action to toggle nav drawer
208 //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
209 getSupportActionBar().setHomeButtonEnabled(true
);
211 mProgressBar
.setIndeterminate(mSyncInProgress
);
212 // always AFTER setContentView(...) ; to work around bug in its implementation
216 Log_OC
.v(TAG
, "onCreate() end");
220 protected void onStart() {
221 Log_OC
.v(TAG
, "onStart() start");
223 Log_OC
.v(TAG
, "onStart() end");
227 protected void onDestroy() {
228 Log_OC
.v(TAG
, "onDestroy() start");
230 Log_OC
.v(TAG
, "onDestroy() end");
234 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
237 protected void onAccountSet(boolean stateWasRecovered
) {
238 super.onAccountSet(stateWasRecovered
);
239 if (getAccount() != null
) {
240 /// Check whether the 'main' OCFile handled by the Activity is contained in the
242 OCFile file
= getFile();
243 // get parent from path
244 String parentPath
= "";
246 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
247 // upload in progress - right now, files are not inserted in the local
248 // cache until the upload is successful get parent from path
249 parentPath
= file
.getRemotePath().substring(0,
250 file
.getRemotePath().lastIndexOf(file
.getFileName()));
251 if (getStorageManager().getFileByPath(parentPath
) == null
)
252 file
= null
; // not able to know the directory where the file is uploading
254 file
= getStorageManager().getFileByPath(file
.getRemotePath());
255 // currentDir = null if not in the current Account
259 // fall back to root folder
260 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
264 if (mAccountWasSet
) {
265 RelativeLayout navigationDrawerLayout
= (RelativeLayout
) findViewById(R
.id
.left_drawer
);
266 if (navigationDrawerLayout
!= null
&& getAccount() != null
) {
267 TextView username
= (TextView
) navigationDrawerLayout
.findViewById(R
.id
.drawer_username
);
268 int lastAtPos
= getAccount().name
.lastIndexOf("@");
269 username
.setText(getAccount().name
.substring(0, lastAtPos
));
273 if (!stateWasRecovered
) {
274 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
275 initFragmentsWithFile();
276 if (file
.isFolder()) {
277 startSyncFolderOperation(file
, false
);
281 updateFragmentsVisibility(!file
.isFolder());
282 updateActionBarTitleAndHomeButton(file
.isFolder() ? null
: file
);
288 private void createMinFragments() {
289 OCFileListFragment listOfFiles
= new OCFileListFragment();
290 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
291 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
292 transaction
.commit();
295 private void initFragmentsWithFile() {
296 if (getAccount() != null
&& getFile() != null
) {
298 OCFileListFragment listOfFiles
= getListOfFilesFragment();
299 if (listOfFiles
!= null
) {
300 listOfFiles
.listDirectory(getCurrentDir());
301 // TODO Enable when "On Device" is recovered
302 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
304 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
308 OCFile file
= getFile();
309 Fragment secondFragment
= chooseInitialSecondFragment(file
);
310 if (secondFragment
!= null
) {
311 setSecondFragment(secondFragment
);
312 updateFragmentsVisibility(true
);
313 updateActionBarTitleAndHomeButton(file
);
316 cleanSecondFragment();
320 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
321 if (getAccount() == null
) {
322 Log_OC
.wtf(TAG
, "\t account is NULL");
324 if (getFile() == null
) {
325 Log_OC
.wtf(TAG
, "\t file is NULL");
330 private Fragment
chooseInitialSecondFragment(OCFile file
) {
331 Fragment secondFragment
= null
;
332 if (file
!= null
&& !file
.isFolder()) {
333 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
334 && file
.getLastSyncDateForProperties() > 0 // temporal fix
336 int startPlaybackPosition
=
337 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
339 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
340 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
341 startPlaybackPosition
, autoplay
);
344 secondFragment
= FileDetailFragment
.newInstance(file
, getAccount());
347 return secondFragment
;
352 * Replaces the second fragment managed by the activity with the received as
355 * Assumes never will be more than two fragments managed at the same time.
357 * @param fragment New second Fragment to set.
359 private void setSecondFragment(Fragment fragment
) {
360 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
361 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
362 transaction
.commit();
366 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
368 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
369 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
371 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
372 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
375 } else if (existsSecondFragment
) {
376 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
377 mLeftFragmentContainer
.setVisibility(View
.GONE
);
379 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
380 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
384 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
385 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
387 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
388 mRightFragmentContainer
.setVisibility(View
.GONE
);
394 private OCFileListFragment
getListOfFilesFragment() {
395 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
396 FileDisplayActivity
.TAG_LIST_OF_FILES
);
397 if (listOfFiles
!= null
) {
398 return (OCFileListFragment
)listOfFiles
;
400 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
404 public FileFragment
getSecondFragment() {
405 Fragment second
= getSupportFragmentManager().findFragmentByTag(
406 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
407 if (second
!= null
) {
408 return (FileFragment
)second
;
413 protected void cleanSecondFragment() {
414 Fragment second
= getSecondFragment();
415 if (second
!= null
) {
416 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
420 updateFragmentsVisibility(false
);
421 updateActionBarTitleAndHomeButton(null
);
424 protected void refreshListOfFilesFragment() {
425 OCFileListFragment fileListFragment
= getListOfFilesFragment();
426 if (fileListFragment
!= null
) {
427 fileListFragment
.listDirectory();
428 // TODO Enable when "On Device" is recovered ?
429 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
433 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
435 FileFragment secondFragment
= getSecondFragment();
436 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
437 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
438 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
439 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
440 OCFile fileInFragment
= detailsFragment
.getFile();
441 if (fileInFragment
!= null
&&
442 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
443 // the user browsed to other file ; forget the automatic preview
444 mWaitingToPreview
= null
;
446 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
447 // grant that the right panel updates the progress bar
448 detailsFragment
.listenForTransferProgress();
449 detailsFragment
.updateFileDetails(true
, false
);
451 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
452 // update the right panel
453 boolean detailsFragmentChanged
= false
;
456 mWaitingToPreview
= getStorageManager().getFileById(
457 mWaitingToPreview
.getFileId()); // update the file from database,
458 // for the local storage path
459 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
460 startMediaPreview(mWaitingToPreview
, 0, true
);
461 detailsFragmentChanged
= true
;
463 getFileOperationsHelper().openFile(mWaitingToPreview
);
466 mWaitingToPreview
= null
;
468 if (!detailsFragmentChanged
) {
469 detailsFragment
.updateFileDetails(false
, (success
));
476 public boolean onPrepareOptionsMenu(Menu menu
) {
477 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
478 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
479 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
480 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
481 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
483 return super.onPrepareOptionsMenu(menu
);
487 public boolean onCreateOptionsMenu(Menu menu
) {
488 MenuInflater inflater
= getMenuInflater();
489 inflater
.inflate(R
.menu
.main_menu
, menu
);
495 public boolean onOptionsItemSelected(MenuItem item
) {
496 boolean retval
= true
;
497 switch (item
.getItemId()) {
498 case R
.id
.action_create_dir
: {
499 CreateFolderDialogFragment dialog
=
500 CreateFolderDialogFragment
.newInstance(getCurrentDir());
501 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
504 case R
.id
.action_sync_account
: {
505 startSynchronization();
508 case R
.id
.action_upload
: {
509 UploadSourceDialogFragment dialog
=
510 UploadSourceDialogFragment
.newInstance(getAccount());
511 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
515 case android
.R
.id
.home
: {
516 FileFragment second
= getSecondFragment();
517 OCFile currentDir
= getCurrentDir();
518 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
519 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
520 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
521 (second
!= null
&& second
.getFile() != null
)) {
525 mDrawerLayout
.openDrawer(GravityCompat
.START
);
529 case R
.id
.action_sort
: {
530 SharedPreferences appPreferences
= PreferenceManager
531 .getDefaultSharedPreferences(this);
533 // Read sorting order, default to sort by name ascending
534 Integer sortOrder
= appPreferences
535 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
537 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
538 builder
.setTitle(R
.string
.actionbar_sort_title
)
539 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
540 new DialogInterface
.OnClickListener() {
541 public void onClick(DialogInterface dialog
, int which
) {
554 builder
.create().show();
558 retval
= super.onOptionsItemSelected(item
);
563 private void startSynchronization() {
564 Log_OC
.d(TAG
, "Got to start sync");
565 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
566 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
567 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
568 // cancel the current synchronizations of any ownCloud account
569 Bundle bundle
= new Bundle();
570 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
571 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
572 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
573 MainApp
.getAuthority());
574 ContentResolver
.requestSync(
576 MainApp
.getAuthority(), bundle
);
578 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
579 MainApp
.getAuthority() + " with new API");
580 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
581 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
582 builder
.setExpedited(true
);
583 builder
.setManual(true
);
586 // Fix bug in Android Lollipop when you click on refresh the whole account
587 Bundle extras
= new Bundle();
588 builder
.setExtras(extras
);
590 SyncRequest request
= builder
.build();
591 ContentResolver
.requestSync(request
);
596 * Called, when the user selected something for uploading
599 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
601 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
603 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
604 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
605 //getClipData is only supported on api level 16+, Jelly Bean
606 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
607 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
608 Intent intent
= new Intent();
609 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
610 requestSimpleUpload(intent
, resultCode
);
613 requestSimpleUpload(data
, resultCode
);
615 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
616 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
617 requestMultipleUpload(data
, resultCode
);
619 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
621 final Intent fData
= data
;
622 final int fResultCode
= resultCode
;
623 getHandler().postDelayed(
627 requestMoveOperation(fData
, fResultCode
);
630 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
634 super.onActivityResult(requestCode
, resultCode
, data
);
639 private void requestMultipleUpload(Intent data
, int resultCode
) {
640 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
641 if (filePaths
!= null
) {
642 String
[] remotePaths
= new String
[filePaths
.length
];
643 String remotePathBase
= getCurrentDir().getRemotePath();
644 for (int j
= 0; j
< remotePaths
.length
; j
++) {
645 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
648 Intent i
= new Intent(this, FileUploader
.class);
649 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
650 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
651 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
652 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
653 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
654 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
658 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
659 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
667 private void requestSimpleUpload(Intent data
, int resultCode
) {
668 String filePath
= null
;
669 String mimeType
= null
;
671 Uri selectedImageUri
= data
.getData();
674 mimeType
= getContentResolver().getType(selectedImageUri
);
676 String fileManagerString
= selectedImageUri
.getPath();
677 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
679 if (selectedImagePath
!= null
)
680 filePath
= selectedImagePath
;
682 filePath
= fileManagerString
;
684 } catch (Exception e
) {
685 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
686 "Intent.ACTION_GET_CONTENT", e
);
689 if (filePath
== null
) {
690 Log_OC
.e(TAG
, "Couldn't resolve path to file");
691 Toast t
= Toast
.makeText(
692 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
700 Intent i
= new Intent(this, FileUploader
.class);
701 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
702 OCFile currentDir
= getCurrentDir();
703 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
705 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
706 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
708 if (cursor
!= null
&& cursor
.moveToFirst()) {
709 String displayName
= cursor
.getString(cursor
.getColumnIndex(
710 OpenableColumns
.DISPLAY_NAME
));
711 Log_OC
.v(TAG
, "Display Name: " + displayName
);
713 displayName
.replace(File
.separatorChar
, '_');
714 displayName
.replace(File
.pathSeparatorChar
, '_');
715 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
718 // and what happens in case of error?; wrong target name for the upload
724 remotePath
+= new File(filePath
).getName();
727 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
728 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
729 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
730 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
731 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
732 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
737 * Request the operation for moving the file/folder from one path to another
739 * @param data Intent received
740 * @param resultCode Result code received
742 private void requestMoveOperation(Intent data
, int resultCode
) {
743 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
744 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
745 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
749 public void onBackPressed() {
750 if (!isDrawerOpen()){
751 OCFileListFragment listOfFiles
= getListOfFilesFragment();
752 if (mDualPane
|| getSecondFragment() == null
) {
753 OCFile currentDir
= getCurrentDir();
754 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
758 if (listOfFiles
!= null
) { // should never be null, indeed
759 listOfFiles
.onBrowseUp();
762 if (listOfFiles
!= null
) { // should never be null, indeed
763 setFile(listOfFiles
.getCurrentFile());
765 cleanSecondFragment();
767 super.onBackPressed();
772 protected void onSaveInstanceState(Bundle outState
) {
773 // responsibility of restore is preferred in onCreate() before than in
774 // onRestoreInstanceState when there are Fragments involved
775 Log_OC
.v(TAG
, "onSaveInstanceState() start");
776 super.onSaveInstanceState(outState
);
777 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
778 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
779 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
780 // mRefreshSharesInProgress);
781 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
783 Log_OC
.v(TAG
, "onSaveInstanceState() end");
789 protected void onResume() {
790 Log_OC
.v(TAG
, "onResume() start");
793 // refresh Navigation Drawer account list
794 mNavigationDrawerAdapter
.updateAccountList();
797 // refresh list of files
798 refreshListOfFilesFragment();
800 // Listen for sync messages
801 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
802 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
803 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
804 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
805 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
806 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
807 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
808 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
809 // syncIntentFilter);
811 // Listen for upload messages
812 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
813 mUploadFinishReceiver
= new UploadFinishReceiver();
814 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
816 // Listen for download messages
817 IntentFilter downloadIntentFilter
= new IntentFilter(
818 FileDownloader
.getDownloadAddedMessage());
819 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
820 mDownloadFinishReceiver
= new DownloadFinishReceiver();
821 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
823 Log_OC
.v(TAG
, "onResume() end");
828 protected void onPause() {
829 Log_OC
.v(TAG
, "onPause() start");
830 if (mSyncBroadcastReceiver
!= null
) {
831 unregisterReceiver(mSyncBroadcastReceiver
);
832 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
833 mSyncBroadcastReceiver
= null
;
835 if (mUploadFinishReceiver
!= null
) {
836 unregisterReceiver(mUploadFinishReceiver
);
837 mUploadFinishReceiver
= null
;
839 if (mDownloadFinishReceiver
!= null
) {
840 unregisterReceiver(mDownloadFinishReceiver
);
841 mDownloadFinishReceiver
= null
;
845 Log_OC
.v(TAG
, "onPause() end");
849 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
852 * {@link BroadcastReceiver} to enable syncing feedback in UI
855 public void onReceive(Context context
, Intent intent
) {
857 String event
= intent
.getAction();
858 Log_OC
.d(TAG
, "Received broadcast " + event
);
859 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
860 String synchFolderRemotePath
=
861 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
862 RemoteOperationResult synchResult
=
863 (RemoteOperationResult
)intent
.getSerializableExtra(
864 FileSyncAdapter
.EXTRA_RESULT
);
865 boolean sameAccount
= (getAccount() != null
&&
866 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
870 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
871 mSyncInProgress
= true
;
874 OCFile currentFile
= (getFile() == null
) ? null
:
875 getStorageManager().getFileByPath(getFile().getRemotePath());
876 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
877 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
879 if (currentDir
== null
) {
880 // current folder was removed from the server
881 Toast
.makeText( FileDisplayActivity
.this,
884 sync_current_folder_was_removed
),
885 synchFolderRemotePath
),
891 if (currentFile
== null
&& !getFile().isFolder()) {
892 // currently selected file was removed in the server, and now we
894 cleanSecondFragment();
895 currentFile
= currentDir
;
898 if (synchFolderRemotePath
!= null
&&
899 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
900 OCFileListFragment fileListFragment
= getListOfFilesFragment();
901 if (fileListFragment
!= null
) {
902 fileListFragment
.listDirectory();
903 // TODO Enable when "On Device" is recovered ?
904 // fileListFragment.listDirectory(currentDir,
905 // MainApp.getOnlyOnDevice());
908 setFile(currentFile
);
911 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
912 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
915 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
917 /// TODO refactor and make common
918 synchResult
!= null
&& !synchResult
.isSuccess() &&
919 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
920 synchResult
.isIdPRedirection() ||
921 (synchResult
.isException() && synchResult
.getException()
922 instanceof AuthenticatorException
))) {
926 OwnCloudClient client
;
927 OwnCloudAccount ocAccount
=
928 new OwnCloudAccount(getAccount(), context
);
929 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
930 removeClientFor(ocAccount
));
932 if (client
!= null
) {
933 OwnCloudCredentials cred
= client
.getCredentials();
935 AccountManager am
= AccountManager
.get(context
);
936 if (cred
.authTokenExpires()) {
937 am
.invalidateAuthToken(
942 am
.clearPassword(getAccount());
946 requestCredentialsUpdate();
948 } catch (AccountNotFoundException e
) {
949 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
954 removeStickyBroadcast(intent
);
955 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
956 mProgressBar
.setIndeterminate(mSyncInProgress
);
957 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
958 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
959 /*|| mRefreshSharesInProgress*/ //);
965 if (synchResult
!= null
) {
966 if (synchResult
.getCode().equals(
967 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
968 mLastSslUntrustedServerResult
= synchResult
;
971 } catch (RuntimeException e
) {
972 // avoid app crashes after changing the serial id of RemoteOperationResult
973 // in owncloud library with broadcast notifications pending to process
974 removeStickyBroadcast(intent
);
980 * Show a text message on screen view for notifying user if content is
981 * loading or folder is empty
983 private void setBackgroundText() {
984 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
985 if (ocFileListFragment
!= null
) {
986 int message
= R
.string
.file_list_loading
;
987 if (!mSyncInProgress
) {
988 // In case file list is empty
989 message
= R
.string
.file_list_empty
;
991 ocFileListFragment
.setMessageForEmptyList(getString(message
));
993 Log_OC
.e(TAG
, "OCFileListFragment is null");
998 * Once the file upload has finished -> update view
1000 private class UploadFinishReceiver
extends BroadcastReceiver
{
1002 * Once the file upload has finished -> update view
1003 * @author David A. Velasco
1004 * {@link BroadcastReceiver} to enable upload feedback in UI
1007 public void onReceive(Context context
, Intent intent
) {
1009 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1010 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1011 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1012 OCFile currentDir
= getCurrentDir();
1013 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1014 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1016 if (sameAccount
&& isDescendant
) {
1017 refreshListOfFilesFragment();
1020 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1022 boolean renamedInUpload
= getFile().getRemotePath().
1023 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1024 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1026 FileFragment details
= getSecondFragment();
1027 boolean detailFragmentIsShown
= (details
!= null
&&
1028 details
instanceof FileDetailFragment
);
1030 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1031 if (uploadWasFine
) {
1032 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1034 if (renamedInUpload
) {
1035 String newName
= (new File(uploadedRemotePath
)).getName();
1036 Toast msg
= Toast
.makeText(
1039 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1044 if (uploadWasFine
|| getFile().fileExists()) {
1045 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1047 cleanSecondFragment();
1050 // Force the preview if the file is an image
1051 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1052 startImagePreview(getFile());
1053 } // TODO what about other kind of previews?
1056 mProgressBar
.setIndeterminate(false
);
1058 if (intent
!= null
) {
1059 removeStickyBroadcast(intent
);
1069 * Class waiting for broadcast events from the {@link FileDownloader} service.
1071 * Updates the UI when a download is started or finished, provided that it is relevant for the
1074 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1076 //int refreshCounter = 0;
1078 public void onReceive(Context context
, Intent intent
) {
1080 boolean sameAccount
= isSameAccount(context
, intent
);
1081 String downloadedRemotePath
=
1082 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1083 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1085 if (sameAccount
&& isDescendant
) {
1086 String linkedToRemotePath
=
1087 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1088 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1089 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1090 refreshListOfFilesFragment();
1092 refreshSecondFragment(
1094 downloadedRemotePath
,
1095 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1099 if (mWaitingToSend
!= null
) {
1101 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1102 if (mWaitingToSend
.isDown()) {
1103 sendDownloadedFile();
1108 if (intent
!= null
) {
1109 removeStickyBroadcast(intent
);
1114 private boolean isDescendant(String downloadedRemotePath
) {
1115 OCFile currentDir
= getCurrentDir();
1117 currentDir
!= null
&&
1118 downloadedRemotePath
!= null
&&
1119 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1123 private boolean isAscendant(String linkedToRemotePath
) {
1124 OCFile currentDir
= getCurrentDir();
1126 currentDir
!= null
&&
1127 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1131 private boolean isSameAccount(Context context
, Intent intent
) {
1132 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1133 return (accountName
!= null
&& getAccount() != null
&&
1134 accountName
.equals(getAccount().name
));
1139 public void browseToRoot() {
1140 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1141 if (listOfFiles
!= null
) { // should never be null, indeed
1142 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1143 listOfFiles
.listDirectory(root
);
1144 // TODO Enable when "On Device" is recovered ?
1145 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1146 setFile(listOfFiles
.getCurrentFile());
1147 startSyncFolderOperation(root
, false
);
1149 cleanSecondFragment();
1157 * Updates action bar and second fragment, if in dual pane mode.
1160 public void onBrowsedDownTo(OCFile directory
) {
1162 cleanSecondFragment();
1164 startSyncFolderOperation(directory
, false
);
1168 * Shows the information of the {@link OCFile} received as a
1169 * parameter in the second fragment.
1171 * @param file {@link OCFile} whose details will be shown
1174 public void showDetails(OCFile file
) {
1175 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1176 setSecondFragment(detailFragment
);
1177 updateFragmentsVisibility(true
);
1178 updateActionBarTitleAndHomeButton(file
);
1183 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1185 // in dual pane mode, keep the focus of title an action bar in the current folder
1186 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1189 super.updateActionBarTitleAndHomeButton(chosenFile
);
1195 protected ServiceConnection
newTransferenceServiceConnection() {
1196 return new ListServiceConnection();
1199 /** Defines callbacks for service binding, passed to bindService() */
1200 private class ListServiceConnection
implements ServiceConnection
{
1203 public void onServiceConnected(ComponentName component
, IBinder service
) {
1204 if (component
.equals(new ComponentName(
1205 FileDisplayActivity
.this, FileDownloader
.class))) {
1206 Log_OC
.d(TAG
, "Download service connected");
1207 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1208 if (mWaitingToPreview
!= null
)
1209 if (getStorageManager() != null
) {
1212 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1213 if (!mWaitingToPreview
.isDown()) {
1214 requestForDownload();
1218 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1219 FileUploader
.class))) {
1220 Log_OC
.d(TAG
, "Upload service connected");
1221 mUploaderBinder
= (FileUploaderBinder
) service
;
1225 // a new chance to get the mDownloadBinder through
1226 // getFileDownloadBinder() - THIS IS A MESS
1227 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1228 if (listOfFiles
!= null
) {
1229 listOfFiles
.listDirectory();
1230 // TODO Enable when "On Device" is recovered ?
1231 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1233 FileFragment secondFragment
= getSecondFragment();
1234 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1235 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1236 detailFragment
.listenForTransferProgress();
1237 detailFragment
.updateFileDetails(false
, false
);
1242 public void onServiceDisconnected(ComponentName component
) {
1243 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1244 FileDownloader
.class))) {
1245 Log_OC
.d(TAG
, "Download service disconnected");
1246 mDownloaderBinder
= null
;
1247 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1248 FileUploader
.class))) {
1249 Log_OC
.d(TAG
, "Upload service disconnected");
1250 mUploaderBinder
= null
;
1256 public void onSavedCertificate() {
1257 startSyncFolderOperation(getCurrentDir(), false
);
1262 public void onFailedSavingCertificate() {
1263 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1264 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1266 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1270 public void onCancelCertificate() {
1275 * Updates the view associated to the activity after the finish of some operation over files
1276 * in the current account.
1278 * @param operation Removal operation performed.
1279 * @param result Result of the removal.
1282 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1283 super.onRemoteOperationFinish(operation
, result
);
1285 if (operation
instanceof RemoveFileOperation
) {
1286 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1288 } else if (operation
instanceof RenameFileOperation
) {
1289 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1291 } else if (operation
instanceof SynchronizeFileOperation
) {
1292 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1294 } else if (operation
instanceof CreateFolderOperation
) {
1295 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1297 } else if (operation
instanceof CreateShareOperation
) {
1298 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1300 } else if (operation
instanceof UnshareLinkOperation
) {
1301 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1303 } else if (operation
instanceof MoveFileOperation
) {
1304 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1310 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1311 RemoteOperationResult result
) {
1312 if (result
.isSuccess()) {
1313 refreshShowDetails();
1314 refreshListOfFilesFragment();
1319 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1320 RemoteOperationResult result
) {
1321 if (result
.isSuccess()) {
1322 refreshShowDetails();
1323 refreshListOfFilesFragment();
1325 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1326 cleanSecondFragment();
1327 refreshListOfFilesFragment();
1331 private void refreshShowDetails() {
1332 FileFragment details
= getSecondFragment();
1333 if (details
!= null
) {
1334 OCFile file
= details
.getFile();
1336 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1337 if (details
instanceof PreviewMediaFragment
) {
1338 // Refresh OCFile of the fragment
1339 ((PreviewMediaFragment
) details
).updateFile(file
);
1344 invalidateOptionsMenu();
1349 * Updates the view associated to the activity after the finish of an operation trying to
1352 * @param operation Removal operation performed.
1353 * @param result Result of the removal.
1355 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1356 RemoteOperationResult result
) {
1357 dismissLoadingDialog();
1359 Toast msg
= Toast
.makeText(this,
1360 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1364 if (result
.isSuccess()) {
1365 OCFile removedFile
= operation
.getFile();
1366 FileFragment second
= getSecondFragment();
1367 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1368 if (second
instanceof PreviewMediaFragment
) {
1369 ((PreviewMediaFragment
)second
).stopPreview(true
);
1371 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1372 cleanSecondFragment();
1374 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1375 refreshListOfFilesFragment();
1377 invalidateOptionsMenu();
1379 if (result
.isSslRecoverableException()) {
1380 mLastSslUntrustedServerResult
= result
;
1381 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1388 * Updates the view associated to the activity after the finish of an operation trying to move a
1391 * @param operation Move operation performed.
1392 * @param result Result of the move operation.
1394 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1395 RemoteOperationResult result
) {
1396 if (result
.isSuccess()) {
1397 dismissLoadingDialog();
1398 refreshListOfFilesFragment();
1400 dismissLoadingDialog();
1402 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1403 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1407 } catch (NotFoundException e
) {
1408 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1415 * Updates the view associated to the activity after the finish of an operation trying to rename
1418 * @param operation Renaming operation performed.
1419 * @param result Result of the renaming.
1421 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1422 RemoteOperationResult result
) {
1423 dismissLoadingDialog();
1424 OCFile renamedFile
= operation
.getFile();
1425 if (result
.isSuccess()) {
1426 FileFragment details
= getSecondFragment();
1427 if (details
!= null
) {
1428 if (details
instanceof FileDetailFragment
&&
1429 renamedFile
.equals(details
.getFile()) ) {
1430 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1431 showDetails(renamedFile
);
1433 } else if (details
instanceof PreviewMediaFragment
&&
1434 renamedFile
.equals(details
.getFile())) {
1435 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1436 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1437 int position
= ((PreviewMediaFragment
)details
).getPosition();
1438 startMediaPreview(renamedFile
, position
, true
);
1440 getFileOperationsHelper().openFile(renamedFile
);
1445 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1446 refreshListOfFilesFragment();
1450 Toast msg
= Toast
.makeText(this,
1451 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1455 if (result
.isSslRecoverableException()) {
1456 mLastSslUntrustedServerResult
= result
;
1457 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1462 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1463 RemoteOperationResult result
) {
1464 if (result
.isSuccess()) {
1465 if (operation
.transferWasRequested()) {
1466 OCFile syncedFile
= operation
.getLocalFile();
1467 onTransferStateChanged(syncedFile
, true
, true
);
1468 invalidateOptionsMenu();
1474 * Updates the view associated to the activity after the finish of an operation trying create a
1477 * @param operation Creation operation performed.
1478 * @param result Result of the creation.
1480 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1481 RemoteOperationResult result
) {
1482 if (result
.isSuccess()) {
1483 dismissLoadingDialog();
1484 refreshListOfFilesFragment();
1486 dismissLoadingDialog();
1488 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1489 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1493 } catch (NotFoundException e
) {
1494 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1504 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1505 refreshListOfFilesFragment();
1506 FileFragment details
= getSecondFragment();
1507 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1508 file
.equals(details
.getFile()) ) {
1509 if (downloading
|| uploading
) {
1510 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1512 if (!file
.fileExists()) {
1513 cleanSecondFragment();
1515 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1523 private void requestForDownload() {
1524 Account account
= getAccount();
1525 //if (!mWaitingToPreview.isDownloading()) {
1526 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1527 Intent i
= new Intent(this, FileDownloader
.class);
1528 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1529 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1535 private OCFile
getCurrentDir() {
1536 OCFile file
= getFile();
1538 if (file
.isFolder()) {
1540 } else if (getStorageManager() != null
) {
1541 String parentPath
= file
.getRemotePath().substring(0,
1542 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1543 return getStorageManager().getFileByPath(parentPath
);
1549 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1550 long currentSyncTime
= System
.currentTimeMillis();
1552 mSyncInProgress
= true
;
1554 // perform folder synchronization
1555 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1558 getFileOperationsHelper().isSharedSupported(),
1560 getStorageManager(),
1562 getApplicationContext()
1564 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1565 mProgressBar
.setIndeterminate(true
);
1567 setBackgroundText();
1571 * Show untrusted cert dialog
1573 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1574 // Show a dialog with the certificate info
1575 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1576 (CertificateCombinedException
) result
.getException());
1577 FragmentManager fm
= getSupportFragmentManager();
1578 FragmentTransaction ft
= fm
.beginTransaction();
1579 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1582 private void requestForDownload(OCFile file
) {
1583 Account account
= getAccount();
1584 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1585 Intent i
= new Intent(this, FileDownloader
.class);
1586 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1587 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1592 private void sendDownloadedFile(){
1593 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1594 mWaitingToSend
= null
;
1599 * Requests the download of the received {@link OCFile} , updates the UI
1600 * to monitor the download progress and prepares the activity to send the file
1601 * when the download finishes.
1603 * @param file {@link OCFile} to download and preview.
1605 public void startDownloadForSending(OCFile file
) {
1606 mWaitingToSend
= file
;
1607 requestForDownload(mWaitingToSend
);
1608 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1609 updateFragmentsVisibility(hasSecondFragment
);
1613 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1615 * @param file Image {@link OCFile} to show.
1617 public void startImagePreview(OCFile file
) {
1618 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1619 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1620 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1621 startActivity(showDetailsIntent
);
1626 * Stars the preview of an already down media {@link OCFile}.
1628 * @param file Media {@link OCFile} to preview.
1629 * @param startPlaybackPosition Media position where the playback will be started,
1631 * @param autoplay When 'true', the playback will start without user
1634 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1635 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1637 setSecondFragment(mediaFragment
);
1638 updateFragmentsVisibility(true
);
1639 updateActionBarTitleAndHomeButton(file
);
1644 * Requests the download of the received {@link OCFile} , updates the UI
1645 * to monitor the download progress and prepares the activity to preview
1646 * or open the file when the download finishes.
1648 * @param file {@link OCFile} to download and preview.
1650 public void startDownloadForPreview(OCFile file
) {
1651 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1652 setSecondFragment(detailFragment
);
1653 mWaitingToPreview
= file
;
1654 requestForDownload();
1655 updateFragmentsVisibility(true
);
1656 updateActionBarTitleAndHomeButton(file
);
1661 public void cancelTransference(OCFile file
) {
1662 getFileOperationsHelper().cancelTransference(file
);
1663 if (mWaitingToPreview
!= null
&&
1664 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1665 mWaitingToPreview
= null
;
1667 if (mWaitingToSend
!= null
&&
1668 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1669 mWaitingToSend
= null
;
1671 onTransferStateChanged(file
, false
, false
);
1675 public void onRefresh(boolean ignoreETag
) {
1676 refreshList(ignoreETag
);
1680 public void onRefresh() {
1684 private void refreshList(boolean ignoreETag
) {
1685 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1686 if (listOfFiles
!= null
) {
1687 OCFile folder
= listOfFiles
.getCurrentFile();
1688 if (folder
!= null
) {
1689 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1690 listDirectory(mFile);*/
1691 startSyncFolderOperation(folder
, ignoreETag
);
1696 private void sortByDate(boolean ascending
){
1697 getListOfFilesFragment().sortByDate(ascending
);
1700 private void sortBySize(boolean ascending
){
1701 getListOfFilesFragment().sortBySize(ascending
);
1704 private void sortByName(boolean ascending
){
1705 getListOfFilesFragment().sortByName(ascending
);
1708 public void allFilesOption() {