This repository has been archived by the owner on Jan 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 59
/
generic_service.go
88 lines (76 loc) · 1.92 KB
/
generic_service.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
* MumbleDJ
* By Matthieu Grieger
* services/generic_service.go
* Copyright (c) 2016 Matthieu Grieger (MIT License)
*/
package services
import (
"errors"
"regexp"
)
// GenericService is a generic struct that should be embedded
// in other service structs, as it provides useful helper
// methods and properties.
type GenericService struct {
ReadableName string
Format string
TrackRegex []*regexp.Regexp
PlaylistRegex []*regexp.Regexp
}
// GetReadableName returns the readable name for the service.
func (gs *GenericService) GetReadableName() string {
return gs.ReadableName
}
// GetFormat returns the youtube-dl format for the service.
func (gs *GenericService) GetFormat() string {
return gs.Format
}
// CheckURL matches the passed URL with a list of regex patterns
// for valid URLs associated with this service. Returns true if a
// match is found, false otherwise.
func (gs *GenericService) CheckURL(url string) bool {
if gs.isTrack(url) || gs.isPlaylist(url) {
return true
}
return false
}
func (gs *GenericService) isTrack(url string) bool {
for _, regex := range gs.TrackRegex {
if regex.MatchString(url) {
return true
}
}
return false
}
func (gs *GenericService) isPlaylist(url string) bool {
for _, regex := range gs.PlaylistRegex {
if regex.MatchString(url) {
return true
}
}
return false
}
func (gs *GenericService) getID(url string) (string, error) {
var allRegex []*regexp.Regexp
if gs.PlaylistRegex != nil {
allRegex = append(gs.TrackRegex, gs.PlaylistRegex...)
} else {
allRegex = gs.TrackRegex
}
for _, regex := range allRegex {
match := regex.FindStringSubmatch(url)
if match == nil {
// Move on to next regex, this one didn't match.
continue
}
result := make(map[string]string)
for i, name := range regex.SubexpNames() {
if i < len(match) {
result[name] = match[i]
}
}
return result["id"], nil
}
return "", errors.New("No match found for URL")
}