-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathMainActivity.kt
More file actions
673 lines (624 loc) · 29.2 KB
/
MainActivity.kt
File metadata and controls
673 lines (624 loc) · 29.2 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
package com.greybox.projectmesh
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.content.Intent
import android.content.SharedPreferences
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.PowerManager
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.greybox.projectmesh.debug.CrashHandler
import com.greybox.projectmesh.debug.CrashScreenActivity
import com.greybox.projectmesh.navigation.BottomNavItem
import com.greybox.projectmesh.navigation.BottomNavigationBar
import com.greybox.projectmesh.server.AppServer
import com.greybox.projectmesh.ui.theme.AppTheme
import com.greybox.projectmesh.ui.theme.ProjectMeshTheme
import com.greybox.projectmesh.viewModel.SharedUriViewModel
import com.greybox.projectmesh.messaging.ui.screens.ChatScreen
import com.greybox.projectmesh.views.HomeScreen
import com.greybox.projectmesh.views.SettingsScreen
import com.greybox.projectmesh.views.NetworkScreen
import com.greybox.projectmesh.views.PingScreen
import com.greybox.projectmesh.views.ReceiveScreen
import com.greybox.projectmesh.views.SelectDestNodeScreen
import com.greybox.projectmesh.views.SendScreen
import com.greybox.projectmesh.views.OnboardingScreen
import com.greybox.projectmesh.testing.TestDeviceService
import org.kodein.di.DI
import org.kodein.di.DIAware
import org.kodein.di.android.closestDI
import org.kodein.di.compose.withDI
import org.kodein.di.instance
import java.io.File
import java.util.Locale
import java.net.InetAddress
import com.greybox.projectmesh.messaging.ui.screens.ChatNodeListScreen
import com.greybox.projectmesh.messaging.ui.screens.ConversationsHomeScreen
import com.greybox.projectmesh.user.UserRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.remember
import kotlinx.coroutines.launch
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.platform.LocalSavedStateRegistryOwner
import androidx.lifecycle.lifecycleScope
import com.greybox.projectmesh.logging.ReleaseTree
import kotlinx.coroutines.launch
import com.greybox.projectmesh.messaging.data.entities.Conversation
import com.greybox.projectmesh.messaging.ui.viewmodels.ChatScreenViewModel
import com.greybox.projectmesh.views.LogScreen
import com.greybox.projectmesh.views.RequestPermissionsScreen
import org.kodein.di.android.BuildConfig
import org.kodein.di.compose.localDI
import timber.log.Timber
class MainActivity : ComponentActivity(), DIAware {
override val di by closestDI()
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.Theme_ProjectMesh)
super.onCreate(savedInstanceState)
// Init Timber for Debug Build
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
} else {
Timber.plant(ReleaseTree())
}
Timber.d("Timber init in ${BuildConfig.BUILD_TYPE}")
// crash screen
CrashHandler.init(applicationContext, CrashScreenActivity::class.java)
val settingPref: SharedPreferences by di.instance(tag = "settings")
val appServer: AppServer by di.instance()
// Run this task asynchronously (default directory creation)
lifecycleScope.launch(Dispatchers.IO) {
ensureDefaultDirectory()
}
//Initialize test device:
TestDeviceService.initialize()
Timber.tag("MainActivity").d("Test device initialized")
setContent {
val meshPrefs = getSharedPreferences("project_mesh_prefs", MODE_PRIVATE)
var hasRunBefore by rememberSaveable {
mutableStateOf(meshPrefs.getBoolean("hasRunBefore", false))
}
// Check if the app was launched from a notification
val launchedFromNotification = intent?.getBooleanExtra("from_notification", false) ?: false
// Request all permission in order
RequestPermissionsScreen(skipPermissions = launchedFromNotification)
var appTheme by remember {
mutableStateOf(AppTheme.valueOf(
settingPref.getString("app_theme", AppTheme.SYSTEM.name) ?:
AppTheme.SYSTEM.name))
}
var languageCode by remember {
mutableStateOf(settingPref.getString(
"language", "en") ?: "en")
}
var restartServerKey by remember {mutableStateOf(0)}
var deviceName by remember {
mutableStateOf(settingPref.getString("device_name", Build.MODEL) ?: Build.MODEL)
}
var autoFinish by remember {
mutableStateOf(settingPref.getBoolean("auto_finish", false))
}
var saveToFolder by remember {
mutableStateOf(
settingPref.getString("save_to_folder", null)
?: "${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)}/Project Mesh"
)
}
// State to trigger recomposition when locale changes
var localeState by rememberSaveable { mutableStateOf(Locale.getDefault()) }
// Remember the current screen across recompositions
var currentScreen by rememberSaveable { mutableStateOf(BottomNavItem.Home.route) }
LaunchedEffect(intent?.getStringExtra("navigateTo")) {
if (intent?.getStringExtra("navigateTo") == BottomNavItem.Receive.route) {
currentScreen = BottomNavItem.Receive.route
}
}
//check for special navigation intents
val action = intent.action
if (action == "OPEN_CHAT_SCREEN") {
val ip = intent.getStringExtra("ip")
if (ip != null) {
try {
// Try to create InetAddress to validate it first
InetAddress.getByName(ip)
// If that succeeds, navigate to chat screen with this IP
val route = "chatScreen/$ip"
currentScreen = route
} catch (e: Exception) {
Timber.tag("MainActivity").e(e, "Invalid IP address in intent: %s", ip)
// Fall back to home screen
currentScreen = BottomNavItem.Home.route
}
}
} else if (action == "OPEN_CHAT_CONVERSATION") {
val conversationId = intent.getStringExtra("conversationId")
if (conversationId != null) {
// Navigate to chat screen with this conversation ID
val route = "chatScreen/$conversationId"
currentScreen = route
}
}
LaunchedEffect(restartServerKey) {
if (restartServerKey > 0){
appServer.restart()
Toast.makeText(this@MainActivity, "Server restart complete", Toast.LENGTH_SHORT).show()
}
}
// Observe language changes and apply locale
LaunchedEffect(languageCode) {
localeState = updateLocale(languageCode)
}
key(localeState) {
ProjectMeshTheme(appTheme = appTheme) {
if (!hasRunBefore) {
OnboardingScreen(
onComplete = {meshPrefs.edit().putBoolean("hasRunBefore", true).apply()
hasRunBefore = true }
)
}
else{
BottomNavApp(
di,
startDestination = currentScreen,
onThemeChange = { selectedTheme -> appTheme = selectedTheme},
onLanguageChange = { selectedLanguage -> languageCode = selectedLanguage},
onNavigateToScreen = {screen ->
currentScreen = screen },
onRestartServer = {restartServerKey++},
onDeviceNameChange = {deviceName = it},
deviceName = deviceName,
onAutoFinishChange = {autoFinish = it},
onSaveToFolderChange = {saveToFolder = it}
)
}
}
}
}
Timber.tag("BuildCheck").d("Build Type is: ${BuildConfig.BUILD_TYPE}")
}
private fun ensureDefaultDirectory() {
val defaultDirectory = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"Project Mesh"
)
if (!defaultDirectory.exists()) {
// Create the directory if it doesn't exist
if (defaultDirectory.mkdirs()) {
Timber.tag("DirectoryCheck").d("Default directory created: ${defaultDirectory
.absolutePath}")
}
else {
Timber.tag("DirectoryCheck").e("Failed to create default directory: %s", defaultDirectory.absolutePath)
}
}
else {
Timber.tag("DirectoryCheck").d("Default directory already exists: ${defaultDirectory
.absolutePath}")
}
}
private fun updateLocale(languageCode: String): Locale {
val locale = Locale(languageCode)
val config = resources.configuration
config.setLocale(locale)
@Suppress("DEPRECATION")
resources.updateConfiguration(config, resources.displayMetrics)
return locale
}
}
@Composable
fun BottomNavApp(di: DI,
startDestination: String,
onThemeChange: (AppTheme) -> Unit,
onLanguageChange: (String) -> Unit,
onNavigateToScreen: (String) -> Unit,
onRestartServer: () -> Unit,
onDeviceNameChange: (String) -> Unit,
deviceName: String,
onAutoFinishChange: (Boolean) -> Unit,
onSaveToFolderChange: (String) -> Unit
) = withDI(di)
{
val appServer: AppServer by di.instance()
val navController = rememberNavController()
// Observe the current route directly through the back stack entry
val currentRoute = navController.currentBackStackEntryFlow.collectAsState(initial = null)
LaunchedEffect(currentRoute.value?.destination?.route) {
if(currentRoute.value?.destination?.route == BottomNavItem.Settings.route){
currentRoute.value?.destination?.route?.let { route ->
onNavigateToScreen(route)
}
}
}
Scaffold(
bottomBar = { BottomNavigationBar(navController) }
){ innerPadding ->
NavHost(navController, startDestination = startDestination, Modifier.padding(innerPadding))
{
composable(BottomNavItem.Home.route) { HomeScreen(deviceName = deviceName) }
composable(BottomNavItem.Network.route) {
// Just call NetworkScreen with no click callback
NetworkScreen(
onNodeClick = {ip -> navController.navigate("pingScreen/$ip")}
)
}
composable("chatScreen/{ip}"){ entry ->
val ip = entry.arguments?.getString("ip")
?: throw IllegalArgumentException("Invalid address")
Timber.tag("Navigation").d("Navigating to chatScreen with parameter: $ip")
//determine if this is an ip address
val isValidIpAddress = ip.matches(Regex("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\$"))
Timber.tag("Navigation").d("Is valid IP address: $isValidIpAddress")
if(isValidIpAddress) {
Timber.tag("Navigation").d("Showing chat for IP address: $ip")
// This is a valid IP address, use normal chat screen
ChatScreen(
virtualAddress = InetAddress.getByName(ip),
onClickButton = {
navController.navigate("pingScreen/${ip}")
}
)
} else {
Timber.tag("Navigation").d("Showing chat for conversation ID: $ip")
//conversation id: handle offline chat
ConversationChatScreen(
conversationId = ip,
onBackClick = {
Timber.tag("Navigation").d("Navigating back from conversation")
navController.popBackStack()
}
)
}
}
composable("pingScreen/{ip}"){ entry ->
val ip = entry.arguments?.getString("ip")
?: throw IllegalArgumentException("Invalid address")
PingScreen(
virtualAddress = InetAddress.getByName(ip)
)
}
composable(BottomNavItem.Send.route) {
val activity = LocalContext.current as ComponentActivity
val sharedUrisViewModel: SharedUriViewModel = viewModel(activity)
SendScreen(
onSwitchToSelectDestNode = { uris ->
Timber.tag("uri_track_nav_send").d("size: %s", uris.size.toString())
Timber.tag("uri_track_nav_send").d("List: $uris")
sharedUrisViewModel.setUris(uris)
navController.navigate("selectDestNode")
}
)
}
composable("selectDestNode"){
val activity = LocalContext.current as ComponentActivity
val sharedUrisViewModel: SharedUriViewModel = viewModel(activity)
val sendUris by sharedUrisViewModel.uris.collectAsState()
Timber.tag("uri_track_nav_selectDestNode").d("size: %s", sendUris.size.toString())
Timber.tag("uri_track_nav_selectDestNode").d("List: $sendUris")
SelectDestNodeScreen(
uris = sendUris,
popBackWhenDone = {navController.popBackStack()},
)
}
composable(BottomNavItem.Receive.route) { ReceiveScreen(
onAutoFinishChange = onAutoFinishChange
) }
composable(BottomNavItem.Log.route) {
LogScreen()
}
composable(BottomNavItem.Settings.route) {
// Retrieve required instances from DI with explicit types
val settingsPrefs: SharedPreferences by di.instance<SharedPreferences>(tag = "settings")
val userRepository: UserRepository by di.instance<UserRepository>()
SettingsScreen(
onThemeChange = onThemeChange,
onLanguageChange = onLanguageChange,
onRestartServer = onRestartServer,
onDeviceNameChange = { newDeviceName ->
Timber.tag("BottomNavApp").d("Device name changed to: $newDeviceName")
// Retrieve the local UUID from SharedPreferences
val localUuid = settingsPrefs.getString("UUID", null)
if (localUuid != null) {
// Update the local user info and broadcast in an IO coroutine
CoroutineScope(Dispatchers.IO).launch {
// 1. Update the local user in the database
userRepository.insertOrUpdateUser(
uuid = localUuid,
name = newDeviceName,
address = appServer.localVirtualAddr.hostAddress // <-- local IP here
)
Timber.tag("BottomNavApp").d("Updated local user with new name:$newDeviceName")
// 2. Retrieve all connected users (those with a non-null address)
val connectedUsers = userRepository.getAllConnectedUsers()
connectedUsers.forEach { user ->
user.address?.let { ip ->
try {
val remoteAddr = InetAddress.getByName(ip)
Timber.tag("BottomNavApp").d("Broadcasting updated info to: $ip")
appServer.pushUserInfoTo(remoteAddr)
} catch (e: Exception) {
Timber.tag("BottomNavApp").e(e, "Error processing IP " +
"address:$ip")
}
}
}
}
} else {
Timber.tag("BottomNavApp").e("Local UUID not found; cannot update user")
}
},
onAutoFinishChange = onAutoFinishChange,
onSaveToFolderChange = onSaveToFolderChange,
)
}
//I'm guessing I can put my Chat button here?
composable(BottomNavItem.Chat.route) {
//latest status of DeviceStatus manager
val deviceStatusRefreshTrigger = DeviceStatusManager.deviceStatusMap.collectAsState().value
// Show a list of nodes, let the user pick one
ConversationsHomeScreen(
onConversationSelected = { userIdentifier ->
// userIdentifier will be either an IP address (for online users)
// or a conversation ID (for offline users)
Timber.tag("Navigation").d("Selected conversation/user: $userIdentifier")
//navigate to the chat screen with this identifier
navController.navigate("chatScreen/${userIdentifier}")
}
)
/*
ChatNodeListScreen(
onNodeSelected = { ip ->
val remoteAddr = InetAddress.getByName(ip)
Timber.tag("ChatHandshake").d("Node selected with IP: $ip, remoteAddr:
$remoteAddr")
// Request remote user info
Timber.tag("ChatHandshake").d("Requesting remote user info from:
${remoteAddr
.hostAddress}")
appServer.requestRemoteUserInfo(remoteAddr)
// Push local user info to remote node
Timber.tag("ChatHandshake").d("Pushing local user info to: ${remoteAddr
.hostAddress}")
appServer.pushUserInfoTo(remoteAddr)
// Navigate to the chat screen
navController.navigate("chatScreen/$ip")
}
)
*/
}
//handle ip address chat screen properly
composable("chatScreen/{ip}"){ entry ->
val ipParam = entry.arguments?.getString("ip")
if (ipParam == null) {
// Handle missing parameter
Text("Error: Missing address parameter")
} else {
// Check if this is an IP address or conversation ID
val isValidIpAddress = ipParam.matches(Regex("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\$"))
val validatedAddress = remember(ipParam) {
if (isValidIpAddress) {
try {
InetAddress.getByName(ipParam)
} catch (e: Exception) {
Timber.tag("Navigation").e(e, "Error creating address from parameter:$ipParam")
null
}
} else {
null
}
}
if (isValidIpAddress && validatedAddress != null) {
// It's a valid IP address
ChatScreen(
virtualAddress = validatedAddress,
onClickButton = {
navController.navigate("pingScreen/${ipParam}")
}
)
} else {
// Handle as conversation ID
ConversationChatScreen(
conversationId = ipParam,
onBackClick = {
navController.popBackStack()
}
)
}
}
}
}
}
}
@Composable
fun ConversationChatScreen (
conversationId: String,
onBackClick: () -> Unit
){
Timber.tag("ConversationChatScreen").d("Starting to load conversation: $conversationId")
var conversationState = remember { mutableStateOf<Conversation?>(null) }
var isLoading = remember { mutableStateOf(true) }
var errorMessage = remember { mutableStateOf<String?>(null) }
//val conversation = conversationState.value
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
// Load the conversation data
LaunchedEffect(conversationId) {
Timber.tag("ConversationChatScreen").d("LaunchedEffect triggered for ID: $conversationId")
coroutineScope.launch {
try {
Timber.tag("ConversationChatScreen").d("Attempting to fetch conversation")
val result = GlobalApp.GlobalUserRepo.conversationRepository.getConversationById(conversationId)
Timber.tag("ConversationChatScreen").d("Fetch result: ${result != null}")
//conversationState.value = result
if (result == null) {
errorMessage.value = "Conversation not found"
isLoading.value = false
/*
Timber.tag("ConversationChatScreen").e("Conversation not found:
$conversationId")
Toast.makeText(
context,
"Conversation not found",
Toast.LENGTH_SHORT
).show()
onBackClick()
*/
}else {
conversationState.value = result
isLoading.value = false
Timber.tag("ConversationChatScreen").d("Loaded conversation: ${result.userName}, online=${result.isOnline}")
}
} catch (e: Exception) {
Timber.tag("ConversationChatScreen").e(e, "Error loading conversation")
errorMessage.value = e.message
isLoading.value = false
/*
Toast.makeText(
context,
"Error loading conversation: ${e.message}",
Toast.LENGTH_SHORT
).show()
onBackClick()
*/
}
}
}
// Show loading state while fetching conversation
if (isLoading.value) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
CircularProgressIndicator()
}
return
}
//show error if loading failed
if (errorMessage.value != null) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text("Error: ${errorMessage.value}")
Button(onClick = onBackClick) {
Text("Go Back")
}
}
}
return
}
//get the conversation from state
val conversation = conversationState.value
if (conversation == null) {
Toast.makeText(context, "Conversation not found", Toast.LENGTH_SHORT).show()
onBackClick()
return
}
val shouldCheckDeviceStatus = remember {
// Only check for devices with real IP addresses, not placeholder or offline devices
conversation.userAddress != null &&
conversation.userAddress != "0.0.0.0" &&
conversation.userAddress != TestDeviceService.TEST_DEVICE_IP_OFFLINE
}
// Initialize isUserOnline based on conversation state first
var isUserOnline by remember { mutableStateOf(conversation.isOnline) }
// If we should check device status, observe DeviceStatusManager
if (shouldCheckDeviceStatus) {
val deviceStatusMap by DeviceStatusManager.deviceStatusMap.collectAsState()
// Update isUserOnline based on DeviceStatusManager
LaunchedEffect(deviceStatusMap) {
conversation.userAddress?.let { ipAddress ->
val statusFromManager = deviceStatusMap[ipAddress] ?: false
if (isUserOnline != statusFromManager) {
Timber.tag("ConversationChatScreen").d("Device status changed for ${conversation
.userName}: ${if (statusFromManager) "online" else "offline"}")
isUserOnline = statusFromManager
}
}
}
}
// Create a virtual address based on the conversation data
val virtualAddress = if (conversation?.userAddress.isNullOrEmpty()) {
//use offline test device address if this is the offline test conversation
if (conversation.userName == TestDeviceService.TEST_DEVICE_NAME_OFFLINE) {
Timber.tag("ConversationChatScreen").d("Using offline test device address")
InetAddress.getByName(TestDeviceService.TEST_DEVICE_IP_OFFLINE)
} else {
//use a placeholder address for regular offline users
Timber.tag("ConversationChatScreen").d("Using placeholder address for offline user")
InetAddress.getByName("0.0.0.0")
}
} else {
//use the actual address if available
Timber.tag("ConversationChatScreen").d("Using actual address: ${conversation.userAddress}")
InetAddress.getByName(conversation.userAddress)
}
Timber.tag("ConversationChatScreen").d("Showing chat screen for: ${conversation.userName}")
// Show the chat screen
ChatScreen(
virtualAddress = virtualAddress,
userName = conversation.userName,
isOffline = !conversation.isOnline,
onClickButton = {
// Disable ping for offline users
Toast.makeText(
context,
"Cannot ping offline users",
Toast.LENGTH_SHORT
).show()
},
viewModel = viewModel(
factory = ViewModelFactory(
di = localDI(),
owner = LocalSavedStateRegistryOwner.current,
vmFactory = { di, savedStateHandle ->
// Make sure to set the conversation ID in the savedStateHandle
savedStateHandle["conversationId"] = conversationId
ChatScreenViewModel(di, savedStateHandle)
},
defaultArgs = Bundle().apply {
putSerializable("virtualAddress", virtualAddress)
putString("conversationId", conversationId)
}
)
)
)
}