-
Notifications
You must be signed in to change notification settings - Fork 0
/
updater.go
94 lines (76 loc) · 1.77 KB
/
updater.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
package main
import (
"log"
"time"
"github.com/jmoiron/sqlx"
)
var (
mainUpdateTickrate = time.Second * 2
listUpdateTickrate = time.Second * 10
)
func startUpdater() {
go newUpdater(mainUpdateTickrate, queryMain)
go newUpdater(listUpdateTickrate, queryLists)
}
func newUpdater(tickrate time.Duration, fn func()) {
ticker := time.NewTicker(tickrate)
defer ticker.Stop()
fn()
for range ticker.C {
fn()
}
}
func queryMain() {
var a API
err := mainStmt.QueryRowx().StructScan(&a)
if err != nil {
log.Printf("database error: %s", err)
return
}
// sqlx seems to have changed something so we can't access the djs.djname field
// from inside of StructScan anymore. So we set it explicitly here
a.DJ.Name = a.DJName
apiMain.Store(a)
}
func queryLists() {
tx, err := Database.Beginx()
if err != nil {
log.Printf("database transaction error: %s", err)
return
}
defer tx.Commit()
queue, err := queryListStmt(tx.Stmtx(queueStmt))
if err != nil {
log.Printf("database error when retrieving queue: %s", err)
return
}
lp, err := queryListStmt(tx.Stmtx(lastPlayedStmt))
if err != nil {
log.Printf("database error when retrieving last played: %s", err)
return
}
apiQueue.Store(queue)
apiLastPlayed.Store(lp)
}
func queryListStmt(stmt *sqlx.Stmt) ([]ListEntryAPI, error) {
rows, err := stmt.Queryx()
if err != nil {
return nil, err
}
defer rows.Close()
var res []ListEntryAPI
for rows.Next() {
var l ListEntryAPI
err = rows.StructScan(&l)
if err != nil {
return nil, err
}
l.Time = formatTimeAgo(l.Timestamp)
res = append(res, l)
}
return res, nil
}
var timeagoFormat = `<time class="timeago" datetime="2006-01-02T15:04:05-0700">15:04:05</time>`
func formatTimeAgo(unix int64) string {
return time.Unix(unix, 0).Format(timeagoFormat)
}