-
Notifications
You must be signed in to change notification settings - Fork 1
/
NameProvider.kt
59 lines (51 loc) · 2.14 KB
/
NameProvider.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.dluvian.voyage.data.provider
import android.util.Log
import com.dluvian.nostr_kt.createNprofile
import com.dluvian.voyage.core.PubkeyHex
import com.dluvian.voyage.core.SHORT_DEBOUNCE
import com.dluvian.voyage.core.launchIO
import com.dluvian.voyage.data.inMemory.MetadataInMemory
import com.dluvian.voyage.data.nostr.NostrSubscriber
import com.dluvian.voyage.data.room.dao.ProfileDao
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import java.util.Collections
import java.util.concurrent.atomic.AtomicBoolean
private const val TAG = "NameProvider"
class NameProvider(
private val profileDao: ProfileDao,
private val nameCache: MutableMap<PubkeyHex, String?>,
private val nostrSubscriber: NostrSubscriber,
private val metadataInMemory: MetadataInMemory,
) {
private val scope = CoroutineScope(Dispatchers.IO)
private val subCache = Collections.synchronizedSet(mutableSetOf<PubkeyHex>())
private val isActive = AtomicBoolean(false)
fun getName(pubkey: PubkeyHex): String? {
val name = nameCache[pubkey]
if (!name.isNullOrEmpty()) return name
if (isActive.compareAndSet(false, true)) {
scope.launchIO {
val inMemoryName = metadataInMemory.getMetadata(pubkey = pubkey)?.name
if (!inMemoryName.isNullOrEmpty()) {
Log.d(TAG, "Found profile $pubkey in memory")
nameCache[pubkey] = inMemoryName
return@launchIO
}
val dbName = profileDao.getName(pubkey = pubkey)
if (!dbName.isNullOrEmpty()) {
Log.d(TAG, "Found profile $pubkey in database")
nameCache[pubkey] = dbName
return@launchIO
}
if (subCache.add(pubkey)) {
Log.d(TAG, "Sub unknown profile $pubkey")
nostrSubscriber.subProfile(nprofile = createNprofile(hex = pubkey))
delay(SHORT_DEBOUNCE)
}
}.invokeOnCompletion { isActive.set(false) }
}
return name
}
}