HTTP API: server, credential and the list of chats (closes #4)
check / check (push) Successful in 1m1s
check / check (push) Successful in 1m1s
The bot now serves an HTTP API on PORT (default 8080) beside the chat client. Every request needs the credential read at startup from the file named by API_TOKEN_FILE, sent as a bearer token; without one, every request is refused. Responses carry the security headers, bodies are capped at 64 KiB and each request's work at 10 seconds. GET /api/v1/chats lists the bot's contacts from the chat client's /_contacts command, ordered by id, and marks the contacts who deleted their chat with the bot, which the chat client keeps listing. bot.Run starts the API after set-up and stops it within 5 seconds; a listener failure ends the bot as a chat client failure does. Model: opus-5-5
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"net/http"
|
||||
"slices"
|
||||
)
|
||||
|
||||
// handleChats lists the bot's chats, ordered by id. The bot talks to
|
||||
// people only one to one, so its chats are its contacts, and a chat's
|
||||
// id is its contact's.
|
||||
func (h *handlers) handleChats() http.HandlerFunc {
|
||||
type chat struct {
|
||||
ID int64 `json:"id"`
|
||||
DisplayName string `json:"display_name"`
|
||||
ContactDeleted bool `json:"contact_deleted"`
|
||||
}
|
||||
|
||||
type response struct {
|
||||
Chats []chat `json:"chats"`
|
||||
}
|
||||
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
contacts, err := h.client.Contacts(r.Context(), h.userID)
|
||||
if err != nil {
|
||||
h.log.Error("listing the chats", "error", err)
|
||||
h.respondError(w, http.StatusInternalServerError,
|
||||
"the chats could not be read")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
chats := make([]chat, 0, len(contacts))
|
||||
for _, c := range contacts {
|
||||
chats = append(chats, chat{
|
||||
ID: c.ContactID,
|
||||
DisplayName: c.Profile.DisplayName,
|
||||
ContactDeleted: c.Deleted(),
|
||||
})
|
||||
}
|
||||
|
||||
slices.SortFunc(chats, func(a, b chat) int { return cmp.Compare(a.ID, b.ID) })
|
||||
|
||||
h.respond(w, http.StatusOK, response{Chats: chats})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user