/
fetcher.go
116 lines (95 loc) 路 2.21 KB
/
fetcher.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
package livescore
import (
"errors"
"time"
"github.com/pauloo27/aryzona/internal/core/routine"
)
type ListenerFn func(*LiveMatch, error)
type LiveMatch struct {
MatchID string
CurrentData *MatchInfo
PreviousData *MatchInfo
Listeners map[string]ListenerFn
}
// errors
var (
ErrMatchAlreadyFollowed = errors.New("match already followed")
ErrMatchHasFinished = errors.New("match has finished")
ErrListenerNotFound = errors.New("listener not found")
)
var (
followedMatches = make(map[string]*LiveMatch)
)
const (
updatePeriod = 30 * time.Second
)
func init() {
routine.GoAndRecover(func() {
for {
for _, match := range followedMatches {
updateLiveMatch(match)
}
time.Sleep(updatePeriod)
}
})
}
func GetLiveMatch(id string) (*LiveMatch, error) {
match, found := followedMatches[id]
if found {
return match, nil
}
return followMatch(id)
}
func followMatch(id string) (*LiveMatch, error) {
match, err := FetchMatchInfo(id)
if err != nil {
return nil, err
}
if match.Time == "FT" {
return nil, ErrMatchHasFinished
}
followedMatches[id] = &LiveMatch{
MatchID: id,
CurrentData: match,
PreviousData: nil,
Listeners: make(map[string]ListenerFn),
}
return followedMatches[id], nil
}
func UnfollowMatch(id string) {
delete(followedMatches, id)
}
func updateLiveMatch(liveMatch *LiveMatch) {
match, err := FetchMatchInfo(liveMatch.MatchID)
if err != nil {
for _, listener := range liveMatch.Listeners {
listener(nil, err)
}
UnfollowMatch(liveMatch.MatchID)
}
liveMatch.PreviousData = liveMatch.CurrentData
liveMatch.CurrentData = match
for _, listener := range liveMatch.Listeners {
listener(liveMatch, nil)
}
if match.Time == "FT" {
UnfollowMatch(liveMatch.MatchID)
for _, listener := range liveMatch.Listeners {
listener(liveMatch, ErrMatchHasFinished)
}
}
}
func (liveMatch *LiveMatch) AddListener(id string, listener ListenerFn) {
liveMatch.Listeners[id] = listener
}
func (liveMatch *LiveMatch) RemoveListener(id string) error {
_, found := liveMatch.Listeners[id]
if !found {
return ErrListenerNotFound
}
delete(liveMatch.Listeners, id)
if len(liveMatch.Listeners) == 0 {
UnfollowMatch(liveMatch.MatchID)
}
return nil
}