-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
364 lines (293 loc) · 9.29 KB
/
main.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package main
import (
"database/sql"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/robfig/config"
)
var conf *config.Config
var configFile = flag.String("c", "twitch_stats.conf", "specify config file")
var streamChannel string
var authToken string
var dsn string
type SubData struct {
Total int `json:"_total"`
}
type FollowData struct {
Total int `json:"_total"`
}
type StreamData struct {
Game string `json:"game,omitempty"`
Channel struct {
Status string `json:"status"`
Followers int `json:"followers"`
} `json:"channel"`
StreamID int `json:"_id"`
Viewers int `json:"viewers"`
}
type TwitchData struct {
Stream StreamData `json:"stream"`
InitialFollowers int
InitialSubscribers int
FinalFollowers int
FinalSubscribers int
StartTime time.Time
EndTime time.Time
ViewersAggregate map[string]int
Started bool
Misses int
MaxViewers int
}
func main() {
flag.Parse()
conf, err := config.ReadDefault(*configFile)
if err != nil {
conf = config.NewDefault()
fmt.Printf("Error loading config file")
}
dsn, err = conf.String("DEFAULT", "DSN")
if err != nil {
log.Printf("Error reading DSN: %s", err)
}
log.SetFlags(log.Ldate | log.Ltime)
logDir, _ := conf.String("DEFAULT", "log_dir")
if logDir == "" {
logDir = "."
}
streamChannel, _ = conf.String("DEFAULT", "StreamChannel")
runTest, _ := conf.Bool("DEFAULT", "TestMode")
authToken, _ = conf.String("DEFAULT", "AuthToken")
monitorInterval, _ := conf.Int("DEFAULT", "MonitorInterval")
monInt := time.Duration(monitorInterval)
filePrefix := "twitch_stats-"
fnTime := time.Now().UTC().Format("200601")
logFile := fmt.Sprintf("%s/%s%s.log", logDir, filePrefix, fnTime)
fp, err := os.OpenFile(logFile, os.O_CREATE|os.O_APPEND|os.O_SYNC|os.O_WRONLY, 0644)
if err != nil {
fmt.Printf("Failed to open log file '%s': %s", logFile, err)
}
log.SetOutput(fp)
log.Printf("Starting monitoring for '%s' with an interval of '%d' seconds.", streamChannel, monitorInterval)
initDB()
if runTest == true {
test()
} else {
run(monInt)
}
}
func run(i time.Duration) {
tick := time.NewTicker(time.Second * i).C
data := &TwitchData{}
for {
select {
case <-tick:
data = checkStatus(data)
}
}
}
func initDB() {
db, err := sql.Open("mysql", dsn)
if err != nil {
log.Printf("Database error: %s", err)
}
sql := `CREATE TABLE IF NOT EXISTS twitch_streams
(
id bigint not null primary key,
status text,
starttime timestamp DEFAULT '0000-00-00 00:00:00',
endtime timestamp DEFAULT '0000-00-00 00:00:00',
initialfollow int,
initialsub int,
endfollow int,
endsub int,
avgviewers int,
maxviewers int,
enterdate timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);`
_, err = db.Exec(sql)
if err != nil {
log.Printf("Error creating table: %s", err)
}
}
func storeStream(id int, status string, startTime time.Time, endTime time.Time, initFollow int, initSub int, endFollow int, endSub int, avgView int, maxViewers int) {
log.Printf("Inserting data: %d, %s, %s, %s, %d, %d, %d, %d, %d, %d, %s\n", id, status, startTime.Format(time.RFC3339), endTime.Format(time.RFC3339), initFollow, initSub, endFollow, endSub, avgView, maxViewers, time.Now().UTC().Format(time.RFC3339))
db, err := sql.Open("mysql", dsn)
if err != nil {
log.Printf("Database error: %s", err)
}
sql := `REPLACE INTO twitch_streams (id,status,starttime,endtime,initialfollow,initialsub,endfollow,endsub,avgviewers,maxviewers,enterdate) VALUES (?,?,?,?,?,?,?,?,?,?,?)`
stmt, _ := db.Prepare(sql)
res, err := stmt.Exec(id, status, startTime.Format(time.RFC3339), endTime.Format(time.RFC3339), initFollow, initSub, endFollow, endSub, avgView, maxViewers, time.Now().UTC().Format(time.RFC3339))
if err != nil {
log.Printf("Database insert error: %s", err)
}
rowsAff, _ := res.RowsAffected()
if rowsAff != 1 {
log.Printf("Rows affected was not 1, returned : %d", rowsAff)
}
}
func test() {
data := &TwitchData{}
fmt.Println(getSubs())
fmt.Println(getFollows())
fmt.Println(checkStatus(data))
}
func checkStatus(i *TwitchData) *TwitchData {
req, err := http.NewRequest("GET", fmt.Sprintf("https://api.twitch.tv/kraken/streams/%s", streamChannel), nil)
req.Header.Set("Accept", "application/vnd.twitchtv.v3+json")
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
log.Printf("Error getting twitch API data: %s", err)
return i
}
if res.StatusCode != 200 {
log.Printf("Received non-200 response from twitch. %d", res.StatusCode)
res.Body.Close()
return i
}
d := json.NewDecoder(res.Body)
decoded := &TwitchData{}
err = d.Decode(&decoded)
res.Body.Close()
if err != nil {
log.Printf("Decode error: %s", err)
return i
}
if !i.Started && len(decoded.Stream.Channel.Status) > 0 {
subs := getSubs()
i.Stream.StreamID = decoded.Stream.StreamID
i.Stream.Channel.Status = decoded.Stream.Channel.Status
i.InitialSubscribers = subs
i.InitialFollowers = decoded.Stream.Channel.Followers
i.StartTime = time.Now().UTC()
i.Started = true
if i.ViewersAggregate == nil {
i.ViewersAggregate = make(map[string]int)
}
i.ViewersAggregate[fmt.Sprint(time.Now())] = decoded.Stream.Viewers
log.Printf("New stream detected. Title: %s, Current Viewers: %d \n", decoded.Stream.Channel.Status, decoded.Stream.Viewers)
return i
}
if len(decoded.Stream.Channel.Status) <= 0 && i.Started {
if i.Misses <= 2 {
i.Misses = i.Misses + 1
return i
}
subs := getSubs()
finalFollow := getFollows()
i.EndTime = time.Now().UTC()
i.FinalFollowers = finalFollow
i.FinalSubscribers = subs
avgViewers := 0
maxUsers := 0
if len(i.ViewersAggregate) > 0 {
v := 0
for _, i := range i.ViewersAggregate {
v = v + i
if i > maxUsers {
maxUsers = i
}
}
numVStat := len(i.ViewersAggregate)
avgViewers = v / numVStat
}
dFol := i.FinalFollowers - i.InitialFollowers
dSub := i.FinalSubscribers - i.InitialSubscribers
status := i.Stream.Channel.Status
streamID := i.Stream.StreamID
startTime := i.StartTime
endTime := i.EndTime
initFollow := i.InitialFollowers
initSub := i.InitialSubscribers
log.Printf("Detected stream end. Title: '%s' Started at: %s, Ended at %s. Average Viewers: %d (Max: %d) | Delta Followers: %d, Delta Subs: %d \n", status, startTime, endTime, avgViewers, maxUsers, dFol, dSub)
storeStream(streamID, status, startTime, endTime, initFollow, initSub, finalFollow, subs, avgViewers, maxUsers)
i = &TwitchData{}
return i
}
if len(decoded.Stream.Channel.Status) > 0 && i.Started && decoded.Stream.Channel.Status == i.Stream.Channel.Status {
if i.Misses > 0 {
i.Misses = 0
}
i.Stream.Channel.Status = decoded.Stream.Channel.Status
i.ViewersAggregate[fmt.Sprint(time.Now())] = decoded.Stream.Viewers
} else if len(decoded.Stream.Channel.Status) > 0 && i.Started && (decoded.Stream.Channel.Status != i.Stream.Channel.Status) {
//Stream ended, new one began.
subs := getSubs()
finalFollow := getFollows()
i.EndTime = time.Now().UTC()
i.FinalFollowers = finalFollow
i.FinalSubscribers = subs
avgViewers := 0
maxUsers := 0
if len(i.ViewersAggregate) > 0 {
v := 0
for _, i := range i.ViewersAggregate {
v = v + i
if i > maxUsers {
maxUsers = i
}
}
numVStat := len(i.ViewersAggregate)
avgViewers = v / numVStat
}
dFol := i.FinalFollowers - i.InitialFollowers
dSub := i.FinalSubscribers - i.InitialSubscribers
status := i.Stream.Channel.Status
streamID := i.Stream.StreamID
startTime := i.StartTime
endTime := i.EndTime
initFollow := i.InitialFollowers
initSub := i.InitialSubscribers
log.Printf("Detected stream end. Title: '%s' Started at: %s, Ended at %s. Average Viewers: %d (Max: %d) | Delta Followers: %d, Delta Subs: %d \n", status, startTime, endTime, avgViewers, maxUsers, dFol, dSub)
storeStream(streamID, status, startTime, endTime, initFollow, initSub, finalFollow, subs, avgViewers, maxUsers)
i = &TwitchData{}
return i
}
return i
}
func getSubs() int {
req, err := http.NewRequest("GET", fmt.Sprintf("https://api.twitch.tv/kraken/channels/%s/subscriptions", streamChannel), nil)
req.Header.Set("Authorization", fmt.Sprintf("OAuth %s", authToken))
req.Header.Set("Accept", "application/vnd.twitchtv.v3+json")
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
log.Printf("Error getting subs: %s", err)
}
decoded := &SubData{}
err = json.NewDecoder(res.Body).Decode(&decoded)
if err != nil {
log.Printf("Error decoding subs data: %s", err)
}
if res.StatusCode != 200 {
log.Printf("Subs Error, API returned non 200 response: %d", res.StatusCode)
}
res.Body.Close()
return decoded.Total
}
func getFollows() int {
req, err := http.NewRequest("GET", fmt.Sprintf("https://api.twitch.tv/kraken/channels/%s/follows", streamChannel), nil)
req.Header.Set("Accept", "application/vnd.twitchtv.v3+json")
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
log.Printf("Error getting follows: %s", err)
}
decoded := &FollowData{}
err = json.NewDecoder(res.Body).Decode(&decoded)
if err != nil {
log.Printf("Error decoding followers data: %s", err)
}
if res.StatusCode != 200 {
log.Printf("Followers Error, API returned non 200 response: %d", res.StatusCode)
}
res.Body.Close()
return decoded.Total
}