-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdevice.go
119 lines (99 loc) · 2.27 KB
/
device.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package devicedetector
import (
"log"
"regexp"
"strings"
"github.com/robicode/device-detector/extractor"
)
type Device struct {
cache *Cache
_device *CachedDevice
_model *CachedModel
_userAgent string
}
// NewDevice creates a new *Device.
func NewDevice(cache *Cache, userAgent string) *Device {
device := &Device{
cache: cache,
_device: nil,
_userAgent: userAgent,
}
entry := device.matchingRegex()
if entry == nil {
return device
}
device._device = entry
return device
}
// Name returns the device name.
func (d *Device) Name() string {
if d._device != nil {
return d._device.Name
}
return ""
}
// Type returns the device type (desktop, smartphone...)
func (d *Device) Type() string {
if d.isHbbTV() || d.isShellTV() {
return "tv"
}
if d._device != nil {
return d._device.Type
}
return ""
}
// Brand returns the device brand
func (d *Device) Brand() string {
if d._device != nil {
return d._device.Brand
}
return ""
}
func (d *Device) isHbbTV() bool {
return regexp.MustCompile(`HbbTV/([1-9]{1}(?:\.[0-9]{1}){1,2})`).MatchString(d._userAgent)
}
func (d *Device) isShellTV() bool {
return regexp.MustCompile(`[a-z]+[ _]Shell[ _]\w{6}`).MatchString(d._userAgent)
}
func (d *Device) matchingRegex() *CachedDevice {
var regexList = NewCacheFileList()
if d.isHbbTV() {
regexList = d.cache.Device.RegexesForHbbTV()
} else {
regexList = d.cache.Device.RegexesForOthers()
}
if d.isShellTV() {
regexList = d.cache.Device.RegexesForShellTV()
}
if regexList == nil {
log.Println("BUG: regexList is nil! This should not happen!")
return nil
}
device := d.cache.Device.regexFind(d._userAgent, regexList)
if device == nil {
return nil
}
if len(device.Models) > 0 {
model := device.FindModel(d._userAgent)
if model != nil {
d._model = model
if strings.TrimSpace(model.Brand) != "" {
device.Brand = model.Brand
}
if strings.TrimSpace(model.Name) != "" {
name := extractor.New(d._userAgent, model.Regex, model.Name).Call()
device.Name = name
}
if strings.TrimSpace(model.Type) != "" {
device.Type = model.Type
}
}
} else {
name := extractor.New(d._userAgent, device.Regex, device.Name).Call()
device.Name = name
}
return device
}
func (d *Device) IsKnown() bool {
return d._device != nil
}