tsviewer/service/channel.go
2019-01-31 20:35:31 +01:00

92 lines
1.7 KiB
Go

package service
import (
"errors"
"git.cliffbreak.de/Cliffbreak/tsviewer/features/api/channel"
"github.com/multiplay/go-ts3"
)
func (s Service) Channel(id int) (*channel.Channel, error) {
channels, err := s.TSClient.Server.ChannelList()
if err != nil {
return nil, err
}
var c *channel.Channel
for _, channel := range channels {
if channel.ID == id {
c = convertChannel(channel)
break
}
}
if c == nil {
return nil, errors.New("channel does not exist")
}
return c, nil
}
func (s Service) Channels() ([]*channel.Channel, error) {
channels, err := s.TSClient.Server.ChannelList()
if err != nil {
return nil, err
}
var cc []*channel.Channel
for i, channel := range channels {
if channel == nil {
continue
}
if channel.ParentID == 0 {
cc = append(cc, convertChannel(channel))
removeItem(&channels, i)
}
}
for _, c := range cc {
addSubChannels(c, &channels)
}
return cc, nil
}
func convertChannel(c *ts3.Channel) *channel.Channel {
return &channel.Channel{
ID: c.ID,
Subchannels: []channel.Channel{},
Name: c.ChannelName,
TotalClients: c.TotalClients,
NeededSubscribePower: c.NeededSubscribePower,
}
}
func removeItem(slice *[]*ts3.Channel, id int) {
ss := *slice
length := len(ss)
if length < id+1 {
ss = nil
} else if length == id+1 {
ss = ss[:id]
} else if length > id+1 {
ss = append(ss[:id], ss[id+1:]...)
}
*slice = ss
}
func addSubChannels(c *channel.Channel, channels *[]*ts3.Channel) {
for i, channel := range *channels {
if c.ID == channel.ParentID {
removeItem(channels, i)
subChannel := convertChannel(channel)
addSubChannels(subChannel, channels)
c.Subchannels = append(c.Subchannels, *subChannel)
}
}
}