Compare commits

..

No commits in common. "master" and "master" have entirely different histories.

31 changed files with 166 additions and 476 deletions

View file

3
.gitignore vendored
View file

@ -13,5 +13,4 @@
*.out
# Custom Blacklist
#CM
config.json

View file

@ -1,22 +0,0 @@
FROM golang:latest
ENV TS3_IP=127.0.0.1
ENV TS3_NAME=serveradmin
ENV TS3_PW=<changeMe>
ENV TS3_PORT=9987
ENV TS3_QUERY=10011
ENV WEB_PORT=8080
ENV BLACKLIST_USER=USER
RUN mkdir /app
WORKDIR /app
RUN mkdir /app/go
RUN export GOPATH=/app/go
COPY main.go .
RUN go get; exit 0
WORKDIR $GOPATH/src/git.cliffbreak.de/Cliffbreak/tsviewer
COPY config.json .
RUN go build
CMD ["./tsviewer"]

View file

@ -1,59 +1,30 @@
# tsviewer **[ALPHA 1.0.1]**
# go-tsviewer **[WIP]**
## **WARNING** This API is not usable ATM
A TS3 Viewer with REST API.
## DOCKER-Config
```bash
docker build -t name/cont:ver .
docker run -e TS3_IP="<SERVER-IP>" -e TS3_PW="<SERVER-ADMIN_PW>" -e WEB_PORT="8080" -d -p 8080:8080 name/cont:ver
```
ENV:
```Docker
ENV TS3_IP=127.0.0.1
ENV TS3_NAME=serveradmin
ENV TS3_PW=<changeMe>
ENV TS3_PORT=9987
ENV TS3_QUERY=10011
ENV WEB_PORT=8080
ENV BLACKLIST_USER=USER
```
A REST API made for TS3 Viewer.
# Features
## Config
The config file is generated automatically on first startup.
```json
{
"ip": "127.0.0.1", // Server IP
"port": 10011, // Dataquery Port
"user": {
"nickname": "serveradmin",
"name": "serveradmin",
"password": ""
"name": "serveradmin", // Username
"password": "" // Password
},
"serverTS": {
"ip": "127.0.0.1",
"portServer": 9987,
"portQuery": 10011
},
"serverWeb": {
"port": 80
"server": {
"port": 9987 // Port of the target server
}
}
```
## URL-Parameter
| Name | Type | Description |
| ---------- | ------ | ------------------------ |
| `pretty` | `bool` | pretty-prints JSON |
| `envelope` | `bool` | wraps JSON in data array |
| Name | Type | Description |
| ---------- | -------- | ------------------------ |
| `pretty` | `bool` | pretty-prints JSON |
| `envelope` | `bool` | wraps JSON in data array |
## Channels
- **`GET`** `/v1/channels/:id`
- **`GET`** `/v1/channels`
```json
@ -66,9 +37,7 @@ The config file is generated automatically on first startup.
"awayMessage": ""
}
```
## Clients
- **`GET`** `/v1/clients/:id`
- **`GET`** `/v1/clients/`
```json
@ -82,9 +51,7 @@ The config file is generated automatically on first startup.
"neededSubscribePower": 0
}
```
## Server
- **`GET`** `/v1/server/info`
```json
{

View file

@ -1,15 +0,0 @@
{
"user": {
"nickname": "serveradmin",
"name": "serveradmin",
"password": "HNxkefVx"
},
"serverTS": {
"ip": "127.0.0.1",
"portServer": 9987,
"portQuery": 10011
},
"serverWeb": {
"port": 80
}
}

View file

@ -1,84 +1,69 @@
package config
import (
"encoding/json"
"io/ioutil"
"log"
"os"
"strconv"
"github.com/spf13/viper"
)
type Config struct {
User struct {
Nickname string
Name string
Password string
}
ServerTS struct {
IP string
PortServer uint16
PortQuery uint16
}
ServerWeb struct {
Port uint16
}
IP string `json:"ip"`
Port uint16 `json:"port"`
User User `json:"user"`
Server Server `json:"server"`
}
type User struct {
Name string `json:"name"`
Password string `json:"password"`
}
type Server struct {
Port uint16 `json:"port"`
}
const FileName = "config.json"
func New() (*Config, error) {
viper.SetConfigName("config")
viper.SetConfigFile("yaml")
viper.AddConfigPath(".")
if err := viper.ReadInConfig(); err != nil {
return nil, err
config := defaults()
configFile, err := os.Open(FileName)
if err != nil {
if err := config.createFile(); err != nil {
return nil, err
}
log.Println(config)
return &config, nil
}
defer configFile.Close()
setDefaults()
jsonParser := json.NewDecoder(configFile)
jsonParser.Decode(&config)
var config Config
err := viper.Unmarshal(&config)
config.overrideWithEnvironmentVars()
return &config, err
return &config, nil
}
func setDefaults() {
viper.SetDefault("User.Nickname", "serveradmin")
viper.SetDefault("User.Name", "serveradmin")
viper.SetDefault("User.Password", "<changeMe>")
viper.SetDefault("ServerTS.IP", "127.0.0.1")
viper.SetDefault("ServerTS.PortServer", "9987")
viper.SetDefault("ServerTS.PortQuery", "10011")
viper.SetDefault("ServerWeb.Port", "80")
func (config Config) createFile() error {
configJSON, err := json.MarshalIndent(config, "", " ")
if err != nil {
return err
}
return ioutil.WriteFile(FileName, configJSON, 0644)
}
func (config *Config) overrideWithEnvironmentVars() {
if nickname := os.Getenv("TS3_NICKNAME"); nickname != "" {
config.User.Nickname = nickname
}
if username := os.Getenv("TS3_NAME"); username != "" {
config.User.Name = username
}
if password := os.Getenv("TS3_PW"); password != "" {
config.User.Password = password
}
if tsIP := os.Getenv("TS3_IP"); tsIP != "" {
config.ServerTS.IP = tsIP
}
if tsPort, err := strconv.Atoi(os.Getenv("TS3_PORT")); tsPort <= 65535 && tsPort >= 0 && err == nil {
config.ServerTS.PortServer = uint16(tsPort)
}
if tsQuery, err := strconv.Atoi(os.Getenv("TS3_QUERY")); tsQuery <= 65535 && tsQuery >= 0 && err == nil {
config.ServerTS.PortQuery = uint16(tsQuery)
}
if webPort, err := strconv.Atoi(os.Getenv("WEB_PORT")); webPort <= 65535 && webPort >= 0 && err == nil {
config.ServerWeb.Port = uint16(webPort)
func defaults() Config {
return Config{
IP: "127.0.0.1",
Port: 10011,
User: User{
Name: "serveradmin",
Password: "",
},
Server: Server{
Port: 9987,
},
}
}

View file

@ -7,8 +7,8 @@ type Service interface {
type Channel struct {
ID int `json:"id"`
Name string `json:"name"`
Subchannels []Channel `json:"subchannels,omitempty"`
Name string `json:"name"`
TotalClients int `json:"totalClients"`
NeededSubscribePower int `json:"neededSubscribePower"`
}

View file

@ -4,13 +4,13 @@ import (
"net/http"
"strconv"
"git.cliffbreak.de/Cliffbreak/tsviewer/response"
"git.cliffbreak.de/haveachin/go-tsviewer/response"
"github.com/go-chi/chi"
)
func ChannelAPIHandler(s Service) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
response.Handler(w, r, response.HandlerFunc(func() (int, error) {
response.Handler(w, response.HandlerFunc(func() (int, error) {
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 64)
if err != nil {
return http.StatusBadRequest, err
@ -28,7 +28,7 @@ func ChannelAPIHandler(s Service) http.HandlerFunc {
func ChannelsAPIHandler(s Service) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
response.Handler(w, r, response.HandlerFunc(func() (int, error) {
response.Handler(w, response.HandlerFunc(func() (int, error) {
cc, err := s.Channels()
if err != nil {
return http.StatusBadRequest, err

View file

@ -4,13 +4,13 @@ import (
"net/http"
"strconv"
"git.cliffbreak.de/Cliffbreak/tsviewer/response"
"git.cliffbreak.de/haveachin/go-tsviewer/response"
"github.com/go-chi/chi"
)
func ClientAPIHandler(s Service) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
response.Handler(w, r, response.HandlerFunc(func() (int, error) {
response.Handler(w, response.HandlerFunc(func() (int, error) {
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 64)
if err != nil {
return http.StatusBadRequest, err
@ -28,7 +28,7 @@ func ClientAPIHandler(s Service) http.HandlerFunc {
func ClientsAPIHandler(s Service) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
response.Handler(w, r, response.HandlerFunc(func() (int, error) {
response.Handler(w, response.HandlerFunc(func() (int, error) {
cc, err := s.Clients()
if err != nil {
return http.StatusBadRequest, err

View file

@ -3,13 +3,13 @@ package server
import (
"net/http"
"git.cliffbreak.de/Cliffbreak/tsviewer/response"
"git.cliffbreak.de/haveachin/go-tsviewer/response"
)
func InfoAPIHandler(s Service) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
response.Handler(w, r, response.HandlerFunc(func() (int, error) {
s, err := s.ServerInfo()
response.Handler(w, response.HandlerFunc(func() (int, error) {
s, err := s.Info()
if err != nil {
return http.StatusNotFound, err
}

View file

@ -3,7 +3,7 @@ package server
import "time"
type Service interface {
ServerInfo() (*Server, error)
Info() (*Server, error)
}
type Server struct {

View file

@ -1,32 +0,0 @@
package index
import (
"html/template"
"net/http"
"git.cliffbreak.de/Cliffbreak/tsviewer/features/web/weberror"
)
func IndexGUIHandler(s Service, t template.Template) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
server, err := s.ServerInfo()
if err != nil {
weberror.NewPage(err, http.StatusNotFound).Send(w, t)
return
}
channels, err := s.ChannelsRaw()
if err != nil {
weberror.NewPage(err, http.StatusNotFound).Send(w, t)
return
}
clients, err := s.Clients()
if err != nil {
weberror.NewPage(err, http.StatusNotFound).Send(w, t)
return
}
NewPage(*server, channels, clients).Send(w, t)
})
}

View file

@ -1,35 +0,0 @@
package index
import (
"html/template"
"io"
"git.cliffbreak.de/Cliffbreak/tsviewer/features/api/channel"
"git.cliffbreak.de/Cliffbreak/tsviewer/features/api/client"
"git.cliffbreak.de/Cliffbreak/tsviewer/features/api/server"
)
type Service interface {
ServerInfo() (*server.Server, error)
Clients() ([]*client.Client, error)
Channels() ([]*channel.Channel, error)
ChannelsRaw() ([]*channel.Channel, error)
}
type IndexPage struct {
Server server.Server
Channels []*channel.Channel
Clients []*client.Client
}
func NewPage(server server.Server, channels []*channel.Channel, clients []*client.Client) *IndexPage {
return &IndexPage{
Server: server,
Channels: channels,
Clients: clients,
}
}
func (page IndexPage) Send(w io.Writer, t template.Template) {
t.Lookup("index.html").Execute(w, page)
}

View file

@ -1,15 +0,0 @@
package index
import (
"html/template"
"github.com/go-chi/chi"
)
func GUIRoutes(s Service, t template.Template) *chi.Mux {
router := chi.NewRouter()
router.Get("/", IndexGUIHandler(s, t))
return router
}

View file

@ -1,22 +0,0 @@
package weberror
import (
"html/template"
"io"
)
type ErrorPage struct {
Error error
StatusCode int
}
func NewPage(err error, statusCode int) *ErrorPage {
return &ErrorPage{
Error: err,
StatusCode: statusCode,
}
}
func (page ErrorPage) Send(w io.Writer, t template.Template) {
t.Lookup("error.html").Execute(w, page)
}

View file

@ -1,35 +0,0 @@
package gui
import (
"fmt"
"html/template"
"io/ioutil"
"strings"
)
func LoadTemplates() (*template.Template, error) {
return loadTemplates("templates/")
}
func loadTemplates(path string) (*template.Template, error) {
dir, err := ioutil.ReadDir(path)
if err != nil {
return nil, err
}
var ff []string
for _, file := range dir {
filename := file.Name()
if strings.HasSuffix(filename, ".html") {
ff = append(ff, fmt.Sprintf("%s%s", path, filename))
}
}
templates, err := template.ParseFiles(ff...)
if err != nil {
return nil, err
}
return templates, nil
}

46
main.go
View file

@ -1,38 +1,27 @@
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"time"
"git.cliffbreak.de/Cliffbreak/tsviewer/config"
"git.cliffbreak.de/Cliffbreak/tsviewer/features/api/channel"
"git.cliffbreak.de/Cliffbreak/tsviewer/features/api/client"
"git.cliffbreak.de/Cliffbreak/tsviewer/features/api/server"
"git.cliffbreak.de/Cliffbreak/tsviewer/features/web/index"
"git.cliffbreak.de/Cliffbreak/tsviewer/gui"
"git.cliffbreak.de/Cliffbreak/tsviewer/service"
"git.cliffbreak.de/haveachin/go-tsviewer/config"
"git.cliffbreak.de/haveachin/go-tsviewer/features/channel"
"git.cliffbreak.de/haveachin/go-tsviewer/features/client"
"git.cliffbreak.de/haveachin/go-tsviewer/features/server"
"git.cliffbreak.de/haveachin/go-tsviewer/service"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/cors"
)
func Routes(s service.Service, t template.Template) *chi.Mux {
func Routes(s service.Service) *chi.Mux {
router := chi.NewRouter()
cors := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"Get"},
})
router.Use(
middleware.Logger,
middleware.Timeout(5*time.Second),
middleware.DefaultCompress,
middleware.RedirectSlashes,
middleware.Recoverer,
cors.Handler,
)
router.Route("/v1", func(r chi.Router) {
@ -41,41 +30,22 @@ func Routes(s service.Service, t template.Template) *chi.Mux {
r.Mount("/server", server.APIRoutes(s))
})
router.Route("/", func(r chi.Router) {
r.Mount("/", index.GUIRoutes(s, t))
})
return router
}
func main() {
log.Println("Loading configurations...")
config, err := config.New()
if err != nil {
log.Fatal(err)
}
log.Println("Configurations loaded!")
log.Println("Starting query service...")
service, err := service.New(*config)
if err != nil {
log.Fatal(err)
}
defer service.TSClient.Close()
log.Println("Query service connected to", fmt.Sprintf("%s:%d!", config.ServerTS.IP, config.ServerTS.PortQuery))
log.Println("Loading templates...")
templates, err := gui.LoadTemplates()
if err != nil {
log.Fatal(err)
}
log.Println("All templates loaded!")
router := Routes(*service)
router := Routes(*service, *templates)
router.Get("/static/*", func(w http.ResponseWriter, r *http.Request) {
http.StripPrefix("/static", http.FileServer(http.Dir("./static"))).ServeHTTP(w, r)
})
log.Println("Starting the web server locally on port", config.ServerWeb.Port)
log.Fatal("Handler: ", http.ListenAndServe(fmt.Sprintf(":%d", config.ServerWeb.Port), router))
log.Fatal("Handler: ", http.ListenAndServe(":8080", router))
}

View file

@ -10,10 +10,12 @@ type Error struct {
}
// NewError creates a new Response fill with an error
func NewError(status int, err error) *Error {
return &Error{
Status: status,
Error: err.Error(),
Timestamp: time.Now().Format("2006-01-02T15:04:05Z"), //.Format("02 Jan 2006, 15:04:05 MST"),
func NewError(status int, err error) *Response {
return &Response{
Content: Error{
Status: status,
Error: err.Error(),
Timestamp: time.Now().Format("2006-01-02T15:04:05Z"), //.Format("02 Jan 2006, 15:04:05 MST"),
},
}
}

View file

@ -5,7 +5,7 @@ import (
"log"
"net/http"
"git.cliffbreak.de/Cliffbreak/tsviewer/request/meta"
"git.cliffbreak.de/haveachin/go-tsviewer/request/meta"
)
type HandlerFunc func() (int, error)
@ -74,14 +74,14 @@ func (resp Response) Send(w http.ResponseWriter, status int) (int, error) {
return status, nil
}
func Handler(w http.ResponseWriter, r *http.Request, hf HandlerFunc) {
func Handler(w http.ResponseWriter, hf HandlerFunc) {
status, err := hf()
if err == nil {
return
}
log.Printf("HTTP %d: %q", status, err)
if status, err = New(NewError(status, err), r).Send(w, status); err != nil {
if status, err = NewError(status, err).Send(w, status); err != nil {
http.Error(w, http.StatusText(status), status)
}
}

View file

@ -3,7 +3,7 @@ package service
import (
"errors"
"git.cliffbreak.de/Cliffbreak/tsviewer/features/api/channel"
"git.cliffbreak.de/haveachin/go-tsviewer/features/channel"
"github.com/multiplay/go-ts3"
)
@ -37,38 +37,17 @@ func (s Service) Channels() ([]*channel.Channel, error) {
var cc []*channel.Channel
for i, channel := range channels {
if channel == nil {
continue
}
if channel.ParentID == 0 {
channels[i] = nil
cc = append(cc, convertChannel(channel))
}
}
for _, c := range cc {
addSubChannels(c, channels)
}
return cc, nil
}
func (s Service) ChannelsRaw() ([]*channel.Channel, error) {
channels, err := s.TSClient.Server.ChannelList()
if err != nil {
return nil, err
}
var cc []*channel.Channel
for _, channel := range channels {
if channel == nil {
if channel.ParentID == 0 {
cc = append(cc, convertChannel(channel))
continue
}
cc = append(cc, convertChannel(channel))
for _, c := range cc {
if c.ID == channel.ParentID {
c.Subchannels = append(c.Subchannels, *convertChannel(channel))
}
}
}
return cc, nil
@ -77,24 +56,9 @@ func (s Service) ChannelsRaw() ([]*channel.Channel, error) {
func convertChannel(c *ts3.Channel) *channel.Channel {
return &channel.Channel{
ID: c.ID,
Name: c.ChannelName,
Subchannels: []channel.Channel{},
Name: c.ChannelName,
TotalClients: c.TotalClients,
NeededSubscribePower: c.NeededSubscribePower,
}
}
func addSubChannels(c *channel.Channel, channels []*ts3.Channel) {
for i, channel := range channels {
if channel == nil {
continue
}
if c.ID == channel.ParentID {
channels[i] = nil
subChannel := convertChannel(channel)
addSubChannels(subChannel, channels)
c.Subchannels = append(c.Subchannels, *subChannel)
}
}
}

View file

@ -3,7 +3,7 @@ package service
import (
"errors"
"git.cliffbreak.de/Cliffbreak/tsviewer/features/api/client"
"git.cliffbreak.de/haveachin/go-tsviewer/features/client"
"github.com/multiplay/go-ts3"
)
@ -26,6 +26,10 @@ func (s Service) Client(id int) (*client.Client, error) {
return nil, errors.New("client does not exist")
}
/* if _, err := s.TSClient.Server.ExecCmd(ts3.NewCmd(fmt.Sprintf("clientinfo clid=%d", c.ID)).WithResponse(&c)); err != nil {
return nil, err
} */
return c, nil
}

View file

@ -3,10 +3,10 @@ package service
import (
"time"
"git.cliffbreak.de/Cliffbreak/tsviewer/features/api/server"
"git.cliffbreak.de/haveachin/go-tsviewer/features/server"
)
func (s Service) ServerInfo() (*server.Server, error) {
func (s Service) Info() (*server.Server, error) {
serverInfo, err := s.TSClient.Server.Info()
if err != nil {
return nil, err

View file

@ -1,11 +1,10 @@
package service
import (
"fmt"
"log"
"time"
"strconv"
"git.cliffbreak.de/Cliffbreak/tsviewer/config"
"git.cliffbreak.de/haveachin/go-tsviewer/config"
"git.cliffbreak.de/haveachin/go-tsviewer/stringer"
ts3 "github.com/multiplay/go-ts3"
)
@ -14,7 +13,12 @@ type Service struct {
}
func New(config config.Config) (*Service, error) {
client, err := ts3.NewClient(fmt.Sprintf("%s:%d", config.ServerTS.IP, config.ServerTS.PortQuery))
addr, err := stringer.Build(config.IP, ":", strconv.Itoa(int(config.Port)))
if err != nil {
return nil, err
}
client, err := ts3.NewClient(addr)
if err != nil {
return nil, err
}
@ -23,22 +27,10 @@ func New(config config.Config) (*Service, error) {
return nil, err
}
if err := client.UsePort(int(config.ServerTS.PortServer)); err != nil {
if err := client.UsePort(int(config.Server.Port)); err != nil {
return nil, err
}
if err := client.SetNick(config.User.Nickname); err != nil {
return nil, err
}
go func() {
for true {
time.Sleep(time.Second * 150)
client.Server.Version()
log.Println("keep alive")
}
}()
return &Service{
TSClient: client,
}, nil

View file

@ -1,22 +0,0 @@
*{
padding: 0;
margin: 0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.content {
max-width: 500px;
margin: auto;
}
h2{
padding-top: 20px;
}
small{
margin-left: 10px;
}
p.client{
margin-left: 10px;
}

49
stringer/stringer.go Normal file
View file

@ -0,0 +1,49 @@
package stringer
import (
"fmt"
"strings"
"unicode"
)
func Build(ss ...string) (string, error) {
var builder strings.Builder
for _, s := range ss {
if _, err := builder.WriteString(s); err != nil {
return "", err
}
}
return builder.String(), nil
}
func ToCamel(str string) string {
if len(str) < 1 {
return str
}
for i, c := range str[1:] {
if c >= 'A' && c <= 'Z' {
str = fmt.Sprintf("%s_%c%s", str[:i+1], unicode.ToLower(c), str[i+2:])
return ToCamel(str)
}
}
return str
}
func ToSnake(str string) string {
if len(str) < 1 {
return str
}
for i, c := range str[1:] {
if c == '_' {
str = fmt.Sprintf("%s%c%s", str[:i+1], unicode.ToUpper(rune(str[i+2])), str[i+3:])
return ToSnake(str)
}
}
return str
}

View file

@ -1,11 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
</head>
<body>
<h1>Oops, an error occurred!</h1>
<p1>Error {{.StatusCode}}</p1>
<p1>{{.Error}}</p1>
</body>
</html>

View file

@ -1,33 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>TS3 Viewer</title>
<link rel="stylesheet" href="static/styles.css">
</head>
<body>
<div class="content">
<h2>Online Members</h2>
<ul>
{{range .Clients}}
<li>{{.Nickname}}</li>
{{end}}
</ul>
<h2>{{.Server.Name}}</h2>
<!-- <small>{{.Server.Version}}</small> -->
{{$clients := .Clients}}
{{range .Channels}}
<p class="channel">{{.Name}}</p>
{{$channelId := .ID}}
{{range $clients}}
{{if eq $channelId .ChannelID}}
<p class="client">{{.Nickname}}</p>
{{end}}
{{end}}
{{end}}
</div>
</body>
</html>