Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / whatsapp / WhatsAppLineSession.kt

WhatsAppLineSession.kt97 lines · 4.1 KiBRaw
1package com.vayunmathur.communicate.data.whatsapp
2
3import android.content.Context
4import com.vayunmathur.communicate.data.whatsapp.registration.WhatsAppDeviceFingerprint
5import com.vayunmathur.library.util.DataStoreUtils
6import kotlinx.coroutines.Dispatchers
7import kotlinx.coroutines.flow.Flow
8import kotlinx.coroutines.flow.SharedFlow
9import kotlinx.coroutines.flow.map
10import kotlinx.coroutines.withContext
11
12/**
13 * Session facade for the WhatsApp primary line, mirroring [GoogleVoiceSession]'s shape so the UI and
14 * the sync service treat all three lines (SIM / Google Voice / WhatsApp) uniformly.
15 *
16 * Owns the reactive sign-in flag + phone-number mirror in DataStore; the authoritative credentials
17 * live in [WhatsAppAuthData] (private prefs). Bridges the [WhatsAppClient] singleton's [state] +
18 * [events] out to callers.
19 */
20class WhatsAppLineSession private constructor(
21 private val store: DataStoreUtils,
22) {
23 /** Reactive sign-in state for the Accounts screen + line pickers. */
24 val signedInFlow: Flow<Boolean>
25 get() = store.booleanFlow(KEY_SIGNED_IN)
26
27 suspend fun isSignedIn(): Boolean = store.getBooleanAwait(KEY_SIGNED_IN, default = false)
28
29 val phoneNumberFlow: Flow<String?>
30 get() = store.stringFlow(KEY_PHONE_NUMBER).map { it }
31
32 suspend fun phoneNumber(): String? = store.getStringAwait(KEY_PHONE_NUMBER)
33
34 /** True when a completed registration is persisted (primary line is live). */
35 fun hasUsableCredentials(context: Context): Boolean =
36 WhatsAppAuthData.load(context)?.registered == true
37
38 /** Lifecycle state mapped from the client's internal handshake state machine. */
39 val state: Flow<WhatsAppState>
40 get() = WhatsAppClient.state.map { it.toPublic() }
41
42 /** The client's event stream. */
43 val events: SharedFlow<WhatsAppEvent>
44 get() = WhatsAppClient.events
45
46 /**
47 * Initialize + connect the primary client if we have usable credentials. Safe to call repeatedly
48 * (WhatsAppClient.init is idempotent). Call from the sync service / MainActivity.
49 */
50 suspend fun init(context: Context) {
51 WhatsAppClient.init(context.applicationContext)
52 // Suspend until the saved-auth load lands (on IO, never blocking the
53 // caller), preserving the old synchronous-init ordering.
54 WhatsAppClient.awaitInitAuth()
55 if (withContext(Dispatchers.IO) { hasUsableCredentials(context) }) {
56 WhatsAppClient.start()
57 }
58 }
59
60 /** Mark the line signed-in after a successful registration and start the client. */
61 suspend fun markRegistered(context: Context, auth: WhatsAppAuthData) {
62 store.setString(KEY_PHONE_NUMBER, auth.phoneNumber)
63 store.setBoolean(KEY_SIGNED_IN, true)
64 WhatsAppClient.init(context.applicationContext)
65 // Registration still waits for init's saved-auth load before
66 // proceeding (incl. the caller's onVerified), just not on Main:
67 // this suspends on the client's IO scope instead of runBlocking.
68 WhatsAppClient.awaitInitAuth()
69 WhatsAppClient.start()
70 }
71
72 suspend fun signOut(context: Context) {
73 WhatsAppClient.stop()
74 WhatsAppAuthData.clear(context)
75 WhatsAppDeviceFingerprint.clear(context)
76 store.removeKeys(listOf(KEY_PHONE_NUMBER))
77 store.setBoolean(KEY_SIGNED_IN, false)
78 }
79
80 /** Preference keys for the WhatsApp line session (signed-in flag, phone number). */
81 companion object {
82 private const val KEY_SIGNED_IN = "wa_signed_in"
83 private const val KEY_PHONE_NUMBER = "wa_phone_number"
84
85 fun get(context: Context): WhatsAppLineSession =
86 WhatsAppLineSession(DataStoreUtils.getInstance(context.applicationContext))
87 }
88}
89
90/** Map the client's internal [WhatsAppClient.State] to the public [WhatsAppState]. */
91private fun WhatsAppClient.State.toPublic(): WhatsAppState = when (this) {
92 is WhatsAppClient.State.Idle -> WhatsAppState.Disconnected
93 is WhatsAppClient.State.NeedsSetup -> WhatsAppState.Disconnected
94 is WhatsAppClient.State.Connecting -> WhatsAppState.Connecting
95 is WhatsAppClient.State.Connected -> WhatsAppState.Ready
96 is WhatsAppClient.State.Disconnected -> WhatsAppState.Disconnected
97}