mirror of
https://github.com/permissionlesstech/bitchat-android.git
synced 2026-07-25 01:05:20 +00:00
Background persistence (#505)
* persistence step 1 * fix build * messages in the background work, notifications not yet * app state store * DM icon shows up * notification launches when app is closed! * keep ui updated * lifecycle fixes * extensive logging, maybe revert later * send nickname in announcement * quit in notification * setting in about sheet * fix quit bitchat * lifecycle fixes * power mode based on background state * stats for both direciotns * fix graph persistence * better counting * count per device * only compute when debug sheet is open? untested * fix read receipts * fix read receipts fully * fix unread badge if messages have been read in focus * foreground promotion fix * fix app kill in notification * adjust to new tor * nice * about sheet design
This commit is contained in:
@@ -19,6 +19,13 @@
|
|||||||
|
|
||||||
<!-- Notification permissions -->
|
<!-- Notification permissions -->
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
<!-- Foreground service and boot permissions for long-running background mesh -->
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
|
<!-- Connected device foreground service type for BLE operations (API 34+) -->
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
|
||||||
|
<!-- Data sync foreground service type (required when declaring dataSync) -->
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||||
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||||
|
|
||||||
<!-- Microphone for voice notes -->
|
<!-- Microphone for voice notes -->
|
||||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||||
@@ -77,5 +84,34 @@
|
|||||||
<category android:name="android.intent.category.LAUNCHER" />
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
|
|
||||||
|
<!-- Persistent foreground service to run the mesh in background -->
|
||||||
|
<service
|
||||||
|
android:name=".service.MeshForegroundService"
|
||||||
|
android:exported="false"
|
||||||
|
android:foregroundServiceType="connectedDevice|dataSync"
|
||||||
|
tools:ignore="DataExtractionRules">
|
||||||
|
</service>
|
||||||
|
|
||||||
|
<!-- Listen for in-app broadcast when POST_NOTIFICATIONS is granted -->
|
||||||
|
<receiver
|
||||||
|
android:name=".service.NotificationPermissionChangedReceiver"
|
||||||
|
android:enabled="true"
|
||||||
|
android:exported="false">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="com.bitchat.android.action.NOTIFICATION_PERMISSION_GRANTED" />
|
||||||
|
</intent-filter>
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<!-- Auto-start mesh service after boot if enabled -->
|
||||||
|
<receiver
|
||||||
|
android:name=".service.BootCompletedReceiver"
|
||||||
|
android:enabled="true"
|
||||||
|
android:exported="false">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||||
|
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
|
||||||
|
</intent-filter>
|
||||||
|
</receiver>
|
||||||
</application>
|
</application>
|
||||||
</manifest>
|
</manifest>
|
||||||
|
|||||||
@@ -41,6 +41,12 @@ class BitchatApplication : Application() {
|
|||||||
// Initialize debug preference manager (persists debug toggles)
|
// Initialize debug preference manager (persists debug toggles)
|
||||||
try { com.bitchat.android.ui.debug.DebugPreferenceManager.init(this) } catch (_: Exception) { }
|
try { com.bitchat.android.ui.debug.DebugPreferenceManager.init(this) } catch (_: Exception) { }
|
||||||
|
|
||||||
|
// Initialize mesh service preferences
|
||||||
|
try { com.bitchat.android.service.MeshServicePreferences.init(this) } catch (_: Exception) { }
|
||||||
|
|
||||||
|
// Proactively start the foreground service to keep mesh alive
|
||||||
|
try { com.bitchat.android.service.MeshForegroundService.start(this) } catch (_: Exception) { }
|
||||||
|
|
||||||
// TorManager already initialized above
|
// TorManager already initialized above
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ class MainActivity : OrientationAwareActivity() {
|
|||||||
private lateinit var locationStatusManager: LocationStatusManager
|
private lateinit var locationStatusManager: LocationStatusManager
|
||||||
private lateinit var batteryOptimizationManager: BatteryOptimizationManager
|
private lateinit var batteryOptimizationManager: BatteryOptimizationManager
|
||||||
|
|
||||||
// Core mesh service - managed at app level
|
// Core mesh service - provided by the foreground service holder
|
||||||
private lateinit var meshService: BluetoothMeshService
|
private lateinit var meshService: BluetoothMeshService
|
||||||
private val mainViewModel: MainViewModel by viewModels()
|
private val mainViewModel: MainViewModel by viewModels()
|
||||||
private val chatViewModel: ChatViewModel by viewModels {
|
private val chatViewModel: ChatViewModel by viewModels {
|
||||||
@@ -66,13 +66,21 @@ class MainActivity : OrientationAwareActivity() {
|
|||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
|
|
||||||
|
// Check if this is a quit request from the notification
|
||||||
|
if (intent.getBooleanExtra("ACTION_QUIT_APP", false)) {
|
||||||
|
android.util.Log.d("MainActivity", "Quit request received in onCreate, finishing activity")
|
||||||
|
finish()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// Enable edge-to-edge display for modern Android look
|
// Enable edge-to-edge display for modern Android look
|
||||||
enableEdgeToEdge()
|
enableEdgeToEdge()
|
||||||
|
|
||||||
// Initialize permission management
|
// Initialize permission management
|
||||||
permissionManager = PermissionManager(this)
|
permissionManager = PermissionManager(this)
|
||||||
// Initialize core mesh service first
|
// Ensure foreground service is running and get mesh instance from holder
|
||||||
meshService = BluetoothMeshService(this)
|
try { com.bitchat.android.service.MeshForegroundService.start(applicationContext) } catch (_: Exception) { }
|
||||||
|
meshService = com.bitchat.android.service.MeshServiceHolder.getOrCreate(applicationContext)
|
||||||
bluetoothStatusManager = BluetoothStatusManager(
|
bluetoothStatusManager = BluetoothStatusManager(
|
||||||
activity = this,
|
activity = this,
|
||||||
context = this,
|
context = this,
|
||||||
@@ -630,6 +638,15 @@ class MainActivity : OrientationAwareActivity() {
|
|||||||
|
|
||||||
override fun onNewIntent(intent: Intent) {
|
override fun onNewIntent(intent: Intent) {
|
||||||
super.onNewIntent(intent)
|
super.onNewIntent(intent)
|
||||||
|
setIntent(intent)
|
||||||
|
|
||||||
|
// Check if this is a quit request from the notification
|
||||||
|
if (intent.getBooleanExtra("ACTION_QUIT_APP", false)) {
|
||||||
|
android.util.Log.d("MainActivity", "Quit request received, finishing activity")
|
||||||
|
finish()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// Handle notification intents when app is already running
|
// Handle notification intents when app is already running
|
||||||
if (mainViewModel.onboardingState.value == OnboardingState.COMPLETE) {
|
if (mainViewModel.onboardingState.value == OnboardingState.COMPLETE) {
|
||||||
handleNotificationIntent(intent)
|
handleNotificationIntent(intent)
|
||||||
@@ -640,6 +657,8 @@ class MainActivity : OrientationAwareActivity() {
|
|||||||
super.onResume()
|
super.onResume()
|
||||||
// Check Bluetooth and Location status on resume and handle accordingly
|
// Check Bluetooth and Location status on resume and handle accordingly
|
||||||
if (mainViewModel.onboardingState.value == OnboardingState.COMPLETE) {
|
if (mainViewModel.onboardingState.value == OnboardingState.COMPLETE) {
|
||||||
|
// Reattach mesh delegate to new ChatViewModel instance after Activity recreation
|
||||||
|
try { meshService.delegate = chatViewModel } catch (_: Exception) { }
|
||||||
// Set app foreground state
|
// Set app foreground state
|
||||||
meshService.connectionManager.setAppBackgroundState(false)
|
meshService.connectionManager.setAppBackgroundState(false)
|
||||||
chatViewModel.setAppBackgroundState(false)
|
chatViewModel.setAppBackgroundState(false)
|
||||||
@@ -665,13 +684,15 @@ class MainActivity : OrientationAwareActivity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onPause() {
|
override fun onPause() {
|
||||||
super.onPause()
|
super.onPause()
|
||||||
// Only set background state if app is fully initialized
|
// Only set background state if app is fully initialized
|
||||||
if (mainViewModel.onboardingState.value == OnboardingState.COMPLETE) {
|
if (mainViewModel.onboardingState.value == OnboardingState.COMPLETE) {
|
||||||
// Set app background state
|
// Set app background state
|
||||||
meshService.connectionManager.setAppBackgroundState(true)
|
meshService.connectionManager.setAppBackgroundState(true)
|
||||||
chatViewModel.setAppBackgroundState(true)
|
chatViewModel.setAppBackgroundState(true)
|
||||||
|
// Detach UI delegate so the foreground service can own DM notifications while UI is closed
|
||||||
|
try { meshService.delegate = null } catch (_: Exception) { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -746,14 +767,6 @@ class MainActivity : OrientationAwareActivity() {
|
|||||||
Log.w("MainActivity", "Error cleaning up location status manager: ${e.message}")
|
Log.w("MainActivity", "Error cleaning up location status manager: ${e.message}")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stop mesh services if app was fully initialized
|
// Do not stop mesh here; ForegroundService owns lifecycle for background reliability
|
||||||
if (mainViewModel.onboardingState.value == OnboardingState.COMPLETE) {
|
|
||||||
try {
|
|
||||||
meshService.stopServices()
|
|
||||||
Log.d("MainActivity", "Mesh services stopped successfully")
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w("MainActivity", "Error stopping mesh services in onDestroy: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -149,6 +149,7 @@ class BluetoothConnectionManager(
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
isActive = true
|
isActive = true
|
||||||
|
Log.d(TAG, "ConnectionManager activated (permissions and adapter OK)")
|
||||||
|
|
||||||
// set the adapter's name to our 8-character peerID for iOS privacy, TODO: Make this configurable
|
// set the adapter's name to our 8-character peerID for iOS privacy, TODO: Make this configurable
|
||||||
// try {
|
// try {
|
||||||
@@ -179,6 +180,7 @@ class BluetoothConnectionManager(
|
|||||||
this@BluetoothConnectionManager.isActive = false
|
this@BluetoothConnectionManager.isActive = false
|
||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
|
Log.d(TAG, "GATT Server started")
|
||||||
} else {
|
} else {
|
||||||
Log.i(TAG, "GATT Server disabled by debug settings; not starting")
|
Log.i(TAG, "GATT Server disabled by debug settings; not starting")
|
||||||
}
|
}
|
||||||
@@ -189,6 +191,7 @@ class BluetoothConnectionManager(
|
|||||||
this@BluetoothConnectionManager.isActive = false
|
this@BluetoothConnectionManager.isActive = false
|
||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
|
Log.d(TAG, "GATT Client started")
|
||||||
} else {
|
} else {
|
||||||
Log.i(TAG, "GATT Client disabled by debug settings; not starting")
|
Log.i(TAG, "GATT Client disabled by debug settings; not starting")
|
||||||
}
|
}
|
||||||
@@ -214,6 +217,7 @@ class BluetoothConnectionManager(
|
|||||||
isActive = false
|
isActive = false
|
||||||
|
|
||||||
connectionScope.launch {
|
connectionScope.launch {
|
||||||
|
Log.d(TAG, "Stopping client/server and power components...")
|
||||||
// Stop component managers
|
// Stop component managers
|
||||||
clientManager.stop()
|
clientManager.stop()
|
||||||
serverManager.stop()
|
serverManager.stop()
|
||||||
@@ -231,6 +235,18 @@ class BluetoothConnectionManager(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Indicates whether this instance can be safely reused for a future start.
|
||||||
|
* Returns false if its coroutine scope has been cancelled.
|
||||||
|
*/
|
||||||
|
fun isReusable(): Boolean {
|
||||||
|
val active = connectionScope.isActive
|
||||||
|
if (!active) {
|
||||||
|
Log.d(TAG, "BluetoothConnectionManager isReusable=false (scope cancelled)")
|
||||||
|
}
|
||||||
|
return active
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set app background state for power optimization
|
* Set app background state for power optimization
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -52,6 +52,12 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
internal val connectionManager = BluetoothConnectionManager(context, myPeerID, fragmentManager) // Made internal for access
|
internal val connectionManager = BluetoothConnectionManager(context, myPeerID, fragmentManager) // Made internal for access
|
||||||
private val packetProcessor = PacketProcessor(myPeerID)
|
private val packetProcessor = PacketProcessor(myPeerID)
|
||||||
private lateinit var gossipSyncManager: GossipSyncManager
|
private lateinit var gossipSyncManager: GossipSyncManager
|
||||||
|
// Service-level notification manager for background (no-UI) DMs
|
||||||
|
private val serviceNotificationManager = com.bitchat.android.ui.NotificationManager(
|
||||||
|
context.applicationContext,
|
||||||
|
androidx.core.app.NotificationManagerCompat.from(context.applicationContext),
|
||||||
|
com.bitchat.android.util.NotificationIntervalManager()
|
||||||
|
)
|
||||||
|
|
||||||
// Service state management
|
// Service state management
|
||||||
private var isActive = false
|
private var isActive = false
|
||||||
@@ -61,8 +67,11 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
|
|
||||||
// Coroutines
|
// Coroutines
|
||||||
private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||||
|
// Tracks whether this instance has been terminated via stopServices()
|
||||||
|
private var terminated = false
|
||||||
|
|
||||||
init {
|
init {
|
||||||
|
Log.i(TAG, "Initializing BluetoothMeshService for peer=$myPeerID")
|
||||||
setupDelegates()
|
setupDelegates()
|
||||||
messageHandler.packetProcessor = packetProcessor
|
messageHandler.packetProcessor = packetProcessor
|
||||||
//startPeriodicDebugLogging()
|
//startPeriodicDebugLogging()
|
||||||
@@ -98,6 +107,7 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
return signPacketBeforeBroadcast(packet)
|
return signPacketBeforeBroadcast(packet)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Log.d(TAG, "Delegates set up; GossipSyncManager initialized")
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -105,6 +115,7 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
*/
|
*/
|
||||||
private fun startPeriodicDebugLogging() {
|
private fun startPeriodicDebugLogging() {
|
||||||
serviceScope.launch {
|
serviceScope.launch {
|
||||||
|
Log.d(TAG, "Starting periodic debug logging loop")
|
||||||
while (isActive) {
|
while (isActive) {
|
||||||
try {
|
try {
|
||||||
delay(10000) // 10 seconds
|
delay(10000) // 10 seconds
|
||||||
@@ -116,6 +127,7 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
Log.e(TAG, "Error in periodic debug logging: ${e.message}")
|
Log.e(TAG, "Error in periodic debug logging: ${e.message}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Log.d(TAG, "Periodic debug logging loop ended (isActive=$isActive)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -124,6 +136,7 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
*/
|
*/
|
||||||
private fun sendPeriodicBroadcastAnnounce() {
|
private fun sendPeriodicBroadcastAnnounce() {
|
||||||
serviceScope.launch {
|
serviceScope.launch {
|
||||||
|
Log.d(TAG, "Starting periodic announce loop")
|
||||||
while (isActive) {
|
while (isActive) {
|
||||||
try {
|
try {
|
||||||
delay(30000) // 30 seconds
|
delay(30000) // 30 seconds
|
||||||
@@ -132,6 +145,7 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
Log.e(TAG, "Error in periodic broadcast announce: ${e.message}")
|
Log.e(TAG, "Error in periodic broadcast announce: ${e.message}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Log.d(TAG, "Periodic announce loop ended (isActive=$isActive)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,6 +153,7 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
* Setup delegate connections between components
|
* Setup delegate connections between components
|
||||||
*/
|
*/
|
||||||
private fun setupDelegates() {
|
private fun setupDelegates() {
|
||||||
|
Log.d(TAG, "Setting up component delegates")
|
||||||
// Provide nickname resolver to BLE broadcaster for detailed logs
|
// Provide nickname resolver to BLE broadcaster for detailed logs
|
||||||
try {
|
try {
|
||||||
connectionManager.setNicknameResolver { pid -> peerManager.getPeerNickname(pid) }
|
connectionManager.setNicknameResolver { pid -> peerManager.getPeerNickname(pid) }
|
||||||
@@ -146,6 +161,9 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
// PeerManager delegates to main mesh service delegate
|
// PeerManager delegates to main mesh service delegate
|
||||||
peerManager.delegate = object : PeerManagerDelegate {
|
peerManager.delegate = object : PeerManagerDelegate {
|
||||||
override fun onPeerListUpdated(peerIDs: List<String>) {
|
override fun onPeerListUpdated(peerIDs: List<String>) {
|
||||||
|
// Update process-wide state first
|
||||||
|
try { com.bitchat.android.services.AppStateStore.setPeers(peerIDs) } catch (_: Exception) { }
|
||||||
|
// Then notify UI delegate if attached
|
||||||
delegate?.didUpdatePeerList(peerIDs)
|
delegate?.didUpdatePeerList(peerIDs)
|
||||||
}
|
}
|
||||||
override fun onPeerRemoved(peerID: String) {
|
override fun onPeerRemoved(peerID: String) {
|
||||||
@@ -165,6 +183,7 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
override fun onKeyExchangeCompleted(peerID: String, peerPublicKeyData: ByteArray) {
|
override fun onKeyExchangeCompleted(peerID: String, peerPublicKeyData: ByteArray) {
|
||||||
// Send announcement and cached messages after key exchange
|
// Send announcement and cached messages after key exchange
|
||||||
serviceScope.launch {
|
serviceScope.launch {
|
||||||
|
Log.d(TAG, "Key exchange completed with $peerID; sending follow-ups")
|
||||||
delay(100)
|
delay(100)
|
||||||
sendAnnouncementToPeer(peerID)
|
sendAnnouncementToPeer(peerID)
|
||||||
|
|
||||||
@@ -352,7 +371,36 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
|
|
||||||
// Callbacks
|
// Callbacks
|
||||||
override fun onMessageReceived(message: BitchatMessage) {
|
override fun onMessageReceived(message: BitchatMessage) {
|
||||||
|
// Always reflect into process-wide store so UI can hydrate after recreation
|
||||||
|
try {
|
||||||
|
when {
|
||||||
|
message.isPrivate -> {
|
||||||
|
val peer = message.senderPeerID ?: ""
|
||||||
|
if (peer.isNotEmpty()) com.bitchat.android.services.AppStateStore.addPrivateMessage(peer, message)
|
||||||
|
}
|
||||||
|
message.channel != null -> {
|
||||||
|
com.bitchat.android.services.AppStateStore.addChannelMessage(message.channel!!, message)
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
com.bitchat.android.services.AppStateStore.addPublicMessage(message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_: Exception) { }
|
||||||
|
// And forward to UI delegate if attached
|
||||||
delegate?.didReceiveMessage(message)
|
delegate?.didReceiveMessage(message)
|
||||||
|
|
||||||
|
// If no UI delegate attached (app closed), show DM notification via service manager
|
||||||
|
if (delegate == null && message.isPrivate) {
|
||||||
|
try {
|
||||||
|
val senderPeerID = message.senderPeerID
|
||||||
|
if (senderPeerID != null) {
|
||||||
|
val nick = try { peerManager.getPeerNickname(senderPeerID) } catch (_: Exception) { null } ?: senderPeerID
|
||||||
|
val preview = com.bitchat.android.ui.NotificationTextUtils.buildPrivateMessagePreview(message)
|
||||||
|
serviceNotificationManager.setAppBackgroundState(true)
|
||||||
|
serviceNotificationManager.showPrivateMessageNotification(senderPeerID, nick, preview)
|
||||||
|
}
|
||||||
|
} catch (_: Exception) { }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onChannelLeave(channel: String, fromPeer: String) {
|
override fun onChannelLeave(channel: String, fromPeer: String) {
|
||||||
@@ -477,12 +525,23 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
// BluetoothConnectionManager delegates
|
// BluetoothConnectionManager delegates
|
||||||
connectionManager.delegate = object : BluetoothConnectionManagerDelegate {
|
connectionManager.delegate = object : BluetoothConnectionManagerDelegate {
|
||||||
override fun onPacketReceived(packet: BitchatPacket, peerID: String, device: android.bluetooth.BluetoothDevice?) {
|
override fun onPacketReceived(packet: BitchatPacket, peerID: String, device: android.bluetooth.BluetoothDevice?) {
|
||||||
|
// Log incoming for debug graphs (do not double-count anywhere else)
|
||||||
|
try {
|
||||||
|
val nick = getPeerNicknames()[peerID]
|
||||||
|
com.bitchat.android.ui.debug.DebugSettingsManager.getInstance().logIncoming(
|
||||||
|
packetType = packet.type.toString(),
|
||||||
|
fromPeerID = peerID,
|
||||||
|
fromNickname = nick,
|
||||||
|
fromDeviceAddress = device?.address
|
||||||
|
)
|
||||||
|
} catch (_: Exception) { }
|
||||||
packetProcessor.processPacket(RoutedPacket(packet, peerID, device?.address))
|
packetProcessor.processPacket(RoutedPacket(packet, peerID, device?.address))
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onDeviceConnected(device: android.bluetooth.BluetoothDevice) {
|
override fun onDeviceConnected(device: android.bluetooth.BluetoothDevice) {
|
||||||
// Send initial announcements after services are ready
|
// Send initial announcements after services are ready
|
||||||
serviceScope.launch {
|
serviceScope.launch {
|
||||||
|
Log.d(TAG, "Device connected: ${device.address}; scheduling announce")
|
||||||
delay(200)
|
delay(200)
|
||||||
sendBroadcastAnnounce()
|
sendBroadcastAnnounce()
|
||||||
}
|
}
|
||||||
@@ -497,6 +556,7 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onDeviceDisconnected(device: android.bluetooth.BluetoothDevice) {
|
override fun onDeviceDisconnected(device: android.bluetooth.BluetoothDevice) {
|
||||||
|
Log.d(TAG, "Device disconnected: ${device.address}")
|
||||||
val addr = device.address
|
val addr = device.address
|
||||||
// Remove mapping and, if that was the last direct path for the peer, clear direct flag
|
// Remove mapping and, if that was the last direct path for the peer, clear direct flag
|
||||||
val peer = connectionManager.addressPeerMap[addr]
|
val peer = connectionManager.addressPeerMap[addr]
|
||||||
@@ -535,6 +595,11 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
Log.w(TAG, "Mesh service already active, ignoring duplicate start request")
|
Log.w(TAG, "Mesh service already active, ignoring duplicate start request")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if (terminated) {
|
||||||
|
// This instance's scope was cancelled previously; refuse to start to avoid using dead scopes.
|
||||||
|
Log.e(TAG, "Mesh service instance was terminated; create a new instance instead of restarting")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
Log.i(TAG, "Starting Bluetooth mesh service with peer ID: $myPeerID")
|
Log.i(TAG, "Starting Bluetooth mesh service with peer ID: $myPeerID")
|
||||||
|
|
||||||
@@ -546,6 +611,7 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
Log.d(TAG, "Started periodic broadcast announcements (every 30 seconds)")
|
Log.d(TAG, "Started periodic broadcast announcements (every 30 seconds)")
|
||||||
// Start periodic syncs
|
// Start periodic syncs
|
||||||
gossipSyncManager.start()
|
gossipSyncManager.start()
|
||||||
|
Log.d(TAG, "GossipSyncManager started")
|
||||||
} else {
|
} else {
|
||||||
Log.e(TAG, "Failed to start Bluetooth services")
|
Log.e(TAG, "Failed to start Bluetooth services")
|
||||||
}
|
}
|
||||||
@@ -567,11 +633,14 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
sendLeaveAnnouncement()
|
sendLeaveAnnouncement()
|
||||||
|
|
||||||
serviceScope.launch {
|
serviceScope.launch {
|
||||||
|
Log.d(TAG, "Stopping subcomponents and cancelling scope...")
|
||||||
delay(200) // Give leave message time to send
|
delay(200) // Give leave message time to send
|
||||||
|
|
||||||
// Stop all components
|
// Stop all components
|
||||||
gossipSyncManager.stop()
|
gossipSyncManager.stop()
|
||||||
|
Log.d(TAG, "GossipSyncManager stopped")
|
||||||
connectionManager.stopServices()
|
connectionManager.stopServices()
|
||||||
|
Log.d(TAG, "BluetoothConnectionManager stop requested")
|
||||||
peerManager.shutdown()
|
peerManager.shutdown()
|
||||||
fragmentManager.shutdown()
|
fragmentManager.shutdown()
|
||||||
securityManager.shutdown()
|
securityManager.shutdown()
|
||||||
@@ -579,10 +648,25 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
messageHandler.shutdown()
|
messageHandler.shutdown()
|
||||||
packetProcessor.shutdown()
|
packetProcessor.shutdown()
|
||||||
|
|
||||||
|
// Mark this instance as terminated and cancel its scope so it won't be reused
|
||||||
|
terminated = true
|
||||||
serviceScope.cancel()
|
serviceScope.cancel()
|
||||||
|
Log.i(TAG, "BluetoothMeshService terminated and scope cancelled")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this instance can be safely reused. Returns false after stopServices() or if
|
||||||
|
* any critical internal scope has been cancelled.
|
||||||
|
*/
|
||||||
|
fun isReusable(): Boolean {
|
||||||
|
val reusable = !terminated && serviceScope.isActive && connectionManager.isReusable()
|
||||||
|
if (!reusable) {
|
||||||
|
Log.d(TAG, "isReusable=false (terminated=$terminated, scopeActive=${serviceScope.isActive}, connReusable=${connectionManager.isReusable()})")
|
||||||
|
}
|
||||||
|
return reusable
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Send public message
|
* Send public message
|
||||||
*/
|
*/
|
||||||
@@ -814,6 +898,13 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// Avoid duplicate read receipts: check persistent store first
|
||||||
|
val seenStore = try { com.bitchat.android.services.SeenMessageStore.getInstance(context.applicationContext) } catch (_: Exception) { null }
|
||||||
|
if (seenStore?.hasRead(messageID) == true) {
|
||||||
|
Log.d(TAG, "Skipping read receipt for $messageID - already marked read")
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
|
||||||
// Create read receipt payload using NoisePayloadType exactly like iOS
|
// Create read receipt payload using NoisePayloadType exactly like iOS
|
||||||
val readReceiptPayload = com.bitchat.android.model.NoisePayload(
|
val readReceiptPayload = com.bitchat.android.model.NoisePayload(
|
||||||
type = com.bitchat.android.model.NoisePayloadType.READ_RECEIPT,
|
type = com.bitchat.android.model.NoisePayloadType.READ_RECEIPT,
|
||||||
@@ -840,6 +931,9 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
connectionManager.broadcastPacket(RoutedPacket(signedPacket))
|
connectionManager.broadcastPacket(RoutedPacket(signedPacket))
|
||||||
Log.d(TAG, "📤 Sent read receipt to $recipientPeerID for message $messageID")
|
Log.d(TAG, "📤 Sent read receipt to $recipientPeerID for message $messageID")
|
||||||
|
|
||||||
|
// Persist as read after successful send
|
||||||
|
try { seenStore?.markRead(messageID) } catch (_: Exception) { }
|
||||||
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "Failed to send read receipt to $recipientPeerID: ${e.message}")
|
Log.e(TAG, "Failed to send read receipt to $recipientPeerID: ${e.message}")
|
||||||
}
|
}
|
||||||
@@ -852,7 +946,7 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
fun sendBroadcastAnnounce() {
|
fun sendBroadcastAnnounce() {
|
||||||
Log.d(TAG, "Sending broadcast announce")
|
Log.d(TAG, "Sending broadcast announce")
|
||||||
serviceScope.launch {
|
serviceScope.launch {
|
||||||
val nickname = delegate?.getNickname() ?: myPeerID
|
val nickname = try { com.bitchat.android.services.NicknameProvider.getNickname(context, myPeerID) } catch (_: Exception) { myPeerID }
|
||||||
|
|
||||||
// Get the static public key for the announcement
|
// Get the static public key for the announcement
|
||||||
val staticKey = encryptionService.getStaticPublicKey()
|
val staticKey = encryptionService.getStaticPublicKey()
|
||||||
@@ -901,7 +995,7 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
fun sendAnnouncementToPeer(peerID: String) {
|
fun sendAnnouncementToPeer(peerID: String) {
|
||||||
if (peerManager.hasAnnouncedToPeer(peerID)) return
|
if (peerManager.hasAnnouncedToPeer(peerID)) return
|
||||||
|
|
||||||
val nickname = delegate?.getNickname() ?: myPeerID
|
val nickname = try { com.bitchat.android.services.NicknameProvider.getNickname(context, myPeerID) } catch (_: Exception) { myPeerID }
|
||||||
|
|
||||||
// Get the static public key for the announcement
|
// Get the static public key for the announcement
|
||||||
val staticKey = encryptionService.getStaticPublicKey()
|
val staticKey = encryptionService.getStaticPublicKey()
|
||||||
@@ -1000,6 +1094,13 @@ class BluetoothMeshService(private val context: Context) {
|
|||||||
return peerManager.getFingerprintForPeer(peerID)
|
return peerManager.getFingerprintForPeer(peerID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get current active peer count (for status/notifications)
|
||||||
|
*/
|
||||||
|
fun getActivePeerCount(): Int {
|
||||||
|
return try { peerManager.getActivePeerCount() } catch (_: Exception) { 0 }
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get peer info for verification purposes
|
* Get peer info for verification purposes
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -73,9 +73,17 @@ class BluetoothPacketBroadcaster(
|
|||||||
try {
|
try {
|
||||||
val fromNick = incomingPeer?.let { nicknameResolver?.invoke(it) }
|
val fromNick = incomingPeer?.let { nicknameResolver?.invoke(it) }
|
||||||
val toNick = toPeer?.let { nicknameResolver?.invoke(it) }
|
val toNick = toPeer?.let { nicknameResolver?.invoke(it) }
|
||||||
val isRelay = (incomingAddr != null || incomingPeer != null)
|
val manager = com.bitchat.android.ui.debug.DebugSettingsManager.getInstance()
|
||||||
|
// Always log outgoing for the actual transmission target
|
||||||
com.bitchat.android.ui.debug.DebugSettingsManager.getInstance().logPacketRelayDetailed(
|
manager.logOutgoing(
|
||||||
|
packetType = typeName,
|
||||||
|
toPeerID = toPeer,
|
||||||
|
toNickname = toNick,
|
||||||
|
toDeviceAddress = toDeviceAddress,
|
||||||
|
previousHopPeerID = incomingPeer
|
||||||
|
)
|
||||||
|
// Keep the verbose relay message for human readability
|
||||||
|
manager.logPacketRelayDetailed(
|
||||||
packetType = typeName,
|
packetType = typeName,
|
||||||
senderPeerID = senderPeerID,
|
senderPeerID = senderPeerID,
|
||||||
senderNickname = senderNick,
|
senderNickname = senderNick,
|
||||||
@@ -86,7 +94,7 @@ class BluetoothPacketBroadcaster(
|
|||||||
toNickname = toNick,
|
toNickname = toNick,
|
||||||
toDeviceAddress = toDeviceAddress,
|
toDeviceAddress = toDeviceAddress,
|
||||||
ttl = ttl,
|
ttl = ttl,
|
||||||
isRelay = isRelay
|
isRelay = true
|
||||||
)
|
)
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
// Silently ignore debug logging failures
|
// Silently ignore debug logging failures
|
||||||
|
|||||||
@@ -224,26 +224,29 @@ class PowerManager(private val context: Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun updatePowerMode() {
|
private fun updatePowerMode() {
|
||||||
val newMode = when {
|
// Determine the base mode from battery/charging state only
|
||||||
// Always use performance mode when charging (unless in background too long)
|
val baseMode = when {
|
||||||
|
// Charging in foreground may use performance
|
||||||
isCharging && !isAppInBackground -> PowerMode.PERFORMANCE
|
isCharging && !isAppInBackground -> PowerMode.PERFORMANCE
|
||||||
|
|
||||||
// Critical battery - use ultra low power
|
// Critical battery - force ultra low power regardless of foreground/background
|
||||||
batteryLevel <= CRITICAL_BATTERY -> PowerMode.ULTRA_LOW_POWER
|
batteryLevel <= CRITICAL_BATTERY -> PowerMode.ULTRA_LOW_POWER
|
||||||
|
|
||||||
// Low battery - use power saver
|
// Low battery - prefer power saver
|
||||||
batteryLevel <= LOW_BATTERY -> PowerMode.POWER_SAVER
|
batteryLevel <= LOW_BATTERY -> PowerMode.POWER_SAVER
|
||||||
|
|
||||||
// Background app with medium battery - use power saver
|
// Otherwise balanced
|
||||||
isAppInBackground && batteryLevel <= MEDIUM_BATTERY -> PowerMode.POWER_SAVER
|
|
||||||
|
|
||||||
// Background app with good battery - use balanced
|
|
||||||
isAppInBackground -> PowerMode.BALANCED
|
|
||||||
|
|
||||||
// Foreground with good battery - use balanced
|
|
||||||
else -> PowerMode.BALANCED
|
else -> PowerMode.BALANCED
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// If app is in background (including when running as a foreground service),
|
||||||
|
// cap the power mode to at least POWER_SAVER. Preserve ULTRA_LOW_POWER.
|
||||||
|
val newMode = if (isAppInBackground) {
|
||||||
|
if (baseMode == PowerMode.ULTRA_LOW_POWER) PowerMode.ULTRA_LOW_POWER else PowerMode.POWER_SAVER
|
||||||
|
} else {
|
||||||
|
baseMode
|
||||||
|
}
|
||||||
|
|
||||||
if (newMode != currentMode) {
|
if (newMode != currentMode) {
|
||||||
val oldMode = currentMode
|
val oldMode = currentMode
|
||||||
currentMode = newMode
|
currentMode = newMode
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package com.bitchat.android.service
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import android.os.Process
|
||||||
|
import androidx.core.app.NotificationManagerCompat
|
||||||
|
import com.bitchat.android.mesh.BluetoothMeshService
|
||||||
|
import com.bitchat.android.net.ArtiTorManager
|
||||||
|
import com.bitchat.android.net.TorMode
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.async
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withTimeoutOrNull
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Coordinates a full application shutdown:
|
||||||
|
* - Stop mesh cleanly
|
||||||
|
* - Stop Tor without changing persistent setting
|
||||||
|
* - Clear in-memory AppState
|
||||||
|
* - Stop foreground service/notification
|
||||||
|
* - Kill the process after completion or after a 5s timeout
|
||||||
|
*/
|
||||||
|
object AppShutdownCoordinator {
|
||||||
|
private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
|
||||||
|
|
||||||
|
fun requestFullShutdownAndKill(
|
||||||
|
app: Application,
|
||||||
|
mesh: BluetoothMeshService?,
|
||||||
|
notificationManager: NotificationManagerCompat,
|
||||||
|
stopForeground: () -> Unit,
|
||||||
|
stopService: () -> Unit
|
||||||
|
) {
|
||||||
|
scope.launch {
|
||||||
|
// Stop mesh (best-effort)
|
||||||
|
try { mesh?.stopServices() } catch (_: Exception) { }
|
||||||
|
|
||||||
|
// Stop Tor temporarily (do not change user setting)
|
||||||
|
val torProvider = ArtiTorManager.getInstance()
|
||||||
|
val torStop = async {
|
||||||
|
try { torProvider.applyMode(app, TorMode.OFF) } catch (_: Exception) { }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear AppState in-memory store
|
||||||
|
try { com.bitchat.android.services.AppStateStore.clear() } catch (_: Exception) { }
|
||||||
|
|
||||||
|
// Stop foreground and clear notification
|
||||||
|
try { stopForeground() } catch (_: Exception) { }
|
||||||
|
try { notificationManager.cancel(10001) } catch (_: Exception) { }
|
||||||
|
|
||||||
|
// Wait up to 5 seconds for shutdown tasks
|
||||||
|
withTimeoutOrNull(5000) {
|
||||||
|
try { torStop.await() } catch (_: Exception) { }
|
||||||
|
delay(100)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stop the service itself
|
||||||
|
try { stopService() } catch (_: Exception) { }
|
||||||
|
|
||||||
|
// Hard kill the app process
|
||||||
|
try { Process.killProcess(Process.myPid()) } catch (_: Exception) { }
|
||||||
|
try { System.exit(0) } catch (_: Exception) { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.bitchat.android.service
|
||||||
|
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
|
||||||
|
class BootCompletedReceiver : BroadcastReceiver() {
|
||||||
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
|
// Ensure preferences are initialized on cold boot before reading values
|
||||||
|
try { MeshServicePreferences.init(context.applicationContext) } catch (_: Exception) { }
|
||||||
|
|
||||||
|
if (MeshServicePreferences.isAutoStartEnabled(true)) {
|
||||||
|
MeshForegroundService.start(context.applicationContext)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,324 @@
|
|||||||
|
package com.bitchat.android.service
|
||||||
|
|
||||||
|
import android.app.Notification
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.app.Service
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.IBinder
|
||||||
|
import androidx.core.app.NotificationCompat
|
||||||
|
import androidx.core.app.NotificationManagerCompat
|
||||||
|
import com.bitchat.android.MainActivity
|
||||||
|
import com.bitchat.android.R
|
||||||
|
import com.bitchat.android.mesh.BluetoothMeshService
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.isActive
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
class MeshForegroundService : Service() {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val CHANNEL_ID = "bitchat_mesh_service"
|
||||||
|
private const val NOTIFICATION_ID = 10001
|
||||||
|
|
||||||
|
const val ACTION_START = "com.bitchat.android.service.START"
|
||||||
|
const val ACTION_STOP = "com.bitchat.android.service.STOP"
|
||||||
|
const val ACTION_QUIT = "com.bitchat.android.service.QUIT"
|
||||||
|
const val ACTION_UPDATE_NOTIFICATION = "com.bitchat.android.service.UPDATE_NOTIFICATION"
|
||||||
|
const val ACTION_NOTIFICATION_PERMISSION_GRANTED = "com.bitchat.android.action.NOTIFICATION_PERMISSION_GRANTED"
|
||||||
|
|
||||||
|
fun start(context: Context) {
|
||||||
|
val intent = Intent(context, MeshForegroundService::class.java).apply { action = ACTION_START }
|
||||||
|
|
||||||
|
// On API >= 26, avoid background-service start restrictions by using startForegroundService
|
||||||
|
// only when we can actually post a notification (Android 13+ requires runtime notif permission)
|
||||||
|
val bgEnabled = MeshServicePreferences.isBackgroundEnabled(true)
|
||||||
|
val hasNotifPerm = hasNotificationPermissionStatic(context)
|
||||||
|
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
if (bgEnabled && hasNotifPerm) {
|
||||||
|
context.startForegroundService(intent)
|
||||||
|
} else {
|
||||||
|
// Do not attempt to start a background service from headless context without notif permission
|
||||||
|
// or when background is disabled, to avoid BackgroundServiceStartNotAllowedException.
|
||||||
|
android.util.Log.i(
|
||||||
|
"MeshForegroundService",
|
||||||
|
"Not starting service on API>=26 (bgEnabled=$bgEnabled, hasNotifPerm=$hasNotifPerm)"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (bgEnabled) {
|
||||||
|
context.startService(intent)
|
||||||
|
} else {
|
||||||
|
android.util.Log.i("MeshForegroundService", "Background disabled; not starting service (pre-O)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper to be invoked right after POST_NOTIFICATIONS is granted to try
|
||||||
|
* promoting/starting the foreground service immediately without polling.
|
||||||
|
*/
|
||||||
|
fun onNotificationPermissionGranted(context: Context) {
|
||||||
|
// If background is enabled and permission now granted, start/promo service
|
||||||
|
val hasNotifPerm = hasNotificationPermissionStatic(context)
|
||||||
|
if (!MeshServicePreferences.isBackgroundEnabled(true) || !hasNotifPerm) return
|
||||||
|
|
||||||
|
val intent = Intent(context, MeshForegroundService::class.java).apply { action = ACTION_UPDATE_NOTIFICATION }
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
// Safe now that we can show a notification
|
||||||
|
context.startForegroundService(intent)
|
||||||
|
} else {
|
||||||
|
context.startService(intent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stop(context: Context) {
|
||||||
|
val intent = Intent(context, MeshForegroundService::class.java).apply { action = ACTION_STOP }
|
||||||
|
context.startService(intent)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun shouldStartAsForeground(context: Context): Boolean {
|
||||||
|
return MeshServicePreferences.isBackgroundEnabled(true) &&
|
||||||
|
hasBluetoothPermissionsStatic(context) &&
|
||||||
|
hasNotificationPermissionStatic(context)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hasBluetoothPermissionsStatic(ctx: Context): Boolean {
|
||||||
|
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||||
|
androidx.core.content.ContextCompat.checkSelfPermission(ctx, android.Manifest.permission.BLUETOOTH_ADVERTISE) == android.content.pm.PackageManager.PERMISSION_GRANTED &&
|
||||||
|
androidx.core.content.ContextCompat.checkSelfPermission(ctx, android.Manifest.permission.BLUETOOTH_CONNECT) == android.content.pm.PackageManager.PERMISSION_GRANTED &&
|
||||||
|
androidx.core.content.ContextCompat.checkSelfPermission(ctx, android.Manifest.permission.BLUETOOTH_SCAN) == android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||||
|
} else {
|
||||||
|
val fine = androidx.core.content.ContextCompat.checkSelfPermission(ctx, android.Manifest.permission.ACCESS_FINE_LOCATION) == android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||||
|
val coarse = androidx.core.content.ContextCompat.checkSelfPermission(ctx, android.Manifest.permission.ACCESS_COARSE_LOCATION) == android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||||
|
fine || coarse
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hasNotificationPermissionStatic(ctx: Context): Boolean {
|
||||||
|
return if (Build.VERSION.SDK_INT >= 33) {
|
||||||
|
androidx.core.content.ContextCompat.checkSelfPermission(ctx, android.Manifest.permission.POST_NOTIFICATIONS) == android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||||
|
} else true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private lateinit var notificationManager: NotificationManagerCompat
|
||||||
|
private var updateJob: Job? = null
|
||||||
|
private var meshService: BluetoothMeshService? = null
|
||||||
|
private val serviceJob = Job()
|
||||||
|
private val scope = CoroutineScope(Dispatchers.Default + serviceJob)
|
||||||
|
private var isInForeground: Boolean = false
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
notificationManager = NotificationManagerCompat.from(this)
|
||||||
|
createChannel()
|
||||||
|
|
||||||
|
// Adopt or create the mesh service
|
||||||
|
val existing = MeshServiceHolder.meshService
|
||||||
|
meshService = existing ?: MeshServiceHolder.getOrCreate(applicationContext)
|
||||||
|
if (existing != null) {
|
||||||
|
android.util.Log.d("MeshForegroundService", "Adopted existing BluetoothMeshService from holder")
|
||||||
|
} else {
|
||||||
|
android.util.Log.i("MeshForegroundService", "Created/adopted new BluetoothMeshService via holder")
|
||||||
|
}
|
||||||
|
MeshServiceHolder.attach(meshService!!)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
|
when (intent?.action) {
|
||||||
|
ACTION_STOP -> {
|
||||||
|
// Stop FGS and mesh cleanly
|
||||||
|
try { meshService?.stopServices() } catch (_: Exception) { }
|
||||||
|
try { MeshServiceHolder.clear() } catch (_: Exception) { }
|
||||||
|
try { stopForeground(true) } catch (_: Exception) { }
|
||||||
|
notificationManager.cancel(NOTIFICATION_ID)
|
||||||
|
isInForeground = false
|
||||||
|
stopSelf()
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
ACTION_QUIT -> {
|
||||||
|
// Fully stop all background activity, stop Tor (without changing setting), then kill the app
|
||||||
|
AppShutdownCoordinator.requestFullShutdownAndKill(
|
||||||
|
app = application,
|
||||||
|
mesh = meshService,
|
||||||
|
notificationManager = notificationManager,
|
||||||
|
stopForeground = {
|
||||||
|
try { stopForeground(true) } catch (_: Exception) { }
|
||||||
|
isInForeground = false
|
||||||
|
},
|
||||||
|
stopService = { stopSelf() }
|
||||||
|
)
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
ACTION_UPDATE_NOTIFICATION -> {
|
||||||
|
// If we became eligible and are not in foreground yet, promote once
|
||||||
|
if (MeshServicePreferences.isBackgroundEnabled(true) && hasAllRequiredPermissions() && !isInForeground) {
|
||||||
|
val n = buildNotification(meshService?.getActivePeerCount() ?: 0)
|
||||||
|
startForeground(NOTIFICATION_ID, n)
|
||||||
|
isInForeground = true
|
||||||
|
} else {
|
||||||
|
updateNotification(force = true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> { /* ACTION_START or null */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure mesh is running (only after permissions are granted)
|
||||||
|
ensureMeshStarted()
|
||||||
|
|
||||||
|
// Promote exactly once when eligible, otherwise stay background (or stop)
|
||||||
|
if (MeshServicePreferences.isBackgroundEnabled(true) && hasAllRequiredPermissions() && !isInForeground) {
|
||||||
|
val notification = buildNotification(meshService?.getActivePeerCount() ?: 0)
|
||||||
|
startForeground(NOTIFICATION_ID, notification)
|
||||||
|
isInForeground = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Periodically refresh the notification with live network size
|
||||||
|
if (updateJob == null) {
|
||||||
|
updateJob = scope.launch {
|
||||||
|
while (isActive) {
|
||||||
|
// Retry enabling mesh/foreground once permissions become available
|
||||||
|
ensureMeshStarted()
|
||||||
|
val eligible = MeshServicePreferences.isBackgroundEnabled(true) && hasAllRequiredPermissions()
|
||||||
|
if (eligible) {
|
||||||
|
// Only update the notification; do not re-call startForeground()
|
||||||
|
updateNotification(force = false)
|
||||||
|
} else {
|
||||||
|
// If disabled or perms missing, ensure we are not in foreground and clear notif
|
||||||
|
if (isInForeground) {
|
||||||
|
try { stopForeground(false) } catch (_: Exception) { }
|
||||||
|
isInForeground = false
|
||||||
|
}
|
||||||
|
notificationManager.cancel(NOTIFICATION_ID)
|
||||||
|
}
|
||||||
|
delay(5000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return START_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ensureMeshStarted() {
|
||||||
|
if (!hasBluetoothPermissions()) return
|
||||||
|
try {
|
||||||
|
android.util.Log.d("MeshForegroundService", "Ensuring mesh service is started")
|
||||||
|
meshService?.startServices()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
android.util.Log.e("MeshForegroundService", "Failed to start mesh service: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateNotification(force: Boolean) {
|
||||||
|
val count = meshService?.getActivePeerCount() ?: 0
|
||||||
|
val notification = buildNotification(count)
|
||||||
|
if (MeshServicePreferences.isBackgroundEnabled(true) && hasAllRequiredPermissions()) {
|
||||||
|
notificationManager.notify(NOTIFICATION_ID, notification)
|
||||||
|
} else if (force) {
|
||||||
|
// If disabled and forced, make sure to remove any prior foreground state
|
||||||
|
try { stopForeground(false) } catch (_: Exception) { }
|
||||||
|
notificationManager.cancel(NOTIFICATION_ID)
|
||||||
|
isInForeground = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hasAllRequiredPermissions(): Boolean {
|
||||||
|
// For starting FGS with connectedDevice|dataSync, we need:
|
||||||
|
// - Foreground service permissions (declared in manifest)
|
||||||
|
// - One of the device-related permissions (we request BL perms at runtime)
|
||||||
|
// - On Android 13+, POST_NOTIFICATIONS to actually show notification
|
||||||
|
return hasBluetoothPermissions() && hasNotificationPermission()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hasBluetoothPermissions(): Boolean {
|
||||||
|
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||||
|
androidx.core.content.ContextCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_ADVERTISE) == android.content.pm.PackageManager.PERMISSION_GRANTED &&
|
||||||
|
androidx.core.content.ContextCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_CONNECT) == android.content.pm.PackageManager.PERMISSION_GRANTED &&
|
||||||
|
androidx.core.content.ContextCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_SCAN) == android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||||
|
} else {
|
||||||
|
// Prior to S, scanning requires location permissions
|
||||||
|
val fine = androidx.core.content.ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||||
|
val coarse = androidx.core.content.ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||||
|
fine || coarse
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hasNotificationPermission(): Boolean {
|
||||||
|
return if (Build.VERSION.SDK_INT >= 33) {
|
||||||
|
androidx.core.content.ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) == android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||||
|
} else true
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildNotification(activeUsers: Int): Notification {
|
||||||
|
val openIntent = Intent(this, MainActivity::class.java)
|
||||||
|
val pendingIntent = PendingIntent.getActivity(
|
||||||
|
this, 0, openIntent,
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= 23) PendingIntent.FLAG_IMMUTABLE else 0)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Action: Quit Bitchat
|
||||||
|
val quitIntent = Intent(this, MeshForegroundService::class.java).apply { action = ACTION_QUIT }
|
||||||
|
val quitPendingIntent = PendingIntent.getService(
|
||||||
|
this, 1, quitIntent,
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= 23) PendingIntent.FLAG_IMMUTABLE else 0)
|
||||||
|
)
|
||||||
|
|
||||||
|
val title = getString(R.string.app_name)
|
||||||
|
val content = getString(R.string.mesh_service_notification_content, activeUsers)
|
||||||
|
|
||||||
|
return NotificationCompat.Builder(this, CHANNEL_ID)
|
||||||
|
.setContentTitle(title)
|
||||||
|
.setContentText(content)
|
||||||
|
.setSmallIcon(R.mipmap.ic_launcher)
|
||||||
|
.setOngoing(true)
|
||||||
|
.setOnlyAlertOnce(true)
|
||||||
|
.setPriority(NotificationCompat.PRIORITY_LOW)
|
||||||
|
.setCategory(NotificationCompat.CATEGORY_SERVICE)
|
||||||
|
.setContentIntent(pendingIntent)
|
||||||
|
// Add an action button that appears when notification is expanded
|
||||||
|
.addAction(
|
||||||
|
android.R.drawable.ic_menu_close_clear_cancel,
|
||||||
|
getString(R.string.notification_action_quit_bitchat),
|
||||||
|
quitPendingIntent
|
||||||
|
)
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun createChannel() {
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
val channel = NotificationChannel(
|
||||||
|
CHANNEL_ID,
|
||||||
|
getString(R.string.mesh_service_channel_name),
|
||||||
|
NotificationManager.IMPORTANCE_LOW
|
||||||
|
).apply {
|
||||||
|
description = getString(R.string.mesh_service_channel_desc)
|
||||||
|
setShowBadge(false)
|
||||||
|
}
|
||||||
|
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
|
||||||
|
.createNotificationChannel(channel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
updateJob?.cancel()
|
||||||
|
updateJob = null
|
||||||
|
// Cancel the service coroutine scope to prevent leaks
|
||||||
|
try { serviceJob.cancel() } catch (_: Exception) { }
|
||||||
|
// Best-effort ensure we are not marked foreground
|
||||||
|
if (isInForeground) {
|
||||||
|
try { stopForeground(true) } catch (_: Exception) { }
|
||||||
|
isInForeground = false
|
||||||
|
}
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBind(intent: Intent?): IBinder? = null
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package com.bitchat.android.service
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.bitchat.android.mesh.BluetoothMeshService
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process-wide holder to share a single BluetoothMeshService instance
|
||||||
|
* between the foreground service and UI (MainActivity/ViewModels).
|
||||||
|
*/
|
||||||
|
object MeshServiceHolder {
|
||||||
|
private const val TAG = "MeshServiceHolder"
|
||||||
|
@Volatile
|
||||||
|
var meshService: BluetoothMeshService? = null
|
||||||
|
private set
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun getOrCreate(context: Context): BluetoothMeshService {
|
||||||
|
val existing = meshService
|
||||||
|
if (existing != null) {
|
||||||
|
// If the existing instance is healthy, reuse it; otherwise, replace it.
|
||||||
|
return try {
|
||||||
|
if (existing.isReusable()) {
|
||||||
|
android.util.Log.d(TAG, "Reusing existing BluetoothMeshService instance")
|
||||||
|
existing
|
||||||
|
} else {
|
||||||
|
android.util.Log.w(TAG, "Existing BluetoothMeshService not reusable; replacing with a fresh instance")
|
||||||
|
// Best-effort stop before replacing
|
||||||
|
try { existing.stopServices() } catch (e: Exception) {
|
||||||
|
android.util.Log.w(TAG, "Error while stopping non-reusable instance: ${e.message}")
|
||||||
|
}
|
||||||
|
val created = BluetoothMeshService(context.applicationContext)
|
||||||
|
android.util.Log.i(TAG, "Created new BluetoothMeshService (replacement)")
|
||||||
|
meshService = created
|
||||||
|
created
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
android.util.Log.e(TAG, "Error checking service reusability; creating new instance: ${e.message}")
|
||||||
|
val created = BluetoothMeshService(context.applicationContext)
|
||||||
|
meshService = created
|
||||||
|
created
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val created = BluetoothMeshService(context.applicationContext)
|
||||||
|
android.util.Log.i(TAG, "Created new BluetoothMeshService (no existing instance)")
|
||||||
|
meshService = created
|
||||||
|
return created
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun attach(service: BluetoothMeshService) {
|
||||||
|
android.util.Log.d(TAG, "Attaching BluetoothMeshService to holder")
|
||||||
|
meshService = service
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun clear() {
|
||||||
|
android.util.Log.d(TAG, "Clearing BluetoothMeshService from holder")
|
||||||
|
meshService = null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package com.bitchat.android.service
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.SharedPreferences
|
||||||
|
|
||||||
|
object MeshServicePreferences {
|
||||||
|
private const val PREFS_NAME = "bitchat_mesh_service_prefs"
|
||||||
|
private const val KEY_AUTO_START = "auto_start_on_boot"
|
||||||
|
private const val KEY_BACKGROUND_ENABLED = "background_enabled"
|
||||||
|
|
||||||
|
private lateinit var prefs: SharedPreferences
|
||||||
|
|
||||||
|
fun init(context: Context) {
|
||||||
|
prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isAutoStartEnabled(default: Boolean = true): Boolean {
|
||||||
|
return prefs.getBoolean(KEY_AUTO_START, default)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setAutoStartEnabled(enabled: Boolean) {
|
||||||
|
prefs.edit().putBoolean(KEY_AUTO_START, enabled).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isBackgroundEnabled(default: Boolean = true): Boolean {
|
||||||
|
return prefs.getBoolean(KEY_BACKGROUND_ENABLED, default)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setBackgroundEnabled(enabled: Boolean) {
|
||||||
|
prefs.edit().putBoolean(KEY_BACKGROUND_ENABLED, enabled).apply()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
package com.bitchat.android.services
|
||||||
|
|
||||||
|
import com.bitchat.android.model.BitchatMessage
|
||||||
|
import com.bitchat.android.model.DeliveryStatus
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process-wide in-memory state store that survives Activity recreation.
|
||||||
|
* The foreground Mesh service updates this store; UI subscribes/hydrates from it.
|
||||||
|
*/
|
||||||
|
object AppStateStore {
|
||||||
|
// Global de-dup set by message id to avoid duplicate keys in Compose lists
|
||||||
|
private val seenMessageIds = mutableSetOf<String>()
|
||||||
|
// Connected peer IDs (mesh ephemeral IDs)
|
||||||
|
private val _peers = MutableStateFlow<List<String>>(emptyList())
|
||||||
|
val peers: StateFlow<List<String>> = _peers.asStateFlow()
|
||||||
|
|
||||||
|
// Public mesh timeline messages (non-channel)
|
||||||
|
private val _publicMessages = MutableStateFlow<List<BitchatMessage>>(emptyList())
|
||||||
|
val publicMessages: StateFlow<List<BitchatMessage>> = _publicMessages.asStateFlow()
|
||||||
|
|
||||||
|
// Private messages by peerID
|
||||||
|
private val _privateMessages = MutableStateFlow<Map<String, List<BitchatMessage>>>(emptyMap())
|
||||||
|
val privateMessages: StateFlow<Map<String, List<BitchatMessage>>> = _privateMessages.asStateFlow()
|
||||||
|
|
||||||
|
// Channel messages by channel name
|
||||||
|
private val _channelMessages = MutableStateFlow<Map<String, List<BitchatMessage>>>(emptyMap())
|
||||||
|
val channelMessages: StateFlow<Map<String, List<BitchatMessage>>> = _channelMessages.asStateFlow()
|
||||||
|
|
||||||
|
fun setPeers(ids: List<String>) {
|
||||||
|
_peers.value = ids
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addPublicMessage(msg: BitchatMessage) {
|
||||||
|
synchronized(this) {
|
||||||
|
if (seenMessageIds.contains(msg.id)) return
|
||||||
|
seenMessageIds.add(msg.id)
|
||||||
|
_publicMessages.value = _publicMessages.value + msg
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addPrivateMessage(peerID: String, msg: BitchatMessage) {
|
||||||
|
synchronized(this) {
|
||||||
|
if (seenMessageIds.contains(msg.id)) return
|
||||||
|
seenMessageIds.add(msg.id)
|
||||||
|
val map = _privateMessages.value.toMutableMap()
|
||||||
|
val list = (map[peerID] ?: emptyList()) + msg
|
||||||
|
map[peerID] = list
|
||||||
|
_privateMessages.value = map
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun statusPriority(status: DeliveryStatus?): Int = when (status) {
|
||||||
|
null -> 0
|
||||||
|
is DeliveryStatus.Sending -> 1
|
||||||
|
is DeliveryStatus.Sent -> 2
|
||||||
|
is DeliveryStatus.PartiallyDelivered -> 3
|
||||||
|
is DeliveryStatus.Delivered -> 4
|
||||||
|
is DeliveryStatus.Read -> 5
|
||||||
|
is DeliveryStatus.Failed -> 0
|
||||||
|
}
|
||||||
|
|
||||||
|
fun updatePrivateMessageStatus(messageID: String, status: DeliveryStatus) {
|
||||||
|
synchronized(this) {
|
||||||
|
val map = _privateMessages.value.toMutableMap()
|
||||||
|
var changed = false
|
||||||
|
map.keys.toList().forEach { peer ->
|
||||||
|
val list = map[peer]?.toMutableList() ?: mutableListOf()
|
||||||
|
val idx = list.indexOfFirst { it.id == messageID }
|
||||||
|
if (idx >= 0) {
|
||||||
|
val current = list[idx].deliveryStatus
|
||||||
|
// Do not downgrade (e.g., Read -> Delivered)
|
||||||
|
if (statusPriority(status) >= statusPriority(current)) {
|
||||||
|
list[idx] = list[idx].copy(deliveryStatus = status)
|
||||||
|
map[peer] = list
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (changed) {
|
||||||
|
_privateMessages.value = map
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addChannelMessage(channel: String, msg: BitchatMessage) {
|
||||||
|
synchronized(this) {
|
||||||
|
if (seenMessageIds.contains(msg.id)) return
|
||||||
|
seenMessageIds.add(msg.id)
|
||||||
|
val map = _channelMessages.value.toMutableMap()
|
||||||
|
val list = (map[channel] ?: emptyList()) + msg
|
||||||
|
map[channel] = list
|
||||||
|
_channelMessages.value = map
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear all in-memory state (used for full app shutdown)
|
||||||
|
fun clear() {
|
||||||
|
synchronized(this) {
|
||||||
|
seenMessageIds.clear()
|
||||||
|
_peers.value = emptyList()
|
||||||
|
_publicMessages.value = emptyList()
|
||||||
|
_privateMessages.value = emptyMap()
|
||||||
|
_channelMessages.value = emptyMap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.bitchat.android.services
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.bitchat.android.ui.DataManager
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Provides current user's nickname for announcements and leave messages.
|
||||||
|
* If no nickname saved, falls back to the provided peerID.
|
||||||
|
*/
|
||||||
|
object NicknameProvider {
|
||||||
|
fun getNickname(context: Context, myPeerID: String): String {
|
||||||
|
return try {
|
||||||
|
val dm = DataManager(context.applicationContext)
|
||||||
|
val nick = dm.loadNickname()
|
||||||
|
if (nick.isNullOrBlank()) myPeerID else nick
|
||||||
|
} catch (_: Exception) {
|
||||||
|
myPeerID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -143,6 +143,41 @@ class ChatViewModel(
|
|||||||
init {
|
init {
|
||||||
// Note: Mesh service delegate is now set by MainActivity
|
// Note: Mesh service delegate is now set by MainActivity
|
||||||
loadAndInitialize()
|
loadAndInitialize()
|
||||||
|
// Hydrate UI state from process-wide AppStateStore to survive Activity recreation
|
||||||
|
viewModelScope.launch {
|
||||||
|
try { com.bitchat.android.services.AppStateStore.peers.collect { peers ->
|
||||||
|
state.setConnectedPeers(peers)
|
||||||
|
state.setIsConnected(peers.isNotEmpty())
|
||||||
|
} } catch (_: Exception) { }
|
||||||
|
}
|
||||||
|
viewModelScope.launch {
|
||||||
|
try { com.bitchat.android.services.AppStateStore.publicMessages.collect { msgs ->
|
||||||
|
// Source of truth is AppStateStore; replace to avoid duplicate keys in LazyColumn
|
||||||
|
state.setMessages(msgs)
|
||||||
|
} } catch (_: Exception) { }
|
||||||
|
}
|
||||||
|
viewModelScope.launch {
|
||||||
|
try { com.bitchat.android.services.AppStateStore.privateMessages.collect { byPeer ->
|
||||||
|
// Replace with store snapshot
|
||||||
|
state.setPrivateChats(byPeer)
|
||||||
|
// Recompute unread set using SeenMessageStore for robustness across Activity recreation
|
||||||
|
try {
|
||||||
|
val seen = com.bitchat.android.services.SeenMessageStore.getInstance(getApplication())
|
||||||
|
val myNick = state.getNicknameValue() ?: meshService.myPeerID
|
||||||
|
val unread = mutableSetOf<String>()
|
||||||
|
byPeer.forEach { (peer, list) ->
|
||||||
|
if (list.any { msg -> msg.sender != myNick && !seen.hasRead(msg.id) }) unread.add(peer)
|
||||||
|
}
|
||||||
|
state.setUnreadPrivateMessages(unread)
|
||||||
|
} catch (_: Exception) { }
|
||||||
|
} } catch (_: Exception) { }
|
||||||
|
}
|
||||||
|
viewModelScope.launch {
|
||||||
|
try { com.bitchat.android.services.AppStateStore.channelMessages.collect { byChannel ->
|
||||||
|
// Replace with store snapshot
|
||||||
|
state.setChannelMessages(byChannel)
|
||||||
|
} } catch (_: Exception) { }
|
||||||
|
}
|
||||||
// Subscribe to BLE transfer progress and reflect in message deliveryStatus
|
// Subscribe to BLE transfer progress and reflect in message deliveryStatus
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
com.bitchat.android.mesh.TransferProgressManager.events.collect { evt ->
|
com.bitchat.android.mesh.TransferProgressManager.events.collect { evt ->
|
||||||
|
|||||||
@@ -47,9 +47,9 @@ class MeshDelegateHandler(
|
|||||||
// Private message
|
// Private message
|
||||||
privateChatManager.handleIncomingPrivateMessage(message)
|
privateChatManager.handleIncomingPrivateMessage(message)
|
||||||
|
|
||||||
// Reactive read receipts: Send immediately if user is currently viewing this chat
|
// Reactive read receipts: if chat is focused, send immediately for this message
|
||||||
message.senderPeerID?.let { senderPeerID ->
|
message.senderPeerID?.let { senderPeerID ->
|
||||||
sendReadReceiptIfFocused(senderPeerID)
|
sendReadReceiptIfFocused(message)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show notification with enhanced information - now includes senderPeerID
|
// Show notification with enhanced information - now includes senderPeerID
|
||||||
@@ -64,15 +64,26 @@ class MeshDelegateHandler(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
} else if (message.channel != null) {
|
} else if (message.channel != null) {
|
||||||
// Channel message
|
// Channel message: AppStateStore is the source of truth for list; only manage unread
|
||||||
if (state.getJoinedChannelsValue().contains(message.channel)) {
|
if (state.getJoinedChannelsValue().contains(message.channel)) {
|
||||||
channelManager.addChannelMessage(message.channel, message, message.senderPeerID)
|
val channel = message.channel
|
||||||
|
val viewingClassic = state.getCurrentChannelValue() == channel
|
||||||
|
val viewingGeohash = try {
|
||||||
|
if (channel.startsWith("geo:")) {
|
||||||
|
val geo = channel.removePrefix("geo:")
|
||||||
|
val selected = state.selectedLocationChannel.value
|
||||||
|
selected is com.bitchat.android.geohash.ChannelID.Location && selected.channel.geohash.equals(geo, ignoreCase = true)
|
||||||
|
} else false
|
||||||
|
} catch (_: Exception) { false }
|
||||||
|
if (!viewingClassic && !viewingGeohash) {
|
||||||
|
val currentUnread = state.getUnreadChannelMessagesValue().toMutableMap()
|
||||||
|
currentUnread[channel] = (currentUnread[channel] ?: 0) + 1
|
||||||
|
state.setUnreadChannelMessages(currentUnread)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Public mesh message - always store to preserve message history
|
// Public mesh message: AppStateStore is the source of truth; avoid double-adding to UI state
|
||||||
messageManager.addMessage(message)
|
// Still run mention detection/notifications
|
||||||
|
|
||||||
// Check for mentions in mesh chat
|
|
||||||
checkAndTriggerMeshMentionNotification(message)
|
checkAndTriggerMeshMentionNotification(message)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -263,21 +274,31 @@ class MeshDelegateHandler(
|
|||||||
* Uses same logic as notification system - send read receipt if user is currently
|
* Uses same logic as notification system - send read receipt if user is currently
|
||||||
* viewing the private chat with this sender AND app is in foreground.
|
* viewing the private chat with this sender AND app is in foreground.
|
||||||
*/
|
*/
|
||||||
private fun sendReadReceiptIfFocused(senderPeerID: String) {
|
private fun sendReadReceiptIfFocused(message: BitchatMessage) {
|
||||||
// Get notification manager's focus state (mirror the notification logic)
|
// Get notification manager's focus state (mirror the notification logic)
|
||||||
val isAppInBackground = notificationManager.getAppBackgroundState()
|
val isAppInBackground = notificationManager.getAppBackgroundState()
|
||||||
val currentPrivateChatPeer = notificationManager.getCurrentPrivateChatPeer()
|
val currentPrivateChatPeer = notificationManager.getCurrentPrivateChatPeer()
|
||||||
|
|
||||||
// Send read receipt if user is currently focused on this specific chat
|
// Send read receipt if user is currently focused on this specific chat
|
||||||
val shouldSendReadReceipt = !isAppInBackground && currentPrivateChatPeer == senderPeerID
|
val senderPeerID = message.senderPeerID
|
||||||
|
val shouldSendReadReceipt = !isAppInBackground && senderPeerID != null && currentPrivateChatPeer == senderPeerID
|
||||||
|
|
||||||
if (shouldSendReadReceipt) {
|
if (shouldSendReadReceipt) {
|
||||||
android.util.Log.d("MeshDelegateHandler", "Sending reactive read receipt for focused chat with $senderPeerID")
|
android.util.Log.d("MeshDelegateHandler", "Sending reactive read receipt for focused chat with $senderPeerID (message=${message.id})")
|
||||||
privateChatManager.sendReadReceiptsForPeer(senderPeerID, getMeshService())
|
val nickname = state.getNicknameValue() ?: "unknown"
|
||||||
} else {
|
// Send directly for this message to avoid relying on unread queues
|
||||||
android.util.Log.d("MeshDelegateHandler", "Skipping read receipt - chat not focused (background: $isAppInBackground, current peer: $currentPrivateChatPeer, sender: $senderPeerID)")
|
getMeshService().sendReadReceipt(message.id, senderPeerID!!, nickname)
|
||||||
|
// Ensure unread badge is cleared for this peer immediately
|
||||||
|
try {
|
||||||
|
val current = state.getUnreadPrivateMessagesValue().toMutableSet()
|
||||||
|
if (current.remove(senderPeerID)) {
|
||||||
|
state.setUnreadPrivateMessages(current)
|
||||||
|
}
|
||||||
|
} catch (_: Exception) { }
|
||||||
|
} else {
|
||||||
|
android.util.Log.d("MeshDelegateHandler", "Skipping read receipt - chat not focused (background: $isAppInBackground, current peer: $currentPrivateChatPeer, sender: $senderPeerID)")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// registerPeerPublicKey REMOVED - fingerprints now handled centrally in PeerManager
|
// registerPeerPublicKey REMOVED - fingerprints now handled centrally in PeerManager
|
||||||
|
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ class MessageManager(private val state: ChatState) {
|
|||||||
val currentMessages = state.getMessagesValue().toMutableList()
|
val currentMessages = state.getMessagesValue().toMutableList()
|
||||||
currentMessages.add(message)
|
currentMessages.add(message)
|
||||||
state.setMessages(currentMessages)
|
state.setMessages(currentMessages)
|
||||||
|
// Reflect into process-wide store so snapshot replacements don't drop local outgoing messages
|
||||||
|
try { com.bitchat.android.services.AppStateStore.addPublicMessage(message) } catch (_: Exception) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
// Log a system message into the main chat (visible to user)
|
// Log a system message into the main chat (visible to user)
|
||||||
@@ -52,6 +54,8 @@ class MessageManager(private val state: ChatState) {
|
|||||||
channelMessageList.add(message)
|
channelMessageList.add(message)
|
||||||
currentChannelMessages[channel] = channelMessageList
|
currentChannelMessages[channel] = channelMessageList
|
||||||
state.setChannelMessages(currentChannelMessages)
|
state.setChannelMessages(currentChannelMessages)
|
||||||
|
// Reflect into process-wide store
|
||||||
|
try { com.bitchat.android.services.AppStateStore.addChannelMessage(channel, message) } catch (_: Exception) { }
|
||||||
|
|
||||||
// Update unread count if not currently viewing this channel
|
// Update unread count if not currently viewing this channel
|
||||||
// Consider both classic channels (state.currentChannel) and geohash location channel selection
|
// Consider both classic channels (state.currentChannel) and geohash location channel selection
|
||||||
@@ -105,6 +109,8 @@ class MessageManager(private val state: ChatState) {
|
|||||||
chatMessages.add(message)
|
chatMessages.add(message)
|
||||||
currentPrivateChats[peerID] = chatMessages
|
currentPrivateChats[peerID] = chatMessages
|
||||||
state.setPrivateChats(currentPrivateChats)
|
state.setPrivateChats(currentPrivateChats)
|
||||||
|
// Reflect into process-wide store
|
||||||
|
try { com.bitchat.android.services.AppStateStore.addPrivateMessage(peerID, message) } catch (_: Exception) { }
|
||||||
|
|
||||||
// Mark as unread if not currently viewing this chat
|
// Mark as unread if not currently viewing this chat
|
||||||
if (state.getSelectedPrivateChatPeerValue() != peerID && message.sender != state.getNicknameValue()) {
|
if (state.getSelectedPrivateChatPeerValue() != peerID && message.sender != state.getNicknameValue()) {
|
||||||
@@ -124,6 +130,8 @@ class MessageManager(private val state: ChatState) {
|
|||||||
chatMessages.add(message)
|
chatMessages.add(message)
|
||||||
currentPrivateChats[peerID] = chatMessages
|
currentPrivateChats[peerID] = chatMessages
|
||||||
state.setPrivateChats(currentPrivateChats)
|
state.setPrivateChats(currentPrivateChats)
|
||||||
|
// Reflect into process-wide store
|
||||||
|
try { com.bitchat.android.services.AppStateStore.addPrivateMessage(peerID, message) } catch (_: Exception) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun clearPrivateMessages(peerID: String) {
|
fun clearPrivateMessages(peerID: String) {
|
||||||
@@ -206,6 +214,21 @@ class MessageManager(private val state: ChatState) {
|
|||||||
|
|
||||||
// MARK: - Delivery Status Updates
|
// MARK: - Delivery Status Updates
|
||||||
|
|
||||||
|
private fun statusPriority(status: DeliveryStatus?): Int = when (status) {
|
||||||
|
null -> 0
|
||||||
|
is DeliveryStatus.Sending -> 1
|
||||||
|
is DeliveryStatus.Sent -> 2
|
||||||
|
is DeliveryStatus.PartiallyDelivered -> 3
|
||||||
|
is DeliveryStatus.Delivered -> 4
|
||||||
|
is DeliveryStatus.Read -> 5
|
||||||
|
is DeliveryStatus.Failed -> 0 // treat as lowest for UI check marks ordering
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun chooseStatus(old: DeliveryStatus?, new: DeliveryStatus): DeliveryStatus? {
|
||||||
|
// Never downgrade (e.g., Read -> Delivered). Keep the higher priority.
|
||||||
|
return if (statusPriority(new) >= statusPriority(old)) new else old
|
||||||
|
}
|
||||||
|
|
||||||
fun updateMessageDeliveryStatus(messageID: String, status: DeliveryStatus) {
|
fun updateMessageDeliveryStatus(messageID: String, status: DeliveryStatus) {
|
||||||
// Update in private chats
|
// Update in private chats
|
||||||
val updatedPrivateChats = state.getPrivateChatsValue().toMutableMap()
|
val updatedPrivateChats = state.getPrivateChatsValue().toMutableMap()
|
||||||
@@ -215,22 +238,32 @@ class MessageManager(private val state: ChatState) {
|
|||||||
val updatedMessages = messages.toMutableList()
|
val updatedMessages = messages.toMutableList()
|
||||||
val messageIndex = updatedMessages.indexOfFirst { it.id == messageID }
|
val messageIndex = updatedMessages.indexOfFirst { it.id == messageID }
|
||||||
if (messageIndex >= 0) {
|
if (messageIndex >= 0) {
|
||||||
updatedMessages[messageIndex] = updatedMessages[messageIndex].copy(deliveryStatus = status)
|
val current = updatedMessages[messageIndex].deliveryStatus
|
||||||
updatedPrivateChats[peerID] = updatedMessages
|
val finalStatus = chooseStatus(current, status)
|
||||||
updated = true
|
if (finalStatus !== current) {
|
||||||
|
updatedMessages[messageIndex] = updatedMessages[messageIndex].copy(deliveryStatus = finalStatus)
|
||||||
|
updatedPrivateChats[peerID] = updatedMessages
|
||||||
|
updated = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (updated) {
|
if (updated) {
|
||||||
state.setPrivateChats(updatedPrivateChats)
|
state.setPrivateChats(updatedPrivateChats)
|
||||||
|
// Keep process-wide store in sync to prevent snapshot overwrites resetting status
|
||||||
|
try { com.bitchat.android.services.AppStateStore.updatePrivateMessageStatus(messageID, status) } catch (_: Exception) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update in main messages
|
// Update in main messages
|
||||||
val updatedMessages = state.getMessagesValue().toMutableList()
|
val updatedMessages = state.getMessagesValue().toMutableList()
|
||||||
val messageIndex = updatedMessages.indexOfFirst { it.id == messageID }
|
val messageIndex = updatedMessages.indexOfFirst { it.id == messageID }
|
||||||
if (messageIndex >= 0) {
|
if (messageIndex >= 0) {
|
||||||
updatedMessages[messageIndex] = updatedMessages[messageIndex].copy(deliveryStatus = status)
|
val current = updatedMessages[messageIndex].deliveryStatus
|
||||||
state.setMessages(updatedMessages)
|
val finalStatus = chooseStatus(current, status)
|
||||||
|
if (finalStatus !== current) {
|
||||||
|
updatedMessages[messageIndex] = updatedMessages[messageIndex].copy(deliveryStatus = finalStatus)
|
||||||
|
state.setMessages(updatedMessages)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update in channel messages
|
// Update in channel messages
|
||||||
@@ -239,8 +272,12 @@ class MessageManager(private val state: ChatState) {
|
|||||||
val channelMessagesList = messages.toMutableList()
|
val channelMessagesList = messages.toMutableList()
|
||||||
val channelMessageIndex = channelMessagesList.indexOfFirst { it.id == messageID }
|
val channelMessageIndex = channelMessagesList.indexOfFirst { it.id == messageID }
|
||||||
if (channelMessageIndex >= 0) {
|
if (channelMessageIndex >= 0) {
|
||||||
channelMessagesList[channelMessageIndex] = channelMessagesList[channelMessageIndex].copy(deliveryStatus = status)
|
val current = channelMessagesList[channelMessageIndex].deliveryStatus
|
||||||
updatedChannelMessages[channel] = channelMessagesList
|
val finalStatus = chooseStatus(current, status)
|
||||||
|
if (finalStatus !== current) {
|
||||||
|
channelMessagesList[channelMessageIndex] = channelMessagesList[channelMessageIndex].copy(deliveryStatus = finalStatus)
|
||||||
|
updatedChannelMessages[channel] = channelMessagesList
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
state.setChannelMessages(updatedChannelMessages)
|
state.setChannelMessages(updatedChannelMessages)
|
||||||
|
|||||||
@@ -292,28 +292,30 @@ class PrivateChatManager(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun handleIncomingPrivateMessage(message: BitchatMessage, suppressUnread: Boolean) {
|
fun handleIncomingPrivateMessage(message: BitchatMessage, suppressUnread: Boolean) {
|
||||||
message.senderPeerID?.let { senderPeerID ->
|
val senderPeerID = message.senderPeerID
|
||||||
|
if (senderPeerID != null) {
|
||||||
|
// Mesh-origin private message: AppStateStore updates the list; avoid double-add here.
|
||||||
if (!isPeerBlocked(senderPeerID)) {
|
if (!isPeerBlocked(senderPeerID)) {
|
||||||
// Add to private messages
|
// Ensure chat exists
|
||||||
if (suppressUnread) {
|
messageManager.initializePrivateChat(senderPeerID)
|
||||||
messageManager.addPrivateMessageNoUnread(senderPeerID, message)
|
// Track as unread for read receipt purposes if not focused
|
||||||
} else {
|
if (!suppressUnread && state.getSelectedPrivateChatPeerValue() != senderPeerID) {
|
||||||
messageManager.addPrivateMessage(senderPeerID, message)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Track as unread for read receipt purposes
|
|
||||||
var unreadCount = 0
|
|
||||||
if (!suppressUnread) {
|
|
||||||
val unreadList = unreadReceivedMessages.getOrPut(senderPeerID) { mutableListOf() }
|
val unreadList = unreadReceivedMessages.getOrPut(senderPeerID) { mutableListOf() }
|
||||||
unreadList.add(message)
|
unreadList.add(message)
|
||||||
unreadCount = unreadList.size
|
Log.d(TAG, "Queued unread from $senderPeerID (count=${unreadList.size})")
|
||||||
|
val currentUnread = state.getUnreadPrivateMessagesValue().toMutableSet()
|
||||||
|
currentUnread.add(senderPeerID)
|
||||||
|
state.setUnreadPrivateMessages(currentUnread)
|
||||||
}
|
}
|
||||||
|
|
||||||
Log.d(
|
|
||||||
TAG,
|
|
||||||
"Added received message ${message.id} from $senderPeerID to unread list (${unreadCount} unread)"
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Non-mesh path (e.g., Nostr): add to UI state using existing logic
|
||||||
|
val inferredPeer = state.getSelectedPrivateChatPeerValue() ?: return
|
||||||
|
if (suppressUnread) {
|
||||||
|
messageManager.addPrivateMessageNoUnread(inferredPeer, message)
|
||||||
|
} else {
|
||||||
|
messageManager.addPrivateMessage(inferredPeer, message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -322,27 +324,33 @@ class PrivateChatManager(
|
|||||||
* Called when the user focuses on a private chat
|
* Called when the user focuses on a private chat
|
||||||
*/
|
*/
|
||||||
fun sendReadReceiptsForPeer(peerID: String, meshService: BluetoothMeshService) {
|
fun sendReadReceiptsForPeer(peerID: String, meshService: BluetoothMeshService) {
|
||||||
val unreadList = unreadReceivedMessages[peerID]
|
// Collect candidate messages: all incoming messages from this peer in the conversation
|
||||||
if (unreadList.isNullOrEmpty()) {
|
val chats = try { state.getPrivateChatsValue() } catch (_: Exception) { emptyMap<String, List<BitchatMessage>>() }
|
||||||
Log.d(TAG, "No unread messages to send read receipts for peer $peerID")
|
val messages = chats[peerID].orEmpty()
|
||||||
return
|
|
||||||
|
if (messages.isEmpty()) {
|
||||||
|
Log.d(TAG, "No messages found for peer $peerID to send read receipts")
|
||||||
}
|
}
|
||||||
|
|
||||||
Log.d(TAG, "Sending read receipts for ${unreadList.size} unread messages from $peerID")
|
val myNickname = state.getNicknameValue() ?: "unknown"
|
||||||
|
var sentCount = 0
|
||||||
// Send read receipt for each unread message - now using direct method call
|
messages.forEach { msg ->
|
||||||
unreadList.forEach { message ->
|
// Only for incoming messages from this peer
|
||||||
try {
|
if (msg.senderPeerID == peerID) {
|
||||||
val myNickname = state.getNicknameValue() ?: "unknown"
|
try {
|
||||||
meshService.sendReadReceipt(message.id, peerID, myNickname)
|
meshService.sendReadReceipt(msg.id, peerID, myNickname)
|
||||||
Log.d(TAG, "Sent read receipt for message ${message.id} to $peerID")
|
sentCount += 1
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.w(TAG, "Failed to send read receipt for message ${message.id}: ${e.message}")
|
Log.w(TAG, "Failed to send read receipt for message ${msg.id}: ${e.message}")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear the unread list since we've sent read receipts
|
// Clear any locally tracked unread queue for this peer
|
||||||
unreadReceivedMessages.remove(peerID)
|
unreadReceivedMessages.remove(peerID)
|
||||||
|
// Also clear UI unread marker for this peer now that chat is focused/read
|
||||||
|
try { messageManager.clearPrivateUnreadMessages(peerID) } catch (_: Exception) { }
|
||||||
|
Log.d(TAG, "Sent $sentCount read receipts for peer $peerID (from conversation messages)")
|
||||||
}
|
}
|
||||||
|
|
||||||
fun cleanupDisconnectedPeer(peerID: String) {
|
fun cleanupDisconnectedPeer(peerID: String) {
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ object DebugPreferenceManager {
|
|||||||
// GCS keys (no migration/back-compat)
|
// GCS keys (no migration/back-compat)
|
||||||
private const val KEY_GCS_MAX_BYTES = "gcs_max_filter_bytes"
|
private const val KEY_GCS_MAX_BYTES = "gcs_max_filter_bytes"
|
||||||
private const val KEY_GCS_FPR = "gcs_filter_fpr_percent"
|
private const val KEY_GCS_FPR = "gcs_filter_fpr_percent"
|
||||||
|
// Removed: persistent notification toggle is now governed by MeshServicePreferences.isBackgroundEnabled
|
||||||
|
|
||||||
private lateinit var prefs: SharedPreferences
|
private lateinit var prefs: SharedPreferences
|
||||||
|
|
||||||
@@ -100,4 +101,6 @@ object DebugPreferenceManager {
|
|||||||
fun setGcsFprPercent(value: Double) {
|
fun setGcsFprPercent(value: Double) {
|
||||||
if (ready()) prefs.edit().putLong(KEY_GCS_FPR, java.lang.Double.doubleToRawLongBits(value)).apply()
|
if (ready()) prefs.edit().putLong(KEY_GCS_FPR, java.lang.Double.doubleToRawLongBits(value)).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// No longer storing persistent notification in debug prefs.
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,6 +36,11 @@ class DebugSettingsManager private constructor() {
|
|||||||
private val _packetRelayEnabled = MutableStateFlow(true)
|
private val _packetRelayEnabled = MutableStateFlow(true)
|
||||||
val packetRelayEnabled: StateFlow<Boolean> = _packetRelayEnabled.asStateFlow()
|
val packetRelayEnabled: StateFlow<Boolean> = _packetRelayEnabled.asStateFlow()
|
||||||
|
|
||||||
|
// Visibility of the debug sheet; gates heavy work
|
||||||
|
private val _debugSheetVisible = MutableStateFlow(false)
|
||||||
|
val debugSheetVisible: StateFlow<Boolean> = _debugSheetVisible.asStateFlow()
|
||||||
|
fun setDebugSheetVisible(visible: Boolean) { _debugSheetVisible.value = visible }
|
||||||
|
|
||||||
// Connection limit overrides (debug)
|
// Connection limit overrides (debug)
|
||||||
private val _maxConnectionsOverall = MutableStateFlow(8)
|
private val _maxConnectionsOverall = MutableStateFlow(8)
|
||||||
val maxConnectionsOverall: StateFlow<Int> = _maxConnectionsOverall.asStateFlow()
|
val maxConnectionsOverall: StateFlow<Int> = _maxConnectionsOverall.asStateFlow()
|
||||||
@@ -75,12 +80,63 @@ class DebugSettingsManager private constructor() {
|
|||||||
|
|
||||||
// Timestamps to compute rolling window stats
|
// Timestamps to compute rolling window stats
|
||||||
private val relayTimestamps = ConcurrentLinkedQueue<Long>()
|
private val relayTimestamps = ConcurrentLinkedQueue<Long>()
|
||||||
|
// Per-device and per-peer rolling timestamps for stacked graphs
|
||||||
|
private val perDeviceRelayTimestamps = mutableMapOf<String, ConcurrentLinkedQueue<Long>>()
|
||||||
|
private val perPeerRelayTimestamps = mutableMapOf<String, ConcurrentLinkedQueue<Long>>()
|
||||||
|
|
||||||
|
// Additional buckets to split incoming vs outgoing
|
||||||
|
private val incomingTimestamps = ConcurrentLinkedQueue<Long>()
|
||||||
|
private val outgoingTimestamps = ConcurrentLinkedQueue<Long>()
|
||||||
|
private val perDeviceIncoming = mutableMapOf<String, ConcurrentLinkedQueue<Long>>()
|
||||||
|
private val perDeviceOutgoing = mutableMapOf<String, ConcurrentLinkedQueue<Long>>()
|
||||||
|
private val perPeerIncoming = mutableMapOf<String, ConcurrentLinkedQueue<Long>>()
|
||||||
|
private val perPeerOutgoing = mutableMapOf<String, ConcurrentLinkedQueue<Long>>()
|
||||||
|
|
||||||
|
// Expose current per-second rates (updated when logging/pruning occurs)
|
||||||
|
private val _perDeviceLastSecond: MutableStateFlow<Map<String, Int>> = MutableStateFlow(emptyMap())
|
||||||
|
val perDeviceLastSecond: StateFlow<Map<String, Int>> = _perDeviceLastSecond.asStateFlow()
|
||||||
|
private val _perPeerLastSecond: MutableStateFlow<Map<String, Int>> = MutableStateFlow(emptyMap())
|
||||||
|
val perPeerLastSecond: StateFlow<Map<String, Int>> = _perPeerLastSecond.asStateFlow()
|
||||||
|
// New flows used by UI for incoming/outgoing stacked plots
|
||||||
|
private val _perDeviceIncomingLastSecond: MutableStateFlow<Map<String, Int>> = MutableStateFlow(emptyMap())
|
||||||
|
val perDeviceIncomingLastSecond: StateFlow<Map<String, Int>> = _perDeviceIncomingLastSecond.asStateFlow()
|
||||||
|
private val _perDeviceOutgoingLastSecond: MutableStateFlow<Map<String, Int>> = MutableStateFlow(emptyMap())
|
||||||
|
val perDeviceOutgoingLastSecond: StateFlow<Map<String, Int>> = _perDeviceOutgoingLastSecond.asStateFlow()
|
||||||
|
private val _perPeerIncomingLastSecond: MutableStateFlow<Map<String, Int>> = MutableStateFlow(emptyMap())
|
||||||
|
val perPeerIncomingLastSecond: StateFlow<Map<String, Int>> = _perPeerIncomingLastSecond.asStateFlow()
|
||||||
|
private val _perPeerOutgoingLastSecond: MutableStateFlow<Map<String, Int>> = MutableStateFlow(emptyMap())
|
||||||
|
val perPeerOutgoingLastSecond: StateFlow<Map<String, Int>> = _perPeerOutgoingLastSecond.asStateFlow()
|
||||||
|
|
||||||
|
// Per-minute counts per key
|
||||||
|
private val _perDeviceIncomingLastMinute: MutableStateFlow<Map<String, Int>> = MutableStateFlow(emptyMap())
|
||||||
|
val perDeviceIncomingLastMinute: StateFlow<Map<String, Int>> = _perDeviceIncomingLastMinute.asStateFlow()
|
||||||
|
private val _perDeviceOutgoingLastMinute: MutableStateFlow<Map<String, Int>> = MutableStateFlow(emptyMap())
|
||||||
|
val perDeviceOutgoingLastMinute: StateFlow<Map<String, Int>> = _perDeviceOutgoingLastMinute.asStateFlow()
|
||||||
|
private val _perPeerIncomingLastMinute: MutableStateFlow<Map<String, Int>> = MutableStateFlow(emptyMap())
|
||||||
|
val perPeerIncomingLastMinute: StateFlow<Map<String, Int>> = _perPeerIncomingLastMinute.asStateFlow()
|
||||||
|
private val _perPeerOutgoingLastMinute: MutableStateFlow<Map<String, Int>> = MutableStateFlow(emptyMap())
|
||||||
|
val perPeerOutgoingLastMinute: StateFlow<Map<String, Int>> = _perPeerOutgoingLastMinute.asStateFlow()
|
||||||
|
|
||||||
|
// Totals per key (since app start)
|
||||||
|
private val deviceIncomingTotalsMap = mutableMapOf<String, Long>()
|
||||||
|
private val deviceOutgoingTotalsMap = mutableMapOf<String, Long>()
|
||||||
|
private val peerIncomingTotalsMap = mutableMapOf<String, Long>()
|
||||||
|
private val peerOutgoingTotalsMap = mutableMapOf<String, Long>()
|
||||||
|
private val _perDeviceIncomingTotalsFlow: MutableStateFlow<Map<String, Long>> = MutableStateFlow(emptyMap())
|
||||||
|
val perDeviceIncomingTotal: StateFlow<Map<String, Long>> = _perDeviceIncomingTotalsFlow.asStateFlow()
|
||||||
|
private val _perDeviceOutgoingTotalsFlow: MutableStateFlow<Map<String, Long>> = MutableStateFlow(emptyMap())
|
||||||
|
val perDeviceOutgoingTotal: StateFlow<Map<String, Long>> = _perDeviceOutgoingTotalsFlow.asStateFlow()
|
||||||
|
private val _perPeerIncomingTotalsFlow: MutableStateFlow<Map<String, Long>> = MutableStateFlow(emptyMap())
|
||||||
|
val perPeerIncomingTotal: StateFlow<Map<String, Long>> = _perPeerIncomingTotalsFlow.asStateFlow()
|
||||||
|
private val _perPeerOutgoingTotalsFlow: MutableStateFlow<Map<String, Long>> = MutableStateFlow(emptyMap())
|
||||||
|
val perPeerOutgoingTotal: StateFlow<Map<String, Long>> = _perPeerOutgoingTotalsFlow.asStateFlow()
|
||||||
|
|
||||||
// Internal data storage for managing debug data
|
// Internal data storage for managing debug data
|
||||||
private val debugMessageQueue = ConcurrentLinkedQueue<DebugMessage>()
|
private val debugMessageQueue = ConcurrentLinkedQueue<DebugMessage>()
|
||||||
private val scanResultsQueue = ConcurrentLinkedQueue<DebugScanResult>()
|
private val scanResultsQueue = ConcurrentLinkedQueue<DebugScanResult>()
|
||||||
|
|
||||||
private fun updateRelayStatsFromTimestamps() {
|
private fun updateRelayStatsFromTimestamps() {
|
||||||
|
if (!_debugSheetVisible.value) return
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
// prune older than 15m
|
// prune older than 15m
|
||||||
while (true) {
|
while (true) {
|
||||||
@@ -89,18 +145,84 @@ class DebugSettingsManager private constructor() {
|
|||||||
relayTimestamps.poll()
|
relayTimestamps.poll()
|
||||||
} else break
|
} else break
|
||||||
}
|
}
|
||||||
|
// prune per-device and per-peer and compute 1s/60s rates
|
||||||
|
fun pruneAndCount1s(map: MutableMap<String, ConcurrentLinkedQueue<Long>>): Map<String, Int> {
|
||||||
|
val result = mutableMapOf<String, Int>()
|
||||||
|
val iterator = map.entries.iterator()
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
val (key, q) = iterator.next()
|
||||||
|
// prune this queue
|
||||||
|
while (true) {
|
||||||
|
val ts = q.peek() ?: break
|
||||||
|
if (now - ts > 15 * 60 * 1000L) {
|
||||||
|
q.poll()
|
||||||
|
} else break
|
||||||
|
}
|
||||||
|
// count last 1s only
|
||||||
|
val count1s = q.count { now - it <= 1_000L }
|
||||||
|
if (q.isEmpty()) {
|
||||||
|
// cleanup empty queues to prevent unbounded growth
|
||||||
|
iterator.remove()
|
||||||
|
}
|
||||||
|
if (count1s > 0) result[key] = count1s
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
fun pruneAndCount60s(map: MutableMap<String, ConcurrentLinkedQueue<Long>>): Map<String, Int> {
|
||||||
|
val result = mutableMapOf<String, Int>()
|
||||||
|
map.forEach { (key, q) ->
|
||||||
|
val count60 = q.count { now - it <= 60_000L }
|
||||||
|
if (count60 > 0) result[key] = count60
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
val perDevice1s = pruneAndCount1s(perDeviceRelayTimestamps)
|
||||||
|
val perPeer1s = pruneAndCount1s(perPeerRelayTimestamps)
|
||||||
|
|
||||||
|
_perDeviceLastSecond.value = perDevice1s
|
||||||
|
_perPeerLastSecond.value = perPeer1s
|
||||||
|
// Also compute incoming/outgoing per-key rates
|
||||||
|
_perDeviceIncomingLastSecond.value = pruneAndCount1s(perDeviceIncoming)
|
||||||
|
_perDeviceOutgoingLastSecond.value = pruneAndCount1s(perDeviceOutgoing)
|
||||||
|
_perPeerIncomingLastSecond.value = pruneAndCount1s(perPeerIncoming)
|
||||||
|
_perPeerOutgoingLastSecond.value = pruneAndCount1s(perPeerOutgoing)
|
||||||
|
_perDeviceIncomingLastMinute.value = pruneAndCount60s(perDeviceIncoming)
|
||||||
|
_perDeviceOutgoingLastMinute.value = pruneAndCount60s(perDeviceOutgoing)
|
||||||
|
_perPeerIncomingLastMinute.value = pruneAndCount60s(perPeerIncoming)
|
||||||
|
_perPeerOutgoingLastMinute.value = pruneAndCount60s(perPeerOutgoing)
|
||||||
val last1s = relayTimestamps.count { now - it <= 1_000L }
|
val last1s = relayTimestamps.count { now - it <= 1_000L }
|
||||||
val last10s = relayTimestamps.count { now - it <= 10_000L }
|
val last10s = relayTimestamps.count { now - it <= 10_000L }
|
||||||
val last1m = relayTimestamps.count { now - it <= 60_000L }
|
val last1m = relayTimestamps.count { now - it <= 60_000L }
|
||||||
val last15m = relayTimestamps.size
|
val last15m = relayTimestamps.size
|
||||||
val total = _relayStats.value.totalRelaysCount + 1
|
// And incoming/outgoing per-second counters
|
||||||
|
val last1sIncoming = incomingTimestamps.count { now - it <= 1_000L }
|
||||||
|
val last1sOutgoing = outgoingTimestamps.count { now - it <= 1_000L }
|
||||||
|
val last10sIncoming = incomingTimestamps.count { now - it <= 10_000L }
|
||||||
|
val last10sOutgoing = outgoingTimestamps.count { now - it <= 10_000L }
|
||||||
|
val last1mIncoming = incomingTimestamps.count { now - it <= 60_000L }
|
||||||
|
val last1mOutgoing = outgoingTimestamps.count { now - it <= 60_000L }
|
||||||
|
val last15mIncoming = incomingTimestamps.size
|
||||||
|
val last15mOutgoing = outgoingTimestamps.size
|
||||||
|
val totalIncoming = _relayStats.value.totalIncomingCount
|
||||||
|
val totalOutgoing = _relayStats.value.totalOutgoingCount
|
||||||
_relayStats.value = PacketRelayStats(
|
_relayStats.value = PacketRelayStats(
|
||||||
totalRelaysCount = total,
|
totalRelaysCount = totalIncoming + totalOutgoing,
|
||||||
lastSecondRelays = last1s,
|
lastSecondRelays = last1s,
|
||||||
last10SecondRelays = last10s,
|
last10SecondRelays = last10s,
|
||||||
lastMinuteRelays = last1m,
|
lastMinuteRelays = last1m,
|
||||||
last15MinuteRelays = last15m,
|
last15MinuteRelays = last15m,
|
||||||
lastResetTime = _relayStats.value.lastResetTime
|
lastResetTime = _relayStats.value.lastResetTime,
|
||||||
|
lastSecondIncoming = last1sIncoming,
|
||||||
|
lastSecondOutgoing = last1sOutgoing,
|
||||||
|
last10SecondIncoming = last10sIncoming,
|
||||||
|
last10SecondOutgoing = last10sOutgoing,
|
||||||
|
lastMinuteIncoming = last1mIncoming,
|
||||||
|
lastMinuteOutgoing = last1mOutgoing,
|
||||||
|
last15MinuteIncoming = last15mIncoming,
|
||||||
|
last15MinuteOutgoing = last15mOutgoing,
|
||||||
|
totalIncomingCount = totalIncoming,
|
||||||
|
totalOutgoingCount = totalOutgoing
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -336,11 +458,61 @@ class DebugSettingsManager private constructor() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update rolling statistics only for relays
|
// Do not update counters here; this path is for readable logs only.
|
||||||
if (isRelay) {
|
}
|
||||||
relayTimestamps.offer(System.currentTimeMillis())
|
|
||||||
updateRelayStatsFromTimestamps()
|
// Explicit incoming/outgoing logging to avoid double counting
|
||||||
|
fun logIncoming(packetType: String, fromPeerID: String?, fromNickname: String?, fromDeviceAddress: String?) {
|
||||||
|
if (verboseLoggingEnabled.value) {
|
||||||
|
val who = fromNickname ?: fromPeerID ?: "unknown"
|
||||||
|
addDebugMessage(DebugMessage.PacketEvent("📥 Incoming $packetType from $who (${fromPeerID ?: "?"}, ${fromDeviceAddress ?: "?"})"))
|
||||||
}
|
}
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
val visible = _debugSheetVisible.value
|
||||||
|
if (visible) incomingTimestamps.offer(now)
|
||||||
|
fromDeviceAddress?.let {
|
||||||
|
perDeviceIncoming.getOrPut(it) { ConcurrentLinkedQueue() }.offer(now)
|
||||||
|
deviceIncomingTotalsMap[it] = (deviceIncomingTotalsMap[it] ?: 0L) + 1L
|
||||||
|
_perDeviceIncomingTotalsFlow.value = deviceIncomingTotalsMap.toMap()
|
||||||
|
}
|
||||||
|
fromPeerID?.let {
|
||||||
|
perPeerIncoming.getOrPut(it) { ConcurrentLinkedQueue() }.offer(now)
|
||||||
|
peerIncomingTotalsMap[it] = (peerIncomingTotalsMap[it] ?: 0L) + 1L
|
||||||
|
_perPeerIncomingTotalsFlow.value = peerIncomingTotalsMap.toMap()
|
||||||
|
}
|
||||||
|
// bump totals
|
||||||
|
val cur = _relayStats.value
|
||||||
|
_relayStats.value = cur.copy(
|
||||||
|
totalIncomingCount = cur.totalIncomingCount + 1,
|
||||||
|
totalRelaysCount = cur.totalRelaysCount + 1
|
||||||
|
)
|
||||||
|
if (visible) updateRelayStatsFromTimestamps()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun logOutgoing(packetType: String, toPeerID: String?, toNickname: String?, toDeviceAddress: String?, previousHopPeerID: String? = null) {
|
||||||
|
if (verboseLoggingEnabled.value) {
|
||||||
|
val who = toNickname ?: toPeerID ?: "unknown"
|
||||||
|
addDebugMessage(DebugMessage.PacketEvent("📤 Outgoing $packetType to $who (${toPeerID ?: "?"}, ${toDeviceAddress ?: "?"})"))
|
||||||
|
}
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
val visible = _debugSheetVisible.value
|
||||||
|
if (visible) outgoingTimestamps.offer(now)
|
||||||
|
toDeviceAddress?.let {
|
||||||
|
perDeviceOutgoing.getOrPut(it) { ConcurrentLinkedQueue() }.offer(now)
|
||||||
|
deviceOutgoingTotalsMap[it] = (deviceOutgoingTotalsMap[it] ?: 0L) + 1L
|
||||||
|
_perDeviceOutgoingTotalsFlow.value = deviceOutgoingTotalsMap.toMap()
|
||||||
|
}
|
||||||
|
(toPeerID ?: previousHopPeerID)?.let {
|
||||||
|
perPeerOutgoing.getOrPut(it) { ConcurrentLinkedQueue() }.offer(now)
|
||||||
|
peerOutgoingTotalsMap[it] = (peerOutgoingTotalsMap[it] ?: 0L) + 1L
|
||||||
|
_perPeerOutgoingTotalsFlow.value = peerOutgoingTotalsMap.toMap()
|
||||||
|
}
|
||||||
|
val cur = _relayStats.value
|
||||||
|
_relayStats.value = cur.copy(
|
||||||
|
totalOutgoingCount = cur.totalOutgoingCount + 1,
|
||||||
|
totalRelaysCount = cur.totalRelaysCount + 1
|
||||||
|
)
|
||||||
|
if (visible) updateRelayStatsFromTimestamps()
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Clear Data
|
// MARK: - Clear Data
|
||||||
@@ -407,5 +579,15 @@ data class PacketRelayStats(
|
|||||||
val last10SecondRelays: Int = 0,
|
val last10SecondRelays: Int = 0,
|
||||||
val lastMinuteRelays: Int = 0,
|
val lastMinuteRelays: Int = 0,
|
||||||
val last15MinuteRelays: Int = 0,
|
val last15MinuteRelays: Int = 0,
|
||||||
val lastResetTime: Date = Date()
|
val lastResetTime: Date = Date(),
|
||||||
|
val lastSecondIncoming: Int = 0,
|
||||||
|
val lastSecondOutgoing: Int = 0,
|
||||||
|
val last10SecondIncoming: Int = 0,
|
||||||
|
val last10SecondOutgoing: Int = 0,
|
||||||
|
val lastMinuteIncoming: Int = 0,
|
||||||
|
val lastMinuteOutgoing: Int = 0,
|
||||||
|
val last15MinuteIncoming: Int = 0,
|
||||||
|
val last15MinuteOutgoing: Int = 0,
|
||||||
|
val totalIncomingCount: Long = 0,
|
||||||
|
val totalOutgoingCount: Long = 0
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -3,9 +3,11 @@ package com.bitchat.android.ui.debug
|
|||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.layout.*
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.layout.FlowRow
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.items
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.Bluetooth
|
import androidx.compose.material.icons.filled.Bluetooth
|
||||||
import androidx.compose.material.icons.filled.BugReport
|
import androidx.compose.material.icons.filled.BugReport
|
||||||
@@ -15,6 +17,7 @@ import androidx.compose.material.icons.filled.PowerSettingsNew
|
|||||||
import androidx.compose.material.icons.filled.SettingsEthernet
|
import androidx.compose.material.icons.filled.SettingsEthernet
|
||||||
import androidx.compose.material3.*
|
import androidx.compose.material3.*
|
||||||
import androidx.compose.runtime.*
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
@@ -27,8 +30,13 @@ import com.bitchat.android.mesh.BluetoothMeshService
|
|||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import com.bitchat.android.R
|
import com.bitchat.android.R
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import com.bitchat.android.service.MeshServicePreferences
|
||||||
|
import com.bitchat.android.service.MeshForegroundService
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
private enum class GraphMode { OVERALL, PER_DEVICE, PER_PEER }
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun DebugSettingsSheet(
|
fun DebugSettingsSheet(
|
||||||
isPresented: Boolean,
|
isPresented: Boolean,
|
||||||
@@ -53,6 +61,8 @@ fun DebugSettingsSheet(
|
|||||||
val seenCapacity by manager.seenPacketCapacity.collectAsState()
|
val seenCapacity by manager.seenPacketCapacity.collectAsState()
|
||||||
val gcsMaxBytes by manager.gcsMaxBytes.collectAsState()
|
val gcsMaxBytes by manager.gcsMaxBytes.collectAsState()
|
||||||
val gcsFpr by manager.gcsFprPercent.collectAsState()
|
val gcsFpr by manager.gcsFprPercent.collectAsState()
|
||||||
|
val context = LocalContext.current
|
||||||
|
// Persistent notification is now controlled solely by MeshServicePreferences.isBackgroundEnabled
|
||||||
|
|
||||||
// Push live connected devices from mesh service whenever sheet is visible
|
// Push live connected devices from mesh service whenever sheet is visible
|
||||||
LaunchedEffect(isPresented) {
|
LaunchedEffect(isPresented) {
|
||||||
@@ -89,6 +99,11 @@ fun DebugSettingsSheet(
|
|||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
sheetState = sheetState
|
sheetState = sheetState
|
||||||
) {
|
) {
|
||||||
|
// Mark debug sheet visible/invisible to gate heavy work
|
||||||
|
LaunchedEffect(Unit) { DebugSettingsManager.getInstance().setDebugSheetVisible(true) }
|
||||||
|
DisposableEffect(Unit) {
|
||||||
|
onDispose { DebugSettingsManager.getInstance().setDebugSheetVisible(false) }
|
||||||
|
}
|
||||||
LazyColumn(
|
LazyColumn(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
@@ -202,88 +217,256 @@ fun DebugSettingsSheet(
|
|||||||
item {
|
item {
|
||||||
Surface(shape = RoundedCornerShape(12.dp), color = colorScheme.surfaceVariant.copy(alpha = 0.2f)) {
|
Surface(shape = RoundedCornerShape(12.dp), color = colorScheme.surfaceVariant.copy(alpha = 0.2f)) {
|
||||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
|
// Persistent notification is controlled by About sheet (MeshServicePreferences.isBackgroundEnabled)
|
||||||
|
|
||||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
Icon(Icons.Filled.PowerSettingsNew, contentDescription = null, tint = Color(0xFFFF9500))
|
Icon(Icons.Filled.PowerSettingsNew, contentDescription = null, tint = Color(0xFFFF9500))
|
||||||
Text(stringResource(R.string.debug_packet_relay), fontFamily = FontFamily.Monospace, fontSize = 14.sp, fontWeight = FontWeight.Medium)
|
Text(stringResource(R.string.debug_packet_relay), fontFamily = FontFamily.Monospace, fontSize = 14.sp, fontWeight = FontWeight.Medium)
|
||||||
Spacer(Modifier.weight(1f))
|
Spacer(Modifier.weight(1f))
|
||||||
Switch(checked = packetRelayEnabled, onCheckedChange = { manager.setPacketRelayEnabled(it) })
|
Switch(checked = packetRelayEnabled, onCheckedChange = { manager.setPacketRelayEnabled(it) })
|
||||||
}
|
}
|
||||||
Text(stringResource(R.string.debug_since_start_fmt, relayStats.totalRelaysCount), fontFamily = FontFamily.Monospace, fontSize = 11.sp)
|
// Removed aggregate labels; we will show per-direction compact labels below titles
|
||||||
Text(stringResource(R.string.debug_relays_window_fmt, relayStats.last10SecondRelays, relayStats.lastMinuteRelays, relayStats.last15MinuteRelays), fontFamily = FontFamily.Monospace, fontSize = 11.sp)
|
// Toggle: overall vs per-connection vs per-peer
|
||||||
// Realtime graph: per-second relays, full-width canvas, bottom-up bars, fast decay
|
var graphMode by rememberSaveable { mutableStateOf(GraphMode.OVERALL) }
|
||||||
var series by remember { mutableStateOf(List(60) { 0f }) }
|
val perDeviceIncoming by manager.perDeviceIncomingLastSecond.collectAsState()
|
||||||
LaunchedEffect(isPresented) {
|
val perPeerIncoming by manager.perPeerIncomingLastSecond.collectAsState()
|
||||||
|
val perDeviceOutgoing by manager.perDeviceOutgoingLastSecond.collectAsState()
|
||||||
|
val perPeerOutgoing by manager.perPeerOutgoingLastSecond.collectAsState()
|
||||||
|
val perDeviceIncoming1m by manager.perDeviceIncomingLastMinute.collectAsState()
|
||||||
|
val perDeviceOutgoing1m by manager.perDeviceOutgoingLastMinute.collectAsState()
|
||||||
|
val perPeerIncoming1m by manager.perPeerIncomingLastMinute.collectAsState()
|
||||||
|
val perPeerOutgoing1m by manager.perPeerOutgoingLastMinute.collectAsState()
|
||||||
|
val perDeviceIncomingTotal by manager.perDeviceIncomingTotal.collectAsState()
|
||||||
|
val perDeviceOutgoingTotal by manager.perDeviceOutgoingTotal.collectAsState()
|
||||||
|
val perPeerIncomingTotal by manager.perPeerIncomingTotal.collectAsState()
|
||||||
|
val perPeerOutgoingTotal by manager.perPeerOutgoingTotal.collectAsState()
|
||||||
|
val nicknameMap = remember { mutableStateOf<Map<String, String?>>(emptyMap()) }
|
||||||
|
val devicePeerMap = remember { mutableStateOf<Map<String, String>>(emptyMap()) }
|
||||||
|
LaunchedEffect(Unit) {
|
||||||
|
try { nicknameMap.value = meshService.getPeerNicknames() } catch (_: Exception) { }
|
||||||
|
// Try to fetch device->peer map periodically for legend resolution
|
||||||
while (isPresented) {
|
while (isPresented) {
|
||||||
val s = relayStats.lastSecondRelays.toFloat()
|
try { devicePeerMap.value = meshService.getDeviceAddressToPeerMapping() } catch (_: Exception) { }
|
||||||
val last = series.lastOrNull() ?: 0f
|
kotlinx.coroutines.delay(1000)
|
||||||
// Faster decay and smoothing
|
|
||||||
val v = last * 0.5f + s * 0.5f
|
|
||||||
series = (series + v).takeLast(60)
|
|
||||||
kotlinx.coroutines.delay(400)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val maxValRaw = series.maxOrNull() ?: 0f
|
|
||||||
val maxVal = if (maxValRaw > 0f) maxValRaw else 0f
|
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
val leftGutter = 40.dp
|
// Mode selector
|
||||||
Box(Modifier.fillMaxWidth().height(56.dp)) {
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
// Graph canvas
|
FilterChip(
|
||||||
androidx.compose.foundation.Canvas(Modifier.fillMaxSize()) {
|
selected = graphMode == GraphMode.OVERALL,
|
||||||
val axisPx = leftGutter.toPx() // reserved left gutter for labels
|
onClick = { graphMode = GraphMode.OVERALL },
|
||||||
val barCount = series.size
|
label = { Text("Overall") }
|
||||||
val availW = (size.width - axisPx).coerceAtLeast(1f)
|
|
||||||
val w = availW / barCount
|
|
||||||
val h = size.height
|
|
||||||
// Baseline at bottom (y = 0)
|
|
||||||
drawLine(
|
|
||||||
color = Color(0x33888888),
|
|
||||||
start = androidx.compose.ui.geometry.Offset(axisPx, h - 1f),
|
|
||||||
end = androidx.compose.ui.geometry.Offset(size.width, h - 1f),
|
|
||||||
strokeWidth = 1f
|
|
||||||
)
|
)
|
||||||
// Bars from bottom-up; skip zeros entirely
|
FilterChip(
|
||||||
series.forEachIndexed { i, value ->
|
selected = graphMode == GraphMode.PER_DEVICE,
|
||||||
if (value > 0f && maxVal > 0f) {
|
onClick = { graphMode = GraphMode.PER_DEVICE },
|
||||||
val ratio = (value / maxVal).coerceIn(0f, 1f)
|
label = { Text("Per Device") },
|
||||||
val barHeight = (h * ratio).coerceAtLeast(0f)
|
leadingIcon = { Icon(Icons.Filled.Devices, contentDescription = null) }
|
||||||
if (barHeight > 0.5f) {
|
)
|
||||||
drawRect(
|
FilterChip(
|
||||||
color = Color(0xFF00C851),
|
selected = graphMode == GraphMode.PER_PEER,
|
||||||
topLeft = androidx.compose.ui.geometry.Offset(x = axisPx + i * w, y = h - barHeight),
|
onClick = { graphMode = GraphMode.PER_PEER },
|
||||||
size = androidx.compose.ui.geometry.Size(w, barHeight)
|
label = { Text("Per Peer") },
|
||||||
)
|
leadingIcon = { Icon(Icons.Filled.SettingsEthernet, contentDescription = null) }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Time series state
|
||||||
|
var overallSeriesIncoming by rememberSaveable { mutableStateOf(List(60) { 0f }) }
|
||||||
|
var overallSeriesOutgoing by rememberSaveable { mutableStateOf(List(60) { 0f }) }
|
||||||
|
var stackedKeysIncoming by rememberSaveable { mutableStateOf(listOf<String>()) }
|
||||||
|
var stackedKeysOutgoing by rememberSaveable { mutableStateOf(listOf<String>()) }
|
||||||
|
var stackedSeriesIncoming by rememberSaveable { mutableStateOf<Map<String, List<Float>>>(emptyMap()) }
|
||||||
|
var stackedSeriesOutgoing by rememberSaveable { mutableStateOf<Map<String, List<Float>>>(emptyMap()) }
|
||||||
|
var highlightedKey by rememberSaveable { mutableStateOf<String?>(null) }
|
||||||
|
|
||||||
|
// Color palette for stacked legend
|
||||||
|
val palette = remember {
|
||||||
|
listOf(
|
||||||
|
Color(0xFF00C851), Color(0xFF007AFF), Color(0xFFFF9500), Color(0xFFFF3B30),
|
||||||
|
Color(0xFF5AC8FA), Color(0xFFAF52DE), Color(0xFFFF2D55), Color(0xFF34C759),
|
||||||
|
Color(0xFFFFCC00), Color(0xFF5856D6)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val colorForKey = remember { mutableStateMapOf<String, Color>() }
|
||||||
|
fun stableColorFor(key: String): Color {
|
||||||
|
// Deterministic fallback color based on key hash using HSV palette
|
||||||
|
val h = (key.hashCode().toUInt().toInt() and 0x7FFFFFFF) % 360
|
||||||
|
return Color.hsv(h.toFloat(), 0.65f, 0.95f)
|
||||||
|
}
|
||||||
|
// Ensure colors are assigned for current keys before drawing
|
||||||
|
fun ensureColors(keys: List<String>) {
|
||||||
|
keys.forEachIndexed { idx, k ->
|
||||||
|
colorForKey.putIfAbsent(k, palette.getOrNull(idx) ?: stableColorFor(k))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(isPresented, graphMode) {
|
||||||
|
while (isPresented) {
|
||||||
|
when (graphMode) {
|
||||||
|
GraphMode.OVERALL -> {
|
||||||
|
val sIn = relayStats.lastSecondIncoming.toFloat()
|
||||||
|
val sOut = relayStats.lastSecondOutgoing.toFloat()
|
||||||
|
overallSeriesIncoming = (overallSeriesIncoming + sIn).takeLast(60)
|
||||||
|
overallSeriesOutgoing = (overallSeriesOutgoing + sOut).takeLast(60)
|
||||||
|
}
|
||||||
|
GraphMode.PER_DEVICE -> {
|
||||||
|
val snapshotIn = perDeviceIncoming
|
||||||
|
val snapshotOut = perDeviceOutgoing
|
||||||
|
fun advance(base: Map<String, List<Float>>, snap: Map<String, Int>): Map<String, List<Float>> {
|
||||||
|
val next = mutableMapOf<String, List<Float>>()
|
||||||
|
val union = (base.keys + snap.keys).toSet()
|
||||||
|
union.forEach { k ->
|
||||||
|
val prev = base[k] ?: List(60) { 0f }
|
||||||
|
val s = (snap[k] ?: 0).toFloat()
|
||||||
|
next[k] = (prev + s).takeLast(60)
|
||||||
|
}
|
||||||
|
return next
|
||||||
|
}
|
||||||
|
// Advance and prune fully-stale series (all-zero in visible window)
|
||||||
|
stackedSeriesIncoming = advance(stackedSeriesIncoming, snapshotIn).filterValues { series -> series.any { it != 0f } }
|
||||||
|
stackedSeriesOutgoing = advance(stackedSeriesOutgoing, snapshotOut).filterValues { series -> series.any { it != 0f } }
|
||||||
|
stackedKeysIncoming = stackedSeriesIncoming.keys.sorted()
|
||||||
|
stackedKeysOutgoing = stackedSeriesOutgoing.keys.sorted()
|
||||||
|
}
|
||||||
|
GraphMode.PER_PEER -> {
|
||||||
|
val snapshotIn = perPeerIncoming
|
||||||
|
val snapshotOut = perPeerOutgoing
|
||||||
|
fun advance(base: Map<String, List<Float>>, snap: Map<String, Int>): Map<String, List<Float>> {
|
||||||
|
val next = mutableMapOf<String, List<Float>>()
|
||||||
|
val union = (base.keys + snap.keys).toSet()
|
||||||
|
union.forEach { k ->
|
||||||
|
val prev = base[k] ?: List(60) { 0f }
|
||||||
|
val s = (snap[k] ?: 0).toFloat()
|
||||||
|
next[k] = (prev + s).takeLast(60)
|
||||||
|
}
|
||||||
|
return next
|
||||||
|
}
|
||||||
|
stackedSeriesIncoming = advance(stackedSeriesIncoming, snapshotIn).filterValues { series -> series.any { it != 0f } }
|
||||||
|
stackedSeriesOutgoing = advance(stackedSeriesOutgoing, snapshotOut).filterValues { series -> series.any { it != 0f } }
|
||||||
|
stackedKeysIncoming = stackedSeriesIncoming.keys.sorted()
|
||||||
|
stackedKeysOutgoing = stackedSeriesOutgoing.keys.sorted()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
kotlinx.coroutines.delay(1000)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Left gutter layout: unit + ticks neatly aligned
|
|
||||||
Row(Modifier.fillMaxSize()) {
|
// Helper functions moved to top-level composable below to avoid scope issues
|
||||||
Box(Modifier.width(leftGutter).fillMaxHeight()) {
|
|
||||||
// Unit label on the far left, centered vertically
|
// Render two blocks: Incoming and Outgoing
|
||||||
Text(
|
Text("Incoming", fontFamily = FontFamily.Monospace, fontSize = 11.sp, color = colorScheme.onSurface.copy(alpha = 0.7f))
|
||||||
"p/s",
|
Text(
|
||||||
fontFamily = FontFamily.Monospace,
|
"${relayStats.lastSecondIncoming}/s • ${relayStats.lastMinuteIncoming}/m • ${relayStats.last15MinuteIncoming}/15m • total ${relayStats.totalIncomingCount}",
|
||||||
fontSize = 10.sp,
|
fontFamily = FontFamily.Monospace, fontSize = 10.sp, color = colorScheme.onSurface.copy(alpha = 0.6f)
|
||||||
color = colorScheme.onSurface.copy(alpha = 0.7f),
|
)
|
||||||
modifier = Modifier.align(Alignment.CenterStart).padding(start = 2.dp).rotate(-90f)
|
DrawGraphBlock(
|
||||||
)
|
title = "Incoming",
|
||||||
// Tick labels right-aligned in gutter, top and bottom aligned
|
stackedKeys = stackedKeysIncoming,
|
||||||
Text(
|
stackedSeries = stackedSeriesIncoming,
|
||||||
"${maxVal.toInt()}",
|
overallSeries = if (graphMode == GraphMode.OVERALL) overallSeriesIncoming else null,
|
||||||
fontFamily = FontFamily.Monospace,
|
graphMode = graphMode,
|
||||||
fontSize = 10.sp,
|
highlightedKey = highlightedKey,
|
||||||
color = colorScheme.onSurface.copy(alpha = 0.7f),
|
onToggleHighlight = { key -> highlightedKey = if (highlightedKey == key) null else key },
|
||||||
modifier = Modifier.align(Alignment.TopEnd).padding(end = 4.dp, top = 0.dp)
|
ensureColors = { keys -> ensureColors(keys) },
|
||||||
)
|
colorForKey = { k -> colorForKey[k] ?: stableColorFor(k) },
|
||||||
Text(
|
legendTitleFor = { key ->
|
||||||
"0",
|
when (graphMode) {
|
||||||
fontFamily = FontFamily.Monospace,
|
GraphMode.PER_PEER -> {
|
||||||
fontSize = 10.sp,
|
val nick = nicknameMap.value[key]
|
||||||
color = colorScheme.onSurface.copy(alpha = 0.7f),
|
val prefix = key.take(6)
|
||||||
modifier = Modifier.align(Alignment.BottomEnd).padding(end = 4.dp, bottom = 0.dp)
|
if (!nick.isNullOrBlank()) "$nick ($prefix)" else prefix
|
||||||
)
|
}
|
||||||
|
GraphMode.PER_DEVICE -> {
|
||||||
|
val device = key
|
||||||
|
val pid = connectedDevices.firstOrNull { it.deviceAddress == device }?.peerID
|
||||||
|
?: devicePeerMap.value[device]
|
||||||
|
if (pid != null) {
|
||||||
|
val nick = nicknameMap.value[pid]
|
||||||
|
val prefix = pid.take(6)
|
||||||
|
"$device (${if (!nick.isNullOrBlank()) "$nick ($prefix)" else prefix})"
|
||||||
|
} else device
|
||||||
|
}
|
||||||
|
else -> key
|
||||||
|
}
|
||||||
|
},
|
||||||
|
legendMetricsFor = { key ->
|
||||||
|
when (graphMode) {
|
||||||
|
GraphMode.PER_PEER -> {
|
||||||
|
val s = perPeerIncoming[key] ?: 0
|
||||||
|
val m = perPeerIncoming1m[key] ?: 0
|
||||||
|
val t = (perPeerIncomingTotal[key] ?: 0L)
|
||||||
|
"${s}/s • ${m}/m • total ${t}"
|
||||||
|
}
|
||||||
|
GraphMode.PER_DEVICE -> {
|
||||||
|
val s = perDeviceIncoming[key] ?: 0
|
||||||
|
val m = perDeviceIncoming1m[key] ?: 0
|
||||||
|
val t = (perDeviceIncomingTotal[key] ?: 0L)
|
||||||
|
"${s}/s • ${m}/m • total ${t}"
|
||||||
|
}
|
||||||
|
else -> ""
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Spacer(Modifier.weight(1f))
|
)
|
||||||
}
|
if (graphMode != GraphMode.OVERALL && stackedKeysIncoming.isNotEmpty()) { /* legend printed inside DrawGraphBlock */ }
|
||||||
|
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
|
Text("Outgoing", fontFamily = FontFamily.Monospace, fontSize = 11.sp, color = colorScheme.onSurface.copy(alpha = 0.7f))
|
||||||
|
Text(
|
||||||
|
"${relayStats.lastSecondOutgoing}/s • ${relayStats.lastMinuteOutgoing}/m • ${relayStats.last15MinuteOutgoing}/15m • total ${relayStats.totalOutgoingCount}",
|
||||||
|
fontFamily = FontFamily.Monospace, fontSize = 10.sp, color = colorScheme.onSurface.copy(alpha = 0.6f)
|
||||||
|
)
|
||||||
|
DrawGraphBlock(
|
||||||
|
title = "Outgoing",
|
||||||
|
stackedKeys = stackedKeysOutgoing,
|
||||||
|
stackedSeries = stackedSeriesOutgoing,
|
||||||
|
overallSeries = if (graphMode == GraphMode.OVERALL) overallSeriesOutgoing else null,
|
||||||
|
graphMode = graphMode,
|
||||||
|
highlightedKey = highlightedKey,
|
||||||
|
onToggleHighlight = { key -> highlightedKey = if (highlightedKey == key) null else key },
|
||||||
|
ensureColors = { keys -> ensureColors(keys) },
|
||||||
|
colorForKey = { k -> colorForKey[k] ?: stableColorFor(k) },
|
||||||
|
legendTitleFor = { key ->
|
||||||
|
when (graphMode) {
|
||||||
|
GraphMode.PER_PEER -> {
|
||||||
|
val nick = nicknameMap.value[key]
|
||||||
|
val prefix = key.take(6)
|
||||||
|
if (!nick.isNullOrBlank()) "$nick ($prefix)" else prefix
|
||||||
|
}
|
||||||
|
GraphMode.PER_DEVICE -> {
|
||||||
|
val device = key
|
||||||
|
val pid = connectedDevices.firstOrNull { it.deviceAddress == device }?.peerID
|
||||||
|
?: devicePeerMap.value[device]
|
||||||
|
if (pid != null) {
|
||||||
|
val nick = nicknameMap.value[pid]
|
||||||
|
val prefix = pid.take(6)
|
||||||
|
"$device (${if (!nick.isNullOrBlank()) "$nick ($prefix)" else prefix})"
|
||||||
|
} else device
|
||||||
|
}
|
||||||
|
else -> key
|
||||||
|
}
|
||||||
|
},
|
||||||
|
legendMetricsFor = { key ->
|
||||||
|
when (graphMode) {
|
||||||
|
GraphMode.PER_PEER -> {
|
||||||
|
val s = perPeerOutgoing[key] ?: 0
|
||||||
|
val m = perPeerOutgoing1m[key] ?: 0
|
||||||
|
val t = (perPeerOutgoingTotal[key] ?: 0L)
|
||||||
|
"${s}/s • ${m}/m • total ${t}"
|
||||||
|
}
|
||||||
|
GraphMode.PER_DEVICE -> {
|
||||||
|
val s = perDeviceOutgoing[key] ?: 0
|
||||||
|
val m = perDeviceOutgoing1m[key] ?: 0
|
||||||
|
val t = (perDeviceOutgoingTotal[key] ?: 0L)
|
||||||
|
"${s}/s • ${m}/m • total ${t}"
|
||||||
|
}
|
||||||
|
else -> ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
if (graphMode != GraphMode.OVERALL && stackedKeysOutgoing.isNotEmpty()) { /* legend printed inside DrawGraphBlock */ }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -399,3 +582,146 @@ fun DebugSettingsSheet(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun DrawGraphBlock(
|
||||||
|
title: String,
|
||||||
|
stackedKeys: List<String>,
|
||||||
|
stackedSeries: Map<String, List<Float>>,
|
||||||
|
overallSeries: List<Float>?,
|
||||||
|
graphMode: GraphMode,
|
||||||
|
highlightedKey: String?,
|
||||||
|
onToggleHighlight: (String) -> Unit,
|
||||||
|
ensureColors: (List<String>) -> Unit,
|
||||||
|
colorForKey: (String) -> Color,
|
||||||
|
legendTitleFor: (String) -> String,
|
||||||
|
legendMetricsFor: (String) -> String
|
||||||
|
) {
|
||||||
|
val colorScheme = MaterialTheme.colorScheme
|
||||||
|
val leftGutter = 40.dp
|
||||||
|
Box(Modifier.fillMaxWidth().height(56.dp)) {
|
||||||
|
androidx.compose.foundation.Canvas(Modifier.fillMaxSize()) {
|
||||||
|
val axisPx = leftGutter.toPx()
|
||||||
|
val barCount = 60
|
||||||
|
val availW = (size.width - axisPx).coerceAtLeast(1f)
|
||||||
|
val w = availW / barCount
|
||||||
|
val h = size.height
|
||||||
|
drawLine(
|
||||||
|
color = Color(0x33888888),
|
||||||
|
start = androidx.compose.ui.geometry.Offset(axisPx, h - 1f),
|
||||||
|
end = androidx.compose.ui.geometry.Offset(size.width, h - 1f),
|
||||||
|
strokeWidth = 1f
|
||||||
|
)
|
||||||
|
|
||||||
|
when (graphMode) {
|
||||||
|
GraphMode.OVERALL -> {
|
||||||
|
val maxValRaw = (overallSeries?.maxOrNull() ?: 0f)
|
||||||
|
val maxVal = if (maxValRaw > 0f) maxValRaw else 0f
|
||||||
|
(overallSeries ?: emptyList()).forEachIndexed { i, value ->
|
||||||
|
if (value > 0f && maxVal > 0f) {
|
||||||
|
val ratio = (value / maxVal).coerceIn(0f, 1f)
|
||||||
|
val barHeight = (h * ratio).coerceAtLeast(0f)
|
||||||
|
if (barHeight > 0.5f) {
|
||||||
|
drawRect(
|
||||||
|
color = Color(0xFF00C851),
|
||||||
|
topLeft = androidx.compose.ui.geometry.Offset(x = axisPx + i * w, y = h - barHeight),
|
||||||
|
size = androidx.compose.ui.geometry.Size(w, barHeight)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
val indices = 0 until 60
|
||||||
|
val totals = indices.map { idx ->
|
||||||
|
stackedSeries.values.sumOf { it.getOrNull(idx)?.toDouble() ?: 0.0 }.toFloat()
|
||||||
|
}
|
||||||
|
val maxTotal = (totals.maxOrNull() ?: 0f)
|
||||||
|
val drawKeysBars = if (stackedKeys.isNotEmpty()) stackedKeys else stackedSeries.keys.sorted()
|
||||||
|
indices.forEach { i ->
|
||||||
|
var yTop = h
|
||||||
|
if (maxTotal > 0f) {
|
||||||
|
ensureColors(drawKeysBars)
|
||||||
|
drawKeysBars.forEach { k ->
|
||||||
|
val v = stackedSeries[k]?.getOrNull(i) ?: 0f
|
||||||
|
if (v > 0f) {
|
||||||
|
val ratio = (v / maxTotal).coerceIn(0f, 1f)
|
||||||
|
val segH = (h * ratio)
|
||||||
|
if (segH > 0.5f) {
|
||||||
|
val top = (yTop - segH)
|
||||||
|
val baseColor = colorForKey(k)
|
||||||
|
val c = if (highlightedKey == null || highlightedKey == k) baseColor else baseColor.copy(alpha = 0.35f)
|
||||||
|
drawRect(
|
||||||
|
color = c,
|
||||||
|
topLeft = androidx.compose.ui.geometry.Offset(x = axisPx + i * w, y = top),
|
||||||
|
size = androidx.compose.ui.geometry.Size(w, segH)
|
||||||
|
)
|
||||||
|
yTop = top
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Row(Modifier.fillMaxSize()) {
|
||||||
|
Box(Modifier.width(leftGutter).fillMaxHeight()) {
|
||||||
|
Text(
|
||||||
|
"p/s",
|
||||||
|
fontFamily = FontFamily.Monospace,
|
||||||
|
fontSize = 10.sp,
|
||||||
|
color = colorScheme.onSurface.copy(alpha = 0.7f),
|
||||||
|
modifier = Modifier.align(Alignment.CenterStart).padding(start = 2.dp).rotate(-90f)
|
||||||
|
)
|
||||||
|
val topLabel = when (graphMode) {
|
||||||
|
GraphMode.OVERALL -> (overallSeries?.maxOrNull() ?: 0f).toInt().toString()
|
||||||
|
else -> {
|
||||||
|
val totals = (0 until 60).map { idx -> stackedSeries.values.sumOf { it.getOrNull(idx)?.toDouble() ?: 0.0 }.toFloat() }
|
||||||
|
(totals.maxOrNull() ?: 0f).toInt().toString()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
topLabel,
|
||||||
|
fontFamily = FontFamily.Monospace,
|
||||||
|
fontSize = 10.sp,
|
||||||
|
color = colorScheme.onSurface.copy(alpha = 0.7f),
|
||||||
|
modifier = Modifier.align(Alignment.TopEnd).padding(end = 4.dp)
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
"0",
|
||||||
|
fontFamily = FontFamily.Monospace,
|
||||||
|
fontSize = 10.sp,
|
||||||
|
color = colorScheme.onSurface.copy(alpha = 0.7f),
|
||||||
|
modifier = Modifier.align(Alignment.BottomEnd).padding(end = 4.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.weight(1f))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val drawKeys = if (stackedKeys.isNotEmpty()) stackedKeys else stackedSeries.keys.sorted()
|
||||||
|
if (graphMode != GraphMode.OVERALL && drawKeys.isNotEmpty()) {
|
||||||
|
Column(Modifier.fillMaxWidth()) {
|
||||||
|
FlowRow(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
drawKeys.forEach { key ->
|
||||||
|
val baseColor = colorForKey(key)
|
||||||
|
val dimmed = highlightedKey != null && highlightedKey != key
|
||||||
|
val swatchColor = if (dimmed) baseColor.copy(alpha = 0.35f) else baseColor
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||||
|
modifier = Modifier.clickable { onToggleHighlight(key) }
|
||||||
|
) {
|
||||||
|
Box(Modifier.size(10.dp).background(swatchColor, RoundedCornerShape(2.dp)))
|
||||||
|
Column {
|
||||||
|
Text(legendTitleFor(key), fontFamily = FontFamily.Monospace, fontSize = 10.sp, color = MaterialTheme.colorScheme.onSurface.copy(alpha = if (dimmed) 0.6f else 0.95f))
|
||||||
|
Text(legendMetricsFor(key), fontFamily = FontFamily.Monospace, fontSize = 9.sp, color = MaterialTheme.colorScheme.onSurface.copy(alpha = if (dimmed) 0.45f else 0.75f))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -80,8 +80,8 @@ object AppConstants {
|
|||||||
const val SCAN_ON_DURATION_ULTRA_LOW_MS: Long = 1_000L
|
const val SCAN_ON_DURATION_ULTRA_LOW_MS: Long = 1_000L
|
||||||
const val SCAN_OFF_DURATION_ULTRA_LOW_MS: Long = 10_000L
|
const val SCAN_OFF_DURATION_ULTRA_LOW_MS: Long = 10_000L
|
||||||
const val MAX_CONNECTIONS_NORMAL: Int = 8
|
const val MAX_CONNECTIONS_NORMAL: Int = 8
|
||||||
const val MAX_CONNECTIONS_POWER_SAVE: Int = 4
|
const val MAX_CONNECTIONS_POWER_SAVE: Int = 8
|
||||||
const val MAX_CONNECTIONS_ULTRA_LOW: Int = 2
|
const val MAX_CONNECTIONS_ULTRA_LOW: Int = 4
|
||||||
}
|
}
|
||||||
|
|
||||||
object Nostr {
|
object Nostr {
|
||||||
|
|||||||
@@ -61,6 +61,11 @@
|
|||||||
<string name="notification_more_locations">and %1$d more locations</string>
|
<string name="notification_more_locations">and %1$d more locations</string>
|
||||||
<string name="notification_and_more">and %1$d more</string>
|
<string name="notification_and_more">and %1$d more</string>
|
||||||
|
|
||||||
|
<!-- Mesh Service Foreground Notification -->
|
||||||
|
<string name="mesh_service_channel_name">Mesh Background Service</string>
|
||||||
|
<string name="mesh_service_channel_desc">Keeps the Bluetooth mesh running in the background</string>
|
||||||
|
<string name="mesh_service_notification_content">Mesh running — %1$d users connected</string>
|
||||||
|
|
||||||
<!-- Favorites accessibility -->
|
<!-- Favorites accessibility -->
|
||||||
<string name="cd_add_favorite">Add to favorites</string>
|
<string name="cd_add_favorite">Add to favorites</string>
|
||||||
<string name="cd_remove_favorite">Remove from favorites</string>
|
<string name="cd_remove_favorite">Remove from favorites</string>
|
||||||
@@ -152,6 +157,9 @@
|
|||||||
<string name="cd_remove_bookmark">Remove bookmark</string>
|
<string name="cd_remove_bookmark">Remove bookmark</string>
|
||||||
<string name="cd_teleport">Teleport</string>
|
<string name="cd_teleport">Teleport</string>
|
||||||
<string name="cd_selected">Selected</string>
|
<string name="cd_selected">Selected</string>
|
||||||
|
<string name="notification_action_quit_bitchat">Quit bitchat</string>
|
||||||
|
<string name="about_background_title">run in background</string>
|
||||||
|
<string name="about_background_desc">keep mesh active when app is closed (foreground service)</string>
|
||||||
<string name="cd_leave_channel">Leave channel</string>
|
<string name="cd_leave_channel">Leave channel</string>
|
||||||
<string name="cd_reachable_via_nostr">Reachable via Nostr</string>
|
<string name="cd_reachable_via_nostr">Reachable via Nostr</string>
|
||||||
<string name="cd_offline_favorite">Offline favorite</string>
|
<string name="cd_offline_favorite">Offline favorite</string>
|
||||||
|
|||||||
Reference in New Issue
Block a user