-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
125 lines (99 loc) · 2.49 KB
/
main.go
File metadata and controls
125 lines (99 loc) · 2.49 KB
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
120
121
122
123
124
125
// Deliver webhook notifications when shazam.com charts are updated.
package main
import (
"fmt"
"time"
"os"
"os/signal"
"syscall"
"github.com/bst27/shazam-webhook/chartlist"
"github.com/bst27/shazam-webhook/config"
"github.com/bst27/shazam-webhook/service/shazam"
"github.com/bst27/shazam-webhook/service/webhook"
"github.com/bst27/shazam-webhook/tracklist"
)
var (
appConfig *config.AppConfig
webhookService webhook.Service
shazamClient shazam.Client
tracklistRepo tracklist.Repository
chartlistRepo chartlist.Repository
shutdownPending bool
)
func bootstrap() {
appConfig = config.Get()
webhookService = webhook.Get()
shazamClient = shazam.New()
tracklistRepo = tracklist.Get()
chartlistRepo = chartlist.Get()
shutdownPending = false
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
// Wait for signal to stop execution
<-sigs
fmt.Println("Stopping application ...")
shutdownPending = true
}()
}
func shutdown() {
_ = webhookService.Close()
}
func main() {
bootstrap()
run()
shutdown()
}
func run() {
initChartlists()
initTracklists()
if !appConfig.SendInitialHooks {
webhookService.Disable()
}
lastPolling := time.Time{}
for !shutdownPending {
time.Sleep(1 * time.Second)
if lastPolling.Add(time.Duration(appConfig.PollingInterval) * time.Second).After(time.Now()) {
continue
}
lastPolling = time.Now()
for _, v := range chartlistRepo.GetAll() {
req := shazamClient.CreateFetchChartsRequest(v.ShazamKey())
tracks, err := req.Send()
if err != nil {
// silently ignore; will be updated in the next iteration
continue
}
for _, t := range tracks {
v.AddTrackIfMissing(t.Subtitle, t.Title)
}
}
for _, c := range chartlistRepo.GetAll() {
for _, t := range tracklistRepo.GetAll() {
if t.IsWatching(c.ShazamKey()) {
c.WriteTracks(t)
}
}
}
if !appConfig.SendInitialHooks {
webhookService.Enable()
}
}
}
func initChartlists() {
for _, shazamChartKey := range appConfig.MonitoredShazamCharts {
chartlistRepo.Add(chartlist.New(shazamChartKey))
}
}
func initTracklists() {
for _, tracklistConfig := range appConfig.Tracklists {
tl := tracklist.New()
for _, shazamChartKey := range tracklistConfig.WatchedShazamCharts {
tl.WatchShazamCharts(shazamChartKey)
}
for _, webhookTarget := range tracklistConfig.WebhookTargets {
tl.RegisterWebhook(webhook.NewReceiver(webhookTarget.URL, webhookService))
}
tracklistRepo.Add(tl)
}
}