/
main.go
354 lines (288 loc) · 8.59 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
package main
import (
"fmt"
"log"
"net/http"
"os"
"sort"
"time"
"database/sql"
"encoding/xml"
"flag"
"strings"
"html/template"
_ "github.com/mattn/go-sqlite3"
"github.com/robfig/config"
)
var conf *config.Config
var configFile = flag.String("c", "corp_member_tracking.conf", "specify config file")
type NotificationHeaders struct {
Notifications []Notifications `xml:"result>rowset>row"`
}
func formatTime(t time.Time) string {
return t.Format("2006-01-02 15:04:05")
}
var tFuncMap = template.FuncMap{
"datetime": formatTime,
}
type Notifications struct {
NotificationID int64 `xml:"notificationID,attr"`
TypeID int `xml:"typeID,attr"`
SenderID int64 `xml:"senderID,attr"`
SenderName string `xml:"senderName,attr"`
SentDate string `xml:"sentDate,attr"`
Read int64 `xml:"read,attr"`
}
type Records struct {
Events []InsertData
}
type InsertData struct {
CharID int64
Date time.Time
NotificationID int64
NotificationTypeID int
SenderName string
}
func main() {
flag.Parse()
conf, err := config.ReadDefault(*configFile)
if err != nil {
conf = config.NewDefault()
fmt.Printf("Error loading config file")
}
log.SetFlags(log.Ldate | log.Ltime)
logDir, _ := conf.String("DEFAULT", "log_dir")
if logDir == "" {
logDir = "."
}
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)
keyid, _ := conf.Int("DEFAULT", "KeyID")
vcode, _ := conf.String("DEFAULT", "vCode")
listenOn, _ := conf.String("DEFAULT", "listen")
initDB()
//Setup the timer. This pulls notifications from the API every 21 minutes. The cache timer is 20 minutes, so it should be ok.
//Some endeavouring dev could probably modify this so that it gets the cache timer from the API and checks at that time, but :effort:
t := time.NewTicker(time.Minute * 21).C
go func() {
for {
select {
case <-t:
getNotifications(keyid, vcode)
}
}
}()
//This is the part that listens and handles the incoming http connections.
http.HandleFunc("/", getStats)
//This part is so that the static files actually load, mainly the css and js shit.
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
http.ListenAndServe(listenOn, nil)
}
func getNotifications(keyid int, vcode string) {
ids := &Records{}
//Make the request to the API
req, err := http.NewRequest("GET", fmt.Sprintf("https://api.eveonline.com/Char/Notifications.xml.aspx?keyid=%d&vcode=%s", keyid, vcode), nil)
client := &http.Client{}
res, err := client.Do(req)
defer res.Body.Close()
if err != nil {
log.Printf("Error getting Header API data: %s", err)
return
}
if res.StatusCode != 200 {
log.Printf("Header API returned non 200 response: %d", res.StatusCode)
return
}
//Now that we have the content from CCP and we have made sure we got a valid result, lets decode it into something we can work with
d := xml.NewDecoder(res.Body)
decoded := &NotificationHeaders{}
err = d.Decode(&decoded)
if err != nil {
log.Printf("Error decoding header API data: %s", err)
}
//Now that its decoded, lets loop through the notifications and pull out the joins (128) and leaves (21)
for _, v := range decoded.Notifications {
if v.TypeID == 21 || v.TypeID == 128 {
sentDate, err := time.Parse("2006-01-02 15:04:05", v.SentDate)
if err != nil {
log.Printf("Error parsing time: %s", err)
}
ids.Events = append(ids.Events, InsertData{CharID: v.SenderID, SenderName: v.SenderName, NotificationID: v.NotificationID, NotificationTypeID: v.TypeID, Date: sentDate})
}
}
//Now that we have only the notifications we care about, lets store it in the db.
storeData(ids)
}
func initDB() {
//Initialize the DB connection. Will create the file if it does not exist
db, err := sql.Open("sqlite3", "./corp_member_tracking.db")
if err != nil {
log.Printf("Error creating database: %s", err)
}
defer db.Close()
sql := `CREATE TABLE IF NOT EXISTS member_tracking (
notificationID integer not null primary key,
charID integer not null,
charName text not null,
notificationTypeID integer not null,
eventDate timestamp not null
)`
//Setup the table if it doesn't already exist
_, err = db.Exec(sql)
if err != nil {
log.Printf("Error creating table: %s", err)
}
}
func storeData(data *Records) {
//Open the connection to the db file
db, err := sql.Open("sqlite3", "./corp_member_tracking.db")
if err != nil {
log.Printf("Error opening database: %s", err)
}
//Lets loop the data passed to us and store it
for _, v := range data.Events {
stmt, err := db.Prepare("INSERT OR REPLACE INTO member_tracking (notificationID, charID, charName, notificationTypeID, eventDate) VALUES (?,?,?,?,?);")
if err != nil {
log.Printf("Error preparing SQL SELECT: %s", err)
continue
}
_, err = stmt.Exec(v.NotificationID, v.CharID, v.SenderName, v.NotificationTypeID, v.Date)
if err != nil {
log.Printf("Error inserting data: %s", err)
continue
}
}
db.Close()
}
func getStats(w http.ResponseWriter, r *http.Request) {
type Char struct {
CharID int64
CharName string
EventDate time.Time
}
type TmplData struct {
Title string
Joins []Char
Leaves []Char
Date string
JoinCount int
LeaveCount int
JoinArr template.JS
LeaveArr template.JS
}
q := r.URL.Path[1:]
if len(q) <= 0 {
q = time.Now().UTC().Format("2006-01")
}
tmplData := TmplData{Title: "Member Stats", Date: q}
db, err := sql.Open("sqlite3", "./corp_member_tracking.db")
if err != nil {
log.Printf("Error opening database: %s", err)
}
defer db.Close()
sql := `SELECT notificationID, charID, charName, notificationTypeID, eventDate FROM member_tracking WHERE strftime("%Y-%m", eventDate) = ?;`
stmt, err := db.Prepare(sql)
if err != nil {
log.Printf("Error preparing statement: %s", err)
return
}
rows, err := stmt.Query(q)
if err != nil {
log.Printf("There was an error executing the statement: %s")
return
}
defer rows.Close()
j := 0
l := 0
for rows.Next() {
var notificationID, charID int64
var charName string
var eventDate time.Time
var notificationTypeID int
err = rows.Scan(¬ificationID, &charID, &charName, ¬ificationTypeID, &eventDate)
if err != nil {
log.Printf("Scan error: %s", err)
continue
}
if notificationTypeID == 21 {
l = l + 1
tmplData.Leaves = append(tmplData.Leaves, Char{CharID: charID, CharName: charName, EventDate: eventDate})
}
if notificationTypeID == 128 {
j = j + 1
tmplData.Joins = append(tmplData.Joins, Char{CharID: charID, CharName: charName, EventDate: eventDate})
}
}
tmplData.JoinCount = j
tmplData.LeaveCount = l
//This whole next section is a giant clusterfuck, but it prints out a nice pretty graph!
sql = `SELECT strftime("%m-%d",eventDate) AS day, notificationTypeID, COUNT(*) as count
FROM member_tracking
WHERE strftime("%Y-%m", eventDate) = ?
GROUP BY strftime("%m-%d",eventDate), notificationTypeID
ORDER BY day ASC`
stmt, err = db.Prepare(sql)
if err != nil {
log.Printf("Error preparing statement: %s", err)
return
}
rows, err = stmt.Query(q)
if err != nil {
log.Printf("There was an error executing the statement: %s")
return
}
defer rows.Close()
var day string
var notificationTypeID, count int
joinMap := make(map[string]int)
leaveMap := make(map[string]int)
days := make(map[int]string)
var keys []int
i := 0
for rows.Next() {
err = rows.Scan(&day, ¬ificationTypeID, &count)
if err != nil {
log.Printf("Scan error: %s", err)
continue
}
days[i] = day
joinMap[day] = 0
leaveMap[day] = 0
if notificationTypeID == 21 {
leaveMap[day] = count
}
if notificationTypeID == 128 {
joinMap[day] = count
}
i = i + 1
}
for k := range days {
keys = append(keys, k)
}
tJ := make([]string, len(keys))
tL := make([]string, len(keys))
sort.Ints(keys)
for k := range keys {
d := days[k]
tJ[k] = fmt.Sprintf("['%s', %d]", d, joinMap[d])
tL[k] = fmt.Sprintf("['%s', %d]", d, leaveMap[d])
}
tmplData.JoinArr = template.JS(strings.Join(tJ, ","))
tmplData.LeaveArr = template.JS(strings.Join(tL, ","))
//This is where the clusterfuck ends.
mainTemplate, err := template.New("template.html").Funcs(tFuncMap).ParseFiles("template.html")
if err != nil {
log.Printf("Template error: %s", err)
return
}
err = mainTemplate.Execute(w, tmplData)
if err != nil {
log.Printf("Template Error: %s", err)
}
}