summaryrefslogtreecommitdiff
path: root/src/helsinki.at/rhimportd/ctrlWebSocket.go
blob: df58f3ffa48c95517286e92c269d08d34fce30a0 (plain)
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
//
//  rhimportd
//
//  The Radio Helsinki Rivendell Import Daemon
//
//
//  Copyright (C) 2015 Christian Pointner <equinox@helsinki.at>
//
//  This file is part of rhimportd.
//
//  rhimportd 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.
//
//  rhimportd 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 rhimportd. If not, see <http://www.gnu.org/licenses/>.
//

package main

import (
	"fmt"
	"github.com/gorilla/websocket"
	"helsinki.at/rhimport"
	"html"
	"math"
	"net/http"
	"time"
)

type webSocketRequestData struct {
	Command            string `json:"COMMAND"`
	Id                 string `json:"ID"`
	UserName           string `json:"LOGIN_NAME"`
	Password           string `json:"PASSWORD"`
	ShowId             uint   `json:"SHOW_ID"`
	ClearShowCarts     bool   `json:"CLEAR_SHOW_CARTS"`
	MusicPoolGroup     string `json:"MUSIC_POOL_GROUP"`
	Cart               uint   `json:"CART_NUMBER"`
	ClearCart          bool   `json:"CLEAR_CART"`
	Cut                uint   `json:"CUT_NUMBER"`
	Channels           uint   `json:"CHANNELS"`
	NormalizationLevel int    `json:"NORMALIZATION_LEVEL"`
	AutotrimLevel      int    `json:"AUTOTRIM_LEVEL"`
	UseMetaData        bool   `json:"USE_METADATA"`
	SourceUri          string `json:"SOURCE_URI"`
	Timeout            uint   `json:"TIMEOUT"`
}

func newWebSocketRequestData(conf *rhimport.Config) *webSocketRequestData {
	rd := new(webSocketRequestData)
	rd.Command = ""
	rd.Id = ""
	rd.UserName = ""
	rd.Password = ""
	rd.ShowId = 0
	rd.ClearShowCarts = false
	rd.MusicPoolGroup = ""
	rd.Cart = 0
	rd.ClearCart = false
	rd.Cut = 0
	rd.Channels = conf.ImportParamDefaults.Channels
	rd.NormalizationLevel = conf.ImportParamDefaults.NormalizationLevel
	rd.AutotrimLevel = conf.ImportParamDefaults.AutotrimLevel
	rd.UseMetaData = conf.ImportParamDefaults.UseMetaData
	rd.SourceUri = ""
	rd.Timeout = 0
	return rd
}

type webSocketResponseData struct {
	ResponseCode     int     `json:"RESPONSE_CODE"`
	Type             string  `json:"TYPE"`
	ErrorString      string  `json:"ERROR_STRING"`
	Id               string  `json:"ID"`
	ProgressStep     int     `json:"PROGRESS_STEP"`
	ProgressStepName string  `json:"PROGRESS_STEP_NAME"`
	Progress         float64 `json:"PROGRESS"`
	Cart             uint    `json:"CART_NUMBER"`
	Cut              uint    `json:"CUT_NUMBER"`
}

func sendWebSocketResponse(ws *websocket.Conn, rd *webSocketResponseData) {
	if err := ws.WriteJSON(*rd); err != nil {
		rhdl.Println("WebScoket Client", ws.RemoteAddr(), "write error:", err)
	}
}

func sendWebSocketErrorResponse(ws *websocket.Conn, id string, code int, err_str string) {
	sendWebSocketResponse(ws, &webSocketResponseData{ResponseCode: code, Type: "ERROR", ErrorString: err_str, Id: id})
}

type webSocketSession struct {
	id       string
	session  *rhimport.SessionChan
	respchan chan webSocketResponseData
	donechan chan rhimport.ImportResult
}

func newWebSocketSession() *webSocketSession {
	session := &webSocketSession{}
	session.respchan = make(chan webSocketResponseData, 10)
	session.donechan = make(chan rhimport.ImportResult, 1)
	return session
}

func webSocketProgress(step int, step_name string, progress float64, userdata interface{}) bool {
	if math.IsNaN(progress) {
		progress = 0.0
	}
	session := userdata.(*webSocketSession)
	select {
	case session.respchan <- webSocketResponseData{http.StatusOK, "PROGRESS", "", session.id, step, step_name, progress * 100, 0, 0}:
	default:
	}
	return true
}

func webSocketDone(res rhimport.ImportResult, userdata interface{}) bool {
	session := userdata.(*webSocketSession)
	session.donechan <- res
	return true
}

func (self *webSocketSession) startNewSession(reqdata *webSocketRequestData, conf *rhimport.Config, rddb *rhimport.RdDbChan, sessions *rhimport.SessionStoreChan) (int, string) {
	ctx := rhimport.NewImportContext(conf, rddb, reqdata.UserName)
	ctx.Password = reqdata.Password
	ctx.Trusted = true // set this to false as soon as the interface is working
	ctx.ShowId = reqdata.ShowId
	ctx.ClearShowCarts = reqdata.ClearShowCarts
	ctx.GroupName = reqdata.MusicPoolGroup
	ctx.Cart = reqdata.Cart
	ctx.ClearCart = reqdata.ClearCart
	ctx.Cut = reqdata.Cut
	ctx.Channels = reqdata.Channels
	ctx.NormalizationLevel = reqdata.NormalizationLevel
	ctx.AutotrimLevel = reqdata.AutotrimLevel
	ctx.UseMetaData = reqdata.UseMetaData
	ctx.SourceUri = reqdata.SourceUri

	id, s, code, errstring := sessions.New(ctx)
	if code != http.StatusOK {
		return code, errstring
	}
	self.id = id
	self.session = s
	if err := s.AddDoneHandler(self, webSocketDone); err != nil {
		return http.StatusInternalServerError, err.Error()
	}
	if err := s.AddProgressHandler(self, webSocketProgress); err != nil {
		return http.StatusInternalServerError, err.Error()
	}
	s.Run(time.Duration(reqdata.Timeout) * time.Second)
	return http.StatusOK, "SUCCESS"
}

func webSocketSessionHandler(reqchan <-chan webSocketRequestData, ws *websocket.Conn, conf *rhimport.Config, rddb *rhimport.RdDbChan, sessions *rhimport.SessionStoreChan) {
	defer ws.Close()

	session := newWebSocketSession()
	for {
		select {
		case reqdata, ok := <-reqchan:
			if !ok {
				return
			}
			switch reqdata.Command {
			case "new":
				if session.id != "" {
					sendWebSocketErrorResponse(ws, "", http.StatusBadRequest, "This connection already handles a session")
					return
				}
				code, errstring := session.startNewSession(&reqdata, conf, rddb, sessions)
				if code != http.StatusOK {
					sendWebSocketErrorResponse(ws, "", code, errstring)
					return
				} else {
					sendWebSocketResponse(ws, &webSocketResponseData{ResponseCode: code, Type: "ACK", Id: session.id})
				}
			case "cancel":
				if session.id == "" {
					sendWebSocketErrorResponse(ws, "", http.StatusBadRequest, "This connection doesn't handle any session")
					return
				}
				session.session.Cancel()
			case "reconnect":
				if session.id != "" {
					sendWebSocketErrorResponse(ws, "", http.StatusBadRequest, "This connection already handles a session")
					return
				}
				sendWebSocketErrorResponse(ws, "", http.StatusNotImplemented, "reconnect session - not yet implemented")
				return
			default:
				sendWebSocketErrorResponse(ws, "", http.StatusBadRequest, fmt.Sprintf("unknown command '%s'", reqdata.Command))
				return
			}
		case respdata := <-session.respchan:
			sendWebSocketResponse(ws, &respdata)
		case donedata := <-session.donechan:
			sendWebSocketResponse(ws, &webSocketResponseData{donedata.ResponseCode, "DONE", donedata.ErrorString, session.id, 0, "", 100.0, donedata.Cart, donedata.Cut})
			// TODO: send close message at this point?
		}
	}
}

func webSocketHandler(conf *rhimport.Config, rddb *rhimport.RdDbChan, sessions *rhimport.SessionStoreChan, trusted bool, w http.ResponseWriter, r *http.Request) {
	rhdl.Printf("WebSocketHandler: request for '%s'", html.EscapeString(r.URL.Path))

	ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(w, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		rhdl.Println("WebSocket Client", ws.RemoteAddr(), "error:", err)
		return
	}
	rhdl.Println("WebSocket Client", ws.RemoteAddr(), "connected")
	reqchan := make(chan webSocketRequestData)
	go webSocketSessionHandler(reqchan, ws, conf, rddb, sessions)
	defer close(reqchan)

	for {
		reqdata := newWebSocketRequestData(conf)
		if err := ws.ReadJSON(&reqdata); err != nil {
			rhdl.Println("WebSocket Client", ws.RemoteAddr(), "disconnected:", err)
			return
		} else {
			//			rhdl.Printf("Websocket Client %s got: %+v", ws.RemoteAddr(), reqdata)
			reqchan <- *reqdata
		}
	}

	return
}