package main
import (
"context"
"encoding/json"
"errors"
"net/http"
"strings"
)
func writeJSON(w http.ResponseWriter, status int, body any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(body)
}
func writeError(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]string{"error": msg})
}
func withCORS(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
h(w, r)
}
}
type tokenVerifier interface {
Verify(ctx context.Context, token string) (string, error)
}
type App struct {
verifier tokenVerifier
store *Store
contacts *Contacts
defaultJitsiURL string
topics *Topics
notifier *Notifier
}
const appURL = "com.quineglobal.quple://call"
func (a *App) Routes(mux *http.ServeMux) {
mux.HandleFunc("/me", withCORS(a.requireAuth(a.handleMe)))
mux.HandleFunc("/register", withCORS(a.requireAuth(a.handleRegister)))
mux.HandleFunc("/poll", withCORS(a.requireAuth(a.handlePoll)))
mux.HandleFunc("/call", withCORS(a.requireAuth(a.handleCall)))
mux.HandleFunc("/calls/{id}", withCORS(a.requireAuth(a.handleCallStatus)))
mux.HandleFunc("/calls/{id}/heartbeat", withCORS(a.requireAuth(a.handleHeartbeat)))
mux.HandleFunc("/calls/{id}/hangup", withCORS(a.requireAuth(a.handleHangUp)))
mux.HandleFunc("/calls/{id}/move", withCORS(a.requireAuth(a.handleMove)))
mux.HandleFunc("/contacts", withCORS(a.requireAuth(a.handleContacts)))
mux.HandleFunc("/contacts/{username}", withCORS(a.requireAuth(a.handleContact)))
}
type authedHandler func(w http.ResponseWriter, r *http.Request, me string)
func (a *App) requireAuth(h authedHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok {
w.Header().Set("WWW-Authenticate", "Bearer")
writeError(w, http.StatusUnauthorized, "sign in required")
return
}
username, err := a.verifier.Verify(r.Context(), token)
if errors.Is(err, errIdentityUnavailable) {
writeError(w, http.StatusServiceUnavailable, err.Error())
return
}
if err != nil {
w.Header().Set("WWW-Authenticate", `Bearer error="invalid_token"`)
writeError(w, http.StatusUnauthorized, "invalid or expired token")
return
}
h(w, r, username)
}
}
func (a *App) handleMe(w http.ResponseWriter, r *http.Request, me string) {
if r.Method != http.MethodGet {
writeError(w, http.StatusMethodNotAllowed, "GET only")
return
}
body := map[string]string{"username": me, "defaultJitsiUrl": a.defaultJitsiURL}
if a.notifier.Enabled() {
topic, err := a.topics.Get(me)
if err != nil {
writeError(w, http.StatusInternalServerError, "could not make a notification topic")
return
}
body["ntfyServer"] = a.notifier.url
body["ntfyTopic"] = topic
}
writeJSON(w, http.StatusOK, body)
}
func (a *App) handleRegister(w http.ResponseWriter, r *http.Request, me string) {
if r.Method != http.MethodPost {
writeError(w, http.StatusMethodNotAllowed, "POST only")
return
}
a.store.Touch(me)
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
func (a *App) handlePoll(w http.ResponseWriter, r *http.Request, me string) {
if r.Method != http.MethodGet {
writeError(w, http.StatusMethodNotAllowed, "GET only")
return
}
device := r.URL.Query().Get("device")
body := map[string]any{"invites": a.store.PendingInvites(me, device)}
if device != "" {
body["calls"] = a.store.ActiveCalls(me, device)
}
writeJSON(w, http.StatusOK, body)
}
func (a *App) handleCall(w http.ResponseWriter, r *http.Request, me string) {
if r.Method != http.MethodPost {
writeError(w, http.StatusMethodNotAllowed, "POST only")
return
}
var body struct {
To string `json:"to"`
JitsiURL string `json:"jitsiUrl"`
Device string `json:"device"`
Name string `json:"name"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
to, err := normalizeUsername(body.To)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if to == me && body.Device == "" {
writeError(w, http.StatusBadRequest, errNeedDevice.Error())
return
}
jitsiURL := a.defaultJitsiURL
if body.JitsiURL != "" {
if jitsiURL, err = normalizeJitsiURL(body.JitsiURL); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
}
a.store.Touch(me)
inv, joined := a.store.PlaceCall(to, body.Device, body.Name, Invite{From: me, MeetingID: newMeetingID(), JitsiURL: jitsiURL})
if joined {
writeJSON(w, http.StatusOK, map[string]any{"meetingId": inv.MeetingID, "jitsiUrl": inv.JitsiURL, "notified": false, "joined": true})
return
}
notified := false
if a.notifier.Enabled() && !a.store.PolledRecently(to) {
if topic, err := a.topics.Get(to); err == nil {
a.notifier.Send(topic, Notification{
Title: "Quple",
Message: me + " is calling. Open Quple to answer.",
Click: appURL,
Tags: "telephone_receiver",
Priority: "5",
})
a.store.MarkNotified(inv.MeetingID)
notified = true
}
}
writeJSON(w, http.StatusOK, map[string]any{"meetingId": inv.MeetingID, "jitsiUrl": jitsiURL, "notified": notified})
}
func writeCallError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, errNoCall):
writeError(w, http.StatusNotFound, err.Error())
case errors.Is(err, errNotParty):
writeError(w, http.StatusForbidden, err.Error())
case errors.Is(err, errNeedDevice):
writeError(w, http.StatusBadRequest, err.Error())
case errors.Is(err, errCallEnded), errors.Is(err, errSelfMove):
writeError(w, http.StatusConflict, err.Error())
default:
writeError(w, http.StatusInternalServerError, err.Error())
}
}
func (a *App) handleHeartbeat(w http.ResponseWriter, r *http.Request, me string) {
if r.Method != http.MethodPost {
writeError(w, http.StatusMethodNotAllowed, "POST only")
return
}
var hb Heartbeat
if r.ContentLength != 0 {
if err := json.NewDecoder(r.Body).Decode(&hb); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
}
st, err := a.store.CallHeartbeat(r.PathValue("id"), me, hb)
if err != nil {
writeCallError(w, err)
return
}
writeJSON(w, http.StatusOK, st)
}
func (a *App) handleCallStatus(w http.ResponseWriter, r *http.Request, me string) {
if r.Method != http.MethodGet {
writeError(w, http.StatusMethodNotAllowed, "GET only")
return
}
st, err := a.store.CallStatus(r.PathValue("id"), me, r.URL.Query().Get("device"))
if err != nil {
writeCallError(w, err)
return
}
writeJSON(w, http.StatusOK, st)
}
func (a *App) handleMove(w http.ResponseWriter, r *http.Request, me string) {
if r.Method != http.MethodPost {
writeError(w, http.StatusMethodNotAllowed, "POST only")
return
}
var body struct {
Device string `json:"device"`
Name string `json:"name"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.Device == "" {
writeError(w, http.StatusBadRequest, `need {"device": ..., "name": ...}`)
return
}
ac, err := a.store.MoveCall(r.PathValue("id"), me, body.Device, body.Name)
if err != nil {
writeCallError(w, err)
return
}
writeJSON(w, http.StatusOK, ac)
}
func (a *App) handleHangUp(w http.ResponseWriter, r *http.Request, me string) {
if r.Method != http.MethodPost {
writeError(w, http.StatusMethodNotAllowed, "POST only")
return
}
var body struct {
Device string `json:"device"`
}
if r.ContentLength != 0 {
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
}
missedBy, err := a.store.HangUp(r.PathValue("id"), me, body.Device)
if err != nil {
writeCallError(w, err)
return
}
if missedBy != "" {
if topic, err := a.topics.Get(missedBy); err == nil {
a.notifier.Send(topic, Notification{
Title: "Quple",
Message: "Missed call from " + me,
Click: appURL,
Tags: "telephone_receiver",
})
}
}
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
type contact struct {
Username string `json:"username"`
Online bool `json:"online"`
}
func (a *App) handleContacts(w http.ResponseWriter, r *http.Request, me string) {
switch r.Method {
case http.MethodGet:
list := []contact{}
for _, name := range a.contacts.List(me) {
list = append(list, contact{Username: name, Online: a.store.IsOnline(name)})
}
writeJSON(w, http.StatusOK, map[string][]contact{"contacts": list})
case http.MethodPost:
var body struct {
Username string `json:"username"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
name, err := normalizeUsername(body.Username)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if name == me {
writeError(w, http.StatusBadRequest, "that's you")
return
}
if err := a.contacts.Add(me, name); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusOK, contact{Username: name, Online: a.store.IsOnline(name)})
default:
writeError(w, http.StatusMethodNotAllowed, "GET or POST only")
}
}
func (a *App) handleContact(w http.ResponseWriter, r *http.Request, me string) {
if r.Method != http.MethodDelete {
writeError(w, http.StatusMethodNotAllowed, "DELETE only")
return
}
name, err := normalizeUsername(r.PathValue("username"))
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if err := a.contacts.Remove(me, name); err != nil {
writeError(w, http.StatusInternalServerError, "could not save contacts")
return
}
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}