-
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathAirSyncViewModel.kt
More file actions
1200 lines (1047 loc) · 48.3 KB
/
AirSyncViewModel.kt
File metadata and controls
1200 lines (1047 loc) · 48.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.sameerasw.airsync.presentation.viewmodel
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.PowerManager
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sameerasw.airsync.data.local.DataStoreManager
import com.sameerasw.airsync.data.repository.AirSyncRepositoryImpl
import com.sameerasw.airsync.domain.model.ConnectedDevice
import com.sameerasw.airsync.domain.model.DeviceInfo
import com.sameerasw.airsync.domain.model.NetworkDeviceConnection
import com.sameerasw.airsync.domain.model.UiState
import com.sameerasw.airsync.domain.repository.AirSyncRepository
import com.sameerasw.airsync.smartspacer.AirSyncDeviceTarget
import com.sameerasw.airsync.utils.DeviceInfoUtil
import com.sameerasw.airsync.utils.DiscoveredDevice
import com.sameerasw.airsync.utils.MacDeviceStatusManager
import com.sameerasw.airsync.utils.NetworkMonitor
import com.sameerasw.airsync.utils.PermissionUtil
import com.sameerasw.airsync.utils.ServiceManager
import com.sameerasw.airsync.utils.ShortcutUtil
import com.sameerasw.airsync.utils.SyncManager
import com.sameerasw.airsync.utils.UDPDiscoveryManager
import com.sameerasw.airsync.utils.WebSocketUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
class AirSyncViewModel(
private val repository: AirSyncRepository
) : ViewModel() {
companion object {
private const val TAG = "AirSyncViewModel"
fun create(context: Context): AirSyncViewModel {
val dataStoreManager = DataStoreManager(context)
val repository = AirSyncRepositoryImpl(dataStoreManager)
return AirSyncViewModel(repository)
}
}
private val _uiState = MutableStateFlow(UiState())
val uiState: StateFlow<UiState> = _uiState.asStateFlow()
private val _deviceInfo = MutableStateFlow(DeviceInfo())
val deviceInfo: StateFlow<DeviceInfo> = _deviceInfo.asStateFlow()
// Network-aware device connections state
private val _networkDevices = MutableStateFlow<List<NetworkDeviceConnection>>(emptyList())
// Discovered devices from UDP
val discoveredDevices: StateFlow<List<DiscoveredDevice>> = UDPDiscoveryManager.discoveredDevices
// Notes Role state
private val _stylusMode = MutableStateFlow(false)
val stylusMode: StateFlow<Boolean> = _stylusMode.asStateFlow()
private val _launchedFromLockScreen = MutableStateFlow(true)
val launchedFromLockScreen: StateFlow<Boolean> = _launchedFromLockScreen.asStateFlow()
private val _isFloatingWindow = MutableStateFlow(true)
val isFloatingWindow: StateFlow<Boolean> = _isFloatingWindow.asStateFlow()
private val _isNotesRoleHeld = MutableStateFlow(false)
val isNotesRoleHeld: StateFlow<Boolean> = _isNotesRoleHeld.asStateFlow()
// Network monitoring
private var isNetworkMonitoringActive = false
private var previousNetworkIp: String? = null
private var appContext: Context? = null
private val powerSaveReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action == PowerManager.ACTION_POWER_SAVE_MODE_CHANGED) {
context?.let { updateBlurState(it) }
}
}
}
// Manual connect canceller reference (set in init) for unregistering
private val manualConnectCanceler: () -> Unit = {
// Cancel any active auto-reconnect when user starts manual connection
try {
WebSocketUtil.cancelAutoReconnect()
} catch (_: Exception) {
}
}
// Connection status listener for WebSocket updates
private val connectionStatusListener: (Boolean) -> Unit = { isWsConnected ->
viewModelScope.launch {
val isBleConnected =
_uiState.value.bleConnectionState == com.sameerasw.airsync.data.ble.BleGattServer.BleConnectionState.AUTHENTICATED
val isGlobalConnected = isWsConnected || isBleConnected
_uiState.value = _uiState.value.copy(
isConnected = isGlobalConnected,
isConnecting = false,
response = if (isGlobalConnected) "Connected successfully!" else "Disconnected",
activeIp = if (isWsConnected) WebSocketUtil.currentIpAddress else null,
macDeviceStatus = if (isGlobalConnected) _uiState.value.macDeviceStatus else null
)
if (isGlobalConnected) {
repository.setFirstMacConnectionTime(System.currentTimeMillis())
updateRatingPromptDisplay()
}
// Update dynamic shortcuts
appContext?.let { ctx ->
ShortcutUtil.refreshShortcuts(ctx, isGlobalConnected)
}
// Notify Smartspacer of connection status change
appContext?.let { context ->
try {
AirSyncDeviceTarget.notifyChange(context)
} catch (_: Exception) {
// Smartspacer might not be installed, ignore
}
}
}
}
init {
// Clear manual disconnect flag on app startup so auto-reconnect works
viewModelScope.launch {
try {
repository.setUserManuallyDisconnected(false)
} catch (_: Exception) {}
}
// Register for WebSocket connection status updates
WebSocketUtil.registerConnectionStatusListener(connectionStatusListener)
try {
WebSocketUtil.registerManualConnectListener(manualConnectCanceler)
} catch (_: Exception) {
}
// Observe Mac device status updates
viewModelScope.launch {
MacDeviceStatusManager.macDeviceStatus.collect { macStatus ->
_uiState.value = _uiState.value.copy(macDeviceStatus = macStatus)
}
}
// Observe manual disconnect flag to immediately cancel any running auto-reconnect
viewModelScope.launch {
repository.getUserManuallyDisconnected().collect { _ ->
// No device status notification to update
}
}
// Observe pitch black theme preference
viewModelScope.launch {
repository.getPitchBlackThemeEnabled().collect { enabled ->
_uiState.value = _uiState.value.copy(isPitchBlackThemeEnabled = enabled)
}
}
// Observe sentry reporting preference
viewModelScope.launch {
repository.getSentryReportingEnabled().collect { enabled ->
_uiState.value = _uiState.value.copy(isSentryReportingEnabled = enabled)
}
}
// Observe widget transparency preference
viewModelScope.launch {
repository.getWidgetTransparency().collect { trans ->
_uiState.value = _uiState.value.copy(widgetTransparency = trans)
}
}
// Observe first run preference for onboarding status
viewModelScope.launch {
repository.getFirstRun().collect { firstRun ->
_uiState.value = _uiState.value.copy(isOnboardingCompleted = !firstRun)
}
}
// Observe Quick Share preference
viewModelScope.launch {
repository.isQuickShareEnabled().collect { enabled ->
_uiState.value = _uiState.value.copy(isQuickShareEnabled = enabled)
}
}
// Observe File Access preference
viewModelScope.launch {
repository.isFileAccessEnabled().collect { enabled ->
_uiState.value = _uiState.value.copy(isFileAccessEnabled = enabled)
}
}
// Observe BLE connection status
viewModelScope.launch {
com.sameerasw.airsync.AirSyncApp.getBleConnectionManager()?.connectionState?.collect { state ->
Log.d("AirSyncViewModel", "BLE connection state changed: $state")
val isBleAuthenticated =
state == com.sameerasw.airsync.data.ble.BleGattServer.BleConnectionState.AUTHENTICATED
val isWsConnected = WebSocketUtil.isConnected()
_uiState.value = _uiState.value.copy(
bleConnectionState = state,
isConnected = isWsConnected || isBleAuthenticated
)
if (isBleAuthenticated && !isWsConnected) {
// Refresh shortcuts and other side effects if this is the only connection
appContext?.let { ctx ->
ShortcutUtil.refreshShortcuts(ctx, true)
}
updateRatingPromptDisplay()
}
}
}
}
override fun onCleared() {
super.onCleared()
// Unregister listeners
WebSocketUtil.unregisterConnectionStatusListener(connectionStatusListener)
try {
WebSocketUtil.unregisterManualConnectListener(manualConnectCanceler)
} catch (_: Exception) {
}
try {
appContext?.unregisterReceiver(powerSaveReceiver)
} catch (_: IllegalArgumentException) {
// Receiver was not registered
} catch (e: Exception) {
// Context may be invalid (Activity leaked)
Log.e(TAG, "Failed to unregister receiver: ${e.message}")
}
}
private fun startObservingDeviceChanges(context: Context) {
val dataStoreManager = DataStoreManager(context)
// Observe both last connected device and network devices for real-time updates
viewModelScope.launch {
dataStoreManager.getLastConnectedDevice()
.distinctUntilChanged()
.collect { device ->
Log.d(
"AirSyncViewModel",
"Last connected device changed: ${device?.name}, isPlus: ${device?.isPlus}"
)
updateDisplayedDevice(context)
}
}
viewModelScope.launch {
dataStoreManager.getAllNetworkDeviceConnections()
.distinctUntilChanged()
.collect { networkDevices ->
Log.d(
"AirSyncViewModel",
"Network devices changed: ${networkDevices.size} devices"
)
_networkDevices.value = networkDevices
updateDisplayedDevice(context)
}
}
}
private fun updateDisplayedDevice(context: Context) {
viewModelScope.launch {
// Get current network IP for network-aware device lookup
val currentIp = DeviceInfoUtil.getWifiIpAddress(context) ?: "Unknown"
_deviceInfo.value = _deviceInfo.value.copy(localIp = currentIp)
// Use network-aware device if available for current network, otherwise use the stored device
val networkAwareDevice = getNetworkAwareLastConnectedDevice()
val storedDevice = repository.getLastConnectedDevice().first()
val deviceToShow = networkAwareDevice ?: storedDevice
// Only update if changed
if (_uiState.value.lastConnectedDevice != deviceToShow) {
Log.d(
"AirSyncViewModel",
"Updating displayed device: ${deviceToShow?.name}, isPlus: ${deviceToShow?.isPlus}, model: ${deviceToShow?.model}"
)
_uiState.value = _uiState.value.copy(lastConnectedDevice = deviceToShow)
}
}
}
fun initializeState(
context: Context,
initialIp: String? = null,
initialPort: String? = null,
showConnectionDialog: Boolean = false,
pcName: String? = null,
isPlus: Boolean = false,
symmetricKey: String? = null
) {
appContext = context.applicationContext
viewModelScope.launch {
// Load saved values
val savedIp = initialIp ?: repository.getIpAddress().first()
val savedPort = initialPort ?: repository.getPort().first()
val savedDeviceName = repository.getDeviceName().first()
val lastConnected = repository.getLastConnectedDevice().first()
val isNotificationSyncEnabled = repository.getNotificationSyncEnabled().first()
val isDeveloperMode = repository.getDeveloperMode().first()
val isClipboardSyncEnabled = repository.getClipboardSyncEnabled().first()
val isAutoReconnectEnabled = repository.getAutoReconnectEnabled().first()
val lastConnectedSymmetricKey = lastConnected?.symmetricKey
val isContinueBrowsingEnabled = repository.getContinueBrowsingEnabled().first()
val isSendNowPlayingEnabled = repository.getSendNowPlayingEnabled().first()
val isKeepPreviousLinkEnabled = repository.getKeepPreviousLinkEnabled().first()
val isMacMediaControlsEnabled = repository.getMacMediaControlsEnabled().first()
val isClipboardHistoryEnabled = repository.getClipboardHistoryEnabled().first()
repository.getDefaultTab().first()
val isEssentialsConnectionEnabled = repository.getEssentialsConnectionEnabled().first()
val isDeviceDiscoveryEnabled = repository.getDeviceDiscoveryEnabled().first()
val isBlurEnabledSetting = repository.getUseBlurEnabled().first()
val isPitchBlackThemeEnabled = repository.getPitchBlackThemeEnabled().first()
val isSentryReportingEnabled = repository.getSentryReportingEnabled().first()
val isFirstRun = repository.getFirstRun().first()
val isPowerSaveMode = DeviceInfoUtil.isPowerSaveMode(context)
val isBlurProblematic = DeviceInfoUtil.isBlurProblematicDevice()
val isQuickShareEnabled = repository.isQuickShareEnabled().first()
// Replicate Essentials logic for initial state
val isBlurEnabled = isBlurEnabledSetting && !isPowerSaveMode && !isBlurProblematic
// Rating tracking
repository.getFirstMacConnectionTime().first()
repository.getLastPromptDismissedVersion().first()
repository.hasRatedApp().first()
// Get device info
val deviceName = savedDeviceName.ifEmpty {
val autoName = DeviceInfoUtil.getDeviceName(context)
repository.saveDeviceName(autoName)
autoName
}
val localIp = DeviceInfoUtil.getWifiIpAddress(context) ?: "Unknown"
_deviceInfo.value = DeviceInfo(name = deviceName, localIp = localIp)
// Load network-aware device connections
loadNetworkDevices()
// Check for network-aware device for current network
val networkAwareDevice = getNetworkAwareLastConnectedDevice()
val deviceToShow = networkAwareDevice ?: lastConnected
// Check permissions
val missingPermissions = PermissionUtil.getAllMissingPermissions(context)
val isNotificationEnabled = PermissionUtil.isNotificationListenerEnabled(context)
// Check current WebSocket connection status
val currentlyConnected = WebSocketUtil.isConnected()
_uiState.value = _uiState.value.copy(
ipAddress = savedIp,
port = savedPort,
deviceNameInput = deviceName,
// Only show dialog if not already connected and showConnectionDialog is true
isDialogVisible = showConnectionDialog && !currentlyConnected,
missingPermissions = missingPermissions,
isNotificationEnabled = isNotificationEnabled,
lastConnectedDevice = deviceToShow,
isNotificationSyncEnabled = isNotificationSyncEnabled,
isDeveloperMode = isDeveloperMode,
isClipboardSyncEnabled = isClipboardSyncEnabled,
isAutoReconnectEnabled = isAutoReconnectEnabled,
isConnected = currentlyConnected,
symmetricKey = symmetricKey ?: lastConnectedSymmetricKey,
isContinueBrowsingEnabled = isContinueBrowsingEnabled,
isSendNowPlayingEnabled = isSendNowPlayingEnabled,
isKeepPreviousLinkEnabled = isKeepPreviousLinkEnabled,
isMacMediaControlsEnabled = isMacMediaControlsEnabled,
isClipboardHistoryEnabled = isClipboardHistoryEnabled,
isEssentialsConnectionEnabled = isEssentialsConnectionEnabled,
isDeviceDiscoveryEnabled = isDeviceDiscoveryEnabled,
isBlurSettingEnabled = isBlurEnabledSetting,
isPowerSaveMode = isPowerSaveMode,
isPitchBlackThemeEnabled = isPitchBlackThemeEnabled,
isBlurEnabled = isBlurEnabled,
isSentryReportingEnabled = isSentryReportingEnabled,
isOnboardingCompleted = !isFirstRun,
isQuickShareEnabled = isQuickShareEnabled
)
updateRatingPromptDisplay()
// If we have PC name from QR code and not already connected, store it temporarily for the dialog
if (pcName != null && showConnectionDialog && !currentlyConnected) {
_uiState.value = _uiState.value.copy(
lastConnectedDevice = ConnectedDevice(
name = pcName,
ipAddress = savedIp,
port = savedPort,
lastConnected = System.currentTimeMillis(),
isPlus = isPlus,
symmetricKey = symmetricKey
)
)
}
// Start observing device changes for real-time updates
startObservingDeviceChanges(context)
// Register power save receiver
context.registerReceiver(
powerSaveReceiver,
IntentFilter(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)
)
// Start AirSync Service conditionally
ServiceManager.updateServiceState(context)
// Initial shortcut state
ShortcutUtil.refreshShortcuts(context, WebSocketUtil.isConnected())
isNetworkMonitoringActive = true
}
}
fun updateIpAddress(ipAddress: String) {
_uiState.value = _uiState.value.copy(ipAddress = ipAddress)
viewModelScope.launch {
repository.saveIpAddress(ipAddress)
}
}
fun updatePort(port: String) {
_uiState.value = _uiState.value.copy(port = port)
viewModelScope.launch {
repository.savePort(port)
}
}
fun updateSymmetricKey(symmetricKey: String?) {
_uiState.value = _uiState.value.copy(symmetricKey = symmetricKey)
}
fun updateManualPcName(name: String) {
_uiState.value = _uiState.value.copy(manualPcName = name)
}
fun updateManualIsPlus(isPlus: Boolean) {
_uiState.value = _uiState.value.copy(manualIsPlus = isPlus)
}
fun prepareForManualConnection() {
val manualDevice = ConnectedDevice(
name = _uiState.value.manualPcName.ifEmpty { "My Mac/PC" },
ipAddress = _uiState.value.ipAddress,
port = _uiState.value.port,
lastConnected = System.currentTimeMillis(),
isPlus = _uiState.value.manualIsPlus,
symmetricKey = _uiState.value.symmetricKey
)
_uiState.value = _uiState.value.copy(
lastConnectedDevice = manualDevice,
isDialogVisible = true
)
}
fun updateDeviceName(name: String) {
_uiState.value = _uiState.value.copy(deviceNameInput = name)
_deviceInfo.value = _deviceInfo.value.copy(name = name)
viewModelScope.launch {
repository.saveDeviceName(name)
}
val ctx = appContext
if (ctx != null) {
// Send updated device info immediately so desktop sees the new name
try {
SyncManager.sendDeviceInfoNow(ctx, name)
} catch (_: Exception) {
// ignore
}
}
}
fun setLoading(loading: Boolean) {
_uiState.value = _uiState.value.copy(isLoading = loading)
}
fun setResponse(response: String) {
_uiState.value = _uiState.value.copy(response = response)
}
fun setDialogVisible(visible: Boolean) {
_uiState.value = _uiState.value.copy(isDialogVisible = visible)
}
fun setPermissionDialogVisible(visible: Boolean) {
_uiState.value = _uiState.value.copy(showPermissionDialog = visible)
}
fun setConnectionStatus(isConnected: Boolean, isConnecting: Boolean = false) {
_uiState.value = _uiState.value.copy(
isConnected = isConnected,
isConnecting = isConnecting,
connectingDeviceId = if (!isConnecting) null else _uiState.value.connectingDeviceId
)
}
fun setConnectingDeviceId(id: String?) {
_uiState.value = _uiState.value.copy(connectingDeviceId = id)
}
fun refreshPermissions(context: Context) {
val missingPermissions = PermissionUtil.getAllMissingPermissions(context)
val isNotificationEnabled = PermissionUtil.isNotificationListenerEnabled(context)
_uiState.value = _uiState.value.copy(
missingPermissions = missingPermissions,
isNotificationEnabled = isNotificationEnabled
)
}
fun saveLastConnectedDevice(
pcName: String? = null,
isPlus: Boolean = false,
symmetricKey: String? = null
) {
viewModelScope.launch {
val deviceName = pcName ?: "My Mac"
val ourIp = _deviceInfo.value.localIp
val clientIp = _uiState.value.ipAddress
val port = _uiState.value.port
// Save using network-aware storage
repository.saveNetworkDeviceConnection(
deviceName,
ourIp,
clientIp,
port,
isPlus,
symmetricKey
)
// Also save to legacy storage for backwards compatibility
val connectedDevice = ConnectedDevice(
name = deviceName,
ipAddress = clientIp,
port = port,
lastConnected = System.currentTimeMillis(),
isPlus = isPlus,
symmetricKey = symmetricKey
)
repository.saveLastConnectedDevice(connectedDevice)
_uiState.value = _uiState.value.copy(lastConnectedDevice = connectedDevice)
// Refresh network devices list
loadNetworkDevices()
// Notify Smartspacer of device update
appContext?.let { context ->
try {
AirSyncDeviceTarget.notifyChange(context)
} catch (_: Exception) {
// Smartspacer might not be installed, ignore
}
}
}
}
private suspend fun loadNetworkDevices() {
repository.getAllNetworkDeviceConnections().first().let { devices ->
_networkDevices.value = devices
}
}
fun getNetworkAwareLastConnectedDevice(): ConnectedDevice? {
val ourIp = _deviceInfo.value.localIp
if (ourIp.isEmpty() || ourIp == "Unknown") return null
// Find the most recent device that has a connection for our current network
val networkDevice = _networkDevices.value
.filter { it.getClientIpForNetwork(ourIp) != null }
.maxByOrNull { it.lastConnected }
return networkDevice?.toConnectedDevice(ourIp)
}
fun setNotificationSyncEnabled(enabled: Boolean) {
_uiState.value = _uiState.value.copy(isNotificationSyncEnabled = enabled)
viewModelScope.launch {
repository.setNotificationSyncEnabled(enabled)
}
}
fun setDeveloperMode(enabled: Boolean) {
_uiState.value = _uiState.value.copy(isDeveloperMode = enabled)
viewModelScope.launch {
repository.setDeveloperMode(enabled)
}
}
fun toggleDeveloperModeVisibility() {
_uiState.value = _uiState.value.copy(
isDeveloperModeVisible = !_uiState.value.isDeveloperModeVisible
)
}
fun setClipboardSyncEnabled(enabled: Boolean) {
_uiState.value = _uiState.value.copy(isClipboardSyncEnabled = enabled)
viewModelScope.launch {
repository.setClipboardSyncEnabled(enabled)
}
}
fun setClipboardHistoryEnabled(enabled: Boolean) {
_uiState.value = _uiState.value.copy(isClipboardHistoryEnabled = enabled)
viewModelScope.launch {
repository.setClipboardHistoryEnabled(enabled)
if (!enabled) {
clearClipboardHistory()
}
}
}
fun setAutoReconnectEnabled(enabled: Boolean) {
_uiState.value = _uiState.value.copy(isAutoReconnectEnabled = enabled)
viewModelScope.launch {
repository.setAutoReconnectEnabled(enabled)
appContext?.let { ServiceManager.updateServiceState(it) }
}
}
fun setUseBlurEnabled(enabled: Boolean, context: Context) {
viewModelScope.launch {
repository.setUseBlurEnabled(enabled)
updateBlurState(context)
}
}
private fun updateBlurState(context: Context) {
viewModelScope.launch {
val isBlurEnabledSetting = repository.getUseBlurEnabled().first()
val isPowerSaveMode = DeviceInfoUtil.isPowerSaveMode(context)
val isBlurProblematic = DeviceInfoUtil.isBlurProblematicDevice()
// 1:1 Logic from Essentials: turned off if power saving is on or device is problematic
val isBlurEnabled = isBlurEnabledSetting && !isPowerSaveMode && !isBlurProblematic
_uiState.value = _uiState.value.copy(
isBlurSettingEnabled = isBlurEnabledSetting,
isPowerSaveMode = isPowerSaveMode,
isBlurEnabled = isBlurEnabled
)
}
}
fun setSentryReportingEnabled(enabled: Boolean) {
_uiState.value = _uiState.value.copy(isSentryReportingEnabled = enabled)
viewModelScope.launch {
repository.setSentryReportingEnabled(enabled)
// Note: Changes typically take effect on next launch as Sentry is initialized in Application.onCreate
}
}
fun setPitchBlackThemeEnabled(enabled: Boolean) {
_uiState.value = _uiState.value.copy(isPitchBlackThemeEnabled = enabled)
viewModelScope.launch {
repository.setPitchBlackThemeEnabled(enabled)
// Note: Currently theme changes check via MainActivity collection instead of restart
}
}
fun setWidgetTransparency(alpha: Float) {
_uiState.value = _uiState.value.copy(widgetTransparency = alpha)
viewModelScope.launch {
repository.setWidgetTransparency(alpha)
appContext?.let { context ->
com.sameerasw.airsync.widget.AirSyncWidgetProvider.updateAllWidgets(context)
}
}
}
fun setDeviceDiscoveryEnabled(context: Context, enabled: Boolean) {
_uiState.value = _uiState.value.copy(isDeviceDiscoveryEnabled = enabled)
viewModelScope.launch {
repository.setDeviceDiscoveryEnabled(enabled)
ServiceManager.updateServiceState(context)
}
}
fun setQuickShareEnabled(context: Context, enabled: Boolean) {
_uiState.value = _uiState.value.copy(isQuickShareEnabled = enabled)
viewModelScope.launch {
repository.setQuickShareEnabled(enabled)
val intent =
Intent(context, com.sameerasw.airsync.quickshare.QuickShareService::class.java)
if (enabled) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
context.startForegroundService(intent)
} else {
context.startService(intent)
}
} else {
context.stopService(intent)
}
}
}
fun setFileAccessEnabled(context: Context, enabled: Boolean) {
_uiState.value = _uiState.value.copy(isFileAccessEnabled = enabled)
viewModelScope.launch {
repository.setFileAccessEnabled(enabled)
ServiceManager.updateServiceState(context)
}
}
fun manualSyncAppIcons(context: Context) {
_uiState.value = _uiState.value.copy(isIconSyncLoading = true, iconSyncMessage = "")
SyncManager.manualSyncAppIcons(context) { _, message ->
viewModelScope.launch {
_uiState.value = _uiState.value.copy(
isIconSyncLoading = false,
iconSyncMessage = message
)
}
}
}
fun clearIconSyncMessage() {
_uiState.value = _uiState.value.copy(iconSyncMessage = "")
}
// Auth failure dialog controls
fun showAuthFailure(message: String) {
_uiState.value =
_uiState.value.copy(showAuthFailureDialog = true, authFailureMessage = message)
}
fun dismissAuthFailure() {
_uiState.value = _uiState.value.copy(showAuthFailureDialog = false, authFailureMessage = "")
}
fun setUserManuallyDisconnected(disconnected: Boolean) {
viewModelScope.launch {
repository.setUserManuallyDisconnected(disconnected)
}
}
// Awaitable variant used when ordering matters (e.g., ensure flag is persisted before disconnect)
suspend fun setUserManuallyDisconnectedAwait(disconnected: Boolean) {
repository.setUserManuallyDisconnected(disconnected)
}
private fun hasNetworkAwareMappingForLastDevice(): ConnectedDevice? {
val ourIp = _deviceInfo.value.localIp
val last = _uiState.value.lastConnectedDevice ?: return null
if (ourIp.isEmpty() || ourIp == "Unknown" || ourIp == "No Wi-Fi") return null
// Find matching device by name with mapping for our IP
val networkDevice = _networkDevices.value.firstOrNull {
it.deviceName == last.name && it.getClientIpForNetwork(ourIp) != null
}
return networkDevice?.toConnectedDevice(ourIp)
}
private suspend fun loadNetworkDevicesForNetworkChange() {
// thin wrapper in case logic needs splitting
loadNetworkDevices()
}
// Start monitoring network changes (Wi-Fi IP) to update mappings and trigger auto-reconnect attempts
fun startNetworkMonitoring(context: Context) {
if (isNetworkMonitoringActive) return
isNetworkMonitoringActive = true
previousNetworkIp = DeviceInfoUtil.getWifiIpAddress(context) ?: DeviceInfoUtil.getLocalIpAddress() ?: "Unknown"
viewModelScope.launch {
try {
NetworkMonitor.observeNetworkChanges(context).collect { networkInfo ->
val currentIp = networkInfo.ipAddress ?: "No Wi-Fi"
if (currentIp != previousNetworkIp) {
previousNetworkIp = currentIp
// Update local device info immediately
_deviceInfo.value = _deviceInfo.value.copy(localIp = currentIp)
// Always refresh network-aware device mappings on network change
loadNetworkDevicesForNetworkChange()
// Cancel any ongoing auto-reconnect loop; we'll restart with the new network context if needed
try {
WebSocketUtil.cancelAutoReconnect()
} catch (_: Exception) {
}
val manual = repository.getUserManuallyDisconnected().first()
val autoOn = repository.getAutoReconnectEnabled().first()
// Determine if we have a mapping for the last connected device on this network
val target = hasNetworkAwareMappingForLastDevice()
if (currentIp == "No Wi-Fi" || currentIp == "Unknown") {
// No usable Wi‑Fi: ensure we stop any active connection and do not attempt reconnect
try {
WebSocketUtil.disconnect(context, isManual = false)
} catch (_: Exception) {
}
// Stop service if needed
ServiceManager.updateServiceState(context)
_uiState.value =
_uiState.value.copy(
isConnected = com.sameerasw.airsync.data.ble.BleGattServer.isAnyAuthenticated(),
isConnecting = false
)
return@collect
} else {
// Ensure service state is updated
ServiceManager.updateServiceState(context)
}
if (target != null) {
// We have a specific device mapping for this network. Switch immediately.
// Update UI fields so the user sees the correct endpoint.
updateIpAddress(target.ipAddress)
updatePort(target.port)
updateSymmetricKey(target.symmetricKey)
// If connected/connecting to old network, disconnect first to force a clean switch
if (WebSocketUtil.isConnected() || WebSocketUtil.isConnecting()) {
try {
WebSocketUtil.disconnect(context, isManual = false)
} catch (_: Exception) {
}
}
// Auto-connect if auto-reconnect is enabled and the user hasn't manually disconnected.
if (autoOn && !manual) {
// Mark as connecting in UI and kick off a non-manual connection (so it won't flip manual flags)
_uiState.value = _uiState.value.copy(isConnecting = true)
try {
WebSocketUtil.connect(
context = context,
ipAddress = target.ipAddress,
port = target.port.toIntOrNull() ?: 6996,
symmetricKey = target.symmetricKey,
manualAttempt = false,
onConnectionStatus = { connected ->
viewModelScope.launch {
_uiState.value = _uiState.value.copy(
isConnected = connected,
isConnecting = false,
response = if (connected) "Connected successfully!" else "Reconnection failed"
)
if (connected) {
// Update last connected record timestamp for this device
try {
// Persist as the last connected device and refresh network-aware mapping timestamps
saveLastConnectedDevice(
pcName = target.name,
isPlus = target.isPlus,
symmetricKey = target.symmetricKey
)
} catch (_: Exception) {
}
} else if (autoOn && !manual) {
// If the immediate connect failed, restart the auto-reconnect loop for this network
try {
WebSocketUtil.requestAutoReconnect(context)
} catch (_: Exception) {
}
}
}
}
)
} catch (_: Exception) {
// Fall back to auto-reconnect loop
try {
WebSocketUtil.requestAutoReconnect(context)
} catch (_: Exception) {
}
}
} else {
// User has disabled auto connect, just update the displayed device/IP
_uiState.value = _uiState.value.copy(isConnecting = false)
}
} else {
// No mapping for this network: disconnect if connected and, if allowed, start generic auto-reconnect
if (WebSocketUtil.isConnected() || WebSocketUtil.isConnecting()) {
try {
WebSocketUtil.disconnect(context, isManual = false)
} catch (_: Exception) {
}
}
if (autoOn && !manual) {
try {
WebSocketUtil.requestAutoReconnect(context)
} catch (_: Exception) {
}
}
}
}
}
} catch (_: Exception) {
// ignore
}
}
}
fun setContinueBrowsingEnabled(enabled: Boolean) {
_uiState.value = _uiState.value.copy(isContinueBrowsingEnabled = enabled)
viewModelScope.launch {
repository.setContinueBrowsingEnabled(enabled)
}
}
fun setSendNowPlayingEnabled(enabled: Boolean) {
_uiState.value = _uiState.value.copy(isSendNowPlayingEnabled = enabled)
viewModelScope.launch {
repository.setSendNowPlayingEnabled(enabled)
appContext?.let { ctx ->
// Update media listener immediate behavior and sync status
com.sameerasw.airsync.service.MediaNotificationListener.setNowPlayingEnabled(
ctx,
enabled
)
}
}
}
fun setKeepPreviousLinkEnabled(enabled: Boolean) {
_uiState.value = _uiState.value.copy(isKeepPreviousLinkEnabled = enabled)
viewModelScope.launch {
repository.setKeepPreviousLinkEnabled(enabled)
}
}
fun setSmartspacerShowWhenDisconnected(enabled: Boolean) {
_uiState.value = _uiState.value.copy(isSmartspacerShowWhenDisconnected = enabled)
viewModelScope.launch {
repository.setSmartspacerShowWhenDisconnected(enabled)
}
// Notify Smartspacer to update immediately
appContext?.let { context ->
try {
AirSyncDeviceTarget.notifyChange(context)
} catch (_: Exception) {
}
}
}
fun setMacMediaControlsEnabled(enabled: Boolean) {
_uiState.value = _uiState.value.copy(isMacMediaControlsEnabled = enabled)
viewModelScope.launch {
repository.setMacMediaControlsEnabled(enabled)
// If disabled, stop the service immediately
if (!enabled) {
appContext?.let { ctx ->
com.sameerasw.airsync.service.MacMediaPlayerService.stopMacMedia(ctx)
}
}
}
}
// Expose DataStore export/import helpers
suspend fun exportAllDataToJson(context: Context): String? {
return try {
val manager = DataStoreManager(context)
manager.exportAllDataToJson()
} catch (e: Exception) {
e.printStackTrace()
null
}
}
suspend fun importDataFromJson(context: Context, json: String): Boolean {
return try {
val manager = DataStoreManager(context)
manager.importAllDataFromJson(json)
} catch (e: Exception) {
e.printStackTrace()
false
}
}
// Clipboard history management
fun addClipboardEntry(text: String, isFromPc: Boolean) {
if (!_uiState.value.isClipboardHistoryEnabled) return
val entry = com.sameerasw.airsync.domain.model.ClipboardEntry(
id = java.util.UUID.randomUUID().toString(),
text = text,
timestamp = System.currentTimeMillis(),