-
Notifications
You must be signed in to change notification settings - Fork 2
/
client_cache.go
76 lines (64 loc) · 1.48 KB
/
client_cache.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
package devicedetector
import (
"log"
"github.com/gijsbers/go-pcre"
"github.com/robicode/device-detector/util"
)
type ClientCache interface {
Find(userAgent string) *CachedClient
}
type Engine struct {
Default string
Versions map[string]string
}
type CachedClient struct {
Regex string
compiledRegex pcre.Regexp
compileError error
compiled bool
Name string
Path string
Type string
Version string
Engine Engine
URL string
}
type EmbeddedClientCache struct {
cleints []CachedClient
}
func NewEmbeddedClientCache() (*EmbeddedClientCache, error) {
files := NewCacheFileList(clientFilenames...)
clients, err := parseClients(files)
if err != nil {
return nil, err
}
return &EmbeddedClientCache{
cleints: clients,
}, nil
}
func (e *EmbeddedClientCache) Find(userAgent string) *CachedClient {
reversed := util.ReverseArray(e.cleints)
var matches []CachedClient
for _, client := range reversed {
if !client.compiled && client.compileError == nil {
re, err := pcre.Compile(util.FixupRegex(client.Regex), pcre.CASELESS)
if err != nil {
client.compileError = err
log.Println(err)
continue
}
client.compiledRegex = re
client.compiled = true
}
if client.compileError == nil {
matcher := client.compiledRegex.MatcherString(userAgent, 0)
if matcher.Matches() {
matches = append(matches, client)
}
}
}
if len(matches) > 0 {
return &matches[len(matches)-1]
}
return nil
}