forked from kkdai/youtube
-
Notifications
You must be signed in to change notification settings - Fork 0
/
video_id.go
34 lines (28 loc) · 799 Bytes
/
video_id.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package youtube
import (
"regexp"
"strings"
)
var videoRegexpList = []*regexp.Regexp{
regexp.MustCompile(`(?:v|embed|shorts|watch\?v)(?:=|/)([^"&?/=%]{11})`),
regexp.MustCompile(`(?:=|/)([^"&?/=%]{11})`),
regexp.MustCompile(`([^"&?/=%]{11})`),
}
// ExtractVideoID extracts the videoID from the given string
func ExtractVideoID(videoID string) (string, error) {
if strings.Contains(videoID, "youtu") || strings.ContainsAny(videoID, "\"?&/<%=") {
for _, re := range videoRegexpList {
if isMatch := re.MatchString(videoID); isMatch {
subs := re.FindStringSubmatch(videoID)
videoID = subs[1]
}
}
}
if strings.ContainsAny(videoID, "?&/<%=") {
return "", ErrInvalidCharactersInVideoID
}
if len(videoID) < 10 {
return "", ErrVideoIDMinLength
}
return videoID, nil
}