diff --git a/common/transporter/structs.go b/common/transporter/structs.go index 4116cff..dbd6543 100644 --- a/common/transporter/structs.go +++ b/common/transporter/structs.go @@ -7,6 +7,7 @@ import ( type ( // TransporterUnique is sent with an ID in order to be returned and sorted + //nolint:revive TransporterUnique struct { // ID is the unique code used to identify a request ID string `json:"id" mapstructure:"id"` diff --git a/common/wsMessages/special/specialWsMessages.go b/common/wsMessages/special/specialWsMessages.go index bc75be1..09a0c45 100644 --- a/common/wsMessages/special/specialWsMessages.go +++ b/common/wsMessages/special/specialWsMessages.go @@ -1,3 +1,4 @@ +//nolint:revive package wsMessages type SpecialWSMessage string diff --git a/common/wsMessages/wsMessages.go b/common/wsMessages/wsMessages.go index 726330c..8db3ee4 100644 --- a/common/wsMessages/wsMessages.go +++ b/common/wsMessages/wsMessages.go @@ -1,3 +1,4 @@ +//nolint:revive package wsMessages type WSMessage string diff --git a/server/helper/getBody.go b/server/helper/getBody.go index 91a98cd..c7bf1e3 100644 --- a/server/helper/getBody.go +++ b/server/helper/getBody.go @@ -1,6 +1,7 @@ package helper import ( + "context" "io" "log" "net/http" @@ -9,17 +10,23 @@ import ( ) func GetBody(url string) (body string, err error) { + ctx, cancelFunc := context.WithTimeout(context.Background(), 2*time.Second) + defer cancelFunc() + client := http.Client{ Timeout: 5 * time.Second, } - response, err := client.Get(url) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + log.Printf("failed to creating request: %v", err) + return + } + response, err := client.Do(req) if err != nil { log.Printf("failed to get http: %+v", err) return } - defer func(Body io.ReadCloser) { - _ = Body.Close() - }(response.Body) + defer response.Body.Close() buf := new(strings.Builder) _, err = io.Copy(buf, response.Body) diff --git a/server/main.go b/server/main.go index 3362ea0..eb5f55c 100644 --- a/server/main.go +++ b/server/main.go @@ -35,18 +35,19 @@ var embeddedFiles embed.FS // main function is the start and the root for the website func main() { - if strings.Contains(os.Args[0], "/var/folders") || strings.Contains(os.Args[0], "/tmp/go") || strings.Contains(os.Args[0], "./streamer") { - if len(os.Args) > 2 { - log.Fatalf("Arguments error") - } - for i := 0; i < len(os.Args)-1; i++ { - os.Args[i] = os.Args[i+1] - } - } else { + if !strings.Contains(os.Args[0], "/var/folders") && !strings.Contains(os.Args[0], "/tmp/go") && !strings.Contains(os.Args[0], "./streamer") { if len(os.Args) > 1 { log.Fatalf("Arguments error") } } + + if len(os.Args) > 2 { + log.Fatalf("Arguments error") + } + for i := 0; i < len(os.Args)-1; i++ { + os.Args[i] = os.Args[i+1] + } + if os.Args[0] == "-v" { verbose = true } else { diff --git a/server/store/file.go b/server/store/file.go index e8107ac..963e089 100644 --- a/server/store/file.go +++ b/server/store/file.go @@ -2,12 +2,14 @@ package store import ( "fmt" - "github.com/ystv/streamer/server/storage" - "google.golang.org/protobuf/proto" "log" "os" "sync" "time" + + "github.com/ystv/streamer/server/storage" + + "google.golang.org/protobuf/proto" ) // FileBackend Applications: apps, Prefix: prefix diff --git a/server/store/store.go b/server/store/store.go index ab1746f..e15147c 100644 --- a/server/store/store.go +++ b/server/store/store.go @@ -1,6 +1,7 @@ package store import ( + "errors" "fmt" "github.com/ystv/streamer/server/storage" @@ -23,7 +24,7 @@ func (store *Store) GetStreams() ([]*storage.Stream, error) { if err != nil { return nil, err } - return streamer.Stream, err + return streamer.GetStream(), err } func (store *Store) FindStream(unique string) (*storage.Stream, error) { @@ -31,8 +32,8 @@ func (store *Store) FindStream(unique string) (*storage.Stream, error) { if err != nil { return nil, err } - for _, c1 := range streamer.Stream { - if c1.Stream == unique { + for _, c1 := range streamer.GetStream() { + if c1.GetStream() == unique { return c1, nil } } @@ -45,9 +46,9 @@ func (store *Store) AddStream(stream *storage.Stream) (*storage.Stream, error) { return nil, err } - for _, c := range streamer.Stream { - if c.Stream == stream.Stream { - return nil, fmt.Errorf("unable to add stream duplicate id for AddStream") + for _, c := range streamer.GetStream() { + if c.GetStream() == stream.GetStream() { + return nil, errors.New("unable to add stream duplicate id for AddStream") } } @@ -66,25 +67,25 @@ func (store *Store) DeleteStream(unique string) error { return err } - s := streamer.Stream + s := streamer.GetStream() found := false var index int var v *storage.Stream for index, v = range s { - if v.Stream == unique { + if v.GetStream() == unique { found = true break } } - if found { - copy(s[index:], s[index+1:]) // Shift a[i+1:] left one index - s[len(s)-1] = nil // Erase last element (write zero value) - streamer.Stream = s[:len(s)-1] // Truncate slice - } else { - return fmt.Errorf("stream not found for DeleteStream") + if !found { + return errors.New("stream not found for DeleteStream") } + copy(s[index:], s[index+1:]) // Shift a[i+1:] left one index + s[len(s)-1] = nil // Erase last element (write zero value) + streamer.Stream = s[:len(s)-1] // Truncate slice + if err = store.backend.Write(streamer); err != nil { return err } @@ -97,16 +98,16 @@ func (store *Store) GetStored() ([]*storage.Stored, error) { if err != nil { return nil, fmt.Errorf("failed to get stored from GetStored: %w", err) } - return streamer.Stored, nil + return streamer.GetStored(), nil } func (store *Store) FindStored(unique string) (*storage.Stored, error) { streamer, err := store.Get() if err != nil { - return nil, fmt.Errorf("failed to get stored from ") + return nil, fmt.Errorf("failed to get stored from FindStored: %w", err) } - for _, c1 := range streamer.Stored { - if c1.Stream == unique { + for _, c1 := range streamer.GetStored() { + if c1.GetStream() == unique { return c1, nil } } @@ -119,9 +120,9 @@ func (store *Store) AddStored(stored *storage.Stored) (*storage.Stored, error) { return nil, err } - for _, c := range streamer.Stored { - if c.Stream == stored.Stream { - return nil, fmt.Errorf("unable to add stored duplicate id for AddStored") + for _, c := range streamer.GetStored() { + if c.GetStream() == stored.GetStream() { + return nil, errors.New("unable to add stored duplicate id for AddStored") } } @@ -140,12 +141,12 @@ func (store *Store) DeleteStored(unique string) error { return err } - s := streamer.Stored + s := streamer.GetStored() found := false var index int var v *storage.Stored for index, v = range s { - if v.Stream == unique { + if v.GetStream() == unique { found = true break } @@ -156,7 +157,7 @@ func (store *Store) DeleteStored(unique string) error { s[len(s)-1] = nil // Erase last element (write zero value) streamer.Stored = s[:len(s)-1] // Truncate slice } else { - return fmt.Errorf("stream not found for DeleteStored") + return errors.New("stream not found for DeleteStored") } if err = store.backend.Write(streamer); err != nil { diff --git a/server/templates/templates.go b/server/templates/templates.go index 418a9aa..b6a6fb4 100644 --- a/server/templates/templates.go +++ b/server/templates/templates.go @@ -55,7 +55,7 @@ func (t *Templater) RenderTemplate(w io.Writer, data interface{}, mainTmpl Templ if err != nil { log.Printf("failed to get templates for template(RenderTemplate): %+v", err) - return fmt.Errorf("failed to get templates for template(RenderTemplate): %+v", err) + return fmt.Errorf("failed to get templates for template(RenderTemplate): %w", err) } return t1.Execute(w, data) diff --git a/server/views/delete.go b/server/views/delete.go index b76e95f..baf8af3 100644 --- a/server/views/delete.go +++ b/server/views/delete.go @@ -2,9 +2,10 @@ package views import ( "fmt" - "github.com/labstack/echo/v4" "log" "net/http" + + "github.com/labstack/echo/v4" ) // DeleteFunc will delete the saved stream before it can start @@ -22,7 +23,7 @@ func (v *Views) DeleteFunc(c echo.Context) error { unique := c.FormValue("unique") if len(unique) != 10 { log.Printf("unique key invalid: %s", unique) - response.Error = fmt.Sprintf("unique key invalid: %s", unique) + response.Error = "unique key invalid: " + unique return c.JSON(http.StatusOK, response) } diff --git a/server/views/errors.go b/server/views/errors.go index 1b27014..24fedf4 100644 --- a/server/views/errors.go +++ b/server/views/errors.go @@ -2,10 +2,11 @@ package views import ( "errors" - "github.com/ystv/streamer/server/templates" "github.com/labstack/echo/v4" "github.com/labstack/gommon/log" + + "github.com/ystv/streamer/server/templates" ) func (v *Views) CustomHTTPErrorHandler(err error, c echo.Context) { diff --git a/server/views/forceRemove.go b/server/views/forceRemove.go index 5c95348..a33f090 100644 --- a/server/views/forceRemove.go +++ b/server/views/forceRemove.go @@ -25,7 +25,7 @@ func (v *Views) ForceRemoveFunc(c echo.Context) error { unique := c.Param("unique") if len(unique) != 10 { log.Printf("unique key invalid: %s", unique) - response.Error = fmt.Sprintf("unique key invalid: %s", unique) + response.Error = "unique key invalid: " + unique return c.JSON(http.StatusOK, response) } @@ -73,7 +73,7 @@ func (v *Views) ForceRemoveFunc(c echo.Context) error { Unique: unique, } - if len(stream.Recording) > 0 && rec { + if len(stream.GetRecording()) > 0 && rec { recorderTransporter := transporter var wsResponse commonTransporter.ResponseTransporter wsResponse, err = v.wsHelper(server.Recorder, recorderTransporter) diff --git a/server/views/generateUnique.go b/server/views/generateUnique.go index 6fee89c..c52844a 100644 --- a/server/views/generateUnique.go +++ b/server/views/generateUnique.go @@ -17,7 +17,7 @@ func (v *Views) generateUnique() (string, error) { streams1, err := v.store.GetStreams() if err != nil { - return "", fmt.Errorf("failed to get streams: %+v", err) + return "", fmt.Errorf("failed to get streams: %w", err) } if len(streams1) == 0 { @@ -25,7 +25,7 @@ func (v *Views) generateUnique() (string, error) { } for _, s := range streams1 { - if s.Stream == string(b) { + if s.GetStream() == string(b) { loop = true break } @@ -34,7 +34,7 @@ func (v *Views) generateUnique() (string, error) { stored, err := v.store.GetStored() if err != nil { - return "", fmt.Errorf("failed to get stored: %+v", err) + return "", fmt.Errorf("failed to get stored: %w", err) } if len(stored) == 0 { @@ -42,7 +42,7 @@ func (v *Views) generateUnique() (string, error) { } for _, s := range stored { - if s.Stream == string(b) { + if s.GetStream() == string(b) { loop = true break } diff --git a/server/views/handleTXLight.go b/server/views/handleTXLight.go index 696316b..fbe4963 100644 --- a/server/views/handleTXLight.go +++ b/server/views/handleTXLight.go @@ -1,6 +1,8 @@ package views import ( + "bytes" + "context" "fmt" "net/http" "strings" @@ -10,40 +12,72 @@ import ( ) func (v *Views) HandleTXLight(url string, function tx.FunctionTX) error { + var req *http.Request var resp *http.Response var err error + ctx, cancelFunc := context.WithTimeout(context.Background(), 2*time.Second) + defer cancelFunc() client := http.Client{ Timeout: 2 * time.Second, } switch function { case tx.TransmissionOn: - resp, err = client.Get(url + tx.TransmissionOn.String()) + req, err = http.NewRequestWithContext(ctx, http.MethodGet, url+tx.TransmissionOn.String(), bytes.NewReader([]byte{})) + if err != nil { + return fmt.Errorf("could not create request: %w", err) + } + resp, err = client.Do(req) if err != nil && !strings.Contains(err.Error(), "unexpected EOF") /*&& (resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusNoContent)*/ { return fmt.Errorf("failed to get response from tx light transmission on: %w", err) + } else if err != nil { + return fmt.Errorf("failed to get response from tx light transmission on: %w", err) } + defer resp.Body.Close() case tx.AllOff: if !v.ExistingStreamCheck() { - resp, err = client.Get(url + tx.AllOff.String()) + req, err = http.NewRequestWithContext(ctx, http.MethodGet, url+tx.AllOff.String(), bytes.NewReader([]byte{})) + if err != nil { + return fmt.Errorf("could not create request: %w", err) + } + resp, err = client.Do(req) if err != nil && !strings.Contains(err.Error(), "unexpected EOF") /*&& (resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusNoContent)*/ { return fmt.Errorf("failed to get response from tx light all off: %w", err) + } else if err != nil { + return fmt.Errorf("failed to get response from tx light all off: %w", err) } + defer resp.Body.Close() } else if !v.SavedStreamCheck() { - resp, err = client.Get(url + tx.RehearsalOn.String()) + req, err = http.NewRequestWithContext(ctx, http.MethodGet, url+tx.RehearsalOn.String(), bytes.NewReader([]byte{})) + if err != nil { + return fmt.Errorf("could not create request: %w", err) + } + resp, err = client.Do(req) if err != nil && !strings.Contains(err.Error(), "unexpected EOF") /*&& (resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusNoContent)*/ { - return fmt.Errorf("failed to get response from tx light rehearsal on: %w", err) + return fmt.Errorf("failed to get response from tx light received on: %w", err) + } else if err != nil { + return fmt.Errorf("failed to get response from tx light received on: %w", err) } + defer resp.Body.Close() } case tx.RehearsalOn: if !v.ActiveStreamCheck() { - resp, err = client.Get(url + tx.RehearsalOn.String()) + req, err = http.NewRequestWithContext(ctx, http.MethodGet, url+tx.RehearsalOn.String(), bytes.NewReader([]byte{})) + if err != nil { + return fmt.Errorf("could not create request: %w", err) + } + resp, err = client.Do(req) if err != nil && !strings.Contains(err.Error(), "unexpected EOF") /*&& (resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusNoContent)*/ { - return fmt.Errorf("failed to get response from tx light rehearsal on: %w", err) + return fmt.Errorf("failed to get response from tx light received on: %w", err) + } else if err != nil { + return fmt.Errorf("failed to get response from tx light received on: %w", err) } + defer resp.Body.Close() } default: return fmt.Errorf("unexpected function string: \"%s\"", function) } + _ = req _ = resp return nil diff --git a/server/views/home.go b/server/views/home.go index d437731..81b620f 100644 --- a/server/views/home.go +++ b/server/views/home.go @@ -31,11 +31,12 @@ func (v *Views) HomeFunc(c echo.Context) error { var err string - if !rec && !fow { + switch { + case !rec && !fow: err = "No recorder or forwarder available" - } else if !rec { + case !rec: err = "No recorder available" - } else if !fow { + case !fow: err = "No forwarder available" } diff --git a/server/views/list.go b/server/views/list.go index beafa13..2839c13 100644 --- a/server/views/list.go +++ b/server/views/list.go @@ -58,8 +58,8 @@ func (v *Views) ListFunc(c echo.Context) error { for _, s := range streams { response.ActiveList = append(response.ActiveList, ListedStream{ - Code: s.Stream, - Input: s.Input, + Code: s.GetStream(), + Input: s.GetInput(), }) } @@ -72,8 +72,8 @@ func (v *Views) ListFunc(c echo.Context) error { for _, s := range stored { response.SavedList = append(response.SavedList, ListedStream{ - Code: s.Stream, - Input: s.Input, + Code: s.GetStream(), + Input: s.GetInput(), }) } diff --git a/server/views/recall.go b/server/views/recall.go index 802b1f4..40e5adb 100644 --- a/server/views/recall.go +++ b/server/views/recall.go @@ -43,7 +43,7 @@ func (v *Views) RecallFunc(c echo.Context) error { unique := c.FormValue("unique") if len(unique) != 10 { log.Printf("unique key invalid: %s", unique) - response.Error = fmt.Sprintf("unique key invalid: %s", unique) + response.Error = "unique key invalid: " + unique return c.JSON(http.StatusOK, response) } @@ -60,17 +60,17 @@ func (v *Views) RecallFunc(c echo.Context) error { return c.JSON(http.StatusOK, response) } - response.Unique = stored.Stream + response.Unique = stored.GetStream() - if len(stored.Recording) > 0 { - response.RecordingPath = stored.Recording + if len(stored.GetRecording()) > 0 { + response.RecordingPath = stored.GetRecording() } - if len(stored.Website) > 0 { - response.WebsiteStream = stored.Website + if len(stored.GetWebsite()) > 0 { + response.WebsiteStream = stored.GetWebsite() } - inputPart := strings.Split(stored.Input, "/") + inputPart := strings.Split(stored.GetInput(), "/") if len(inputPart) != 2 { log.Printf("failed to get input stream string, invalid array size: %d, %+v", len(inputPart), inputPart) response.Error = fmt.Sprintf("failed to get input stream string, invalid array size: %d, %+v", len(inputPart), inputPart) @@ -80,7 +80,7 @@ func (v *Views) RecallFunc(c echo.Context) error { response.InputStream = inputPart[1] response.Streams = []RecallStream{} - for _, stream := range stored.Streams { + for _, stream := range stored.GetStreams() { var recallStream RecallStream splitStream := strings.Split(stream, "|") if len(splitStream) != 2 { diff --git a/server/views/resume.go b/server/views/resume.go index d243cf7..7867d9e 100644 --- a/server/views/resume.go +++ b/server/views/resume.go @@ -50,9 +50,9 @@ func (v *Views) ResumeFunc(c echo.Context) error { log.Printf("accepted resume: %s", unique) response.Response = "ACCEPTED!" - response.Website = len(stream.Website) > 0 - response.Recording = len(stream.Recording) > 0 - response.Streams = uint64(len(stream.Streams)) + response.Website = len(stream.GetWebsite()) > 0 + response.Recording = len(stream.GetRecording()) > 0 + response.Streams = uint64(len(stream.GetStreams())) return c.JSON(http.StatusOK, response) } return echo.NewHTTPError(http.StatusMethodNotAllowed, "invalid method") diff --git a/server/views/save.go b/server/views/save.go index 59ff49c..8829cb3 100644 --- a/server/views/save.go +++ b/server/views/save.go @@ -2,10 +2,11 @@ package views import ( "fmt" - "github.com/labstack/echo/v4" "log" "net/http" + "github.com/labstack/echo/v4" + "github.com/ystv/streamer/server/helper/tx" "github.com/ystv/streamer/server/storage" "github.com/ystv/streamer/server/templates" diff --git a/server/views/serverError.go b/server/views/serverError.go index 659a8cf..ed76ad1 100644 --- a/server/views/serverError.go +++ b/server/views/serverError.go @@ -39,7 +39,7 @@ func (v *Views) ServerErrorFunc(c echo.Context) error { return c.JSON(http.StatusOK, response) } - recorder = len(stream.Recording) > 0 + recorder = len(stream.GetRecording()) > 0 } _, rec := v.cache.Get(server.Recorder.String()) @@ -49,11 +49,12 @@ func (v *Views) ServerErrorFunc(c echo.Context) error { errExtra := ", this may be temporary, if this persists for more than a minute then please contact #computing on Slack
" - if !rec && !fow && recorder { + switch { + case !rec && !fow && recorder: errString = "No recorder or forwarder available" + errExtra - } else if !rec && recorder { + case !rec && recorder: errString = "No recorder available" + errExtra - } else if !fow { + case !fow: errString = "No forwarder available" + errExtra } diff --git a/server/views/startSaveValidationHelper.go b/server/views/startSaveValidationHelper.go index c14f0e0..7a40a74 100644 --- a/server/views/startSaveValidationHelper.go +++ b/server/views/startSaveValidationHelper.go @@ -2,6 +2,7 @@ package views import ( "encoding/xml" + "errors" "fmt" "math" "regexp" @@ -32,7 +33,7 @@ func (v *Views) startSaveValidationHelper(c echo.Context, valType ValidationType streamPageContent, err := helper.GetBody("http://" + v.conf.StreamServer + "stat") if err != nil { - response.Error = fmt.Errorf("failed to get streams from stream server: %+v", err) + response.Error = fmt.Errorf("failed to get streams from stream server: %w", err) return response } @@ -40,7 +41,7 @@ func (v *Views) startSaveValidationHelper(c echo.Context, valType ValidationType err = xml.Unmarshal([]byte(streamPageContent), &rtmp) if err != nil { - response.Error = fmt.Errorf("failed to unmarshal xml: %+v", err) + response.Error = fmt.Errorf("failed to unmarshal xml: %w", err) return response } @@ -59,7 +60,7 @@ func (v *Views) startSaveValidationHelper(c echo.Context, valType ValidationType } if !found { - response.Error = fmt.Errorf("unable to find current stream input") + response.Error = errors.New("unable to find current stream input") return response } case saveValidation: @@ -75,7 +76,7 @@ func (v *Views) startSaveValidationHelper(c echo.Context, valType ValidationType } input = fmt.Sprintf("%s/%s", endpoint, streamInput) default: - response.Error = fmt.Errorf("invalid validation type") + response.Error = errors.New("invalid validation type") return response } @@ -89,18 +90,18 @@ func (v *Views) startSaveValidationHelper(c echo.Context, valType ValidationType savePath := c.FormValue("save_path") if len(savePath) == 0 && recordCheckbox { - response.Error = fmt.Errorf("invalid save path value") + response.Error = errors.New("invalid save path value") return response } if recordCheckbox && !strings.HasSuffix(savePath, ".mkv") { - response.Error = fmt.Errorf("the save path must end in \".mkv\"") + response.Error = errors.New("the save path must end in \".mkv\"") return response } websiteCheckboxRaw := c.FormValue("website_stream") if websiteCheckboxRaw != "" && websiteCheckboxRaw != "on" { - response.Error = fmt.Errorf("invalid website stream checkbox value: %s", recordCheckboxRaw) + response.Error = errors.New("invalid website stream checkbox value: " + recordCheckboxRaw) return response } @@ -108,7 +109,7 @@ func (v *Views) startSaveValidationHelper(c echo.Context, valType ValidationType websiteStreamEndpoint := c.FormValue("website_stream_endpoint") if websiteCheckbox && !strings.Contains(websiteStreamEndpoint, "?pwd=") { - response.Error = fmt.Errorf("the website stream endpoint must contain \"?pwd=\"") + response.Error = errors.New("the website stream endpoint must contain \"?pwd=\"") return response } @@ -118,7 +119,7 @@ func (v *Views) startSaveValidationHelper(c echo.Context, valType ValidationType if v.websiteCheck(websiteStreamEndpoint) { websiteOut = websiteStreamEndpoint } else { - response.Error = fmt.Errorf("website key check has failed") + response.Error = errors.New("website key check has failed") return response } } @@ -137,26 +138,22 @@ func (v *Views) startSaveValidationHelper(c echo.Context, valType ValidationType } sort.Ints(numbers) - streamServerRegex, err := regexp.Compile("^(rtmps?:\\/\\/)?" + // protocol + streamServerRegex := regexp.MustCompile("^(rtmps?:\\/\\/)?" + // protocol "((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" + // domain name "((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address "(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path "(\\?[;&a-z\\d%_.~+=-]*)?" + // query string "(\\#[-a-z\\d_]*)?$") // fragment locator - if err != nil { - response.Error = fmt.Errorf("failed to compile regex: %+v", err) - return response - } - var streams []string + streams := make([]string, 0) for _, index := range numbers { streamServer := c.FormValue("stream_server_" + strconv.Itoa(index)) if len(streamServer) == 0 { - response.Error = fmt.Errorf("invalid length of stream_server_%d", index) + response.Error = errors.New("invalid length of stream_server_" + strconv.Itoa(index)) return response } if !streamServerRegex.Match([]byte(streamServer)) { - response.Error = fmt.Errorf("invalid value of stream_server_%d: %+v", index, err) + response.Error = errors.New("invalid value of stream_server_" + strconv.Itoa(index)) return response } if streamServer[len(streamServer)-1] != '/' { @@ -167,7 +164,7 @@ func (v *Views) startSaveValidationHelper(c echo.Context, valType ValidationType } streamKey := c.FormValue("stream_key_" + strconv.Itoa(index)) if len(streamKey) == 0 { - response.Error = fmt.Errorf("invalid length of stream_key_%d", index) + response.Error = errors.New("invalid length of stream_key_" + strconv.Itoa(index)) return response } streamServer += streamKey @@ -175,7 +172,7 @@ func (v *Views) startSaveValidationHelper(c echo.Context, valType ValidationType } if len(streams) == 0 { - response.Error = fmt.Errorf("invalid length of streams") + response.Error = errors.New("invalid length of streams") return response } diff --git a/server/views/startUnique.go b/server/views/startUnique.go index a425551..61f5e3a 100644 --- a/server/views/startUnique.go +++ b/server/views/startUnique.go @@ -23,7 +23,7 @@ func (v *Views) StartUniqueFunc(c echo.Context) error { unique := c.FormValue("unique_code") if len(unique) != 10 { log.Printf("unique key invalid: %s", unique) - response.Error = fmt.Sprintf("unique key invalid: %s", unique) + response.Error = "unique key invalid: " + unique return c.JSON(http.StatusOK, response) } diff --git a/server/views/startingWSHelper.go b/server/views/startingWSHelper.go index 1a82907..75ded9d 100644 --- a/server/views/startingWSHelper.go +++ b/server/views/startingWSHelper.go @@ -1,6 +1,7 @@ package views import ( + "errors" "fmt" "log" "strings" @@ -30,7 +31,7 @@ func (v *Views) startingWSHelper(c echo.Context, unique string, startingType Sta formValues := v.startSaveValidationHelper(c, valType) if formValues.Error != nil { - return fmt.Errorf("invalid form input: %+v", formValues.Error) + return fmt.Errorf("invalid form input: %w", formValues.Error) } transporter := commonTransporter.Transporter{ @@ -118,17 +119,17 @@ func (v *Views) startingWSHelper(c echo.Context, unique string, startingType Sta Streams: formValues.Streams, }) if err != nil { - return fmt.Errorf("failed to add stream: %+v", err) + return fmt.Errorf("failed to add stream: %w", err) } if s == nil { - return fmt.Errorf("failed to add stream, data is empty") + return errors.New("failed to add stream, data is empty") } if startingType == storedStart { err = v.store.DeleteStored(unique) if err != nil { - return fmt.Errorf("failed to delete stored: %+v, unique: %s", err, unique) + return fmt.Errorf("failed to delete stored: %w, unique: %s", err, unique) } } diff --git a/server/views/status.go b/server/views/status.go index 9d0efd5..6bfa6fd 100644 --- a/server/views/status.go +++ b/server/views/status.go @@ -29,7 +29,7 @@ func (v *Views) StatusFunc(c echo.Context) error { unique := c.FormValue("unique_code") if len(unique) != 10 { log.Printf("unique key invalid: %s", unique) - errResponse.Error = fmt.Sprintf("unique key invalid: %s", unique) + errResponse.Error = "unique key invalid: " + unique return c.JSON(http.StatusOK, errResponse) } @@ -52,8 +52,8 @@ func (v *Views) StatusFunc(c echo.Context) error { } fStatus := commonTransporter.ForwarderStatus{ - Website: len(stream.Website) > 0, - Streams: len(stream.Streams), + Website: len(stream.GetWebsite()) > 0, + Streams: len(stream.GetStreams()), } var statusResponse StatusResponse @@ -61,7 +61,7 @@ func (v *Views) StatusFunc(c echo.Context) error { wg.Add(2) go func() { defer wg.Done() - if len(stream.Recording) > 0 { + if len(stream.GetRecording()) > 0 { recorderTransporter := transporter individualResponse := StatusResponseIndividual{ diff --git a/server/views/stop.go b/server/views/stop.go index eb05dc1..0adcd09 100644 --- a/server/views/stop.go +++ b/server/views/stop.go @@ -1,6 +1,7 @@ package views import ( + "errors" "fmt" "log" "net/http" @@ -32,7 +33,7 @@ func (v *Views) StopFunc(c echo.Context) error { unique := c.FormValue("unique_code") if len(unique) != 10 { log.Printf("unique key invalid: %s", unique) - response.Error = fmt.Sprintf("unique key invalid: %s", unique) + response.Error = "unique key invalid: " + unique return c.JSON(http.StatusOK, response) } @@ -57,12 +58,13 @@ func (v *Views) StopFunc(c echo.Context) error { _, rec := v.cache.Get(server.Recorder.String()) _, fow := v.cache.Get(server.Forwarder.String()) - if (!rec && len(stream.Recording) > 0) && !fow { - err = fmt.Errorf("no recorder or forwarder available") - } else if !rec && len(stream.Recording) > 0 { - err = fmt.Errorf("no recorder available") - } else if !fow { - err = fmt.Errorf("no forwarder available") + switch { + case (!rec && len(stream.GetRecording()) > 0) && !fow: + err = errors.New("no recorder or forwarder available") + case !rec && len(stream.GetRecording()) > 0: + err = errors.New("no recorder available") + case !fow: + err = errors.New("no forwarder available") } var wg sync.WaitGroup @@ -70,7 +72,7 @@ func (v *Views) StopFunc(c echo.Context) error { wg.Add(2) go func() { defer wg.Done() - if len(stream.Recording) > 0 { + if len(stream.GetRecording()) > 0 { recorderTransporter := transporter var wsResponse commonTransporter.ResponseTransporter wsResponse, err = v.wsHelper(server.Recorder, recorderTransporter) diff --git a/server/views/views.go b/server/views/views.go index 0fec015..4527a99 100644 --- a/server/views/views.go +++ b/server/views/views.go @@ -2,6 +2,7 @@ package views import ( "encoding/xml" + //nolint:gosec "math/rand" "time" @@ -143,6 +144,7 @@ const ( ) var ( + //nolint:gosec seededRand = rand.New(rand.NewSource(time.Now().UnixNano())) wsUpgrade = websocket.Upgrader{} diff --git a/server/views/watchdog.go b/server/views/watchdog.go index d85914a..ed5b24d 100644 --- a/server/views/watchdog.go +++ b/server/views/watchdog.go @@ -33,12 +33,12 @@ func (v *Views) BeginWatchdog() { go func() { transporter := commonTransporter.Transporter{ Action: action.Status, - Unique: stream1.Stream, + Unique: stream1.GetStream(), } fStatus := commonTransporter.ForwarderStatus{ - Website: len(stream1.Website) > 0, - Streams: len(stream1.Streams), + Website: len(stream1.GetWebsite()) > 0, + Streams: len(stream1.GetStreams()), } var forwarderError, recorderError bool @@ -47,7 +47,7 @@ func (v *Views) BeginWatchdog() { wg.Add(2) go func() { defer wg.Done() - if len(stream1.Recording) > 0 && rec { + if len(stream1.GetRecording()) > 0 && rec { recorderTransporter := transporter var response commonTransporter.ResponseTransporter @@ -100,7 +100,7 @@ func (v *Views) BeginWatchdog() { if recorderError && rec { stopTransporter := commonTransporter.Transporter{ Action: action.Stop, - Unique: stream1.Stream, + Unique: stream1.GetStream(), } var wsResponse commonTransporter.ResponseTransporter wsResponse, err = v.wsHelper(server.Recorder, stopTransporter) @@ -116,10 +116,10 @@ func (v *Views) BeginWatchdog() { startTransporter := commonTransporter.Transporter{ Action: action.Start, - Unique: stream1.Stream, + Unique: stream1.GetStream(), Payload: commonTransporter.RecorderStart{ - StreamIn: stream1.Input, - PathOut: stream1.Recording, + StreamIn: stream1.GetInput(), + PathOut: stream1.GetRecording(), }, } wsResponse, err = v.wsHelper(server.Recorder, startTransporter) @@ -133,13 +133,13 @@ func (v *Views) BeginWatchdog() { log.Printf("invalid response from Recorder for watchdog start: %#v", wsResponse) } - log.Printf("watchdog successfully restarted Recorder: %s", stream1.Streams) + log.Printf("watchdog successfully restarted Recorder: %s", stream1.GetStreams()) } if forwarderError && fow { stopTransporter := commonTransporter.Transporter{ Action: action.Stop, - Unique: stream1.Stream, + Unique: stream1.GetStream(), } var wsResponse commonTransporter.ResponseTransporter wsResponse, err = v.wsHelper(server.Forwarder, stopTransporter) @@ -155,11 +155,11 @@ func (v *Views) BeginWatchdog() { startTransporter := commonTransporter.Transporter{ Action: action.Start, - Unique: stream1.Stream, + Unique: stream1.GetStream(), Payload: commonTransporter.ForwarderStart{ - StreamIn: stream1.Input, - WebsiteOut: stream1.Website, - Streams: stream1.Streams, + StreamIn: stream1.GetInput(), + WebsiteOut: stream1.GetWebsite(), + Streams: stream1.GetStreams(), }, } wsResponse, err = v.wsHelper(server.Forwarder, startTransporter) @@ -173,7 +173,7 @@ func (v *Views) BeginWatchdog() { log.Printf("invalid response from Forwarder for watchdog start: %#v", wsResponse) } - log.Printf("watchdog successfully restarted Forwarder: %s", stream1.Streams) + log.Printf("watchdog successfully restarted Forwarder: %s", stream1.GetStreams()) } }() } diff --git a/server/views/websiteCheck.go b/server/views/websiteCheck.go index 8849f3c..d304fd0 100644 --- a/server/views/websiteCheck.go +++ b/server/views/websiteCheck.go @@ -1,6 +1,7 @@ package views import ( + "context" "io" "log" "net/http" @@ -24,8 +25,12 @@ func (v *Views) websiteCheck(endpoint string) bool { data.Set("name", splitting[0]) data.Set("pwd", splitting[1]) - client := &http.Client{} - r, err := http.NewRequest("POST", v.conf.KeyChecker, strings.NewReader(data.Encode())) + ctx, cancelFunc := context.WithTimeout(context.Background(), 2*time.Second) + defer cancelFunc() + client := &http.Client{ + Timeout: 2 * time.Second, + } + r, err := http.NewRequestWithContext(ctx, http.MethodPost, v.conf.KeyChecker, strings.NewReader(data.Encode())) if err != nil { log.Printf("failed to create new request for website check: %+v", err) return true // sending back true if the checker is down @@ -40,9 +45,9 @@ func (v *Views) websiteCheck(endpoint string) bool { log.Printf("failed to send request for website check: %+v", err) return true // sending back true if the checker is down } - defer func(Body io.ReadCloser) { - _ = Body.Close() - }(res.Body) + + defer res.Body.Close() + body, err := io.ReadAll(res.Body) if err != nil { log.Printf("failed to read body for website check: %+v", err) diff --git a/server/views/websocket.go b/server/views/websocket.go index ed9ef83..c187e24 100644 --- a/server/views/websocket.go +++ b/server/views/websocket.go @@ -140,9 +140,9 @@ func (v *Views) Websocket(c echo.Context) error { } var receive []byte - switch transportUniqueReturning.Payload.(type) { + switch t := transportUniqueReturning.Payload.(type) { case string: - receive = []byte(transportUniqueReturning.Payload.(string)) + receive = []byte(t) case map[string]interface{}, commonTransporter.ResponseTransporter: receive, err = json.Marshal(transportUniqueReturning.Payload) if err != nil { diff --git a/server/views/wsHelper.go b/server/views/wsHelper.go index b899ad0..2fc5f8b 100644 --- a/server/views/wsHelper.go +++ b/server/views/wsHelper.go @@ -37,7 +37,7 @@ func (v *Views) wsHelper(name server.Server, transporter commonTransporter.Trans err := json.Unmarshal(received, &responseTransporter) if err != nil { - return commonTransporter.ResponseTransporter{}, fmt.Errorf("failed to unmarshal response: %w, recieved message: %s", err, string(received)) + return commonTransporter.ResponseTransporter{}, fmt.Errorf("failed to unmarshal response: %w, received message: %s", err, string(received)) } return responseTransporter, nil