]>
code.octet-stream.net Git - broadcaster/blob - server/radio_sync.go
4 "code.octet-stream.net/broadcaster/internal/protocol"
6 "golang.org/x/net/websocket"
10 func RadioSync(ws
*websocket
.Conn
) {
11 log
.Println("A websocket connected, I think")
12 buf
:= make([]byte, 16384)
15 isAuthenticated
:= false
18 // Ignore any massively oversize messages
19 n
, err
:= ws
.Read(buf
)
22 log
.Println("Lost websocket to radio:", radio
.Name
)
23 status
.RadioDisconnected(radio
.Id
)
25 log
.Println("Lost unauthenticated websocket")
37 t
, msg
, err
:= protocol
.ParseMessage(buf
[:n
])
43 if !isAuthenticated
&& t
!= protocol
.AuthenticateType
{
47 if t
== protocol
.AuthenticateType
&& !isAuthenticated
{
48 authMsg
:= msg
.(protocol
.AuthenticateMessage
)
49 r
, err
:= db
.GetRadioByToken(authMsg
.Token
)
51 log
.Println("Could not find radio for offered token", authMsg
.Token
)
54 log
.Println("Radio authenticated:", radio
.Name
)
55 isAuthenticated
= true
56 commandRouter
.AddWebsocket(r
.Id
, ws
)
57 defer commandRouter
.RemoveWebsocket(ws
)
59 go KeepFilesUpdated(ws
)
60 go KeepPlaylistsUpdated(ws
)
63 if t
== protocol
.StatusType
{
64 statusMsg
:= msg
.(protocol
.StatusMessage
)
65 log
.Println("Received Status from", radio
.Name
, ":", statusMsg
)
66 status
.MergeStatus(radio
.Id
, statusMsg
)
71 func sendPlaylistsMessageToRadio(ws
*websocket
.Conn
, p
[]Playlist
) error
{
72 playlistSpecs
:= make([]protocol
.PlaylistSpec
, 0)
75 entrySpecs
:= make([]protocol
.EntrySpec
, 0)
76 for _
, e
:= range db
.GetEntriesForPlaylist(v
.Id
) {
77 entrySpecs
= append(entrySpecs
, protocol
.EntrySpec
{Filename
: e
.Filename
, DelaySeconds
: e
.DelaySeconds
, IsRelative
: e
.IsRelative
})
79 playlistSpecs
= append(playlistSpecs
, protocol
.PlaylistSpec
{Id
: v
.Id
, Name
: v
.Name
, StartTime
: v
.StartTime
, Entries
: entrySpecs
})
82 playlists
:= protocol
.PlaylistsMessage
{
83 T
: protocol
.PlaylistsType
,
84 Playlists
: playlistSpecs
,
86 msg
, _
:= json
.Marshal(playlists
)
87 _
, err
:= ws
.Write(msg
)
91 func KeepPlaylistsUpdated(ws
*websocket
.Conn
) {
93 p
, ch
:= playlists
.WatchForChanges()
94 err
:= sendPlaylistsMessageToRadio(ws
, p
)
102 func sendFilesMessageToRadio(ws
*websocket
.Conn
, f
[]FileSpec
) error
{
103 specs
:= make([]protocol
.FileSpec
, 0)
104 for _
, v
:= range f
{
105 specs
= append(specs
, protocol
.FileSpec
{Name
: v
.Name
, Hash
: v
.Hash
})
107 files
:= protocol
.FilesMessage
{
108 T
: protocol
.FilesType
,
111 msg
, _
:= json
.Marshal(files
)
112 _
, err
:= ws
.Write(msg
)
116 func KeepFilesUpdated(ws
*websocket
.Conn
) {
118 f
, ch
:= files
.WatchForChanges()
119 err
:= sendFilesMessageToRadio(ws
, f
)