summaryrefslogtreecommitdiff
path: root/api/presence/presence.go
blob: 645b34e133510288af7472fc4ba1bbae869ff19f (plain) (blame)
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
package presence

import (
	"encoding/json"
	"log"
	"net/http"

	"penguins.lan/api/types"
	"penguins.lan/api/ws"
	"penguins.lan/database"
	"penguins.lan/utils"
)

type Waddler struct {
	Username string `json:"username"`
	Status   string `json:"status"`
	LastSeen string `json:"lastSeen"`
}

func waddlers(context *types.RequestContext, hub *ws.Hub) []Waddler {
	users, err := database.ListUsers(context.DBConn)
	if err != nil {
		log.Println("presence: list users failed:", err)
	}
	onChat := hub.Online()
	onNetwork, err := database.NetworkUserIDs(context.DBConn)
	if err != nil {
		log.Println("presence: network ids failed:", err)
	}

	list := make([]Waddler, 0, len(users))
	for _, u := range users {
		status := "offline"
		if onNetwork[u.ID] {
			status = "network"
		}
		if onChat[u.ID] {
			status = "chat"
		}
		list = append(list, Waddler{u.Username, status, utils.FormatSince(u.LastSeen)})
	}
	return list
}

func RosterContinuation(hub *ws.Hub) types.Continuation {
	return func(context *types.RequestContext, req *http.Request, resp http.ResponseWriter) types.ContinuationChain {
		return func(success types.Continuation, _failure types.Continuation) types.ContinuationChain {
			(*context.TemplateData)["Users"] = waddlers(context, hub)
			return success(context, req, resp)
		}
	}
}

func StatusContinuation(hub *ws.Hub) types.Continuation {
	return func(context *types.RequestContext, req *http.Request, resp http.ResponseWriter) types.ContinuationChain {
		return func(success types.Continuation, _failure types.Continuation) types.ContinuationChain {
			resp.Header().Set("Content-Type", "application/json")
			if err := json.NewEncoder(resp).Encode(waddlers(context, hub)); err != nil {
				log.Println("presence: encode failed:", err)
			}
			return success(context, req, resp)
		}
	}
}