-
Notifications
You must be signed in to change notification settings - Fork 0
/
extract.go
252 lines (237 loc) · 7.42 KB
/
extract.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
package extract
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"sync"
"time"
"github.com/alecthomas/kong"
"github.com/hasura/go-graphql-client"
"github.com/origin-finkle/logs/internal/common"
"github.com/origin-finkle/logs/internal/logger"
"github.com/origin-finkle/logs/internal/models"
"github.com/origin-finkle/logs/internal/wcl"
"github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
)
func filenameForReportCode(folder, code string) string {
return fmt.Sprintf("%s/%s.json", folder, code)
}
type Extract struct {
ReportIDs []string `arg:"" optional:"" name:"report-id" help:"Report ID"`
Folder string `name:"folder" help:"Folder to store data in" type:"existingdir"`
CheckOnRemote bool `name:"check-on-remote" help:"Instead of checking locally, check on remote"`
BeginDate string `name:"begin-date" help:"Override state date of search"`
}
func (e *Extract) Extract(app *kong.Context) {
ctx := context.Background()
if e.Folder == "" {
app.Fatalf("--folder is mandatory")
}
if len(e.ReportIDs) == 0 {
end := time.Now()
var start time.Time
if e.BeginDate != "" {
var err error
start, err = time.Parse("2006-01-02", e.BeginDate)
if err != nil {
app.Fatalf("invalid begin date: %s", err)
}
} else {
start = end.AddDate(0, 0, -14)
}
var q ListReports
err := wcl.Query(ctx, &q, map[string]interface{}{
"guildID": graphql.Int(643830),
"startTime": graphql.Float(start.Unix() * 1e3),
"endTime": graphql.Float(end.Unix() * 1e3),
})
if err != nil {
app.Fatalf("error while requesting reports: %s", err)
}
for _, report := range q.ReportData.Reports.Data {
ctx := logger.ContextWithLogger(ctx, logrus.WithField("report_code", report.Code))
logrus.Debugf("Checking report %s", report.Code)
lastActivityAgo := time.Since(time.Unix(int64(report.EndTime/1000), 0))
if lastActivityAgo < 30*time.Minute {
logger.FromContext(ctx).Infof("report cannot be processed, finished %s ago", lastActivityAgo)
continue
}
if e.shouldExtractReport(ctx, string(report.Code)) {
logger.FromContext(ctx).Infof("will process %s", report.Code)
e.ReportIDs = append(e.ReportIDs, string(report.Code))
}
}
}
var wg sync.WaitGroup
for _, code := range e.ReportIDs {
wg.Add(1)
go func(code string) {
ctx := logger.ContextWithLogger(ctx, logrus.WithField("report_code", code))
defer wg.Done()
location := filenameForReportCode(e.Folder, code)
logger.FromContext(ctx).Infof("will write to file %s", location)
file, err := os.Create(location)
if err != nil {
app.Fatalf("could not create file %s: %s", location, err)
}
defer file.Close()
if err := doReport(ctx, file, code); err != nil {
app.Fatalf("error while loading report %s: %s", code, err)
}
}(code)
}
wg.Wait()
}
func (e *Extract) shouldExtractReport(ctx context.Context, reportCode string) bool {
if !e.CheckOnRemote {
location := filenameForReportCode(e.Folder, reportCode)
if _, err := os.Stat(location); err == nil {
// file exists, skip
logger.FromContext(ctx).Infof("skipping %s, as it has already been processed", reportCode)
return false
}
return true
}
url := fmt.Sprintf("https://raw.githubusercontent.com/origin-finkle/wcl-origin/master/raid-data/%s.json", reportCode)
req, err := http.NewRequest("HEAD", url, nil)
if err != nil {
logger.FromContext(ctx).WithError(err).Warn("could not check report existency")
return false
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
logger.FromContext(ctx).WithError(err).Warn("could not check report existency")
return false
}
logger.FromContext(ctx).Debugf("HEAD %s returned %d", url, resp.StatusCode)
return resp.StatusCode == 404 // 404 means we don't have the file on remote
}
var bossNames = map[string]bool{
"Hydross the Unstable": true,
"Fathom-Lord Karathress": true,
"Lady Vashj": true,
"Morogrim Tidewalker": true,
"The Lurker Below": true,
"Leotheras the Blind": true,
"Magtheridon": true,
"Moroes": true,
"Attumen the Huntsman": true,
"Maiden of Virtue": true,
"Netherspite": true,
"Opera Hall": true,
"Prince Malchezaar": true,
"Shade of Aran": true,
"Terestian Illhoof": true,
"The Curator": true,
"Nightbane": true,
"High King Maulgar": true,
"Gruul the Dragonkiller": true,
"Al'ar": true,
"Void Reaver": true,
"High Astromancer Solarian": true,
"Kael'tha Sunstrider": true,
"Rage Winterchill": true,
"Anetheron": true,
"Kaz'rogal": true,
"Azgalor": true,
"Archimonde": true,
"High Warlord Naj'entus": true,
"Supremus": true,
"Shade of Akama": true,
"Teron Gorefiend": true,
"Gurtogg Bloodboil": true,
"Reliquary of Souls": true,
"Mother Shahraz": true,
"The Illidari Council": true,
"Illidan Stormrage": true,
}
func doReport(ctx context.Context, file io.Writer, code string) error {
var q GetReport
err := wcl.Query(ctx, &q, map[string]interface{}{
"code": graphql.String(code),
})
if err != nil {
return err
}
report := q.toReport()
fightIndex := map[string]int{}
var g errgroup.Group
trashIdx := 0
for _, fight := range report.Fights {
fightIndex[fight.Name]++
if !fight.Kill {
if bossNames[fight.Name] {
fight.InternalName = fmt.Sprintf("%s - Wipe %d (%.1f%%)", fight.InternalName, fightIndex[fight.Name], fight.FightPercentage)
} else {
// trash
trashIdx++
fight.InternalName = fmt.Sprintf("Trash %d - %s", trashIdx, fight.InternalName)
}
}
f := fight // redefine for closure
g.Go(func() error {
ctx := logger.ContextWithLogger(ctx, logger.FromContext(ctx).WithField("fight_name", f.InternalName))
return doReportEvents(ctx, report, f)
})
}
if err := g.Wait(); err != nil {
return err
}
enc := json.NewEncoder(file)
common.SetupJSONEncoder(enc)
return enc.Encode(report)
}
func doReportEvents(ctx context.Context, report *models.Report, fight *models.Fight) error {
startTime := fight.StartTime
endTime := fight.EndTime
for {
if startTime == 0 {
break
}
if startTime == fight.EndTime {
endTime += 1
}
var q GetReportEvents
logger.FromContext(ctx).Infof("fetching events with page %d", startTime)
data, err := wcl.QueryRaw(ctx, &q, map[string]interface{}{
"code": graphql.String(report.Code),
"startTime": graphql.Float(startTime),
"endTime": graphql.Float(endTime),
})
if err != nil {
return err
}
var eventsFetched struct {
ReportData struct {
Report struct {
Events struct {
Data []json.RawMessage `json:"data"`
NextPageTimestamp int64 `json:"nextPageTimestamp"`
} `json:"events"`
} `json:"report"`
} `json:"reportData"`
}
if err := json.Unmarshal(*data, &eventsFetched); err != nil {
return err
}
for _, event := range eventsFetched.ReportData.Report.Events.Data {
var ef eventFilter
if err := json.Unmarshal(event, &ef); err != nil {
return err
}
switch ef.Type {
case "combatantinfo", "applybuff", "cast":
fight.Events = append(fight.Events, event)
}
}
startTime = eventsFetched.ReportData.Report.Events.NextPageTimestamp
}
return nil
}
type eventFilter struct {
Type string `json:"type"`
}