]>
code.octet-stream.net Git - broadcaster/blob - server/radio_sync.go
3dfd4ed5395c008b6cdfe9889fda4d8e6de240ae
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
)
59 // send initial file message
60 err
= sendFilesMessageToRadio(ws
)
65 go KeepPlaylistsUpdated(ws
)
67 // send initial playlists message
68 err
= sendPlaylistsMessageToRadio(ws
)
74 if t
== protocol
.StatusType
{
75 statusMsg
:= msg
.(protocol
.StatusMessage
)
76 log
.Println("Received Status from", radio
.Name
, ":", statusMsg
)
77 status
.MergeStatus(radio
.Id
, statusMsg
)
82 func sendPlaylistsMessageToRadio(ws
*websocket
.Conn
) error
{
83 playlistSpecs
:= make([]protocol
.PlaylistSpec
, 0)
84 for _
, v
:= range db
.GetPlaylists() {
86 entrySpecs
:= make([]protocol
.EntrySpec
, 0)
87 for _
, e
:= range db
.GetEntriesForPlaylist(v
.Id
) {
88 entrySpecs
= append(entrySpecs
, protocol
.EntrySpec
{Filename
: e
.Filename
, DelaySeconds
: e
.DelaySeconds
, IsRelative
: e
.IsRelative
})
90 playlistSpecs
= append(playlistSpecs
, protocol
.PlaylistSpec
{Id
: v
.Id
, Name
: v
.Name
, StartTime
: v
.StartTime
, Entries
: entrySpecs
})
93 playlists
:= protocol
.PlaylistsMessage
{
94 T
: protocol
.PlaylistsType
,
95 Playlists
: playlistSpecs
,
97 msg
, _
:= json
.Marshal(playlists
)
98 _
, err
:= ws
.Write(msg
)
102 func KeepPlaylistsUpdated(ws
*websocket
.Conn
) {
105 err
:= sendPlaylistsMessageToRadio(ws
)
112 func sendFilesMessageToRadio(ws
*websocket
.Conn
) error
{
113 specs
:= make([]protocol
.FileSpec
, 0)
114 for _
, v
:= range files
.Files() {
115 specs
= append(specs
, protocol
.FileSpec
{Name
: v
.Name
, Hash
: v
.Hash
})
117 files
:= protocol
.FilesMessage
{
118 T
: protocol
.FilesType
,
121 msg
, _
:= json
.Marshal(files
)
122 _
, err
:= ws
.Write(msg
)
126 func KeepFilesUpdated(ws
*websocket
.Conn
) {
128 <-files
.ChangeChannel()
129 err
:= sendFilesMessageToRadio(ws
)