-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathWebApiAdapter.kt
More file actions
158 lines (141 loc) · 5.74 KB
/
WebApiAdapter.kt
File metadata and controls
158 lines (141 loc) · 5.74 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package com.example.util.simpletimetracker.api
import com.example.util.simpletimetracker.wear_api.WearCommunicationAPI
import com.example.util.simpletimetracker.wear_api.WearStartActivityRequest
import com.example.util.simpletimetracker.wear_api.WearStopActivityRequest
import fi.iki.elonen.NanoHTTPD
import kotlinx.coroutines.runBlocking
import org.json.JSONArray
import org.json.JSONObject
import javax.inject.Inject
class WebApiAdapter @Inject constructor(
// Reuse the SAME interface that Wear OS uses!
private val wearApi: WearCommunicationAPI,
) : NanoHTTPD(8080) {
override fun serve(session: IHTTPSession): Response {
val headers = mutableMapOf(
"Access-Control-Allow-Origin" to "*",
"Access-Control-Allow-Methods" to "GET, POST, OPTIONS",
"Access-Control-Allow-Headers" to "Content-Type"
)
if (session.method == Method.OPTIONS) {
return newFixedLengthResponse(Response.Status.OK, MIME_PLAINTEXT, "")
.apply { headers.forEach { (k, v) -> addHeader(k, v) } }
}
return try {
when {
// GET /api/activities
session.uri == "/api/activities" && session.method == Method.GET -> {
getAllActivities(headers)
}
// GET /api/running
session.uri == "/api/running" && session.method == Method.GET -> {
getRunningActivities(headers)
}
// POST /api/start/:id
session.uri.startsWith("/api/start/") && session.method == Method.POST -> {
val id = session.uri.substringAfterLast("/").toLongOrNull()
startActivity(id, headers)
}
// POST /api/stop/:id
session.uri.startsWith("/api/stop/") && session.method == Method.POST -> {
val id = session.uri.substringAfterLast("/").toLongOrNull()
stopActivity(id, headers)
}
else -> {
newFixedLengthResponse(
Response.Status.NOT_FOUND,
"application/json",
"""{"error": "Not found"}"""
).apply { headers.forEach { (k, v) -> addHeader(k, v) } }
}
}
} catch (e: Exception) {
newFixedLengthResponse(
Response.Status.INTERNAL_ERROR,
"application/json",
"""{"error": "${e.message}"}"""
).apply { headers.forEach { (k, v) -> addHeader(k, v) } }
}
}
private fun getAllActivities(headers: Map<String, String>): Response = runBlocking {
// Reuse the EXACT same method Wear OS uses!
val activities = wearApi.queryActivities()
val currentState = wearApi.queryCurrentActivities()
val runningIds = currentState.currentActivities.map { it.id }.toSet()
val json = JSONArray()
activities.forEach { activity ->
json.put(JSONObject().apply {
put("id", activity.id)
put("name", activity.name)
put("icon", activity.icon)
put("color", activity.color)
put("isRunning", runningIds.contains(activity.id))
})
}
newFixedLengthResponse(
Response.Status.OK,
"application/json",
json.toString()
).apply {
headers.forEach { (k, v) -> addHeader(k, v) }
}
}
private fun getRunningActivities(headers: Map<String, String>): Response = runBlocking {
// Reuse the EXACT same method Wear OS uses!
val currentState = wearApi.queryCurrentActivities()
val activities = wearApi.queryActivities().associateBy { it.id }
val json = JSONArray()
currentState.currentActivities.forEach { current ->
val activity = activities[current.id]
json.put(JSONObject().apply {
put("id", current.id)
put("name", activity?.name ?: "Unknown")
put("timeStarted", current.startedAt)
put("duration", System.currentTimeMillis() - current.startedAt)
})
}
newFixedLengthResponse(
Response.Status.OK,
"application/json",
json.toString()
).apply {
headers.forEach { (k, v) -> addHeader(k, v) }
}
}
private fun startActivity(id: Long?, headers: Map<String, String>): Response = runBlocking {
if (id == null) {
return@runBlocking newFixedLengthResponse(
Response.Status.BAD_REQUEST,
"application/json",
"""{"error": "Invalid ID"}"""
)
}
// Reuse the EXACT same method Wear OS uses!
wearApi.startActivity(WearStartActivityRequest(id = id, tags = null))
newFixedLengthResponse(
Response.Status.OK,
"application/json",
"""{"success": true}"""
).apply {
headers.forEach { (k, v) -> addHeader(k, v) }
}
}
private fun stopActivity(id: Long?, headers: Map<String, String>): Response = runBlocking {
if (id == null) {
return@runBlocking newFixedLengthResponse(
Response.Status.BAD_REQUEST,
"application/json",
"""{"error": "Invalid ID"}"""
)
}
// Reuse the EXACT same method Wear OS uses!
wearApi.stopActivity(WearStopActivityRequest(id = id))
newFixedLengthResponse(
Response.Status.OK,
"application/json",
"""{"success": true}"""
).apply {
headers.forEach { (k, v) -> addHeader(k, v) }
}
}
}