]>
code.octet-stream.net Git - broadcaster/blob - server/radio_sync.go
9fd9a658a834622b8b4a02b560e963b01a231445
4 "code.octet-stream.net/broadcaster/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
57 go KeepFilesUpdated(ws
)
58 go KeepPlaylistsUpdated(ws
)
61 if t
== protocol
.StatusType
{
62 statusMsg
:= msg
.(protocol
.StatusMessage
)
63 log
.Println("Received Status from", radio
.Name
, ":", statusMsg
)
64 status
.MergeStatus(radio
.Id
, statusMsg
)
69 func sendPlaylistsMessageToRadio(ws
*websocket
.Conn
, p
[]Playlist
) error
{
70 playlistSpecs
:= make([]protocol
.PlaylistSpec
, 0)
73 entrySpecs
:= make([]protocol
.EntrySpec
, 0)
74 for _
, e
:= range db
.GetEntriesForPlaylist(v
.Id
) {
75 entrySpecs
= append(entrySpecs
, protocol
.EntrySpec
{Filename
: e
.Filename
, DelaySeconds
: e
.DelaySeconds
, IsRelative
: e
.IsRelative
})
77 playlistSpecs
= append(playlistSpecs
, protocol
.PlaylistSpec
{Id
: v
.Id
, Name
: v
.Name
, StartTime
: v
.StartTime
, Entries
: entrySpecs
})
80 playlists
:= protocol
.PlaylistsMessage
{
81 T
: protocol
.PlaylistsType
,
82 Playlists
: playlistSpecs
,
84 msg
, _
:= json
.Marshal(playlists
)
85 _
, err
:= ws
.Write(msg
)
89 func KeepPlaylistsUpdated(ws
*websocket
.Conn
) {
91 p
, ch
:= playlists
.WatchForChanges()
92 err
:= sendPlaylistsMessageToRadio(ws
, p
)
100 func sendFilesMessageToRadio(ws
*websocket
.Conn
, f
[]FileSpec
) error
{
101 specs
:= make([]protocol
.FileSpec
, 0)
102 for _
, v
:= range f
{
103 specs
= append(specs
, protocol
.FileSpec
{Name
: v
.Name
, Hash
: v
.Hash
})
105 files
:= protocol
.FilesMessage
{
106 T
: protocol
.FilesType
,
109 msg
, _
:= json
.Marshal(files
)
110 _
, err
:= ws
.Write(msg
)
114 func KeepFilesUpdated(ws
*websocket
.Conn
) {
116 f
, ch
:= files
.WatchForChanges()
117 err
:= sendFilesMessageToRadio(ws
, f
)