papibot/pkg/validation/validation.go

56 lines
1.0 KiB
Go
Raw Normal View History

2025-02-09 00:25:41 -05:00
package validation
import (
"errors"
2025-02-13 23:55:18 -05:00
"fmt"
"log"
2025-02-09 00:25:41 -05:00
neturl "net/url"
"strings"
)
// Errors
var (
ErrNotAUrl = errors.New("not a URL")
ErrIncorrectProtocol = errors.New("incorrect url protocol")
ErrServiceUnsupported = errors.New("not a URL")
)
// Music hosts that we support
var musicHosts = []string{
"youtube.com",
2025-02-13 23:55:18 -05:00
"www.youtube.com",
2025-02-09 00:25:41 -05:00
}
func IsUrl(url string) (bool, *neturl.URL) {
2025-02-13 23:55:18 -05:00
// If a URL has no scheme, this will fail.
// So we'll add one if not present
if !strings.Contains(url, "://") {
url = fmt.Sprintf("https://%s", url)
}
2025-02-09 00:25:41 -05:00
parsed, err := neturl.ParseRequestURI(url)
return (err == nil), parsed
}
func IsMusicUrl(url string) (bool, error) {
isUrl, parsed := IsUrl(url)
if !isUrl {
return false, ErrNotAUrl
}
// If we have a scheme and it's not http/https we fail
if parsed.Scheme != "" && !strings.Contains(parsed.Scheme, "http") {
return false, ErrIncorrectProtocol
}
for _, host := range musicHosts {
2025-02-13 23:55:18 -05:00
log.Println(parsed.Host)
2025-02-09 00:25:41 -05:00
if host == parsed.Host {
return true, nil
}
}
return false, ErrServiceUnsupported
}