jellyfixer/main.go
2020-12-08 12:46:52 +01:00

102 lines
2.3 KiB
Go

// nolint:gomnd,exhaustivestruct
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"time"
"git.xsfx.dev/xsteadfastx/logginghandler"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
// Logic Jellyfin URL
type Logic struct {
BaseURL string
}
// PublicInfo Chromecast configuration Payload
type PublicInfo struct {
ID string
LocalAddress string
OperatingSystem string
ProductName string
ServerName string
StartupWizardCompleted bool
Version string
}
func (l Logic) ServeHTTP(w http.ResponseWriter, r *http.Request) {
logger := logginghandler.Logger(r)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) // nolint:gomnd
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s/System/Info/Public", l.BaseURL), nil)
if err != nil {
logger.Error().Msg(err.Error())
http.Error(w, "could not create request jellyfin", http.StatusInternalServerError)
return
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
logger.Error().Msg(err.Error())
http.Error(w, "could not access jellyfin", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
logger.Error().Msg(err.Error())
http.Error(w, "could not read body", http.StatusInternalServerError)
return
}
var jd PublicInfo
if err := json.Unmarshal(body, &jd); err != nil {
logger.Error().Msg(err.Error())
http.Error(w, "could not unmarshal body", http.StatusInternalServerError)
return
}
url := os.Getenv("JELLYFIN_URL")
jd.LocalAddress = url
nd, err := json.Marshal(jd)
if err != nil {
logger.Error().Msg(err.Error())
http.Error(w, "could not marshal body", http.StatusInternalServerError)
return
}
if _, err := w.Write(nd); err != nil {
logger.Error().Msg(err.Error())
}
}
func main() {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
log.Logger = log.Logger.With().Caller().Logger()
if len(os.Args) != 2 {
log.Fatal().Msg("could not get base url as argument")
}
l := Logic{BaseURL: os.Args[1]}
handler := logginghandler.Handler(l)
http.Handle("/", handler)
log.Info().Msg("starting server...")
log.Fatal().Msg(http.ListenAndServe("0.0.0.0:8088", nil).Error())
}