-
Notifications
You must be signed in to change notification settings - Fork 0
/
sockets.go
157 lines (137 loc) · 4.17 KB
/
sockets.go
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
package sockets
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"sync"
"time"
"golang.org/x/net/websocket"
"github.com/ngalaiko/miniboard/backend/authorizations"
"github.com/ngalaiko/miniboard/backend/httpx"
"github.com/ngalaiko/miniboard/backend/items"
"github.com/ngalaiko/miniboard/backend/subscriptions"
"github.com/ngalaiko/miniboard/backend/tags"
"github.com/ngalaiko/miniboard/backend/web/render"
)
type itemsService interface {
Get(ctx context.Context, id string, userID string) (*items.Item, error)
List(ctx context.Context, userID string, pageSize int, createdLT *time.Time, subscriptionID *string, tagID *string) ([]*items.Item, error)
}
type subscriptionsService interface {
Create(ctx context.Context, userID string, url *url.URL, tagIDs []string) (*subscriptions.Subscription, error)
List(ctx context.Context, userID string, pageSize int, createdLT *time.Time) ([]*subscriptions.Subscription, error)
}
type tagsService interface {
Create(ctx context.Context, userID string, title string) (*tags.Tag, error)
GetByTitle(ctx context.Context, userID string, title string) (*tags.Tag, error)
List(ctx context.Context, userID string, pageSize int, createdLT *time.Time) ([]*tags.Tag, error)
}
type request struct {
ID uint `json:"id"`
Event string `json:"event"`
Params map[string]string `json:"params"`
}
type logger interface {
Error(string, ...interface{})
}
type Sockets struct {
logger logger
itemsService itemsService
tagsService tagsService
subscriptionsService subscriptionsService
render *render.Templates
openSocketsGuard *sync.RWMutex
openSockets map[string][]*websocket.Conn
}
func New(
logger logger,
itemsService itemsService,
tagsService tagsService,
subscriptionsService subscriptionsService,
render *render.Templates,
) *Sockets {
return &Sockets{
logger: logger,
itemsService: itemsService,
tagsService: tagsService,
subscriptionsService: subscriptionsService,
render: render,
openSocketsGuard: &sync.RWMutex{},
openSockets: make(map[string][]*websocket.Conn),
}
}
func (s *Sockets) Receive() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token, auth := authorizations.FromContext(r.Context())
if !auth {
httpx.Error(w, s.logger, fmt.Errorf(""), http.StatusUnauthorized)
} else {
websocket.Handler(s.handle(token.UserID)).ServeHTTP(w, r)
}
}
}
func (s *Sockets) register(userID string, ws *websocket.Conn) {
s.openSocketsGuard.Lock()
s.openSockets[userID] = append(s.openSockets[userID], ws)
s.openSocketsGuard.Unlock()
}
func (s *Sockets) unregister(userID string, ws *websocket.Conn) {
s.openSocketsGuard.Lock()
defer s.openSocketsGuard.Unlock()
for i, w := range s.openSockets[userID] {
if *w != *ws {
continue
}
s.openSockets[userID] = append(s.openSockets[userID][:i], s.openSockets[userID][i+1:]...)
return
}
}
func (s *Sockets) handle(userID string) func(*websocket.Conn) {
return func(ws *websocket.Conn) {
s.register(userID, ws)
defer s.unregister(userID, ws)
for {
req := &request{}
err := websocket.JSON.Receive(ws, req)
switch {
case err == nil:
switch req.Event {
case "items:select":
s.itemsSelect(ws, userID, req)
case "items:loadmore":
s.itemsLoadmore(ws, userID, req)
case "items:load":
s.itemsLoad(ws, userID, req)
case "subscriptions:create":
s.subscriptionsCreate(ws, userID, req)
case "subscriptions:import":
s.subscriptionsImport(ws, userID, req)
default:
s.respond(ws, &response{
ID: req.ID,
Error: fmt.Sprintf("unknown event '%s'", req.Event),
})
}
case errors.Is(err, io.EOF):
return
default:
s.logger.Error("failed to read a request: %s", err)
}
}
}
}
func (s *Sockets) respond(ws *websocket.Conn, resp *response) {
if err := websocket.JSON.Send(ws, resp); err != nil {
s.logger.Error("failed to write response message: %s", err)
}
}
func (s *Sockets) broadcast(userID string, resp *response) {
s.openSocketsGuard.RLock()
for _, ws := range s.openSockets[userID] {
s.respond(ws, resp)
}
s.openSocketsGuard.RUnlock()
}