[core] Add content-type detection for remote rule subscriptions

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2022-12-18 13:50:38 +01:00
parent f9716d6591
commit 114c9e9039
Signed by: luzifer
GPG key ID: D91C3E91E4CAD6F5

View file

@ -21,7 +21,12 @@ import (
"github.com/Luzifer/twitch-bot/v3/pkg/twitch" "github.com/Luzifer/twitch-bot/v3/pkg/twitch"
) )
const remoteRuleFetchTimeout = 5 * time.Second const (
contentTypeJSON = "json"
contentTypeYAML = "yaml"
remoteRuleFetchTimeout = 5 * time.Second
)
type ( type (
Rule struct { Rule struct {
@ -167,12 +172,17 @@ func (r *Rule) UpdateFromSubscription() (bool, error) {
return false, errors.Errorf("unxpected HTTP status %d", resp.StatusCode) return false, errors.Errorf("unxpected HTTP status %d", resp.StatusCode)
} }
inputType, err := r.fileTypeFromRequest(remoteURL, resp)
if err != nil {
return false, errors.Wrap(err, "detecting content type")
}
var newRule Rule var newRule Rule
switch path.Ext(remoteURL.Path) { switch inputType {
case ".json": case contentTypeJSON:
err = json.NewDecoder(resp.Body).Decode(&newRule) err = json.NewDecoder(resp.Body).Decode(&newRule)
case ".yaml", ".yml": case contentTypeYAML:
err = yaml.NewDecoder(resp.Body).Decode(&newRule) err = yaml.NewDecoder(resp.Body).Decode(&newRule)
default: default:
@ -475,6 +485,26 @@ func (r *Rule) allowExecuteUserWhitelist(logger *log.Entry, m *irc.Message, even
return true return true
} }
func (r Rule) fileTypeFromRequest(remoteURL *url.URL, resp *http.Response) (string, error) {
switch path.Ext(remoteURL.Path) {
case ".json":
return contentTypeJSON, nil
case ".yaml", ".yml":
return contentTypeYAML, nil
}
switch strings.Split(resp.Header.Get("Content-Type"), ";")[0] {
case "application/json":
return contentTypeJSON, nil
case "application/yaml", "application/x-yaml", "text/x-yaml":
return contentTypeYAML, nil
}
return "", errors.New("no valid file type detected")
}
func (r Rule) hash() string { func (r Rule) hash() string {
h, err := hashstructure.Hash(r, hashstructure.FormatV2, nil) h, err := hashstructure.Hash(r, hashstructure.FormatV2, nil)
if err != nil { if err != nil {