-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathMainViewModel.kt
663 lines (572 loc) · 25.6 KB
/
MainViewModel.kt
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
/*
* Infomaniak kDrive - Android
* Copyright (C) 2022-2024 Infomaniak Network SA
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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://www.gnu.org/licenses/>.
*/
package com.infomaniak.drive.ui
import android.app.Application
import android.content.Context
import android.provider.MediaStore
import androidx.collection.arrayMapOf
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.*
import androidx.navigation.NavController
import androidx.work.WorkInfo
import androidx.work.WorkManager
import androidx.work.WorkQuery
import com.google.gson.JsonObject
import com.infomaniak.drive.MainApplication
import com.infomaniak.drive.MatomoDrive.trackNewElementEvent
import com.infomaniak.drive.R
import com.infomaniak.drive.data.api.ApiRepository
import com.infomaniak.drive.data.cache.FileController
import com.infomaniak.drive.data.cache.FolderFilesProvider
import com.infomaniak.drive.data.cache.FolderFilesProvider.SourceRestrictionType.ONLY_FROM_REMOTE
import com.infomaniak.drive.data.models.*
import com.infomaniak.drive.data.models.File.SortType
import com.infomaniak.drive.data.models.ShareLink.ShareLinkFilePermission
import com.infomaniak.drive.data.models.ShareableItems.FeedbackAccessResource
import com.infomaniak.drive.data.models.file.FileExternalImport.FileExternalImportStatus
import com.infomaniak.drive.data.services.DownloadWorker
import com.infomaniak.drive.ui.addFiles.UploadFilesHelper
import com.infomaniak.drive.utils.*
import com.infomaniak.drive.utils.MediaUtils.deleteInMediaScan
import com.infomaniak.drive.utils.MediaUtils.isMedia
import com.infomaniak.drive.utils.SyncUtils.isSyncScheduled
import com.infomaniak.drive.utils.SyncUtils.syncImmediately
import com.infomaniak.lib.core.models.ApiResponse
import com.infomaniak.lib.core.networking.HttpClient
import com.infomaniak.lib.core.networking.NetworkAvailability
import com.infomaniak.lib.core.utils.SentryLog
import com.infomaniak.lib.core.utils.SingleLiveEvent
import io.realm.Realm
import io.realm.kotlin.toFlow
import io.sentry.Breadcrumb
import io.sentry.Sentry
import io.sentry.SentryLevel
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import java.util.Date
class MainViewModel(
appContext: Application,
private val savedStateHandle: SavedStateHandle,
) : AndroidViewModel(appContext) {
var selectFolderUserDrive: UserDrive? = null
val realm: Realm by lazy {
selectFolderUserDrive?.let {
FileController.getRealmInstance(it)
} ?: FileController.getRealmInstance()
}
private val privateFolder = MutableLiveData<File>()
private val _currentFolder = MutableLiveData<File?>()
val currentFolder: LiveData<File?> = _currentFolder // Use `setCurrentFolder` and `postCurrentFolder` to set value on it
val currentFolderOpenAddFileBottom = MutableLiveData<File>()
var currentPreviewFileList = LinkedHashMap<Int, File>()
private val _pendingUploadsCount = MutableLiveData<Int?>(null)
val createDropBoxSuccess = SingleLiveEvent<DropBox>()
val navigateFileListTo = SingleLiveEvent<File>()
val deleteFileFromHome = SingleLiveEvent<Boolean>()
val refreshActivities = SingleLiveEvent<Boolean>()
val updateOfflineFile = SingleLiveEvent<FileId>()
val updateVisibleFiles = MutableLiveData<Boolean>()
val isBulkDownloadRunning = MutableLiveData<Boolean>()
@OptIn(ExperimentalCoroutinesApi::class)
val isNetworkAvailable = NetworkAvailability([email protected]()).isNetworkAvailable
.mapLatest {
onNetworkAvailabilityChanged(it)
it
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(stopTimeoutMillis = TIMEOUT_MS_NETWORK_AVAILABILITY_MS),
initialValue = null
)
inline val hasNetwork get() = isNetworkAvailable.value != false
var mustOpenUploadShortcut: Boolean = true
get() = savedStateHandle[SAVED_STATE_MUST_OPEN_UPLOAD_SHORTCUT_KEY] ?: field
set(value) {
savedStateHandle[SAVED_STATE_MUST_OPEN_UPLOAD_SHORTCUT_KEY] = value
field = value
}
var ignoreSyncOffline = false
var uploadFilesHelper: UploadFilesHelper? = null
val notificationPermission by lazy { NotificationPermission() }
private var rootFilesJob: Job = Job()
private var getFileDetailsJob = Job()
private var syncOfflineFilesJob: Job? = null
private var setCurrentFolderJob = Job()
val deleteFilesFromGallery = SingleLiveEvent<List<Int>>()
private fun getContext() = getApplication<MainApplication>()
fun setCurrentFolder(folder: File?) {
folder?.let {
setCurrentFolderJob.cancel()
saveCurrentFolderId()
uploadFilesHelper?.setParentFolder(it)
_currentFolder.value = it
}
}
fun setCurrentFolderAsRoot(): Job {
setCurrentFolderJob.cancel()
setCurrentFolderJob = Job()
return viewModelScope.launch(Dispatchers.IO + setCurrentFolderJob) {
val file = privateFolder.value ?: FileController.getPrivateFolder().also { privateFolder.postValue(it) }
setCurrentFolderJob.ensureActive()
_currentFolder.postValue(file)
}
}
private fun postCurrentFolder(file: File?) {
setCurrentFolderJob.cancel()
_currentFolder.postValue(file)
}
fun initUploadFilesHelper(fragmentActivity: FragmentActivity, navController: NavController) {
uploadFilesHelper = UploadFilesHelper(
activity = fragmentActivity,
navController = navController,
onOpeningPicker = {
fragmentActivity.trackNewElementEvent("uploadFile")
uploadFilesHelper?.let { setParentFolder() } ?: Sentry.captureMessage("UploadFilesHelper is null. It should not!")
},
)
initCurrentFolderFromRealm()
setParentFolder()
}
fun loadRootFiles() {
rootFilesJob.cancel()
rootFilesJob = viewModelScope.launch(Dispatchers.IO) {
if (hasNetwork) {
FolderFilesProvider.getFiles(
FolderFilesProvider.FolderFilesProviderArgs(
folderId = Utils.ROOT_ID,
isFirstPage = true,
order = SortType.NAME_AZ,
sourceRestrictionType = ONLY_FROM_REMOTE,
userDrive = UserDrive(),
)
)
}
}
}
fun navigateFileListTo(navController: NavController, fileId: Int, isSharedWithMe: Boolean = false) {
// Clear FileListFragment stack
navController.popBackStack(R.id.rootFilesFragment, false)
if (fileId <= Utils.ROOT_ID) return // Deeplinks could lead us to navigating to the true root
// Emit destination folder id
viewModelScope.launch(Dispatchers.IO) {
val userDrive = UserDrive(sharedWithMe = isSharedWithMe)
val file = FileController.getFileById(fileId, userDrive)
?: FileController.getFileDetails(fileId, userDrive)
?: return@launch
navigateFileListTo.postValue(file)
}
}
fun loadCurrentFolder(folderId: Int, userDrive: UserDrive) = viewModelScope.launch(Dispatchers.IO) {
postCurrentFolder(FileController.getFileById(folderId, userDrive))
}
fun createMultiSelectMediator(): MediatorLiveData<MultiSelectMediatorState> =
MediatorLiveData<MultiSelectMediatorState>().apply {
value = MultiSelectMediatorState(numberOfSuccessfulActions = 0, totalOfActions = 0, errorCode = null)
}
fun updateMultiSelectMediator(mediator: MediatorLiveData<MultiSelectMediatorState>): (FileResult) -> Unit = { fileRequest ->
var numberOfSuccessfulActions = mediator.value!!.numberOfSuccessfulActions
if (fileRequest.isSuccess) numberOfSuccessfulActions++
val totalOfActions = mediator.value!!.totalOfActions + 1
mediator.value = MultiSelectMediatorState(
numberOfSuccessfulActions,
totalOfActions,
fileRequest.errorCode,
)
}
fun createShareLink(file: File) = liveData(Dispatchers.IO) {
val body = ShareLink().ShareLinkSettings(right = ShareLinkFilePermission.PUBLIC, canDownload = true, canEdit = false)
val apiResponse = ApiRepository.createShareLink(file, body)
if (apiResponse.isSuccess()) {
FileController.updateFile(file.id) { it.shareLink = apiResponse.data }
}
emit(apiResponse)
}
fun getDropBox(file: File) = liveData(Dispatchers.IO) {
emit(ApiRepository.getDropBox(file))
}
fun createDropBoxFolder(
file: File,
emailWhenFinished: Boolean,
limitFileSize: Long? = null,
password: String? = null,
validUntil: Long? = null
) = liveData(Dispatchers.IO) {
val body = arrayMapOf(
"email_when_finished" to emailWhenFinished,
"limit_file_size" to limitFileSize,
"password" to password
)
validUntil?.let { body.put("valid_until", validUntil) }
with(ApiRepository.postDropBox(file, body)) {
if (isSuccess()) FileController.updateDropBox(file.id, data)
emit(this)
}
}
fun updateDropBox(file: File, newDropBox: DropBox) = liveData(Dispatchers.IO) {
val data = JsonObject().apply {
addProperty("email_when_finished", newDropBox.newHasNotification)
addProperty("valid_until", newDropBox.newValidUntil?.time?.let { it / 1000 })
addProperty("limit_file_size", newDropBox.newLimitFileSize)
if (newDropBox.newPassword && !newDropBox.newPasswordValue.isNullOrBlank()) {
addProperty("password", newDropBox.newPasswordValue)
} else if (!newDropBox.newPassword) {
val password: String? = null
addProperty("password", password)
}
}
with(ApiRepository.updateDropBox(file, data)) {
if (isSuccess()) FileController.updateDropBox(file.id, newDropBox)
emit(this)
}
}
fun deleteDropBox(file: File) = liveData(Dispatchers.IO) {
emit(ApiRepository.deleteDropBox(file))
}
fun deleteFileShareLink(file: File) = liveData(Dispatchers.IO) {
val apiResponse = ApiRepository.deleteFileShareLink(file)
if (apiResponse.isSuccess()) FileController.updateFile(file.id) {
it.shareLink = null
it.rights?.canBecomeShareLink = true
}
emit(apiResponse)
}
fun getShareLink(file: File) = liveData(Dispatchers.IO) {
emit(ApiRepository.getShareLink(file))
}
fun getFileShare(fileId: Int, userDrive: UserDrive? = null) = liveData(Dispatchers.IO) {
val okHttpClient = userDrive?.userId?.let { AccountUtils.getHttpClient(it) } ?: HttpClient.okHttpClient
val driveId = userDrive?.driveId ?: AccountUtils.currentDriveId
val apiResponse = ApiRepository.getFileShare(okHttpClient, File(id = fileId, driveId = driveId))
emit(apiResponse)
}
fun createOffice(driveId: Int, folderId: Int, createFile: CreateFile) = liveData(Dispatchers.IO) {
emit(ApiRepository.createOfficeFile(driveId, folderId, createFile))
}
fun addFileToFavorites(file: File, userDrive: UserDrive? = null, onSuccess: (() -> Unit)? = null) =
liveData(Dispatchers.IO) {
with(ApiRepository.postFavoriteFile(file)) {
emit(FileResult(this.isSuccess()))
if (isSuccess()) {
FileController.updateFile(file.id, userDrive = userDrive) {
it.isFavorite = true
}
onSuccess?.invoke()
}
}
}
fun deleteFileFromFavorites(file: File, userDrive: UserDrive? = null, onSuccess: ((File) -> Unit)? = null) =
liveData(Dispatchers.IO) {
with(ApiRepository.deleteFavoriteFile(file)) {
emit(FileResult(this.isSuccess()))
if (isSuccess()) {
FileController.updateFile(file.id, userDrive = userDrive) {
it.isFavorite = false
onSuccess?.invoke(it)
}
}
}
}
fun getFileDetails(fileId: Int, userDrive: UserDrive): LiveData<File?> {
getFileDetailsJob.cancel()
getFileDetailsJob = Job()
return liveData(Dispatchers.IO + getFileDetailsJob) {
emit(FileController.getFileDetails(fileId, userDrive))
}
}
fun moveFile(file: File, newParent: File, onSuccess: ((fileId: Int) -> Unit)? = null) = liveData(Dispatchers.IO) {
val apiResponse = ApiRepository.moveFile(file, newParent)
if (apiResponse.isSuccess()) {
FileController.getRealmInstance().use { realm ->
file.getStoredFile(getContext())?.let { ioFile ->
if (ioFile.exists()) moveIfOfflineFileOrDelete(file, ioFile, newParent)
}
FileController.updateFile(file.parentId, realm) { localFolder ->
// Ignore expired transactions when it's suspended
// In case the phone is slow or in standby, the transaction can create an IllegalStateException
// because realm will not be available anymore, the transaction is resumed afterwards
// so we ignore the cases where it fails.
runCatching { localFolder.children.remove(file) }
}
FileController.addChild(newParent.id, file.apply { parentId = newParent.id }, realm)
}
onSuccess?.invoke(file.id)
}
emit(FileResult(isSuccess = apiResponse.isSuccess(), errorCode = apiResponse.error?.code))
}
fun renameFile(file: File, newName: String) = liveData(Dispatchers.IO) {
emit(FileController.renameFile(file, newName))
}
fun updateFolderColor(file: File, color: String, userDrive: UserDrive) = liveData(Dispatchers.IO) {
emit(FileResult(isSuccess = FileController.updateFolderColor(file, color, userDrive).isSuccess()))
}
fun manageCategory(categoryId: Int, files: List<File>, isAdding: Boolean) = liveData(Dispatchers.IO) {
with(manageCategoryApiCall(files, categoryId, isAdding)) {
data?.forEach { feedbackResource ->
if (feedbackResource.result) {
FileController.updateFile(feedbackResource.id) {
if (isAdding) {
it.categories.add(FileCategory(categoryId, userId = AccountUtils.currentUserId, addedAt = Date()))
} else {
it.categories.find(categoryId)?.deleteFromRealm()
}
}
}
}
emit(this)
}
}
fun deleteFile(file: File, userDrive: UserDrive? = null, onSuccess: ((fileId: Int) -> Unit)? = null) =
liveData(Dispatchers.IO) {
with(FileController.deleteFile(file, userDrive = userDrive, context = getContext(), onSuccess = onSuccess)) {
emit(
FileResult(
isSuccess = this.isSuccess(),
data = this.data,
errorCode = this.error?.code,
errorResId = this.translatedError
)
)
}
}
fun restoreTrashFile(file: File, newFolderId: Int? = null, onSuccess: (() -> Unit)? = null) = liveData(Dispatchers.IO) {
val body = newFolderId?.let { mapOf("destination_directory_id" to it) }
with(ApiRepository.postRestoreTrashFile(file, body)) {
emit(FileResult(this.isSuccess(), errorCode = this.error?.code))
if (isSuccess()) onSuccess?.invoke()
}
}
fun deleteTrashFile(file: File, onSuccess: (() -> Unit)? = null) = liveData(Dispatchers.IO) {
with(ApiRepository.deleteTrashFile(file)) {
emit(FileResult(this.isSuccess()))
if (isSuccess()) onSuccess?.invoke()
}
}
fun duplicateFile(
file: File,
destinationId: Int? = null,
onSuccess: ((apiResponse: ApiResponse<File>) -> Unit)? = null,
) = liveData(Dispatchers.IO) {
ApiRepository.duplicateFile(file, destinationId ?: Utils.ROOT_ID).let { apiResponse ->
if (apiResponse.isSuccess()) onSuccess?.invoke(apiResponse)
emit(FileResult(isSuccess = apiResponse.isSuccess(), data = apiResponse.data, errorCode = apiResponse.error?.code))
}
}
fun convertFile(file: File) = liveData(Dispatchers.IO) {
emit(ApiRepository.convertFile(file))
}
fun cancelExternalImport(importId: Int) = liveData(Dispatchers.IO) {
val driveId = AccountUtils.currentDriveId
val apiResponse = ApiRepository.cancelExternalImport(driveId, importId)
if (apiResponse.isSuccess()) {
FileController.updateExternalImportStatus(driveId, importId, FileExternalImportStatus.CANCELING)
}
emit(apiResponse)
}
@OptIn(ExperimentalCoroutinesApi::class)
val pendingUploadsCount: LiveData<Int> = _pendingUploadsCount.switchMap { folderId ->
UploadFile.getCurrentUserPendingUploadFile(folderId)
.toFlow()
.mapLatest { list -> list.count() }
.distinctUntilChanged()
.cancellable()
.asLiveData()
}
fun observeDownloadOffline(context: Context) = WorkManager.getInstance(context).getWorkInfosLiveData(
WorkQuery.Builder
.fromUniqueWorkNames(arrayListOf(DownloadWorker.TAG))
.addStates(arrayListOf(WorkInfo.State.RUNNING, WorkInfo.State.SUCCEEDED))
.build()
)
fun restartUploadWorkerIfNeeded() {
viewModelScope.launch {
if (UploadFile.getAllPendingUploadsCount() > 0 && !getContext().isSyncScheduled()) {
getContext().syncImmediately()
}
}
}
fun removeSelectedFilesFromOffline(files: List<File>, onSuccess: (() -> Unit)? = null) = liveData {
val filesId = files.map {
val file: File = it.freeze()
if (!file.isFolder()) {
val offlineFile = file.getOfflineFile(getApplication())
val cacheFile = file.getCacheFile(getApplication())
if (file.isOffline && offlineFile != null) {
deleteFile(file, offlineFile, cacheFile)
}
}
file.id
}
viewModelScope.launch(Dispatchers.IO) {
FileController.updateIsOfflineForFiles(fileIds = filesId, isOffline = false)
onSuccess?.invoke()
emit(FileResult(isSuccess = true))
}
}
fun removeOfflineFile(
file: File,
offlineFile: IOFile,
cacheFile: IOFile,
userDrive: UserDrive = UserDrive(),
onFileRemovedFromOffline: (() -> Unit)? = null,
) {
// We need to call this method outside the UI thread
viewModelScope.launch(Dispatchers.IO) {
FileController.updateOfflineStatus(file.id, isOffline = false)
}
deleteFile(file, offlineFile, cacheFile, userDrive, onFileRemovedFromOffline)
}
private fun deleteFile(
file: File,
offlineFile: IOFile,
cacheFile: IOFile,
userDrive: UserDrive = UserDrive(),
onFileRemovedFromOffline: (() -> Unit)? = null,
) {
viewModelScope.launch {
if (file.isMedia()) file.deleteInMediaScan(getContext(), userDrive)
if (cacheFile.exists()) cacheFile.delete()
if (offlineFile.exists()) {
offlineFile.delete()
}
onFileRemovedFromOffline?.invoke()
}
}
fun syncOfflineFiles() {
syncOfflineFilesJob?.cancel()
syncOfflineFilesJob = viewModelScope.launch(Dispatchers.IO) {
SyncOfflineUtils.startSyncOffline(getContext())
}
}
fun cancelSyncOfflineFiles() {
syncOfflineFilesJob?.cancel()
}
// Only for API 29 and below, otherwise use MediaStore.createDeleteRequest()
fun deleteSynchronizedFilesOnDevice(filesToDelete: ArrayList<UploadFile>) = viewModelScope.launch(Dispatchers.IO) {
val fileDeleted = arrayListOf<UploadFile>()
filesToDelete.forEach { uploadFile ->
try {
val uri = uploadFile.getUriObject()
val query = getContext().contentResolver.query(uri, arrayOf(MediaStore.Images.Media.DATA), null, null, null)
query?.use { cursor ->
if (cursor.moveToFirst()) {
var columnIndex: Int? = null
try {
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
val pathname = cursor.getString(columnIndex)
IOFile(pathname).delete()
getContext().contentResolver.delete(uri, null, null)
} catch (nullPointerException: NullPointerException) {
Sentry.withScope { scope ->
scope.setExtra("columnIndex", columnIndex.toString())
Sentry.captureException(Exception("deleteSynchronizedFilesOnDevice()"))
}
} finally {
fileDeleted.add(uploadFile)
}
}
} ?: fileDeleted.add(uploadFile)
} catch (exception: SecurityException) {
Sentry.captureException(exception)
exception.printStackTrace()
fileDeleted.add(uploadFile)
}
}
UploadFile.deleteAll(fileDeleted)
}
fun checkBulkDownloadStatus() = viewModelScope.launch {
val isRunning = DownloadOfflineFileManager.isBulkDownloadWorkerRunning(getContext())
isBulkDownloadRunning.value = isRunning
ignoreSyncOffline = isRunning
}
fun markFilesAsOffline(filesId: List<Int>, isMarkedAsOffline: Boolean) = viewModelScope.launch(Dispatchers.IO) {
FileController.getRealmInstance().use { realm ->
FileController.markFilesAsOffline(customRealm = realm, filesId = filesId, isMarkedAsOffline = isMarkedAsOffline)
}
}
private suspend fun onNetworkAvailabilityChanged(isNetworkAvailable: Boolean) {
SentryLog.d("Internet availability", if (isNetworkAvailable) "Available" else "Unavailable")
Sentry.addBreadcrumb(Breadcrumb().apply {
category = "Network"
message = "Internet access is available : $isNetworkAvailable"
level = if (isNetworkAvailable) SentryLevel.INFO else SentryLevel.WARNING
})
if (isNetworkAvailable) {
AccountUtils.updateCurrentUserAndDrives([email protected]())
restartUploadWorkerIfNeeded()
}
}
private fun moveIfOfflineFileOrDelete(file: File, ioFile: IOFile, newParent: File) {
if (file.isOffline) ioFile.renameTo(IOFile("${newParent.getRemotePath()}/${file.name}"))
else ioFile.delete()
}
private fun saveCurrentFolder() {
saveCurrentFolderId()
uploadFilesHelper?.setParentFolder(currentFolder.value!!)
}
private fun setParentFolder() {
currentFolder.value?.let {
saveCurrentFolder()
} ?: run {
initCurrentFolderFromRealm()
}
}
private fun manageCategoryApiCall(
files: List<File>,
categoryId: Int,
isAdding: Boolean,
): ApiResponse<List<FeedbackAccessResource<Int, Unit>>> {
return if (isAdding) ApiRepository.addCategory(files, categoryId) else ApiRepository.removeCategory(files, categoryId)
}
private fun saveCurrentFolderId() {
currentFolder.value?.let { savedStateHandle[SAVED_STATE_FOLDER_ID_KEY] = it.id }
}
private fun initCurrentFolderFromRealm() {
val savedFolderId: Int? = savedStateHandle[SAVED_STATE_FOLDER_ID_KEY]
if (currentFolder.value == null && savedFolderId != null) {
FileController.getFileById(savedFolderId)?.let {
_currentFolder.value = it
saveCurrentFolder()
}
}
}
fun switchToNextUser(onUserSwitched: () -> Unit) = viewModelScope.launch(Dispatchers.IO) {
if (AccountUtils.getAllUsersSync().size < 2) return@launch
AccountUtils.switchToNextUser()
withContext(Dispatchers.Main) { onUserSwitched() }
}
override fun onCleared() {
realm.close()
super.onCleared()
}
data class FileResult(
val isSuccess: Boolean,
val errorResId: Int? = null,
val data: Any? = null,
val errorCode: String? = null
)
data class MultiSelectMediatorState(
var numberOfSuccessfulActions: Int,
var totalOfActions: Int,
var errorCode: String?,
)
companion object {
private const val SAVED_STATE_FOLDER_ID_KEY = "folderId"
private const val SAVED_STATE_MUST_OPEN_UPLOAD_SHORTCUT_KEY = "mustOpenUploadShortcut"
private const val TIMEOUT_MS_NETWORK_AVAILABILITY_MS = 500L
}
}