-
-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathgithub.go
More file actions
128 lines (109 loc) · 2.3 KB
/
github.go
File metadata and controls
128 lines (109 loc) · 2.3 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
126
127
128
package github
import (
"context"
"log"
"os"
"time"
"github.com/jmoiron/sqlx"
"github.com/shurcooL/graphql"
"golang.org/x/oauth2"
)
var accessToken = os.Getenv("GITHUB_ACCESS_TOKEN")
var client = graphql.NewClient(
"https://api.github.com/graphql",
oauth2.NewClient(
context.Background(),
oauth2.StaticTokenSource(&oauth2.Token{AccessToken: accessToken}),
),
)
type pageInfo struct {
EndCursor graphql.String
HasNextPage bool
}
type rateLimit struct {
Cost, Limit, Remaining int
ResetAt time.Time
}
func Run(db *sqlx.DB, hourly bool) {
if accessToken == "" {
return
}
var (
cost int
limit rateLimit
)
var jobs []func(*sqlx.DB) ([]rateLimit, error)
if hourly {
jobs = append(jobs, updateUsernames)
} else {
jobs = append(jobs, ideas, pullRequests, sponsors, stars, votes)
}
for _, job := range jobs {
limits, err := job(db)
if err != nil {
log.Print(err)
continue
}
for _, limit = range limits {
cost += limit.Cost
}
}
log.Printf(
"GitHub API: Spent %d, %d/%d left, resets in %v",
cost, limit.Remaining, limit.Limit, time.Until(limit.ResetAt).Round(time.Second),
)
}
func awardCheevos(db *sqlx.DB, earnedUsers map[int]time.Time, cheevoID string) {
rows, err := db.Query(
"SELECT earned, user_id FROM cheevos WHERE cheevo = $1",
cheevoID,
)
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
var earned time.Time
var userID int
if err := rows.Scan(&earned, &userID); err != nil {
panic(err)
}
if newEarned, ok := earnedUsers[userID]; ok {
delete(earnedUsers, userID)
if earned != newEarned {
if _, err := db.Exec(
`UPDATE cheevos
SET earned = $1
WHERE cheevo = $2
AND user_id = $3`,
newEarned,
cheevoID,
userID,
); err != nil {
panic(err)
}
}
} else if _, err := db.Exec(
"DELETE FROM cheevos WHERE cheevo = $1 AND user_id = $2",
cheevoID,
userID,
); err != nil {
panic(err)
}
}
if err := rows.Err(); err != nil {
panic(err)
}
for userID, earned := range earnedUsers {
if _, err := db.Exec(
`INSERT INTO cheevos (earned, user_id, cheevo)
SELECT $1, $2, $3
WHERE EXISTS (SELECT * FROM users WHERE id = $2)`,
earned,
userID,
cheevoID,
); err != nil {
panic(err)
}
}
}