Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions app/src/main/java/chat/stoat/api/routes/user/Relationships.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package chat.stoat.api.routes.user

import chat.stoat.api.StoatAPI
import chat.stoat.api.StoatAPIError
import chat.stoat.api.StoatHttp
import chat.stoat.api.StoatJson
Expand All @@ -13,6 +14,27 @@ import io.ktor.http.ContentType
import io.ktor.http.contentType
import kotlinx.serialization.SerializationException

private fun updateOutgoingRelationshipInCache(friendTag: String, userIdHint: String?) {
if (userIdHint != null) {
val byId = StoatAPI.userCache[userIdHint]
if (byId != null) {
StoatAPI.userCache[userIdHint] = byId.copy(relationship = "Outgoing")
return
}
}

val username = friendTag.substringBeforeLast("#", "")
val discriminator = friendTag.substringAfterLast("#", "")
if (username.isBlank() || discriminator.isBlank()) return

val user = StoatAPI.userCache.values.firstOrNull {
it.username == username && it.discriminator == discriminator
} ?: return

val userId = user.id ?: return
StoatAPI.userCache[userId] = user.copy(relationship = "Outgoing")
}

suspend fun blockUser(userId: String) {
val response = StoatHttp.put("/users/$userId/block".api())
.bodyAsText()
Expand All @@ -37,7 +59,7 @@ suspend fun unblockUser(userId: String) {
}
}

suspend fun friendUser(username: String) {
suspend fun friendUser(username: String, userIdHint: String? = null) {
val response = StoatHttp.post("/users/friend".api()) {
contentType(ContentType.Application.Json)
setBody(mapOf("username" to username))
Expand All @@ -48,7 +70,8 @@ suspend fun friendUser(username: String) {
val error = StoatJson.decodeFromString(StoatAPIError.serializer(), body)
throw Exception(error.type)
} catch (e: SerializationException) {
// Not an error
// Not an error. Apply a local cache fallback so UI updates immediately.
updateOutgoingRelationshipInCache(username, userIdHint)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ fun UserButtons(
onClick = {
scope.launch {
try {
friendUser("${user.username}#${user.discriminator}")
friendUser("${user.username}#${user.discriminator}", user.id)
} catch (e: Exception) {
// Button did nothing, but not an error
if (e.message == "NoEffect") return@launch
Expand All @@ -92,7 +92,7 @@ fun UserButtons(
onClick = {
scope.launch {
try {
friendUser("${user.username}#${user.discriminator}")
friendUser("${user.username}#${user.discriminator}", user.id)
} catch (e: Exception) {
if (e.message == "NoEffect") return@launch
logcat(LogPriority.ERROR) { e.asLog() }
Expand Down
Loading