summaryrefslogtreecommitdiff
path: root/cmd/dolmetschctld/web_socket.go
blob: dcbb31151b5b21fafc3fedb4908234f9e8c1b633 (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
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
//
//  dolmetschctl
//
//
//  Copyright (C) 2019 Christian Pointner <equinox@spreadspace.org>
//
//  This file is part of dolmetschctl.
//
//  dolmetschctl is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  any later version.
//
//  dolmetschctl is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with dolmetschctl. If not, see <http://www.gnu.org/licenses/>.
//

package main

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

	"github.com/gorilla/websocket"
	"spreadspace.org/dolmetschctl/pkg/types"
)

func sendWebSocketResponse(ws *websocket.Conn, rd interface{}) {
	if err := ws.WriteJSON(rd); err != nil {
		log.Println("Web(socket) client", ws.RemoteAddr(), "write error:", err)
	}
}

func sendWebSocketErrorResponse(ws *websocket.Conn, code int, errStr string) {
	rd := &types.WebSocketResponseError{}
	rd.ResponseCode = code
	rd.Type = "error"
	rd.ErrorString = errStr
	sendWebSocketResponse(ws, rd)
}

type webSocketSession struct {
	ws           *websocket.Conn
	sm           *StateMachine
	stateSubCh   chan types.FullState
	stateUnsubCh chan<- struct{}
}

func (s *webSocketSession) handleRequest(req types.WebSocketRequest) {
	switch req.Command {
	case "state":
		if len(req.Args) != 0 {
			sendWebSocketErrorResponse(s.ws, http.StatusBadRequest, "command 'state' expects no arguments")
			return
		}

		var result types.WebSocketResponseState
		result.ResponseCode = http.StatusOK
		result.Type = "state"
		result.State, result.Ratio, result.Lang = s.sm.GetState()
		sendWebSocketResponse(s.ws, result)
	case "subscribe":
		if len(req.Args) != 0 {
			sendWebSocketErrorResponse(s.ws, http.StatusBadRequest, "command 'subscribe' expects no arguments")
			return
		}

		s.stateUnsubCh = s.sm.SubscribeState(s.stateSubCh)

		var result types.WebSocketResponseState
		result.ResponseCode = http.StatusOK
		result.Type = "state"
		result.State, result.Ratio, result.Lang = s.sm.GetState()
		sendWebSocketResponse(s.ws, result)
	case "languages":
		if len(req.Args) != 0 {
			sendWebSocketErrorResponse(s.ws, http.StatusBadRequest, "command 'languages' expects no arguments")
			return
		}

		var result types.WebSocketResponseLanguages
		result.ResponseCode = http.StatusOK
		result.Type = "languages"
		result.Languages = s.sm.GetLanguages()
		sendWebSocketResponse(s.ws, result)
	case "language":
		if len(req.Args) != 1 {
			sendWebSocketErrorResponse(s.ws, http.StatusBadRequest, "command 'language' expects exatly one argument")
			return
		}

		if err := s.sm.SetLanguage(types.Language(req.Args[0])); err != nil {
			sendWebSocketErrorResponse(s.ws, http.StatusBadRequest, err.Error())
			return
		}

		var result types.WebSocketResponseState
		result.ResponseCode = http.StatusOK
		result.Type = "state"
		result.State, result.Ratio, result.Lang = s.sm.GetState()
		sendWebSocketResponse(s.ws, result)
	default:
		sendWebSocketErrorResponse(s.ws, http.StatusBadRequest, "unkown command: '"+req.Command+"'")
	}
}

func (s *webSocketSession) Handler(reqCh <-chan types.WebSocketRequest) {
	defer func() {
		s.ws.Close()
		if s.stateUnsubCh != nil {
			close(s.stateUnsubCh)
		}
	}()

	s.stateSubCh = make(chan types.FullState, 100)
	for {
		select {
		case state, ok := <-s.stateSubCh:
			if !ok {
				return
			}
			var result types.WebSocketResponseState
			result.ResponseCode = http.StatusOK
			result.Type = "state"
			result.State = state.State
			result.Ratio = state.Ratio
			result.Lang = state.Language
			sendWebSocketResponse(s.ws, result)
		case req, ok := <-reqCh:
			if !ok {
				return
			}
			s.handleRequest(req)
		}
	}
}

func webSocketHandler(sm *StateMachine, w http.ResponseWriter, r *http.Request) {
	ws, err := websocket.Upgrade(w, r, nil, 64*1024, 64*1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(w, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		log.Println("Web(socket) client", ws.RemoteAddr(), "error:", err)
		return
	}
	log.Println("Web(socket) client", ws.RemoteAddr(), "connected")
	reqCh := make(chan types.WebSocketRequest)
	session := webSocketSession{ws: ws, sm: sm}
	go session.Handler(reqCh)
	defer close(reqCh)

	for {
		t, r, err := ws.NextReader()
		if err != nil {
			log.Println("Web(socket) client", ws.RemoteAddr(), "disconnected:", err)
			return
		}

		switch t {
		case websocket.TextMessage:
			var req types.WebSocketRequest
			dec := json.NewDecoder(r)
			dec.DisallowUnknownFields()
			if err := dec.Decode(&req); err != nil {
				if err == io.EOF {
					err = io.ErrUnexpectedEOF
				}
				log.Println("Web(socket) client", ws.RemoteAddr(), "request error:", err)
				sendWebSocketErrorResponse(ws, http.StatusBadRequest, err.Error())
				return
			}

			reqCh <- req
		case websocket.BinaryMessage:
			sendWebSocketErrorResponse(ws, http.StatusBadRequest, "binary messages are not allowed")
			io.Copy(ioutil.Discard, r) // consume all the data
		}
	}
}