-
-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathSteamContentManager.kt
More file actions
1621 lines (1420 loc) · 75.3 KB
/
Copy pathSteamContentManager.kt
File metadata and controls
1621 lines (1420 loc) · 75.3 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
package com.nendo.argosy.data.steam
import android.content.Context
import android.util.Log
import com.nendo.argosy.data.download.DownloadForegroundService
import com.nendo.argosy.data.local.dao.GameDao
import com.nendo.argosy.data.local.dao.SteamDownloadQueueDao
import com.nendo.argosy.data.local.entity.SteamDownloadDbState
import com.nendo.argosy.data.local.entity.SteamDownloadQueueEntity
import com.nendo.argosy.core.notification.NotificationManager
import com.nendo.argosy.core.notification.NotificationType
import com.nendo.argosy.data.model.GameSource
import com.nendo.argosy.data.preferences.UserPreferencesRepository
import com.nendo.argosy.util.AppPaths
import dagger.hilt.android.qualifiers.ApplicationContext
import `in`.dragonbra.javasteam.steam.handlers.steamapps.SteamApps
import `in`.dragonbra.javasteam.steam.handlers.steamcontent.SteamContent
import `in`.dragonbra.javasteam.steam.steamclient.SteamClient
import `in`.dragonbra.javasteam.steam.steamclient.callbackmgr.CallbackManager
import `in`.dragonbra.javasteam.depotdownloader.DepotDownloader
import `in`.dragonbra.javasteam.depotdownloader.IDownloadListener
import `in`.dragonbra.javasteam.depotdownloader.data.AppItem
import `in`.dragonbra.javasteam.depotdownloader.data.DownloadItem
import `in`.dragonbra.javasteam.types.KeyValue
import kotlinx.coroutines.future.await
import java.io.Closeable
import kotlin.coroutines.coroutineContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import javax.inject.Inject
import javax.inject.Singleton
private const val TAG = "SteamContentManager"
private const val DOWNLOAD_INFO_DIR = ".DownloadInfo"
sealed class SteamDownloadState {
data object Idle : SteamDownloadState()
data class Preparing(val appId: Long, val gameName: String) : SteamDownloadState()
data class Connecting(val appId: Long, val gameName: String) : SteamDownloadState()
data class FetchingManifest(val appId: Long, val gameName: String, val depotId: Int) : SteamDownloadState()
data class Validating(val appId: Long, val gameName: String, val statusDetail: String = "") : SteamDownloadState()
data class Downloading(
val appId: Long,
val gameName: String,
val progress: Float,
val currentDepot: Int,
val totalDepots: Int
) : SteamDownloadState()
data class Moving(val appId: Long, val gameName: String) : SteamDownloadState()
data class Completed(val appId: Long, val gameName: String, val installPath: String) : SteamDownloadState()
data class Failed(val appId: Long, val gameName: String, val error: String) : SteamDownloadState()
data class Paused(val appId: Long, val gameName: String, val progress: Float, val needsVerification: Boolean = false) : SteamDownloadState()
data class Cleaning(val appId: Long, val gameName: String) : SteamDownloadState()
}
data class DepotInfo(
val depotId: Int,
val manifestId: Long,
val name: String,
val os: String?,
val arch: String?,
val size: Long
)
data class SteamDownloadProgress(
val appId: Long,
val gameName: String,
val coverPath: String?,
val progress: Float,
val totalBytes: Long,
val bytesDownloaded: Long,
val state: SteamDownloadState,
val bytesPerSecond: Long = 0L
) {
val progressPercent: Int get() = (progress * 100).toInt()
}
data class QueuedSteamDownload(
val appId: Long,
val gameName: String,
val coverPath: String?,
val appInfo: KeyValue?,
val targetInstallPath: String? = null
)
@Singleton
class SteamContentManager @Inject constructor(
@ApplicationContext private val context: Context,
private val gameDao: GameDao,
private val preferencesRepository: UserPreferencesRepository,
private val steamAuthManager: SteamAuthManager,
private val steamLibraryManager: SteamLibraryManager,
private val notificationManager: NotificationManager,
private val steamDownloadQueueDao: SteamDownloadQueueDao,
private val downloadManager: dagger.Lazy<com.nendo.argosy.data.download.DownloadManager>,
val depotManager: SteamDepotManager,
val pathResolver: SteamPathResolver,
private val progressTracker: SteamProgressTracker,
private val downloadTracker: SteamDownloadTracker,
private val fileAccessLayer: com.nendo.argosy.data.storage.FileAccessLayer
) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val heartbeatDispatcher = java.util.concurrent.Executors.newSingleThreadExecutor { r ->
Thread(r, "steam-heartbeat").apply { isDaemon = true }
}.asCoroutineDispatcher()
private var steamClient: SteamClient? = null
private var activeDepotDownloader: DepotDownloader? = null
private var picsSubscription: Closeable? = null
private val _downloadState = MutableStateFlow<SteamDownloadState>(SteamDownloadState.Idle)
val downloadState: StateFlow<SteamDownloadState> = _downloadState.asStateFlow()
private val _activeDownload = MutableStateFlow<SteamDownloadProgress?>(null)
val activeDownload: StateFlow<SteamDownloadProgress?> = _activeDownload.asStateFlow()
private val _downloadQueue = MutableStateFlow<List<QueuedSteamDownload>>(emptyList())
val downloadQueue: StateFlow<List<QueuedSteamDownload>> = _downloadQueue.asStateFlow()
private val _completedDownloads = MutableStateFlow<List<SteamDownloadProgress>>(emptyList())
val completedDownloads: StateFlow<List<SteamDownloadProgress>> = _completedDownloads.asStateFlow()
fun clearCompletedDownloads() {
_completedDownloads.value = emptyList()
if (_activeDownload.value?.state is SteamDownloadState.Completed) {
_activeDownload.value = null
}
}
private var currentDownloadJob: kotlinx.coroutines.Job? = null
private var isCancelled = false
private var lastDbProgressUpdate = 0L
private companion object {
const val DB_PROGRESS_INTERVAL_MS = 30_000L
}
init {
scope.launch {
restoreSteamQueueFromDatabase()
}
}
private suspend fun restoreSteamQueueFromDatabase() = withContext(Dispatchers.IO) {
steamDownloadQueueDao.clearFinished()
// Recover orphaned downloads: game has localPath pointing to staging but no queue entry
recoverOrphanedStagingDownloads()
val pending = steamDownloadQueueDao.getPendingDownloads()
if (pending.isEmpty()) return@withContext
// Handle interrupted deploys first -- resume file copy
val deploying = pending.filter { it.state == SteamDownloadDbState.DEPLOYING.name }
for (entity in deploying) {
resumeInterruptedDeploy(entity)
}
// Re-fetch after deploy handling (some may now be COMPLETED)
val afterDeploy = steamDownloadQueueDao.getPendingDownloads()
if (afterDeploy.isEmpty()) return@withContext
for (entity in afterDeploy) {
if (entity.state in listOf(SteamDownloadDbState.DOWNLOADING.name, SteamDownloadDbState.PREPARING.name)) {
steamDownloadQueueDao.updateState(entity.appId, SteamDownloadDbState.PAUSED.name)
// Clear localPath if it points to staging so game doesn't appear installed
gameDao.getBySteamAppId(entity.appId)?.let { game ->
if (game.localPath?.contains(AppPaths.STEAM_STAGING_DIR) == true) {
gameDao.update(game.copy(localPath = null))
}
}
}
}
val paused = afterDeploy.filter {
it.state in listOf(SteamDownloadDbState.PAUSED.name, SteamDownloadDbState.DOWNLOADING.name, SteamDownloadDbState.PREPARING.name)
}
val queued = afterDeploy.filter { it.state == SteamDownloadDbState.QUEUED.name }
if (paused.isNotEmpty()) {
val primary = paused.first()
val bytesDownloaded = primary.installPath?.let { progressTracker.loadPersistedBytes(it) } ?: primary.bytesDownloaded
val pausedState = SteamDownloadState.Paused(primary.appId, primary.gameName, 0f, needsVerification = true)
_downloadState.value = pausedState
_activeDownload.value = SteamDownloadProgress(
appId = primary.appId,
gameName = primary.gameName,
coverPath = primary.coverPath,
progress = 0f,
totalBytes = primary.totalBytes,
bytesDownloaded = bytesDownloaded,
state = pausedState
)
Log.d(TAG, "Restored active from DB: ${primary.gameName}")
val restPaused = paused.drop(1)
_downloadQueue.value = (restPaused + queued).map { entity ->
QueuedSteamDownload(entity.appId, entity.gameName, entity.coverPath, null, entity.installPath)
}
} else if (queued.isNotEmpty()) {
_downloadQueue.value = queued.map { entity ->
QueuedSteamDownload(entity.appId, entity.gameName, entity.coverPath, null, entity.installPath)
}
}
Log.d(TAG, "Restored ${paused.size} paused + ${queued.size} queued from DB")
}
private suspend fun recoverOrphanedStagingDownloads() {
val stagingRoot = AppPaths.steamStagingRoot(context.filesDir)
if (!stagingRoot.exists()) return
val steamGames = gameDao.getAllWithSteamAppId()
for (game in steamGames) {
val localPath = game.localPath ?: continue
if (!localPath.contains(AppPaths.STEAM_STAGING_DIR)) continue
val appId = game.steamAppId ?: continue
val existing = steamDownloadQueueDao.getByAppId(appId)
if (existing != null) continue
val stagingDir = File(localPath)
if (stagingDir.exists() && (stagingDir.listFiles()?.isNotEmpty() == true)) {
Log.d(TAG, "Recovering orphaned staging download: ${game.title} (appId=$appId)")
steamDownloadQueueDao.insert(SteamDownloadQueueEntity(
appId = appId,
gameName = game.title,
coverPath = game.coverPath,
installDir = null,
installPath = localPath,
totalBytes = 0L,
bytesDownloaded = progressTracker.loadPersistedBytes(localPath),
state = SteamDownloadDbState.PAUSED.name,
errorReason = null
))
gameDao.update(game.copy(localPath = null))
} else {
Log.d(TAG, "Clearing stale staging path for ${game.title}")
gameDao.update(game.copy(localPath = null))
}
}
}
private suspend fun resumeInterruptedDeploy(entity: SteamDownloadQueueEntity) {
val appId = entity.appId
val gameName = entity.gameName
val stagingDir = AppPaths.steamStagingDir(context.filesDir, appId)
// Resolve final path from installDir (Steam name), not installPath (may still point to staging)
val finalDir = if (entity.installDir != null) {
pathResolver.getInstallDirByName(entity.installDir)
} else {
pathResolver.getInstallDir(appId)
}
Log.d(TAG, "Resuming interrupted deploy for $gameName: staging=${stagingDir.exists()}, final=${finalDir.exists()}")
// Case 1: Final dir has .download_complete -- move finished, just clean up
if (File(finalDir, ".download_complete").exists()) {
Log.d(TAG, "Deploy already complete for $gameName, cleaning up")
if (stagingDir.exists()) stagingDir.deleteRecursively()
gameDao.getBySteamAppId(appId)?.let { game ->
if (game.localPath != finalDir.absolutePath) {
gameDao.update(game.copy(localPath = finalDir.absolutePath, source = GameSource.STEAM))
}
}
steamDownloadQueueDao.updateState(appId, SteamDownloadDbState.COMPLETED.name)
return
}
// Case 2: Staging dir still has files -- resume the copy
if (stagingDir.exists() && (stagingDir.listFiles()?.isNotEmpty() == true)) {
Log.d(TAG, "Resuming file copy for $gameName: staging -> ${finalDir.absolutePath}")
_downloadState.value = SteamDownloadState.Moving(appId, gameName)
_activeDownload.value = SteamDownloadProgress(
appId = appId,
gameName = gameName,
coverPath = entity.coverPath,
progress = 1f,
totalBytes = entity.totalBytes,
bytesDownloaded = entity.totalBytes,
state = SteamDownloadState.Moving(appId, gameName)
)
scope.launch(Dispatchers.IO) {
try {
finalDir.mkdirs()
val destFree = pathResolver.getAvailableBytes(finalDir)
val stagingSize = pathResolver.getDirectorySize(stagingDir)
if (destFree != null && destFree < stagingSize) {
Log.e(TAG, "Insufficient destination space for deploy resume: ${destFree / 1024 / 1024}MB free, need ${stagingSize / 1024 / 1024}MB")
steamDownloadQueueDao.updateState(appId, SteamDownloadDbState.PAUSED.name,
"Waiting for destination storage (need ${stagingSize / 1024 / 1024}MB)")
_downloadState.value = SteamDownloadState.Paused(appId, gameName, 1f)
_activeDownload.value = _activeDownload.value?.copy(
state = SteamDownloadState.Paused(appId, gameName, 1f)
)
return@launch
}
val moved = pathResolver.moveDirectory(stagingDir, finalDir)
if (!moved) {
Log.e(TAG, "Failed to resume deploy for $gameName")
steamDownloadQueueDao.updateState(appId, SteamDownloadDbState.FAILED.name, "File move failed")
_downloadState.value = SteamDownloadState.Failed(appId, gameName, "File move failed")
_activeDownload.value = _activeDownload.value?.copy(
state = SteamDownloadState.Failed(appId, gameName, "File move failed")
)
return@launch
}
gameDao.getBySteamAppId(appId)?.let { game ->
gameDao.update(game.copy(
localPath = finalDir.absolutePath,
source = GameSource.STEAM,
addedAt = java.time.Instant.now()
))
}
File(finalDir, ".download_complete").createNewFile()
File(finalDir, ".download_in_progress").delete()
File(finalDir, DOWNLOAD_INFO_DIR).mkdirs()
steamDownloadQueueDao.updateState(appId, SteamDownloadDbState.COMPLETED.name)
_downloadState.value = SteamDownloadState.Completed(appId, gameName, finalDir.absolutePath)
_activeDownload.value = null
Log.d(TAG, "Deploy resume complete: $gameName -> ${finalDir.absolutePath}")
} catch (e: Exception) {
Log.e(TAG, "Deploy resume failed for $gameName", e)
steamDownloadQueueDao.updateState(appId, SteamDownloadDbState.FAILED.name, e.message)
_downloadState.value = SteamDownloadState.Failed(appId, gameName, e.message ?: "Deploy failed")
}
}
return
}
// Case 3: Staging gone, final dir incomplete -- need re-download
Log.w(TAG, "Cannot resume deploy for $gameName: staging gone, final incomplete. Marking as failed.")
if (finalDir.exists()) finalDir.deleteRecursively()
steamDownloadQueueDao.updateState(appId, SteamDownloadDbState.FAILED.name, "Deploy interrupted, staging lost")
}
fun initialize(client: SteamClient, apps: SteamApps, cm: CallbackManager) {
steamClient = client
val content = client.getHandler(SteamContent::class.java)!!
depotManager.initialize(client, apps, content, cm)
Log.d(TAG, "SteamContentManager initialized")
}
suspend fun hasPendingDownloads(): Boolean {
return steamDownloadQueueDao.getPendingDownloads().isNotEmpty()
}
suspend fun restorePausedDownloads() {
val active = _activeDownload.value ?: return
if (active.state !is SteamDownloadState.Paused) return
if (!isConnected() || currentDownloadJob?.isActive == true) return
Log.d(TAG, "Auto-resuming ${active.gameName} (Steam connected)")
queueDownloadOptimistic(active.appId, active.gameName, active.coverPath)
}
fun onDownloadSlotFreed() {
if (_downloadQueue.value.isNotEmpty() && currentDownloadJob?.isActive != true) {
Log.d(TAG, "Download slot freed, checking Steam queue")
processNextInQueue()
}
}
fun hasActiveSteamDownload(): Boolean {
val state = _downloadState.value
return state is SteamDownloadState.Downloading ||
state is SteamDownloadState.Preparing ||
state is SteamDownloadState.Connecting ||
state is SteamDownloadState.FetchingManifest ||
state is SteamDownloadState.Validating ||
state is SteamDownloadState.Moving
}
fun isConnected(): Boolean {
val hasHandlers = depotManager.isConnected()
val loggedIn = steamAuthManager.isLoggedIn.value
Log.v(TAG, "isConnected check: hasHandlers=$hasHandlers, loggedIn=$loggedIn")
return hasHandlers && loggedIn
}
fun onDisconnected() {
Log.d(TAG, "Steam disconnected, clearing handlers")
val state = _downloadState.value
// Moving and Cleaning are local file operations that don't need Steam -- let them finish
if (state !is SteamDownloadState.Idle && state !is SteamDownloadState.Paused &&
state !is SteamDownloadState.Completed && state !is SteamDownloadState.Failed &&
state !is SteamDownloadState.Moving && state !is SteamDownloadState.Cleaning) {
pauseDownload()
}
scope.launch(Dispatchers.IO) {
val pending = steamDownloadQueueDao.getPendingDownloads()
pending.filter { it.state in listOf(SteamDownloadDbState.DOWNLOADING.name, SteamDownloadDbState.PREPARING.name) }.forEach {
steamDownloadQueueDao.updateState(it.appId, SteamDownloadDbState.PAUSED.name)
}
}
steamClient = null
depotManager.clearHandlers()
}
suspend fun ensureConnected(): Boolean {
if (isConnected()) return true
if (steamAuthManager.sessionDead) {
Log.e(TAG, "Steam session dead, cannot auto-connect")
notificationManager.show(
title = "Steam session expired",
subtitle = "Sign in from Settings > Steam to download",
type = NotificationType.WARNING,
key = "steam_not_signed_in"
)
return false
}
Log.d(TAG, "Steam not connected, starting service and waiting...")
val active = _activeDownload.value
if (active != null) {
val connectingState = SteamDownloadState.Connecting(active.appId, active.gameName)
_downloadState.value = connectingState
_activeDownload.value = active.copy(state = connectingState)
}
val intent = android.content.Intent(context, SteamService::class.java).apply {
putExtra(SteamService.EXTRA_FORCE_CONNECT, true)
}
context.startService(intent)
// Poll for connection with timeout
val deadline = System.currentTimeMillis() + 30_000L
while (System.currentTimeMillis() < deadline) {
if (isConnected()) {
Log.d(TAG, "Steam connected after waiting")
return true
}
kotlinx.coroutines.delay(500)
}
Log.e(TAG, "Steam connection timeout (connected=${isConnected()}, loggedIn=${steamAuthManager.isLoggedIn.value})")
return false
}
fun notifyConnected() {
Log.v(TAG, "notifyConnected called")
}
suspend fun fetchAppInfo(appId: Int): KeyValue {
if (!isConnected()) {
if (!ensureConnected()) {
throw IllegalStateException("Steam not connected")
}
}
return depotManager.fetchAppInfo(appId)
}
suspend fun downloadGame(
appId: Long,
gameName: String,
coverPath: String?
) = withContext(Dispatchers.IO) {
val appInfo = fetchAppInfo(appId.toInt())
downloadGame(appId, gameName, appInfo, coverPath)
}
fun queueDownloadOptimistic(appId: Long, gameName: String, coverPath: String?) {
if (!canQueue(appId)) return
if (steamAuthManager.sessionDead) {
notificationManager.show(
title = "Steam session expired",
subtitle = "Sign in from Settings > Steam to download",
type = NotificationType.WARNING,
key = "steam_not_signed_in"
)
// Revert to paused so the download stays visible
val active = _activeDownload.value
if (active != null) {
val pausedState = SteamDownloadState.Paused(appId, gameName, active.progress)
_downloadState.value = pausedState
_activeDownload.value = active.copy(state = pausedState)
}
return
}
DownloadForegroundService.start(context)
val active = _activeDownload.value
if (currentDownloadJob?.isActive == true && active?.appId != appId) {
// Something else is downloading -- add to queue with optimistic UI
_downloadQueue.value = _downloadQueue.value + QueuedSteamDownload(appId, gameName, coverPath, appInfo = null)
persistQueueEntry(appId, gameName, coverPath)
Log.d(TAG, "Optimistically queued: $gameName (queue size: ${_downloadQueue.value.size})")
return
}
// Nothing active or resuming paused/failed -- become the active download immediately
if (active?.appId == appId && (active.state is SteamDownloadState.Paused || active.state is SteamDownloadState.Failed)) {
val queuedState = SteamDownloadState.Preparing(appId, gameName)
_downloadState.value = queuedState
_activeDownload.value = active.copy(state = queuedState)
Log.d(TAG, "Optimistic retry for $appId, transitioning ${active.state::class.simpleName} -> Preparing")
} else {
_downloadState.value = SteamDownloadState.Preparing(appId, gameName)
_activeDownload.value = SteamDownloadProgress(
appId = appId,
gameName = gameName,
coverPath = coverPath,
progress = 0f,
totalBytes = 0L,
bytesDownloaded = 0L,
state = SteamDownloadState.Preparing(appId, gameName)
)
}
_downloadQueue.value = _downloadQueue.value + QueuedSteamDownload(appId, gameName, coverPath, appInfo = null)
persistQueueEntry(appId, gameName, coverPath)
Log.d(TAG, "Optimistically activated: $gameName")
if (currentDownloadJob?.isActive != true) {
processNextInQueue()
}
}
private fun persistQueueEntry(appId: Long, gameName: String, coverPath: String?) {
scope.launch(Dispatchers.IO) {
val snapshotPath = runCatching {
pathResolver.snapshotInstallDirAtEnqueue(appId, null).absolutePath
}.getOrNull()
try {
steamDownloadQueueDao.insert(SteamDownloadQueueEntity(
appId = appId,
gameName = gameName,
coverPath = coverPath,
installDir = null,
installPath = snapshotPath,
totalBytes = 0L,
bytesDownloaded = 0L,
state = SteamDownloadDbState.QUEUED.name,
errorReason = null
))
Log.d(TAG, "Persisted queue entry: $gameName -> ${snapshotPath ?: "<resolve later>"}")
} catch (e: Exception) {
Log.e(TAG, "Failed to persist queue entry for $gameName", e)
}
if (snapshotPath != null) {
_downloadQueue.value = _downloadQueue.value.map {
if (it.appId == appId && it.targetInstallPath == null) it.copy(targetInstallPath = snapshotPath) else it
}
}
}
}
fun queueDownload(appId: Long, gameName: String, appInfo: KeyValue, coverPath: String?) {
if (!canQueue(appId)) return
DownloadForegroundService.start(context)
val active = _activeDownload.value
// Transition paused/failed -> Preparing without nulling activeDownload
if (active?.appId == appId && (active.state is SteamDownloadState.Paused || active.state is SteamDownloadState.Failed)) {
val preparingState = SteamDownloadState.Preparing(appId, gameName)
_downloadState.value = preparingState
_activeDownload.value = active.copy(state = preparingState)
Log.d(TAG, "Retrying $appId: ${active.state::class.simpleName} -> Preparing")
}
val installDirName = appInfo["config"]?.get("installdir")?.asString()
scope.launch(Dispatchers.IO) {
val snapshotPath = runCatching {
pathResolver.snapshotInstallDirAtEnqueue(appId, installDirName).absolutePath
}.getOrNull()
try {
steamDownloadQueueDao.insert(SteamDownloadQueueEntity(
appId = appId,
gameName = gameName,
coverPath = coverPath,
installDir = installDirName,
installPath = snapshotPath,
totalBytes = 0L,
bytesDownloaded = 0L,
state = SteamDownloadDbState.QUEUED.name,
errorReason = null
))
} catch (e: Exception) {
Log.e(TAG, "Failed to persist queue entry for $gameName", e)
}
val queued = QueuedSteamDownload(appId, gameName, coverPath, appInfo, snapshotPath)
_downloadQueue.value = _downloadQueue.value + queued
Log.d(TAG, "Queued Steam download: $gameName -> ${snapshotPath ?: "<resolve later>"} (queue size: ${_downloadQueue.value.size})")
if (currentDownloadJob?.isActive != true) {
processNextInQueue()
}
}
}
private fun canQueue(appId: Long): Boolean {
val active = _activeDownload.value
if (active?.appId == appId) {
val state = active.state
if (state is SteamDownloadState.Paused || state is SteamDownloadState.Failed) {
// Allow re-queuing paused or failed downloads
return true
}
Log.d(TAG, "Game $appId already active in state ${state::class.simpleName}")
return false
}
if (_downloadQueue.value.any { it.appId == appId }) {
Log.d(TAG, "Game $appId already in queue")
return false
}
return true
}
private fun processNextInQueue() {
val queue = _downloadQueue.value
if (queue.isEmpty()) {
Log.d(TAG, "Download queue empty")
return
}
val next = queue.first()
_downloadQueue.value = queue.drop(1)
Log.d(TAG, "Starting next queued download: ${next.gameName}")
scope.launch {
// Check shared slot budget before starting
val maxConcurrent = preferencesRepository.userPreferences.first().maxConcurrentDownloads
val rommActive = downloadManager.get().activeDownloadCount
if (rommActive + 1 > maxConcurrent) {
Log.d(TAG, "No download slots available (romm=$rommActive, max=$maxConcurrent), re-queuing ${next.gameName}")
_downloadQueue.value = listOf(next) + _downloadQueue.value
return@launch
}
val appInfo = next.appInfo ?: try {
fetchAppInfo(next.appId.toInt())
} catch (e: Exception) {
Log.e(TAG, "Failed to fetch app info for ${next.gameName}: ${e.message}")
val active = _activeDownload.value
if (active != null) {
val pausedState = SteamDownloadState.Paused(next.appId, next.gameName, active.progress)
_downloadState.value = pausedState
_activeDownload.value = active.copy(state = pausedState)
}
steamDownloadQueueDao.updateState(next.appId, SteamDownloadDbState.PAUSED.name)
return@launch
}
startDownload(next.appId, next.gameName, appInfo, next.coverPath, next.targetInstallPath)
}
}
suspend fun downloadGame(
appId: Long,
gameName: String,
appInfo: KeyValue,
coverPath: String?
) {
queueDownload(appId, gameName, appInfo, coverPath)
}
private suspend fun startDownload(
appId: Long,
gameName: String,
appInfo: KeyValue,
coverPath: String?,
snapshottedInstallPath: String? = null
) {
val client = steamClient
if (client == null) {
val failedState = SteamDownloadState.Failed(appId, gameName, "Steam not connected")
_downloadState.value = failedState
_activeDownload.value = _activeDownload.value?.copy(state = failedState)
scope.launch(Dispatchers.IO) {
steamDownloadQueueDao.updateState(appId, SteamDownloadDbState.FAILED.name, "Steam not connected")
}
return
}
isCancelled = false
progressTracker.resetSpeedTracking()
currentDownloadJob = scope.launch {
var heartbeatJob: Job? = null
try {
_downloadState.value = SteamDownloadState.Preparing(appId, gameName)
// Resolve destination: honor enqueue-time snapshot so mid-queue preference
// changes don't redirect an in-flight download. New downloads re-snapshot.
val steamInstallDir = appInfo["config"]?.get("installdir")?.asString()
val installDir = when {
snapshottedInstallPath != null -> File(snapshottedInstallPath)
steamInstallDir != null -> pathResolver.getInstallDirByName(steamInstallDir)
else -> pathResolver.getInstallDir(appId)
}
installDir.mkdirs()
if (!installDir.exists() || !installDir.canWrite()) {
val msg = "Install path not accessible: ${installDir.absolutePath}"
Log.w(TAG, msg)
notificationManager.show(
title = "Cannot download $gameName",
subtitle = msg,
type = NotificationType.WARNING,
key = "steam_path_$appId"
)
val pausedState = SteamDownloadState.Paused(appId, gameName, 0f)
_downloadState.value = pausedState
_activeDownload.value = _activeDownload.value?.copy(state = pausedState)
steamDownloadQueueDao.updateState(appId, SteamDownloadDbState.PAUSED.name, msg)
processNextInQueue()
return@launch
}
File(installDir, ".download_in_progress").createNewFile()
Log.d(TAG, "Install path for $appId: ${installDir.absolutePath}")
// Migrate old staging downloads to destination
val oldStagingDir = AppPaths.steamStagingDir(context.filesDir, appId)
if (oldStagingDir.exists() && oldStagingDir.listFiles()?.isNotEmpty() == true) {
if (!installDir.exists() || installDir.listFiles().isNullOrEmpty()) {
Log.d(TAG, "Migrating old staging -> destination: ${oldStagingDir.absolutePath} -> ${installDir.absolutePath}")
pathResolver.moveDirectory(oldStagingDir, installDir)
} else {
Log.d(TAG, "Cleaning stale staging dir (destination already has files)")
oldStagingDir.deleteRecursively()
}
}
// Preserve .DepotDownloader if resuming from DB queue.
// Clean it only for fresh downloads.
val isResume = steamDownloadQueueDao.getByAppId(appId)?.state in
listOf(SteamDownloadDbState.PAUSED.name, SteamDownloadDbState.DOWNLOADING.name, SteamDownloadDbState.PREPARING.name)
val depotDir = File(installDir, ".DepotDownloader")
if (depotDir.exists() && !isResume) {
depotDir.deleteRecursively()
Log.d(TAG, "Cleaned stale .DepotDownloader state (fresh download)")
}
File(installDir, ".download_complete").delete()
// Store install path so restore/cleanup can find it
gameDao.getBySteamAppId(appId)?.let { game ->
if (game.localPath != installDir.absolutePath) {
gameDao.update(game.copy(localPath = installDir.absolutePath))
}
}
steamDownloadQueueDao.updateInstallPath(appId, installDir.absolutePath)
if (steamInstallDir != null) {
steamDownloadQueueDao.updateInstallDir(appId, steamInstallDir)
}
steamDownloadQueueDao.updateState(appId, SteamDownloadDbState.PREPARING.name)
_activeDownload.value = SteamDownloadProgress(
appId = appId,
gameName = gameName,
coverPath = coverPath,
progress = 0f,
totalBytes = 0L,
bytesDownloaded = 0L,
state = _downloadState.value
)
val allDepots = depotManager.getWindowsDepots(appInfo)
if (allDepots.isEmpty()) {
throw IllegalStateException("No Windows depots found for this game")
}
Log.v(TAG, "All depots discovered: ${allDepots.map { "${it.depotId}(manifest=${it.manifestId})" }}")
val sizeResult = depotManager.fetchDepotSizes(appId.toInt(), allDepots)
val totalSize = sizeResult.totalSize
Log.v(TAG, "Size result: accessible=${sizeResult.accessibleDepotIds}, sizes=${sizeResult.depotSizes.map { "${it.key}=${it.value / 1024 / 1024}MB" }}")
val depots = if (sizeResult.accessibleDepotIds.isNotEmpty()) {
allDepots.filter { it.depotId in sizeResult.accessibleDepotIds }
} else {
Log.w(TAG, "No depots returned sizes, falling back to all ${allDepots.size} depots")
allDepots
}
if (depots.isEmpty()) {
throw IllegalStateException("No accessible depots for this game")
}
Log.d(TAG, "Final depot list: ${depots.map { "${it.depotId}(${it.name})" }}")
Log.d(TAG, "Total: ${totalSize / 1024 / 1024}MB for $gameName (${depots.size}/${allDepots.size} depots)")
// Storage check -- downloading directly to destination
val requiredDestBytes = (totalSize * 1.05).toLong()
val destFreeBytes = pathResolver.getAvailableBytes(installDir)
if (destFreeBytes != null) {
Log.d(TAG, "Storage check: destination free=${destFreeBytes / 1024 / 1024}MB, required=${requiredDestBytes / 1024 / 1024}MB (1.05x)")
if (destFreeBytes < requiredDestBytes) {
val msg = "Not enough storage (${destFreeBytes / 1024 / 1024}MB free, need ${requiredDestBytes / 1024 / 1024}MB)"
Log.w(TAG, msg)
notificationManager.show(title = "Cannot download $gameName", subtitle = msg, type = NotificationType.WARNING, key = "steam_storage_$appId")
val pausedState = SteamDownloadState.Paused(appId, gameName, 0f)
_downloadState.value = pausedState
_activeDownload.value = _activeDownload.value?.copy(state = pausedState)
steamDownloadQueueDao.updateState(appId, SteamDownloadDbState.PAUSED.name, msg)
processNextInQueue()
return@launch
}
} else {
Log.w(TAG, "Cannot check destination storage (path not stattable), proceeding")
}
val depotSizes = sizeResult.depotSizes
val expectedFileSizes = sizeResult.fileSizes
val baselineBytes = progressTracker.loadPersistedBytes(installDir.absolutePath)
// Track cumulative uncompressed bytes per depot (concurrent-safe).
// Total progress = baselineBytes + sum of all per-depot bytes.
val perDepotBytes = java.util.concurrent.ConcurrentHashMap<Int, Long>()
val bytesDownloaded = java.util.concurrent.atomic.AtomicLong(baselineBytes)
val completedDepots = java.util.concurrent.atomic.AtomicInteger(0)
Log.d(TAG, "Starting: $gameName (${depots.size} depots, ${totalSize / 1024 / 1024}MB, baseline=${baselineBytes / 1024 / 1024}MB)")
Log.v(TAG, "depotSizes map: ${depotSizes.entries.joinToString { "${it.key}=${it.value / 1024 / 1024}MB" }}")
val initialProgress = if (totalSize > 0) (baselineBytes.toFloat() / totalSize).coerceIn(0f, 1f) else 0f
// Stay in Preparing until DepotDownloader starts actual chunk downloads.
// The onStatusUpdate callback will transition through FetchingManifest/Validating.
// The progress poller will flip to Downloading once bytes start flowing.
val initialState = SteamDownloadState.Preparing(appId, gameName)
_downloadState.value = initialState
_activeDownload.value = SteamDownloadProgress(
appId, gameName, coverPath, initialProgress, totalSize, baselineBytes, initialState
)
// Load resume tracking data
val completedDepotIds = downloadTracker.getCompletedDepotIds(appId)
val completedFileNames = downloadTracker.getCompletedFileNames(appId)
if (completedDepotIds.isNotEmpty() || completedFileNames.isNotEmpty()) {
Log.d(TAG, "Resume tracking: ${completedDepotIds.size} depots complete, ${completedFileNames.size} files pre-validated")
}
Log.d(TAG, "Loading licenses...")
val licenses = steamLibraryManager.getLicenses()
if (licenses.isEmpty()) {
throw IllegalStateException("No Steam licenses available")
}
// Thread pool sizes based on CPU cores (balanced for mobile)
val cpuCores = Runtime.getRuntime().availableProcessors()
val maxDownloads = (cpuCores * 1.2).toInt().coerceAtLeast(2)
val maxDecompress = (cpuCores * 0.4).toInt().coerceAtLeast(2)
Log.v(TAG, "CPU cores=$cpuCores, maxDownloads=$maxDownloads, maxDecompress=$maxDecompress")
val depotDownloader = DepotDownloader(
client,
licenses,
debug = false,
androidEmulation = true,
maxDownloads = maxDownloads,
maxDecompress = maxDecompress,
parentJob = coroutineContext[Job]
)
activeDepotDownloader = depotDownloader
val depotIds = depots.map { it.depotId }.sorted()
val depotIdToIndex = depotIds.mapIndexed { index, id -> id to index }.toMap()
depotDownloader.addListener(object : IDownloadListener {
override fun onItemAdded(item: DownloadItem) {
Log.v(TAG, "DepotDownloader: item ${item.appId} added")
}
override fun onDownloadStarted(item: DownloadItem) {
Log.v(TAG, "DepotDownloader: item ${item.appId} started (baseline=${baselineBytes / 1024 / 1024}MB)")
}
override fun onDownloadCompleted(item: DownloadItem) {
Log.i(TAG, "DepotDownloader: item ${item.appId} completed")
}
override fun onDownloadFailed(item: DownloadItem, error: Throwable) {
Log.e(TAG, "DepotDownloader: item ${item.appId} failed", error)
_downloadState.value = SteamDownloadState.Failed(appId, gameName, error.message ?: "Download failed")
}
override fun onStatusUpdate(message: String) {
Log.v(TAG, "DepotDownloader status: $message")
// Only update _downloadState -- the progress poller is the single
// source of truth for _activeDownload to avoid racing values
when {
message.startsWith("Downloading manifest") -> {
val depotMatch = Regex("depot (\\d+)").find(message)
val depotId = depotMatch?.groupValues?.get(1)?.toIntOrNull() ?: 0
val state = SteamDownloadState.FetchingManifest(appId, gameName, depotId)
_downloadState.value = state
_activeDownload.value = _activeDownload.value?.copy(state = state)
}
message.startsWith("Validating") -> {
// Don't override Downloading state -- validation and download
// run concurrently during resume, causing UI flicker
if (_downloadState.value !is SteamDownloadState.Downloading) {
val detail = message.removePrefix("Validating: ").take(60)
val state = SteamDownloadState.Validating(appId, gameName, detail)
_downloadState.value = state
_activeDownload.value = _activeDownload.value?.copy(state = state)
}
}
message.startsWith("Finalizing") -> {
val state = SteamDownloadState.Validating(appId, gameName, "Finalizing...")
_downloadState.value = state
_activeDownload.value = _activeDownload.value?.copy(
state = state,
bytesPerSecond = 0L
)
}
}
}
override fun onFileCompleted(depotId: Int, fileName: String, pct: Float) {
Log.v(TAG, "DepotDownloader file completed: depot=$depotId, file=$fileName, pct=$pct")
val manifestId = depots.firstOrNull { it.depotId == depotId }?.manifestId ?: 0L
val installPrefix = installDir.absolutePath + "/"
val relativeName = if (fileName.startsWith(installPrefix)) {
fileName.removePrefix(installPrefix)
} else {
fileName
}
// Verify the on-disk file matches manifest size before recording.
// DepotDownloader's callback can fire before the OS has flushed the
// last writes; if we record then crash, resume would skip a partial
// file. Drop unverifiable events; DepotDownloader will re-emit on retry.
val expectedSize = expectedFileSizes[depotId to relativeName]
if (expectedSize != null) {
val onDiskFile = File(fileName)
val actual = onDiskFile.length()
if (!onDiskFile.exists() || actual != expectedSize) {
Log.w(TAG, "Skipping completion record: $relativeName depot=$depotId expected=$expectedSize on-disk=$actual exists=${onDiskFile.exists()}")
return
}
} else {
Log.v(TAG, "No manifest size indexed for depot=$depotId file=$relativeName; recording without size verification")
}
downloadTracker.onFileCompleted(appId, depotId, manifestId, relativeName)
}
override fun onChunkCompleted(
depotId: Int,
depotPercentComplete: Float,
compressedBytes: Long,
uncompressedBytes: Long
) {
// uncompressedBytes is cumulative within this depot.
// Store per-depot and sum all depots for total progress.
perDepotBytes[depotId] = uncompressedBytes
val currentBytes = baselineBytes + perDepotBytes.values.sum()
bytesDownloaded.set(currentBytes)
val pctInt = (depotPercentComplete * 100).toInt()
if (pctInt % 25 == 0 && pctInt > 0) {
Log.v(TAG, "Chunk: depot=$depotId, depotPct=$pctInt%, depotBytes=${uncompressedBytes / 1024 / 1024}MB, total=${currentBytes / 1024 / 1024}MB/${totalSize / 1024 / 1024}MB")
}
val now = System.currentTimeMillis()
progressTracker.addSpeedSample(now, currentBytes)
val progress = if (totalSize > 0) (currentBytes.toFloat() / totalSize).coerceIn(0f, 1f) else 0f
val speed = progressTracker.computeSpeed(now)
val prevState = _downloadState.value
val state = SteamDownloadState.Downloading(
appId, gameName, progress, completedDepots.get(), depots.size
)
_downloadState.value = state
_activeDownload.value = SteamDownloadProgress(
appId, gameName, coverPath, progress, totalSize, currentBytes, state, speed
)
if (prevState !is SteamDownloadState.Downloading) {
scope.launch(Dispatchers.IO) {
steamDownloadQueueDao.updateState(appId, SteamDownloadDbState.DOWNLOADING.name)
}
}
if (now - lastDbProgressUpdate > DB_PROGRESS_INTERVAL_MS) {
lastDbProgressUpdate = now
progressTracker.persistBytes(installDir.absolutePath, currentBytes)
scope.launch(Dispatchers.IO) {
steamDownloadQueueDao.updateProgress(appId, currentBytes, totalSize)
}
}
}
override fun onDepotCompleted(depotId: Int, compressedBytes: Long, uncompressedBytes: Long) {
val knownSize = depotSizes[depotId] ?: 0L
val currentTotal = bytesDownloaded.get()
Log.i(TAG, "Depot $depotId completed: " +
"depotBytes=${uncompressedBytes / 1024 / 1024}MB, " +
"manifestSize=${knownSize / 1024 / 1024}MB, " +
"totalProgress=${currentTotal / 1024 / 1024}MB, " +
"totalSize=${totalSize / 1024 / 1024}MB")