-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #86 from MobileNativeFoundation/chat/websockets
Set Up Backend For Chat
- Loading branch information
Showing
7 changed files
with
148 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
8 changes: 8 additions & 0 deletions
8
...er/src/main/kotlin/org/mobilenativefoundation/trails/backend/server/plugins/WebSockets.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
package org.mobilenativefoundation.trails.backend.server.plugins | ||
|
||
import io.ktor.server.application.* | ||
import io.ktor.server.websocket.* | ||
|
||
fun Application.configureWebSockets() { | ||
install(WebSockets) | ||
} |
96 changes: 96 additions & 0 deletions
96
...ver/src/main/kotlin/org/mobilenativefoundation/trails/backend/server/routes/ChatRoutes.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
package org.mobilenativefoundation.trails.backend.server.routes | ||
|
||
import io.ktor.http.* | ||
import io.ktor.server.response.* | ||
import io.ktor.server.routing.* | ||
import io.ktor.server.websocket.* | ||
import io.ktor.websocket.* | ||
import kotlinx.coroutines.channels.consumeEach | ||
import kotlinx.datetime.* | ||
import kotlinx.serialization.Serializable | ||
import kotlinx.serialization.encodeToString | ||
import kotlinx.serialization.json.Json | ||
import org.mobilenativefoundation.trails.backend.server.TrailsDatabase | ||
import java.util.concurrent.ConcurrentHashMap | ||
|
||
class ChatRoutes(private val trailsDatabase: TrailsDatabase) { | ||
|
||
private val chatSessionConnections = ConcurrentHashMap<Int, ConcurrentHashMap<Int, DefaultWebSocketServerSession>>() | ||
|
||
fun Route.chat() { | ||
webSocket("/chat/{chatSessionId}/{userId}") { | ||
val chatSessionId = call.parameters["chatSessionId"]?.toIntOrNull() | ||
val userId = call.parameters["userId"]?.toIntOrNull() | ||
|
||
if (userId == null) { | ||
call.respond(HttpStatusCode.BadRequest, "Invalid or missing user ID.") | ||
return@webSocket | ||
} | ||
|
||
if (chatSessionId == null) { | ||
call.respond(HttpStatusCode.BadRequest, "Invalid or missing chat session ID.") | ||
return@webSocket | ||
} | ||
|
||
val chatSessionParticipantIds = | ||
trailsDatabase.chatQueries.getParticipantsByChatSessionId(chatSessionId).executeAsList() | ||
val isParticipant = userId in chatSessionParticipantIds | ||
|
||
if (!isParticipant) { | ||
close(CloseReason(CloseReason.Codes.VIOLATED_POLICY, "Unauthorized")) | ||
return@webSocket | ||
} | ||
|
||
val connections = chatSessionConnections.getOrPut(chatSessionId) { | ||
ConcurrentHashMap() | ||
} | ||
|
||
connections[userId] = this | ||
|
||
try { | ||
incoming.consumeEach { frame -> | ||
if (frame is Frame.Text) { | ||
val receivedText = frame.readText() | ||
val chatMessage = Json.decodeFromString<ChatMessage>(receivedText) | ||
|
||
// Store the message in the database | ||
trailsDatabase.chatQueries.insertChatMessage( | ||
chat_session_id = chatSessionId, | ||
from_user_id = userId, | ||
content = chatMessage.content, | ||
timestamp = chatMessage.timestamp.toJavaLocalDateTime() | ||
) | ||
|
||
// Send the message to all active participants in the chat session | ||
connections.forEach { (participantId, session) -> | ||
if (participantId != userId) { | ||
session.send( | ||
Frame.Text( | ||
Json.encodeToString(chatMessage) | ||
) | ||
) | ||
} | ||
} | ||
} | ||
} | ||
} catch (e: Exception) { | ||
println("Error for user $userId: ${e.localizedMessage}.") | ||
} finally { | ||
print("User disconnected: $userId.") | ||
connections.remove(userId) | ||
if (connections.isEmpty()) { | ||
chatSessionConnections.remove(chatSessionId) | ||
} | ||
} | ||
|
||
} | ||
} | ||
} | ||
|
||
@Serializable | ||
data class ChatMessage( | ||
val chatSessionId: Int, | ||
val fromUserId: Int, | ||
val content: String, | ||
val timestamp: LocalDateTime = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()) | ||
) |
34 changes: 34 additions & 0 deletions
34
backend/server/src/main/sqldelight/org/mobilenativefoundation/trails/backend/server/Chat.sq
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
CREATE TABLE chatSession( | ||
id SERIAL PRIMARY KEY | ||
); | ||
|
||
CREATE TABLE chatSessionParticipant( | ||
chat_session_id INT NOT NULL REFERENCES chatSession(id) ON DELETE CASCADE, | ||
user_id INT NOT NULL REFERENCES user(id), | ||
PRIMARY KEY (chat_session_id, user_id) | ||
); | ||
|
||
CREATE TABLE chatMessage( | ||
id SERIAL PRIMARY KEY, | ||
chat_session_id INT NOT NULL REFERENCES chatSession(id) ON DELETE CASCADE, | ||
from_user_id INT NOT NULL REFERENCES user(id), | ||
content TEXT NOT NULL, | ||
timestamp TIMESTAMP NOT NULL | ||
); | ||
|
||
-- Queries | ||
|
||
getMessagesByChatSessionId: | ||
SELECT * FROM chatMessage | ||
WHERE chat_session_id = ? | ||
ORDER BY timestamp ASC; | ||
|
||
insertChatMessage: | ||
INSERT INTO chatMessage (chat_session_id, from_user_id, content, timestamp) VALUES (?, ?, ?, ?); | ||
|
||
insertChatSessionParticipant: | ||
INSERT INTO chatSessionParticipant (chat_session_id, user_id) VALUES (?, ?); | ||
|
||
getParticipantsByChatSessionId: | ||
SELECT user_id FROM chatSessionParticipant | ||
WHERE chat_session_id = ?; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters