313 lines
9.2 KiB
Go
313 lines
9.2 KiB
Go
package api
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"messenger/internal/store"
|
|
)
|
|
|
|
func (a *API) live(w http.ResponseWriter, _ *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
|
}
|
|
|
|
func (a *API) ready(w http.ResponseWriter, r *http.Request) {
|
|
if a.shutting.Load() {
|
|
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервер останавливается", 1)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
|
}
|
|
|
|
func (a *API) route(w http.ResponseWriter, r *http.Request) {
|
|
path := r.URL.Path
|
|
switch {
|
|
case path == "/api/v1/users" && r.Method == http.MethodPost:
|
|
a.createUser(w, r)
|
|
case path == "/api/v1/users/me" && r.Method == http.MethodGet:
|
|
a.currentUser(w, r)
|
|
case path == "/api/v1/chats" && r.Method == http.MethodPost:
|
|
a.createChat(w, r)
|
|
case path == "/api/v1/chats" && r.Method == http.MethodGet:
|
|
a.listChats(w, r)
|
|
default:
|
|
chatID, messages, ok := splitChatPath(path)
|
|
if !ok {
|
|
if knownWrongMethod(path) {
|
|
a.fail(w, r, http.StatusMethodNotAllowed, "invalid_request", "Метод не поддерживается", 0)
|
|
return
|
|
}
|
|
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
|
return
|
|
}
|
|
switch {
|
|
case !messages && r.Method == http.MethodGet:
|
|
a.getChat(w, r, chatID)
|
|
case messages && r.Method == http.MethodPost:
|
|
a.createMessage(w, r, chatID)
|
|
case messages && r.Method == http.MethodGet:
|
|
a.listMessages(w, r, chatID)
|
|
default:
|
|
a.fail(w, r, http.StatusMethodNotAllowed, "invalid_request", "Метод не поддерживается", 0)
|
|
}
|
|
}
|
|
}
|
|
|
|
func knownWrongMethod(path string) bool {
|
|
switch path {
|
|
case "/api/v1/users", "/api/v1/users/me", "/api/v1/chats":
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func (a *API) createUser(w http.ResponseWriter, r *http.Request) {
|
|
var body struct {
|
|
Username string `json:"username"`
|
|
DisplayName string `json:"display_name"`
|
|
}
|
|
if !a.readJSON(w, r, &body) {
|
|
return
|
|
}
|
|
if !usernameRe.MatchString(body.Username) || !validText(body.DisplayName, 1, 100) {
|
|
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректные поля пользователя", 0)
|
|
return
|
|
}
|
|
user, err := a.store.CreateUser(body.Username, body.DisplayName)
|
|
if err == store.ErrConflict {
|
|
a.fail(w, r, http.StatusConflict, "conflict", "Имя пользователя уже занято", 0)
|
|
return
|
|
}
|
|
if err != nil {
|
|
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusCreated, asUser(user))
|
|
}
|
|
|
|
func (a *API) currentUser(w http.ResponseWriter, r *http.Request) {
|
|
user, ok := a.authenticate(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, asUser(user))
|
|
}
|
|
|
|
func (a *API) createChat(w http.ResponseWriter, r *http.Request) {
|
|
caller, ok := a.authenticate(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
var body struct {
|
|
Title string `json:"title"`
|
|
MemberIDs []string `json:"member_ids"`
|
|
}
|
|
if !a.readJSON(w, r, &body) {
|
|
return
|
|
}
|
|
if !validText(body.Title, 1, 100) || len(body.MemberIDs) < 1 || len(body.MemberIDs) > 100 {
|
|
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректные поля чата", 0)
|
|
return
|
|
}
|
|
ids := make([]string, len(body.MemberIDs))
|
|
seen := make(map[string]struct{}, len(body.MemberIDs))
|
|
callerIn := false
|
|
for i, raw := range body.MemberIDs {
|
|
id, ok := canonicalUUID(raw)
|
|
if !ok {
|
|
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
|
return
|
|
}
|
|
if _, dup := seen[id]; dup {
|
|
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
|
return
|
|
}
|
|
seen[id] = struct{}{}
|
|
if _, exists := a.store.User(id); !exists {
|
|
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
|
return
|
|
}
|
|
if id == caller.ID {
|
|
callerIn = true
|
|
}
|
|
ids[i] = id
|
|
}
|
|
if !callerIn {
|
|
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
|
return
|
|
}
|
|
chat, err := a.store.CreateChat(body.Title, ids, caller.ID)
|
|
switch err {
|
|
case nil:
|
|
writeJSON(w, http.StatusCreated, asChat(chat))
|
|
case store.ErrInvalid:
|
|
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
|
default:
|
|
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
|
}
|
|
}
|
|
|
|
func (a *API) listChats(w http.ResponseWriter, r *http.Request) {
|
|
user, ok := a.authenticate(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
limit, cur, ok := a.pageQuery(w, r, "chats:"+user.ID)
|
|
if !ok {
|
|
return
|
|
}
|
|
items, hasMore, err := a.store.ListChats(user.ID, cur, limit)
|
|
if err == store.ErrBadCursor {
|
|
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
|
return
|
|
}
|
|
if err != nil {
|
|
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
|
return
|
|
}
|
|
out := make([]chatJSON, 0, len(items))
|
|
for _, c := range items {
|
|
out = append(out, asChat(c))
|
|
}
|
|
var next *string
|
|
if hasMore && len(items) > 0 {
|
|
last := items[len(items)-1]
|
|
encoded := encodeCursor(cursorPayload{Scope: "chats:" + user.ID, ID: last.ID, At: formatTime(last.CreatedAt)})
|
|
next = &encoded
|
|
}
|
|
writeJSON(w, http.StatusOK, chatPage{Items: out, NextCursor: next})
|
|
}
|
|
|
|
func (a *API) getChat(w http.ResponseWriter, r *http.Request, rawID string) {
|
|
user, ok := a.authenticate(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
id, ok := a.chatID(w, r, rawID)
|
|
if !ok {
|
|
return
|
|
}
|
|
chat, err := a.store.ChatFor(id, user.ID)
|
|
if err == store.ErrNotFound {
|
|
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
|
return
|
|
}
|
|
if err != nil {
|
|
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, asChat(chat))
|
|
}
|
|
|
|
func (a *API) createMessage(w http.ResponseWriter, r *http.Request, rawID string) {
|
|
user, ok := a.authenticate(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
id, ok := a.chatID(w, r, rawID)
|
|
if !ok {
|
|
return
|
|
}
|
|
if _, err := a.store.ChatFor(id, user.ID); err == store.ErrNotFound {
|
|
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
|
return
|
|
} else if err != nil {
|
|
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
|
return
|
|
}
|
|
var body struct {
|
|
Text string `json:"text"`
|
|
}
|
|
if !a.readJSON(w, r, &body) {
|
|
return
|
|
}
|
|
if !validText(body.Text, 1, 4000) {
|
|
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный текст сообщения", 0)
|
|
return
|
|
}
|
|
msg, err := a.store.AddMessage(id, user.ID, body.Text)
|
|
switch err {
|
|
case nil:
|
|
writeJSON(w, http.StatusCreated, asMessage(msg))
|
|
case store.ErrNotFound:
|
|
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
|
default:
|
|
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
|
}
|
|
}
|
|
|
|
func (a *API) listMessages(w http.ResponseWriter, r *http.Request, rawID string) {
|
|
user, ok := a.authenticate(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
id, ok := a.chatID(w, r, rawID)
|
|
if !ok {
|
|
return
|
|
}
|
|
if _, err := a.store.ChatFor(id, user.ID); err == store.ErrNotFound {
|
|
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
|
return
|
|
} else if err != nil {
|
|
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
|
return
|
|
}
|
|
limit, cur, ok := a.pageQuery(w, r, "msg:"+id)
|
|
if !ok {
|
|
return
|
|
}
|
|
items, hasMore, err := a.store.ListMessages(id, user.ID, cur, limit)
|
|
if err == store.ErrBadCursor {
|
|
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
|
return
|
|
}
|
|
if err == store.ErrNotFound {
|
|
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
|
return
|
|
}
|
|
if err != nil {
|
|
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
|
return
|
|
}
|
|
out := make([]messageJSON, 0, len(items))
|
|
for _, m := range items {
|
|
out = append(out, asMessage(m))
|
|
}
|
|
var next *string
|
|
if hasMore && len(items) > 0 {
|
|
last := items[len(items)-1]
|
|
encoded := encodeCursor(cursorPayload{Scope: "msg:" + id, ID: last.ID, At: formatTime(last.CreatedAt)})
|
|
next = &encoded
|
|
}
|
|
writeJSON(w, http.StatusOK, messagePage{Items: out, NextCursor: next})
|
|
}
|
|
|
|
func (a *API) chatID(w http.ResponseWriter, r *http.Request, raw string) (string, bool) {
|
|
id, ok := canonicalUUID(raw)
|
|
if !ok {
|
|
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный идентификатор", 0)
|
|
return "", false
|
|
}
|
|
return id, true
|
|
}
|
|
|
|
func splitChatPath(path string) (id string, messages bool, ok bool) {
|
|
const prefix = "/api/v1/chats/"
|
|
if !strings.HasPrefix(path, prefix) {
|
|
return "", false, false
|
|
}
|
|
rest := strings.TrimPrefix(path, prefix)
|
|
if rest == "" || strings.Contains(rest, "/") && !strings.HasSuffix(rest, "/messages") {
|
|
return "", false, false
|
|
}
|
|
if strings.HasSuffix(rest, "/messages") {
|
|
id = strings.TrimSuffix(rest, "/messages")
|
|
if id == "" || strings.Contains(id, "/") {
|
|
return "", false, false
|
|
}
|
|
return id, true, true
|
|
}
|
|
return rest, false, true
|
|
}
|