forked from owncloud/android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileDisplayActivity.kt
More file actions
2104 lines (1854 loc) · 83.9 KB
/
FileDisplayActivity.kt
File metadata and controls
2104 lines (1854 loc) · 83.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ownCloud Android client application
*
* @author Bartek Przybylski
* @author David A. Velasco
* @author David González Verdugo
* @author Christian Schabesberger
* @author Shashvat Kedia
* @author Abel García de Prada
* @author Juan Carlos Garrote Gascón
* @author Aitor Ballesteros Pavón
* @author Jorge Aguado Recio
*
* Copyright (C) 2011 Bartek Przybylski
* Copyright (C) 2025 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.activity
import android.Manifest.permission.POST_NOTIFICATIONS
import android.accounts.Account
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.RemoteException
import android.util.TypedValue
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.work.WorkManager
import com.owncloud.android.AppRater
import com.owncloud.android.BuildConfig
import com.owncloud.android.MainApp
import com.owncloud.android.R
import com.owncloud.android.data.providers.SharedPreferencesProvider
import com.owncloud.android.databinding.ActivityMainBinding
import com.owncloud.android.domain.capabilities.model.OCCapability
import com.owncloud.android.domain.exceptions.AccountNotFoundException
import com.owncloud.android.domain.exceptions.DeepLinkException
import com.owncloud.android.domain.exceptions.FileNotFoundException
import com.owncloud.android.domain.exceptions.SSLRecoverablePeerUnverifiedException
import com.owncloud.android.domain.exceptions.UnauthorizedException
import com.owncloud.android.domain.files.model.FileListOption
import com.owncloud.android.domain.files.model.OCFile
import com.owncloud.android.domain.files.model.OCFile.Companion.ROOT_PARENT_ID
import com.owncloud.android.domain.spaces.model.OCSpace
import com.owncloud.android.domain.utils.Event
import com.owncloud.android.extensions.checkPasscodeEnforced
import com.owncloud.android.extensions.collectLatestLifecycleFlow
import com.owncloud.android.extensions.goToUrl
import com.owncloud.android.extensions.isDownloadPending
import com.owncloud.android.extensions.manageOptionLockSelected
import com.owncloud.android.extensions.observeWorkerTillItFinishes
import com.owncloud.android.extensions.openOCFile
import com.owncloud.android.extensions.parseError
import com.owncloud.android.extensions.sendDownloadedFilesByShareSheet
import com.owncloud.android.extensions.showErrorInSnackbar
import com.owncloud.android.extensions.showMessageInSnackbar
import com.owncloud.android.extensions.showSnackbarWithAction
import com.owncloud.android.lib.common.accounts.AccountUtils
import com.owncloud.android.lib.common.authentication.OwnCloudBearerCredentials
import com.owncloud.android.lib.common.network.CertificateCombinedException
import com.owncloud.android.lib.common.operations.RemoteOperationResult
import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode
import com.owncloud.android.lib.resources.status.OwnCloudVersion
import com.owncloud.android.operations.SyncProfileOperation
import com.owncloud.android.presentation.accounts.ManageAccountsViewModel
import com.owncloud.android.presentation.authentication.AccountUtils.getCurrentOwnCloudAccount
import com.owncloud.android.presentation.capabilities.CapabilityViewModel
import com.owncloud.android.presentation.common.UIResult
import com.owncloud.android.presentation.conflicts.ConflictsResolveActivity
import com.owncloud.android.presentation.files.details.FileDetailsFragment
import com.owncloud.android.presentation.files.filelist.MainEmptyListFragment
import com.owncloud.android.presentation.files.filelist.MainFileListFragment
import com.owncloud.android.presentation.files.operations.FileOperation
import com.owncloud.android.presentation.files.operations.FileOperationsViewModel
import com.owncloud.android.presentation.security.LockType
import com.owncloud.android.presentation.security.SecurityEnforced
import com.owncloud.android.presentation.security.bayPassUnlockOnce
import com.owncloud.android.presentation.shares.SharesFragment
import com.owncloud.android.presentation.spaces.SpacesListFragment
import com.owncloud.android.presentation.spaces.SpacesListFragment.Companion.BUNDLE_KEY_CLICK_SPACE
import com.owncloud.android.presentation.spaces.SpacesListFragment.Companion.REQUEST_KEY_CLICK_SPACE
import com.owncloud.android.presentation.spaces.SpacesListViewModel
import com.owncloud.android.presentation.transfers.TransfersViewModel
import com.owncloud.android.providers.WorkManagerProvider
import com.owncloud.android.syncadapter.FileSyncAdapter
import com.owncloud.android.ui.dialog.FileAlreadyExistsDialog
import com.owncloud.android.ui.fragment.FileFragment
import com.owncloud.android.ui.fragment.TaskRetainerFragment
import com.owncloud.android.ui.helpers.FilesUploadHelper
import com.owncloud.android.ui.preview.PreviewAudioFragment
import com.owncloud.android.ui.preview.PreviewImageActivity
import com.owncloud.android.ui.preview.PreviewImageFragment
import com.owncloud.android.ui.preview.PreviewTextFragment
import com.owncloud.android.ui.preview.PreviewVideoActivity
import com.owncloud.android.usecases.synchronization.SynchronizeFileUseCase
import com.owncloud.android.usecases.transfers.downloads.DownloadFileUseCase
import com.owncloud.android.utils.PreferenceUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.koin.android.ext.android.inject
import org.koin.androidx.viewmodel.ext.android.getViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
import timber.log.Timber
import java.io.File
import kotlin.coroutines.CoroutineContext
/**
* Displays, what files the user has available in his ownCloud. This is the main view.
*/
class FileDisplayActivity : FileActivity(),
CoroutineScope,
FileFragment.ContainerActivity,
SecurityEnforced,
MainFileListFragment.FileActions,
MainFileListFragment.UploadActions {
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
private var syncBroadcastReceiver: SyncBroadcastReceiver? = null
private var lastSslUntrustedServerResult: RemoteOperationResult<*>? = null
/**
* FileDisplayActivity is based on those two containers.
* Left one is used for showing a list of files - [mainFileListFragment]
* Right one is used for showing previews, details... - [secondFragment]
*
* We should rename them to a more accurate names.
*
* When one is shown, the other is hidden. The main logic for this is inside [updateFragmentsVisibility]
*/
private var leftFragmentContainer: FrameLayout? = null
private var rightFragmentContainer: FrameLayout? = null
private val mainFileListFragment: MainFileListFragment?
get() = supportFragmentManager.findFragmentByTag(TAG_LIST_OF_FILES) as MainFileListFragment?
private val secondFragment: FileFragment?
get() = supportFragmentManager.findFragmentByTag(TAG_SECOND_FRAGMENT) as FileFragment?
private var selectAllMenuItem: MenuItem? = null
private var fileWaitingToPreview: OCFile? = null
private var syncInProgress = false
var fileListOption = FileListOption.ALL_FILES
private var waitingToSend: OCFile? = null
private var waitingToOpen: OCFile? = null
private var copyMoveTargetFolder: OCFile? = null
private var localBroadcastManager: LocalBroadcastManager? = null
private val fileOperationsViewModel: FileOperationsViewModel by viewModel()
private val transfersViewModel: TransfersViewModel by viewModel()
private lateinit var spacesListViewModel: SpacesListViewModel
private val manageAccountsViewModel: ManageAccountsViewModel by viewModel()
private val sharedPreferences: SharedPreferencesProvider by inject()
var filesUploadHelper: FilesUploadHelper? = null
internal set
private lateinit var binding: ActivityMainBinding
private var isLightUser = false
private var isMultiPersonal = false
override fun onCreate(savedInstanceState: Bundle?) {
Timber.v("onCreate() start")
super.onCreate(savedInstanceState) // this calls onAccountChanged() when ownCloud Account is valid
checkPasscodeEnforced(this)
if (BuildConfig.DEBUG) {
sharedPreferences.putInt(MainApp.PREFERENCE_KEY_LAST_SEEN_VERSION_CODE, MainApp.versionCode)
}
sharedPreferences.putBoolean(PREFERENCE_CLEAR_DATA_ALREADY_TRIGGERED, true)
localBroadcastManager = LocalBroadcastManager.getInstance(this)
handleDeepLink()
/// Load of saved instance state
if (savedInstanceState != null) {
Timber.d(savedInstanceState.toString())
fileWaitingToPreview = savedInstanceState.getParcelable(KEY_WAITING_TO_PREVIEW)
syncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS)
waitingToSend = savedInstanceState.getParcelable(KEY_WAITING_TO_SEND)
filesUploadHelper = savedInstanceState.getParcelable(KEY_UPLOAD_HELPER)
fileListOption =
savedInstanceState.getParcelable(KEY_FILE_LIST_OPTION) as? FileListOption ?: FileListOption.ALL_FILES
if (account != null) {
filesUploadHelper?.init(this, account.name)
}
} else {
fileWaitingToPreview = null
syncInProgress = false
waitingToSend = null
fileListOption =
intent.getParcelableExtra(EXTRA_FILE_LIST_OPTION) as? FileListOption ?: FileListOption.ALL_FILES
filesUploadHelper = FilesUploadHelper(
this,
if (account == null) "" else account.name
)
}
/// USER INTERFACE
// Inflate and set the layout view
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
// setup toolbar
setupRootToolbar(
isSearchEnabled = true,
title = getString(R.string.default_display_name_for_root_folder),
isAvatarRequested = true,
)
// setup drawer
setupDrawer()
setupNavigationBottomBar(getMenuItemForFileListOption(fileListOption))
leftFragmentContainer = findViewById(R.id.left_fragment_container)
rightFragmentContainer = findViewById(R.id.right_fragment_container)
// Init Fragment without UI to retain AsyncTask across configuration changes
val fm = supportFragmentManager
var taskRetainerFragment =
fm.findFragmentByTag(TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT) as TaskRetainerFragment?
if (taskRetainerFragment == null) {
taskRetainerFragment = TaskRetainerFragment()
fm.beginTransaction()
.add(taskRetainerFragment, TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT).commit()
} // else, Fragment already created and retained across configuration change
supportFragmentManager.setFragmentResultListener(REQUEST_KEY_CLICK_SPACE, this) { _, bundle ->
val rootSpaceFolder = bundle.getParcelable<OCFile>(BUNDLE_KEY_CLICK_SPACE)
file = rootSpaceFolder
initAndShowListOfFiles()
}
if (resources.getBoolean(R.bool.enable_rate_me_feature) && !BuildConfig.DEBUG) {
AppRater.appLaunched(this, packageName)
}
checkNotificationPermission()
Timber.v("onCreate() end")
}
private fun checkNotificationPermission() {
// Ask for permission only in case it's api >= 33 and notifications are not granted.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
ContextCompat.checkSelfPermission(this, POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
) return
// Permission denied. Can be because notifications are off by default or because they were denied by the user.
val alreadyRequested = sharedPreferences.getBoolean(PREFERENCE_NOTIFICATION_PERMISSION_REQUESTED, false)
val shouldShowPermissionRequest = shouldShowRequestPermissionRationale(POST_NOTIFICATIONS)
Timber.d("Already requested notification permission $alreadyRequested and should ask again $shouldShowPermissionRequest")
if (!alreadyRequested || shouldShowPermissionRequest) {
// Not requested yet or system considers we can request the permission again.
val requestPermissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
Timber.d("Permission to send notifications granted: $isGranted")
if (!isGranted) {
showSnackMessage(getString(R.string.notifications_permission_denied))
}
sharedPreferences.putBoolean(PREFERENCE_NOTIFICATION_PERMISSION_REQUESTED, true)
}
requestPermissionLauncher.launch(POST_NOTIFICATIONS)
}
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
if (savedInstanceState == null && mAccountWasSet) {
val capabilitiesViewModel: CapabilityViewModel by viewModel {
parametersOf(
account?.name
)
}
capabilitiesViewModel.capabilities.observe(this, Event.EventObserver {
onCapabilitiesOperationFinish(it)
})
isLightUser = manageAccountsViewModel.checkUserLight(account.name)
isMultiPersonal = capabilitiesViewModel.checkMultiPersonal()
navigateTo(fileListOption, initialState = true)
}
startListeningToOperations()
}
/**
* Called when the ownCloud [Account] associated to the Activity was just updated.
*/
override fun onAccountSet(stateWasRecovered: Boolean) {
super.onAccountSet(stateWasRecovered)
if (account != null) {
/// Check whether the 'main' OCFile handled by the Activity is contained in the
// current Account
var file: OCFile? = file
// get parent from path
val parentPath: String
if (file != null) {
if (file.isAvailableLocally) {
// upload in progress - right now, files are not inserted in the local
// cache until the upload is successful get parent from path
parentPath = file.remotePath.substring(
0,
file.remotePath.lastIndexOf(file.fileName)
)
if (storageManager.getFileByPath(parentPath, file.spaceId) == null) {
file = null // not able to know the directory where the file is uploading
}
} else {
file = storageManager.getFileByPath(file.remotePath, file.spaceId)
// currentDir = null if not in the current Account
}
}
if (file == null) {
// fall back to root folder
file = storageManager.getRootPersonalFolder() // never returns null
}
setFile(file)
if (mAccountWasSet) {
setAccountInDrawer(account)
}
if (!stateWasRecovered) {
Timber.d("Initializing Fragments in onAccountChanged..")
initFragmentsWithFile()
val syncProfileOperation = SyncProfileOperation(account)
syncProfileOperation.syncUserProfile()
val workManagerProvider = WorkManagerProvider(context = baseContext)
workManagerProvider.enqueueAvailableOfflinePeriodicWorker()
} else {
file?.isFolder?.let { isFolder ->
updateFragmentsVisibility(!isFolder)
updateToolbar(if (isFolder) null else file)
}
}
}
spacesListViewModel = getViewModel { parametersOf(account.name, false) }
spacesListViewModel.refreshSpacesFromServer()
}
private fun initAndShowListOfFiles(fileListOption: FileListOption = FileListOption.ALL_FILES) {
val mainListOfFiles = MainFileListFragment.newInstance(
initialFolderToDisplay = file,
fileListOption = fileListOption,
accountName = getCurrentOwnCloudAccount(applicationContext).name
).apply {
fileActions = this@FileDisplayActivity
uploadActions = this@FileDisplayActivity
setSearchListener(findViewById(R.id.root_toolbar_search_view))
}
this.fileListOption = fileListOption
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.left_fragment_container, mainListOfFiles, TAG_LIST_OF_FILES)
transaction.commit()
}
private fun initAndShowListOfSpaces() {
val listOfSpaces = SpacesListFragment.newInstance(
showPersonalSpace = false,
isPickerMode = false,
accountName = com.owncloud.android.presentation.authentication.AccountUtils.getCurrentOwnCloudAccount(applicationContext).name
).apply {
setSearchListener(findViewById(R.id.root_toolbar_search_view))
}
this.fileListOption = FileListOption.SPACES_LIST
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.left_fragment_container, listOfSpaces, TAG_LIST_OF_SPACES)
transaction.commit()
}
private fun initAndShowListOfShares() {
val sharesFragment = SharesFragment()
this.fileListOption = FileListOption.SHARED_BY_LINK
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.left_fragment_container, sharesFragment)
transaction.commit()
}
private fun initAndShowEmptyPersonalSpace() {
val emptyListFragment = MainEmptyListFragment()
this.fileListOption = FileListOption.ALL_FILES
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.left_fragment_container, emptyListFragment)
transaction.commit()
}
private fun initFragmentsWithFile() {
if (account != null && file != null) {
/// First fragment
mainFileListFragment?.navigateToFolder(currentDir)
?: Timber.e("Still have a chance to lose the initialization of list fragment >(")
/// Second fragment
val file = file
val secondFragment = chooseInitialSecondFragment(file)
secondFragment?.let {
setSecondFragment(it)
updateToolbar(it.file)
} ?: cleanSecondFragment()
} else {
Timber.e("initFragmentsWithFile() called with invalid nulls! account is $account, file is $file")
}
}
/**
* Choose the second fragment that is going to be shown
*
* @param file used to decide which fragment should be chosen.
*
* @return a new second fragment instance if it has not been chosen before, or the fragment
* previously chosen otherwise
*/
private fun chooseInitialSecondFragment(file: OCFile): FileFragment? {
val secondFragment = supportFragmentManager.findFragmentByTag(TAG_SECOND_FRAGMENT) as FileFragment?
// Return second fragment if it has been already chosen
return if (secondFragment != null) {
secondFragment
// Return null if we receive a folder. This way, second fragment will be cleared. We should move this logic out of here.
} else if (file.isFolder) {
null
// Otherwise, decide which fragment should be shown.
} else {
when {
PreviewAudioFragment.canBePreviewed(file) -> {
val startPlaybackPosition = intent.getIntExtra(PreviewVideoActivity.EXTRA_PLAY_POSITION, 0)
val autoplay = intent.getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true)
PreviewAudioFragment.newInstance(
file,
account,
startPlaybackPosition,
autoplay
)
}
PreviewTextFragment.canBePreviewed(file) -> {
PreviewTextFragment.newInstance(
file,
account
)
}
else -> {
FileDetailsFragment.newInstance(file, account, false, isMultiPersonal)
}
}
}
}
/**
* Replaces the second fragment managed by the activity with the received as
* a parameter.
*
*
* Assumes never will be more than two fragments managed at the same time.
*
* @param fragment New second Fragment to set.
*/
private fun setSecondFragment(fragment: Fragment) {
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT)
transaction.commitNow()
updateFragmentsVisibility(true)
}
private fun showBottomNavBar(show: Boolean) {
binding.navCoordinatorLayout.bottomNavView.isVisible = show
}
/**
* Handle the visibility of the two main containers in the activity.
*
* Showing list of files should hide right container
* Showing preview or details should hide left container
*
* @param existsSecondFragment - true if showing details or preview of a file
*/
private fun updateFragmentsVisibility(existsSecondFragment: Boolean) {
leftFragmentContainer?.isVisible = !existsSecondFragment
rightFragmentContainer?.isVisible = existsSecondFragment
showBottomNavBar(show = !existsSecondFragment)
}
private fun cleanSecondFragment() {
val second = secondFragment
if (second != null) {
val tr = supportFragmentManager.beginTransaction()
tr.remove(second)
tr.commitNow()
}
updateFragmentsVisibility(false)
updateToolbar(null)
}
private fun refreshListOfFilesFragment() {
// TODO Remove commented code
/*val fileListFragment = listOfFilesFragment
fileListFragment?.listDirectory(reloadData)*/
if (file != null) {
val fileListFragment = mainFileListFragment
mainFileListFragment?.fileActions = this
fileListFragment?.navigateToFolder(file)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
// Allow or disallow touches with other visible windows
val actionBarView = findViewById<View>(R.id.action_bar)
if (actionBarView != null) {
actionBarView.filterTouchesWhenObscured =
PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(applicationContext)
}
selectAllMenuItem = menu.findItem(R.id.action_select_all)
if (secondFragment == null) {
selectAllMenuItem?.isVisible = true
} else {
val shareFileMenuItem = menu.findItem(R.id.action_share_current_folder)
menu.removeItem(shareFileMenuItem.itemId)
}
setRolesAccessibilityToMenuItems()
return true
}
private fun setRolesAccessibilityToMenuItems() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
selectAllMenuItem?.contentDescription = "${getString(R.string.actionbar_select_all)} ${getString(R.string.button_role_accessibility)}"
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
onBackPressed()
}
}
return super.onOptionsItemSelected(item)
}
/**
* Called, when the user selected something for uploading
*/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
bayPassUnlockOnce()
// Handle calls form internal activities.
if (requestCode == REQUEST_CODE__SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == RESULT_OK_AND_MOVE)) {
if (!manageAccountsViewModel.hasEnoughQuota(account.name)) {
showMessageInSnackbar(message = getString(R.string.failed_upload_quota_exceeded_text))
}
requestUploadOfContentFromApps(data)
} else if (requestCode == REQUEST_CODE__UPLOAD_FROM_CAMERA) {
if (resultCode == RESULT_OK || resultCode == RESULT_OK_AND_MOVE) {
filesUploadHelper?.onActivityResult(object : FilesUploadHelper.OnCheckAvailableSpaceListener {
override fun onCheckAvailableSpaceStart() {
}
override fun onCheckAvailableSpaceFinished(
hasEnoughSpace: Boolean,
capturedFilePaths: Array<String>
) {
if (hasEnoughSpace) {
if (!manageAccountsViewModel.hasEnoughQuota(account.name)) {
showMessageInSnackbar(message = getString(R.string.failed_upload_quota_exceeded_text))
}
requestUploadOfFilesFromFileSystem(capturedFilePaths)
}
}
})
} else if (requestCode == RESULT_CANCELED) {
filesUploadHelper?.deleteImageFile()
}
// requestUploadOfFilesFromFileSystem(data,resultCode);
} else if (requestCode == REQUEST_CODE__MOVE_FILES && resultCode == RESULT_OK) {
requestMoveOperation(data!!)
} else if (requestCode == REQUEST_CODE__COPY_FILES && resultCode == RESULT_OK) {
handler.postDelayed(
{ requestCopyOperation(data!!) },
DELAY_TO_REQUEST_OPERATIONS_LATER
)
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
private fun requestUploadOfFilesFromFileSystem(filePaths: Array<String>?) {
if (filePaths != null) {
val remotePaths = arrayOfNulls<String>(filePaths.size)
val remotePathBase = currentDir?.remotePath
for (j in remotePaths.indices) {
remotePaths[j] = remotePathBase + File(filePaths[j]).name
}
transfersViewModel.uploadFilesFromSystem(
accountName = account.name,
listOfLocalPaths = filePaths.toList(),
uploadFolderPath = remotePathBase!!,
spaceId = currentDir.spaceId,
)
} else {
Timber.d("User clicked on 'Update' with no selection")
showMessageInSnackbar(R.id.list_layout, getString(R.string.filedisplay_no_file_selected))
}
}
private fun requestUploadOfContentFromApps(contentIntent: Intent?) {
val streamsToUpload = ArrayList<Uri>()
if (contentIntent!!.clipData != null && contentIntent.clipData!!.itemCount > 0) {
for (i in 0 until contentIntent.clipData!!.itemCount) {
streamsToUpload.add(contentIntent.clipData!!.getItemAt(i).uri)
}
} else {
streamsToUpload.add(contentIntent.data!!)
}
val currentDir = currentDir
val remotePath = currentDir?.remotePath ?: OCFile.ROOT_PATH
// Try to retain access to that file for some time, so we have enough time to upload it
streamsToUpload.forEach { uri ->
try {
contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
} catch (remoteException: RemoteException) {
Timber.w(remoteException)
}
}
transfersViewModel.uploadFilesFromContentUri(
accountName = account.name,
listOfContentUris = streamsToUpload,
uploadFolderPath = remotePath,
spaceId = currentDir.spaceId,
)
}
/**
* Request the operation for moving the file/folder from one path to another
*
* @param data Intent received
*/
private fun requestMoveOperation(data: Intent) {
val folderToMoveAt = data.getParcelableExtra<OCFile>(FolderPickerActivity.EXTRA_FOLDER) ?: return
val files = data.getParcelableArrayListExtra<OCFile>(FolderPickerActivity.EXTRA_FILES) ?: return
copyMoveTargetFolder = folderToMoveAt
val moveOperation = FileOperation.MoveOperation(
listOfFilesToMove = files.toList(),
targetFolder = folderToMoveAt,
isUserLogged = com.owncloud.android.presentation.authentication.AccountUtils.getCurrentOwnCloudAccount(this) != null,
)
fileOperationsViewModel.performOperation(moveOperation)
}
/**
* Request the operation for copying the file/folder from one path to another
*
* @param data Intent received
*/
private fun requestCopyOperation(data: Intent) {
val folderToCopyAt = data.getParcelableExtra<OCFile>(FolderPickerActivity.EXTRA_FOLDER) ?: return
val files = data.getParcelableArrayListExtra<OCFile>(FolderPickerActivity.EXTRA_FILES) ?: return
copyMoveTargetFolder = folderToCopyAt
val copyOperation = FileOperation.CopyOperation(
listOfFilesToCopy = files.toList(),
targetFolder = folderToCopyAt,
isUserLogged = com.owncloud.android.presentation.authentication.AccountUtils.getCurrentOwnCloudAccount(this) != null,
)
fileOperationsViewModel.performOperation(copyOperation)
}
override fun onBackPressed() {
val isFabOpen = mainFileListFragment?.isFabExpanded() ?: false
/*
* BackPressed priority/hierarchy:
* 1. close drawer if opened
* 2. close FAB if open (only if drawer isn't open)
* 3. navigate up (only if drawer and FAB aren't open)
*/
if (isDrawerOpen() && isFabOpen) {
// close drawer first
super.onBackPressed()
} else if (isDrawerOpen() && !isFabOpen) {
// close drawer
super.onBackPressed()
} else if (!isDrawerOpen() && isFabOpen) {
// close fab
mainFileListFragment?.collapseFab()
mainFileListFragment?.setFabMainContentDescription()
} else {
// Every single menu is collapsed. We can navigate up.
if (secondFragment != null) {
// If secondFragment was shown, we need to navigate to the parent of the displayed file
// Need a cleanup
val folderIdToDisplay =
if (fileListOption == FileListOption.AV_OFFLINE) storageManager.getRootPersonalFolder()!!.id!!
else secondFragment!!.file!!.parentId!!
mainFileListFragment?.navigateToFolderId(folderIdToDisplay)
cleanSecondFragment()
updateToolbar(mainFileListFragment?.getCurrentFile())
} else {
val currentDirDisplayed = mainFileListFragment?.getCurrentFile()
// If current file is null (we are in the spaces list, for example), close the app
if (currentDirDisplayed == null) {
finish()
return
}
// If current file is root folder
else if (currentDirDisplayed.parentId == ROOT_PARENT_ID) {
// If current space is a project space or personal in a multi-personal account, navigate back to the spaces list
if (mainFileListFragment?.getCurrentSpace()?.isProject == true ||
(mainFileListFragment?.getCurrentSpace()?.isPersonal == true && isMultiPersonal)) {
navigateTo(FileListOption.SPACES_LIST)
}
// If current space is not a project space (personal or shares) or it is null ("Files" in oC10), close the app
else {
finish()
return
}
} else {
mainFileListFragment?.onBrowseUp()
}
}
}
}
override fun onSaveInstanceState(outState: Bundle) {
// responsibility of restore is preferred in onCreate() before than in
// onRestoreInstanceState when there are Fragments involved
Timber.v("onSaveInstanceState() start")
super.onSaveInstanceState(outState)
outState.putParcelable(KEY_WAITING_TO_PREVIEW, fileWaitingToPreview)
outState.putBoolean(KEY_SYNC_IN_PROGRESS, syncInProgress)
outState.putParcelable(KEY_FILE_LIST_OPTION, fileListOption)
//outState.putBoolean(KEY_REFRESH_SHARES_IN_PROGRESS,
// mRefreshSharesInProgress);
outState.putParcelable(KEY_WAITING_TO_SEND, waitingToSend)
outState.putParcelable(KEY_UPLOAD_HELPER, filesUploadHelper)
Timber.v("onSaveInstanceState() end")
}
override fun onResume() {
Timber.v("onResume() start")
super.onResume()
updateBottombar(mainFileListFragment?.getCurrentSpace())
if (mainFileListFragment?.getCurrentSpace()?.isProject == true ||
(mainFileListFragment?.getCurrentSpace()?.isPersonal == true && isMultiPersonal)) {
updateToolbar(null, mainFileListFragment?.getCurrentSpace())
}
if (secondFragment == null) {
mainFileListFragment?.updateFileListOption(fileListOption, file)
// refresh list of files
refreshListOfFilesFragment()
}
// Listen for sync messages
val syncIntentFilter = IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START)
syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END)
syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED)
syncBroadcastReceiver = SyncBroadcastReceiver()
localBroadcastManager!!.registerReceiver(syncBroadcastReceiver!!, syncIntentFilter)
showDialogs()
Timber.v("onResume() end")
}
override fun onPause() {
Timber.v("onPause() start")
if (syncBroadcastReceiver != null) {
localBroadcastManager!!.unregisterReceiver(syncBroadcastReceiver!!)
syncBroadcastReceiver = null
}
super.onPause()
dismissDialogs()
Timber.v("onPause() end")
}
private inner class SyncBroadcastReceiver : BroadcastReceiver() {
/**
* [BroadcastReceiver] to enable syncing feedback in UI
*/
override fun onReceive(context: Context, intent: Intent) {
val event = intent.action
Timber.d("Received broadcast $event")
val accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME)
val synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH)
val serverVersion = intent.getParcelableExtra<OwnCloudVersion>(FileSyncAdapter.EXTRA_SERVER_VERSION)
if (serverVersion != null && !serverVersion.isServerVersionSupported) {
Timber.d("Server version not supported")
showRequestAccountChangeNotice(getString(R.string.server_not_supported), true)
}
val synchResult = intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT) as? RemoteOperationResult<*>
val sameAccount = account != null && accountName == account.name && storageManager != null
if (sameAccount) {
if (FileSyncAdapter.EVENT_FULL_SYNC_START == event) {
syncInProgress = true
} else {
var currentFile: OCFile? = file?.let { storageManager.getFileByPath(file.remotePath, file.spaceId) }
val currentDir = currentDir?.let { storageManager.getFileByPath(currentDir!!.remotePath, currentDir.spaceId) }
if (currentDir == null) {
// current folder was removed from the server
showMessageInSnackbar(
R.id.list_layout,
String.format(
getString(R.string.sync_current_folder_was_removed),
synchFolderRemotePath
)
)
browseToRoot()
} else {
if (currentFile == null && !file.isFolder) {
// currently selected file was removed in the server, and now we
// know it
cleanSecondFragment()
currentFile = currentDir
}
if (synchFolderRemotePath != null && currentDir.remotePath == synchFolderRemotePath) {
mainFileListFragment?.navigateToFolder(currentDir)
}
file = currentFile
}
syncInProgress =
FileSyncAdapter.EVENT_FULL_SYNC_END != event
}
mainFileListFragment?.setProgressBarAsIndeterminate(syncInProgress)
Timber.d("Setting progress visibility to $syncInProgress")
}
if (synchResult?.code == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
lastSslUntrustedServerResult = synchResult
} else if (synchResult?.code == ResultCode.SPECIFIC_SERVICE_UNAVAILABLE) {
if (synchResult.httpCode == 503) {
if (synchResult.httpPhrase == "Error: Call to a member function getUID() on null") {
showRequestAccountChangeNotice(getString(R.string.auth_failure_snackbar), false)
} else {
showMessageInSnackbar(R.id.list_layout, synchResult.httpPhrase)
}
} else {
showRequestAccountChangeNotice(getString(R.string.auth_failure_snackbar), false)
}
}
}
}
fun browseToRoot() {
val listOfFiles = mainFileListFragment
if (listOfFiles != null) { // should never be null, indeed
val root = storageManager.getRootPersonalFolder()
listOfFiles.navigateToFolder(root!!)
file = root
}
cleanSecondFragment()
}
/**
* Shows the information of the [OCFile] received as a
* parameter in the second fragment.
*
* @param file [OCFile] whose details will be shown
*/
override fun showDetails(file: OCFile) {
navigateToDetails(account = account, ocFile = file, syncFileAtOpen = false)
updateToolbar(file)
setFile(file)
}
override fun syncFile(file: OCFile) {
fileOperationsViewModel.performOperation(FileOperation.SynchronizeFileOperation(file, account.name))
}
override fun openFile(file: OCFile) {
if (file.isAvailableLocally) {
fileOperationsHelper.openFile(file)
fileOperationsViewModel.setLastUsageFile(file)
} else {
startDownloadForOpening(file)
}
}
override fun sendDownloadedFile(file: OCFile) {
sendDownloadedFilesByShareSheet(listOf(file))
}
private fun updateToolbar(chosenFileFromParam: OCFile?, space: OCSpace? = null) {
val chosenFile = chosenFileFromParam ?: file // If no file is passed, current file decides
// If we come from a preview activity (image or video), not updating toolbar when initializing this activity
// or it will show the root folder one
if (intent.action == ACTION_DETAILS && chosenFile?.remotePath == OCFile.ROOT_PATH && secondFragment is FileDetailsFragment) return
if (chosenFile == null || (chosenFile.remotePath == OCFile.ROOT_PATH && (space == null || isNotProjectSpaceAndMultiPersonalMode(space) ||
isMultiPersonalModeInAvailableOffline(space))
)) {
val title =
when (fileListOption) {
FileListOption.AV_OFFLINE -> getString(R.string.drawer_item_only_available_offline)
FileListOption.SHARED_BY_LINK -> if (chosenFile == null || chosenFile.spaceId != null) {
getString(R.string.bottom_nav_shares)
} else {
getString(R.string.bottom_nav_links)
}
FileListOption.ALL_FILES -> getString(R.string.default_display_name_for_root_folder)
FileListOption.SPACES_LIST -> getString(R.string.bottom_nav_spaces)
}
setTitle(title)
setupRootToolbar(title = title, isSearchEnabled = true, isAvatarRequested = false)
} else if ((space?.isProject == true || (space?.isPersonal == true && isMultiPersonal)) && chosenFile.remotePath == OCFile.ROOT_PATH) {
updateStandardToolbar(title = space.name, displayHomeAsUpEnabled = true, homeButtonEnabled = true)
} else {
updateStandardToolbar(title = chosenFile.fileName, displayHomeAsUpEnabled = true, homeButtonEnabled = true)
}
}