This repository was archived by the owner on Jul 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 168
/
Copy pathIndex.kt
48 lines (41 loc) · 1.77 KB
/
Index.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
package org.jetbrains.demo.thinkter
import org.jetbrains.demo.thinkter.dao.*
import org.jetbrains.demo.thinkter.model.*
import io.ktor.application.*
import io.ktor.html.*
import io.ktor.http.*
import io.ktor.locations.*
import io.ktor.request.contentType
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.sessions.*
import java.time.*
fun Route.index(storage: ThinkterStorage) {
get<Index> {
val user = call.sessions.get<Session>()?.let { storage.user(it.userId) }
val top = storage.top(10).map(storage::getThought)
val latest = storage.latest(10).map(storage::getThought)
if(call.request.contentType().match(ContentType.Application.Json)) {
call.response.pipeline.intercept(ApplicationSendPipeline.After) {
val etagString = user?.userId + "," + top.joinToString { it.id.toString() } + latest.joinToString { it.id.toString() }
call.response.etag(etagString)
}
call.respond(IndexResponse(top, latest))
}else{
call.respondHtmlTemplate(ApplicationPage()) {
caption { +"Thinkter" }
}
}
}
get<Poll> { poll ->
if (poll.lastTime.isBlank()) {
call.respond(PollResponse(System.currentTimeMillis(), "0"))
} else {
val time = System.currentTimeMillis()
val lastTime = poll.lastTime.toLong()
val count = storage.latest(10).reversed().takeWhile { storage.getThought(it).toEpochMilli() > lastTime }.size
call.respond(PollResponse(time, if (count == 10) "10+" else count.toString()))
}
}
}
private fun Thought.toEpochMilli() = LocalDateTime.parse(date).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()