Skip to content

Commit 57e257f

Browse files
committed
merge: #85 DM inbox from /api/dm/conversations (PR #90)
2 parents 7e90909 + 0be5109 commit 57e257f

16 files changed

Lines changed: 474 additions & 83 deletions

File tree

‎feature/directmessages/src/androidTest/kotlin/com/interlinedlist/android/feature/directmessages/ui/InboxScreenTest.kt‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ class InboxScreenTest {
2222

2323
private fun conversation(username: String, unread: Boolean) = Conversation(
2424
username = username, displayName = "Adron Hall", avatarUrl = null,
25-
lastMessageBody = "hey there", lastMessageAtMillis = 1L, hasUnread = unread,
25+
lastMessageBody = "hey there", lastMessageAtMillis = 1L,
26+
unreadCount = if (unread) 1 else 0,
2627
)
2728

2829
@Test

‎feature/directmessages/src/main/kotlin/com/interlinedlist/android/feature/directmessages/data/DefaultDirectMessagesRepository.kt‎

Lines changed: 5 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,9 @@ import com.interlinedlist.android.core.common.result.ApiResult
55
import com.interlinedlist.android.core.common.result.map
66
import com.interlinedlist.android.core.network.error.safeApiCall
77
import com.interlinedlist.android.feature.directmessages.data.local.ConversationDao
8-
import com.interlinedlist.android.feature.directmessages.data.local.ConversationEntity
98
import com.interlinedlist.android.feature.directmessages.data.local.DirectMessageDao
109
import com.interlinedlist.android.feature.directmessages.data.local.DirectMessageEntity
1110
import com.interlinedlist.android.feature.directmessages.data.remote.DirectMessagesApi
12-
import com.interlinedlist.android.feature.directmessages.data.remote.dto.MessageDto
1311
import com.interlinedlist.android.feature.directmessages.data.remote.dto.RecipientDto
1412
import com.interlinedlist.android.feature.directmessages.data.remote.dto.SendMessageRequest
1513
import kotlinx.coroutines.flow.Flow
@@ -43,11 +41,12 @@ class DefaultDirectMessagesRepository @Inject constructor(
4341

4442
override suspend fun refreshInbox(cursor: String?): ApiResult<String?> =
4543
withContext(dispatchers.io) {
46-
safeApiCall(json) { api.getInbox(cursor = cursor) }.let { result ->
44+
safeApiCall(json) { api.getConversations(cursor = cursor) }.let { result ->
4745
when (result) {
4846
is ApiResult.Success -> {
49-
val summaries = result.data.items.mapNotNull { it.toConversationSummary() }
50-
if (summaries.isNotEmpty()) conversationDao.upsertAll(summaries)
47+
val me = currentUserId
48+
val rows = result.data.rows.mapNotNull { it.toEntity(me) }
49+
if (rows.isNotEmpty()) conversationDao.upsertAll(rows)
5150
ApiResult.Success(result.data.nextCursor)
5251
}
5352
is ApiResult.Failure -> result
@@ -119,7 +118,7 @@ class DefaultDirectMessagesRepository @Inject constructor(
119118
)
120119
when (val result = safeApiCall(json) { api.send(request) }) {
121120
is ApiResult.Success -> {
122-
val serverMessage = result.data.message()
121+
val serverMessage = result.data.createdMessage()
123122
if (serverMessage != null && serverMessage.id.isNotBlank()) {
124123
messageDao.deleteById(optimisticId)
125124
val entity = serverMessage.toEntity(username)
@@ -181,26 +180,4 @@ class DefaultDirectMessagesRepository @Inject constructor(
181180
override suspend fun unreadCount(): ApiResult<Int> = withContext(dispatchers.io) {
182181
safeApiCall(json) { api.getUnreadCount() }.map { it.count }
183182
}
184-
185-
/**
186-
* Folds an inbox message into a conversation summary. The other participant
187-
* is whichever end of the message is not the current user; the embedded
188-
* author sub-object (present on the inbox endpoint) supplies display info.
189-
*/
190-
private fun MessageDto.toConversationSummary(): ConversationEntity? {
191-
val me = currentUserId
192-
val other = embeddedAuthor
193-
val otherUsername = other?.username
194-
?: return null // Without a username we cannot key the conversation.
195-
val received = me != null && recipientId == me
196-
return ConversationEntity(
197-
username = otherUsername,
198-
displayName = other.displayName,
199-
avatarUrl = other.avatar,
200-
lastMessageId = id,
201-
lastMessageBody = body,
202-
lastMessageAtMillis = parseIsoMillis(createdAt),
203-
hasUnread = received && readAt == null,
204-
)
205-
}
206183
}

‎feature/directmessages/src/main/kotlin/com/interlinedlist/android/feature/directmessages/data/DirectMessagesRepository.kt‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,17 @@ interface DirectMessagesRepository {
1313
/** The signed-in user's id, used to tell "mine" from "theirs" in a thread. */
1414
val currentUserId: String?
1515

16-
/** Newest-first stream of cached conversation summaries. */
16+
/** Newest-first stream of cached conversations, one row per conversation. */
1717
fun observeConversations(): Flow<List<Conversation>>
1818

1919
/** Oldest-first stream of a single conversation's cached messages. */
2020
fun observeThread(username: String): Flow<List<DirectMessage>>
2121

2222
/**
23-
* Refreshes one page of the inbox. Pass `null` to load the first page; pass
24-
* the previous result's cursor to page. Returns the next cursor (or null).
23+
* Refreshes one page of the inbox from `GET /api/dm/conversations`. Pass
24+
* `null` to load the first page; pass the previous result's cursor to page.
25+
* Pages are merged into the cache, so paging appends. Returns the next
26+
* cursor (or null when the last page has been reached).
2527
*/
2628
suspend fun refreshInbox(cursor: String? = null): ApiResult<String?>
2729

‎feature/directmessages/src/main/kotlin/com/interlinedlist/android/feature/directmessages/data/DmMappers.kt‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package com.interlinedlist.android.feature.directmessages.data
22

33
import com.interlinedlist.android.feature.directmessages.data.local.ConversationEntity
44
import com.interlinedlist.android.feature.directmessages.data.local.DirectMessageEntity
5+
import com.interlinedlist.android.feature.directmessages.data.remote.dto.ConversationDto
56
import com.interlinedlist.android.feature.directmessages.data.remote.dto.MessageDto
67
import com.interlinedlist.android.feature.directmessages.data.remote.dto.RecipientDto
78
import java.time.Instant
@@ -49,13 +50,51 @@ internal fun DirectMessageEntity.toDomain(): DirectMessage = DirectMessage(
4950
pending = pending,
5051
)
5152

53+
/**
54+
* Maps a conversation row into its cache entity, or null when the row carries no
55+
* participant username — without one the conversation cannot be keyed or opened.
56+
*
57+
* [currentUserId] is only consulted when the row omits unread bookkeeping and a
58+
* nested last message has to stand in for it.
59+
*/
60+
internal fun ConversationDto.toEntity(currentUserId: String?): ConversationEntity? {
61+
val other = participant ?: return null
62+
val otherUsername = other.username.takeIf { it.isNotBlank() } ?: return null
63+
return ConversationEntity(
64+
username = otherUsername,
65+
pairKey = pairKey,
66+
displayName = other.displayName,
67+
avatarUrl = other.avatar,
68+
lastMessageId = newestMessageId,
69+
lastMessageBody = previewText,
70+
lastMessageAtMillis = parseIsoMillis(lastActivityAt),
71+
unreadCount = resolveUnreadCount(currentUserId),
72+
)
73+
}
74+
75+
/**
76+
* The row's unread count, preferring what the server reports and otherwise
77+
* inferring it from the newest message: unread only when the current user is the
78+
* one who received it.
79+
*/
80+
private fun ConversationDto.resolveUnreadCount(currentUserId: String?): Int = when {
81+
unreadCount != null -> unreadCount.coerceAtLeast(0)
82+
hasUnread != null -> if (hasUnread) 1 else 0
83+
else -> {
84+
val newest = newestMessage
85+
val received = currentUserId != null && newest?.recipientId == currentUserId
86+
if (received && (newest?.readAt ?: readAt) == null) 1 else 0
87+
}
88+
}
89+
5290
internal fun ConversationEntity.toDomain(): Conversation = Conversation(
5391
username = username,
5492
displayName = displayName,
5593
avatarUrl = avatarUrl,
5694
lastMessageBody = lastMessageBody,
5795
lastMessageAtMillis = lastMessageAtMillis,
58-
hasUnread = hasUnread,
96+
unreadCount = unreadCount,
97+
pairKey = pairKey,
5998
)
6099

61100
internal fun RecipientDto.toDomain(): Recipient = Recipient(

‎feature/directmessages/src/main/kotlin/com/interlinedlist/android/feature/directmessages/data/DmModels.kt‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,22 @@
11
package com.interlinedlist.android.feature.directmessages.data
22

3-
/** A conversation summary shown in the inbox list. */
3+
/**
4+
* A conversation shown in the inbox — one row per `pairKey`, as returned by
5+
* `GET /api/dm/conversations`.
6+
*/
47
data class Conversation(
58
val username: String,
69
val displayName: String?,
710
val avatarUrl: String?,
811
val lastMessageBody: String,
912
val lastMessageAtMillis: Long,
10-
val hasUnread: Boolean,
11-
)
13+
/** Unread received messages in this conversation, per the server. */
14+
val unreadCount: Int,
15+
val pairKey: String? = null,
16+
) {
17+
/** Whether the inbox row should render its unread affordance. */
18+
val hasUnread: Boolean get() = unreadCount > 0
19+
}
1220

1321
/** A single direct message shown in a thread. */
1422
data class DirectMessage(

‎feature/directmessages/src/main/kotlin/com/interlinedlist/android/feature/directmessages/data/local/ConversationDao.kt‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ interface ConversationDao {
2020
@Insert(onConflict = OnConflictStrategy.REPLACE)
2121
suspend fun upsertAll(conversations: List<ConversationEntity>)
2222

23-
@Query("UPDATE dm_conversation SET hasUnread = 0 WHERE username = :username")
23+
/** Zeroes a conversation's unread count (the server does this on thread open). */
24+
@Query("UPDATE dm_conversation SET unreadCount = 0 WHERE username = :username")
2425
suspend fun clearUnread(username: String)
2526

2627
@Query("DELETE FROM dm_conversation")

‎feature/directmessages/src/main/kotlin/com/interlinedlist/android/feature/directmessages/data/local/ConversationEntity.kt‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,23 @@ import androidx.room.Entity
44
import androidx.room.PrimaryKey
55

66
/**
7-
* A per-conversation summary backing the inbox list. Keyed by the other
8-
* participant's username so it aligns with the thread endpoints.
7+
* A conversation row from `GET /api/dm/conversations`, cached as the inbox's
8+
* source of truth. Distinct from [DirectMessageEntity]: this is the server's
9+
* per-conversation summary, not a message.
10+
*
11+
* Keyed by the other participant's username because every thread-scoped
12+
* operation in this module (thread fetch, polling, navigation) is addressed by
13+
* username; [pairKey] keeps the server's own grouping anchor alongside it.
914
*/
1015
@Entity(tableName = "dm_conversation")
1116
data class ConversationEntity(
1217
@PrimaryKey val username: String,
18+
val pairKey: String?,
1319
val displayName: String?,
1420
val avatarUrl: String?,
1521
val lastMessageId: String,
1622
val lastMessageBody: String,
1723
val lastMessageAtMillis: Long,
18-
/** Whether the latest received message in this conversation is unread. */
19-
val hasUnread: Boolean,
24+
/** Unread received messages in this conversation, as reported by the server. */
25+
val unreadCount: Int,
2026
)

‎feature/directmessages/src/main/kotlin/com/interlinedlist/android/feature/directmessages/data/local/DirectMessagesDatabase.kt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import androidx.room.TypeConverters
1010
*/
1111
@Database(
1212
entities = [DirectMessageEntity::class, ConversationEntity::class],
13-
version = 1,
13+
version = 2,
1414
exportSchema = false,
1515
)
1616
@TypeConverters(DmConverters::class)

‎feature/directmessages/src/main/kotlin/com/interlinedlist/android/feature/directmessages/data/remote/DirectMessagesApi.kt‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package com.interlinedlist.android.feature.directmessages.data.remote
22

3+
import com.interlinedlist.android.feature.directmessages.data.remote.dto.ConversationsResponse
34
import com.interlinedlist.android.feature.directmessages.data.remote.dto.ImageUploadResponse
4-
import com.interlinedlist.android.feature.directmessages.data.remote.dto.InboxResponse
55
import com.interlinedlist.android.feature.directmessages.data.remote.dto.MessageDto
66
import com.interlinedlist.android.feature.directmessages.data.remote.dto.RecipientsResponse
77
import com.interlinedlist.android.feature.directmessages.data.remote.dto.SendMessageRequest
@@ -28,13 +28,15 @@ import retrofit2.http.Query
2828
*/
2929
interface DirectMessagesApi {
3030

31-
/** Lists a DM folder (default inbox), cursor-paginated by `nextCursor`. */
32-
@GET("api/dm")
33-
suspend fun getInbox(
34-
@Query("folder") folder: String? = null,
31+
/**
32+
* The inbox: one row per conversation (grouped by `pairKey`), newest
33+
* activity first, cursor-paginated by `nextCursor`.
34+
*/
35+
@GET("api/dm/conversations")
36+
suspend fun getConversations(
3537
@Query("cursor") cursor: String? = null,
3638
@Query("take") take: Int? = null,
37-
): InboxResponse
39+
): ConversationsResponse
3840

3941
/** Sends a direct message. */
4042
@POST("api/dm")
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package com.interlinedlist.android.feature.directmessages.data.remote.dto
2+
3+
import kotlinx.serialization.Serializable
4+
5+
/**
6+
* Wire model for one row of `GET /api/dm/conversations` — a conversation
7+
* grouped by `pairKey`, newest activity first. This is the inbox's data source;
8+
* it is deliberately *not* the message DTO.
9+
*
10+
* The OpenAPI spec declares this response as a bare `object` and the public help
11+
* centre does not document it, so the row is modelled defensively: every field
12+
* is optional, and the keys this API is known to use interchangeably are all
13+
* accepted — the other participant as `otherUser` (as on the thread endpoint),
14+
* `user` or `author` (the documented envelope quirk); the newest message either
15+
* nested under `lastMessage`/`message` or flattened onto the row. Unknown keys
16+
* are ignored by the shared Json configuration.
17+
*/
18+
@Serializable
19+
data class ConversationDto(
20+
/** Stable, sorted `a:b` anchor identifying the conversation server-side. */
21+
val pairKey: String? = null,
22+
// The other participant, under whichever key the endpoint used.
23+
val otherUser: RecipientDto? = null,
24+
val user: RecipientDto? = null,
25+
val author: RecipientDto? = null,
26+
// The newest message, either nested...
27+
val lastMessage: MessageDto? = null,
28+
val message: MessageDto? = null,
29+
// ...or flattened onto the row itself.
30+
val lastMessageId: String? = null,
31+
val lastMessageBody: String? = null,
32+
val preview: String? = null,
33+
val body: String? = null,
34+
val lastMessageAt: String? = null,
35+
val updatedAt: String? = null,
36+
val createdAt: String? = null,
37+
val readAt: String? = null,
38+
// Unread bookkeeping; `unreadCount` is per conversation, not per folder.
39+
val unreadCount: Int? = null,
40+
val hasUnread: Boolean? = null,
41+
) {
42+
/** The conversation partner under whichever key the endpoint used. */
43+
val participant: RecipientDto? get() = otherUser ?: user ?: author
44+
45+
/** The newest message of the conversation when the row nests one. */
46+
val newestMessage: MessageDto? get() = lastMessage ?: message
47+
48+
/** Plain-text excerpt to render on the inbox row. */
49+
val previewText: String
50+
get() = (preview ?: lastMessageBody ?: body ?: newestMessage?.body).orEmpty()
51+
52+
/** ISO-8601 timestamp of the conversation's newest activity. */
53+
val lastActivityAt: String?
54+
get() = lastMessageAt ?: newestMessage?.createdAt ?: updatedAt ?: createdAt
55+
56+
/** Id of the newest message, when the row identifies one. */
57+
val newestMessageId: String get() = (lastMessageId ?: newestMessage?.id).orEmpty()
58+
}

0 commit comments

Comments
 (0)