package ytid import ( "fmt" "regexp" "github.com/flosch/pongo2" p2v3 "gopkg.in/flosch/pongo2.v3" ) var ( regexpYoutubeDomain = regexp.MustCompile(`youtu\.?be`) regexpURLPatterns = []*regexp.Regexp{ regexp.MustCompile(`youtu\.be\/([^#\&\?]{11})`), regexp.MustCompile(`\?v=([^#\&\?]{11})`), regexp.MustCompile(`\&v=([^#\&\?]{11})`), regexp.MustCompile(`embed\/([^#\&\?]{11})`), regexp.MustCompile(`\/v\/([^#\&\?]{11})`), } ) func RegisterPongo2V3() { p2v3.RegisterFilter("ytid", filterYtid2v3) } func filterYtid2v3(in *p2v3.Value, param *p2v3.Value) (*p2v3.Value, *p2v3.Error) { return p2v3.AsValue(GetID(in.String())), nil } func RegisterPongo() { pongo2.RegisterFilter("ytid", filterYtid) } func filterYtid(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) { return pongo2.AsValue(GetID(in.String())), nil } func GetID(url string) string { if !regexpYoutubeDomain.MatchString(url) { return "" } for _, pattern := range regexpURLPatterns { if pattern.MatchString(url) { return pattern.FindStringSubmatch(url)[1] } } return "" } func GetIDWithError(url string) (string, error) { if !regexpYoutubeDomain.MatchString(url) { return "", fmt.Errorf("ytid: not a youtube domain") } for _, pattern := range regexpURLPatterns { if pattern.MatchString(url) { return pattern.FindStringSubmatch(url)[1], nil } } return "", fmt.Errorf("ytid: no match found") }