-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
2162 lines (1841 loc) · 68.9 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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"archive/zip"
"bufio"
"bytes"
"context"
"crypto/md5"
"encoding/base64"
"encoding/csv"
"encoding/hex"
"encoding/json"
"errors"
"sync"
"fmt"
"io"
"log/slog"
"math"
"net/http"
"net/http/httptrace"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"regexp"
"slices"
"sort"
"strconv"
"strings"
"time"
"github.com/lmittmann/tint"
"github.com/santhosh-tekuri/jsonschema/v5"
"github.com/snabb/httpreaderat"
flag "github.com/spf13/pflag"
"github.com/tidwall/gjson"
bufra "github.com/avvmoto/buf-readerat"
)
var APP_VERSION = "unreleased" // modified at release with `-ldflags "-X main.APP_VERSION=X.X.X"`
var APP_LOC = "https://github.com/ogri-la/github-wow-addon-catalogue-go"
var CACHE_DURATION = 24 // hours. how long cached files should live for generally.
var CACHE_DURATION_SEARCH = 2 // hours. how long cached *search* files should live for.
var CACHE_DURATION_ZIP = -1 // hours. how long cached zipfile entries should live for.
var CACHE_DURATION_RELEASE_JSON = -1 // hours. how long cached release.json entries should live for.
// prevents issuing the same warnings multiple times when going backwards and forwards
// and upside down through the search results.
var WARNED = map[string]bool{}
var API_URL = "https://api.github.com"
// we know the latest release is broken, try the previous one instead.
var REPO_EXCEPTIONS = map[string]bool{
"TimothyLuke/GSE-Advanced-Macro-Compiler": true, // 2024-06-07, latest release missing assets
}
// projects that do their release over several Github releases.
// this leads to their data flipflopping about.
var REPO_MULTI_RELEASE = map[string]bool{
"Mortalknight/GW2_UI": true,
"Nevcairiel/GatherMate2": true,
"Nevcairiel/Inventorian": true,
"Witnesscm/NDui_Plus": true,
"siweia/NDui": true,
"Wutname1/SpartanUI": true,
"xod-wow/LiteBag": true, // beta releases missing classic
"michaelnpsp/Grid2": true, // stable releases get the full set, the multiple beta releases get partial assets
"nebularg/PitBull4": true,
"casualshammy/NameplateCooldowns": true,
"Slothpala/RaidFrameSettings": true, // betas missing release
"MarcLF/AuctionBuddy": true,
"Syiana/SUI": true, // looks like releases have been disabled, but still available at /releases, weird.
"MotherGinger/RecklessAbandon-Classic": true,
"sfmict/CursorMod": true,
"sfmict/HidingBar": true,
"valkyrnstudios/RankSentinel": true, // sometimes cata, sometimes not
"TorelTwiddler/CanIMogIt": true,
"Gogo1951/Open-Sesame": true,
"Gogo1951/TFTB": true,
// these guys are breaking up their releases across multiple github releases,
// but they're actually doing something good! they're keeping their last major version updated.
// I'd like to accommodate this somehow. group releases by major version, nolib, game track?
"1onar/KeyUI": false,
}
var KNOWN_DUPLICATE_LIST = [][]string{
// Dominos bundles Masque_Dominos
{"tullamods/Dominos", "SFX-WoW/Masque_Dominos"},
// RealUI bundles Masque
{"RealUI/RealUI", "SFX-WoW/Masque"},
// XiconQoo/RETabBinder is a backport of AcidWeb/RETabBinder
// - https://github.com/XiconQoo/RETabBinder/issues/1
{"XiconQoo/RETabBinder", "AcidWeb/RETabBinder"},
}
// case insensitive repository prefixes
var REPO_BLACKLIST = map[string]bool{
"foo/": true, // dummy, for unit tests
"layday/wow-addon-template": true, // template
// mine
"WOWRainbowUI/RainbowUI-Retail": true, // addon bundle, very large, incorrect filestructure
"WOWRainbowUI/RainbowUI-Era": true, // addon bundle, very large, incorrect filestructure
"Expensify/App": true, // not an addon, not sure how it made it into list but I noticed it when it disappeared from list
// layday's blacklist
//"ogri-la/elvui": true, // Mirror
//"ogri-la/tukui": true, // Mirror
"alchem1ster/AddOns-Update-Tool": true, // Not an add-on
"alchem1ster/AddOnsFixer": true, // Not an add-on
"Aviana/": true,
"BilboTheGreedy/Azerite": true, // Not an add-on
"blazer404/TargetCharmsRe": true, // Fork
"Centias/BankItems": true, // Fork
"DaMitchell/HelloWorld": true, // Dummy add-on
"dratr/BattlePetCount": true, // Fork
"gorilla-devs/": true, // Minecraft stuff
"HappyRot/AddOns": true, // Compilation
"hippuli/": true, // Fork galore
"JsMacros/": true, // Minecraft stuff
"juraj-hrivnak/Underdog": true, // Minecraft stuff
"kamoo1/Kamoo-s-TSM-App": true, // Not an add-on
"Kirri777/WorldQuestsList": true, // Fork
"livepeer/": true, // Minecraft stuff
"lowlee/MikScrollingBattleText": true, // Fork
"lowlee/MSBTOptions": true, // Fork
"MikeD89/KarazhanChess": true, // Hijacking BigWigs' TOC IDs, probably by accident
"Oppzippy/HuokanGoldLogger": true, // Archived
"pinged-eu/wow-addon-helloworld": true, // Dummy add-on
"rePublic-Studios/rPLauncher": true, // Minecraft stuff
"smashedr/MethodAltManager": true, // Fork
"szjunklol/Accountant": true, // Fork
"unix/curseforge-release": true, // Template
"unrealshape/AddOns": true, // Add-on compilation
"vicitafirea/InterfaceColors-Addon": true, // Custom client add-on
"vicitafirea/TimeOfDayIndicator-AddOn": true, // Custom client add-on
"vicitafirea/TurtleHardcoreMessages-AddOn": true, // Custom client add-on
"vicitafirea/WarcraftUI-UpperBar-AddOn": true, // Custom client add-on
"wagyourtail/JsMacros": true, // More Minecraft stuff
"WowUp/WowUp": true, // Not an add-on
"ynazar1/Arh": true, // Fork
}
type SubCommand = string
const (
ScrapeSubCommand SubCommand = "scrape"
FindDuplicatesSubCommand SubCommand = "find-duplicates"
DumpReleaseDotJsonSubCommand SubCommand = "dump-release-dot-json"
)
var KNOWN_SUBCOMMANDS = []SubCommand{
ScrapeSubCommand,
FindDuplicatesSubCommand,
DumpReleaseDotJsonSubCommand,
}
type FindDuplicatesCommand struct {
InputFileList []string
}
type ScrapeCommand struct {
InputFileList []string
OutputFileList []string
SkipSearch bool // don't search github, just use input files
UseExpiredCache bool // use cached data, even if it's expired
FilterPattern string // a regex to be applied to `project.FullName`
FilterPatternRegexp *regexp.Regexp // the compiled form of `FilterPattern`
}
type Flags struct {
SubCommand SubCommand // cli subcommand, e.g. 'scrape'
LogLevel slog.Level
ScrapeCommand ScrapeCommand // cli args for the 'scrape' command
FindDuplicatesCommand FindDuplicatesCommand // cli args for the 'find-duplicates' command
}
// global state, see `STATE`
type State struct {
CWD string // Current Working Directory
GithubToken string // Github credentials, pulled from ENV
Client *http.Client // shared HTTP client for persistent connections
Schema *jsonschema.Schema // validates release.json files
Flags Flags
RunStart time.Time // time app started
}
var STATE *State
// limit concurrent HTTP requests
var HTTPSem = make(chan int, 50)
func take_http_token() {
HTTPSem <- 1
}
func release_http_token() {
<-HTTPSem
}
// type alias for the WoW 'flavor'.
type Flavor = string
// "For avoidance of doubt, these are all the file name formats presently supported on all clients and the order that each client will attempt to load them in currently.
// On the wiki we're recommending that people use a single specific suffix for each client for overall consistency, which corresponds to the first file in each sub-list below and is the format used by Blizzard."
// - https://github.com/Stanzilla/WoWUIBugs/issues/68#issuecomment-889431675
// - https://wowpedia.fandom.com/wiki/TOC_format
const (
MainlineFlavor Flavor = "mainline"
VanillaFlavor Flavor = "vanilla"
TBCFlavor Flavor = "tbc"
WrathFlavor Flavor = "wrath"
CataFlavor Flavor = "cata"
)
// all known flavours.
var FLAVOR_LIST = []Flavor{
MainlineFlavor, VanillaFlavor, TBCFlavor, WrathFlavor, CataFlavor,
}
// mapping of alias => canonical flavour
var FLAVOR_ALIAS_MAP = map[string]Flavor{
"classic": VanillaFlavor,
"bcc": TBCFlavor,
"wotlk": WrathFlavor,
"wotlkc": WrathFlavor,
}
// for sorting output
var FLAVOR_WEIGHTS = map[Flavor]int{
MainlineFlavor: 0,
VanillaFlavor: 1,
TBCFlavor: 2,
WrathFlavor: 3,
CataFlavor: 4,
}
var INTERFACE_RANGES = map[int]Flavor{
1_00_00: VanillaFlavor,
2_00_00: TBCFlavor,
3_00_00: WrathFlavor,
4_00_00: CataFlavor,
5_00_00: MainlineFlavor,
6_00_00: MainlineFlavor,
7_00_00: MainlineFlavor,
8_00_00: MainlineFlavor,
9_00_00: MainlineFlavor,
10_00_00: MainlineFlavor,
11_00_00: MainlineFlavor,
}
// returns a single list of unique, sorted, `Flavor` strings.
func unique_sorted_flavor_list(fll ...[]Flavor) []Flavor {
flavor_list := flatten(fll...)
for i, flavor := range flavor_list {
flavor := strings.ToLower(flavor)
actual_flavor, is_alias := FLAVOR_ALIAS_MAP[flavor]
if is_alias {
flavor_list[i] = actual_flavor
}
}
flavor_list = unique(flavor_list)
sort.Slice(flavor_list, func(i, j int) bool {
return FLAVOR_WEIGHTS[flavor_list[i]] < FLAVOR_WEIGHTS[flavor_list[j]]
})
return flavor_list
}
// a Github search result.
// different types of search return different types of information,
// this captures a common subset.
type GithubRepo struct {
ID int `json:"id"`
Name string `json:"name"` // "AdiBags"
FullName string `json:"full_name"` // "AdiAddons/AdiBags"
URL string `json:"html_url"` // "https://github/AdiAddons/AdiBags"
Description string `json:"description"`
ProjectIDMap map[string]string `json:"project-id-map,omitempty"` // {"x-wowi-id": "foobar", ...}
}
// read a csv `row` and return a `Project` struct.
func repo_from_csv_row(row []string) GithubRepo {
id, err := strconv.Atoi(row[0])
if err != nil {
slog.Error("failed to convert 'id' value in CSV to an integer", "row", row, "val", row[0], "error", err)
fatal()
}
project_id_map := map[string]string{}
if row[7] != "" {
project_id_map["x-curse-project-id"] = row[7]
}
if row[8] != "" {
project_id_map["x-wago-id"] = row[8]
}
if row[9] != "" {
project_id_map["x-wowi-id"] = row[9]
}
return GithubRepo{
ID: id,
Name: row[1],
FullName: row[2],
URL: row[3],
Description: row[4],
// 5 last-updated
// 6 flavors
ProjectIDMap: project_id_map,
}
}
type ReleaseJsonEntryMetadata struct {
Flavor Flavor `json:"flavor"`
Interface int `json:"interface"`
}
type ReleaseJsonEntry struct {
Name string `json:"name"`
Filename string `json:"filename"`
NoLib bool `json:"nolib"`
Metadata []ReleaseJsonEntryMetadata `json:"metadata"`
}
// a `release.json` file.
type ReleaseDotJson struct {
ReleaseJsonEntryList []ReleaseJsonEntry `json:"releases"`
}
// a Github release has many assets.
type GithubReleaseAsset struct {
Name string `json:"name"`
BrowserDownloadURL string `json:"browser_download_url"`
ContentType string `json:"content_type"`
}
// a Github repository has many releases.
type GithubRelease struct {
Name string `json:"name"` // "2.2.2"
AssetList []GithubReleaseAsset `json:"assets"`
PublishedAtDate time.Time `json:"published_at"`
}
// result of scraping a repository
type Project struct {
GithubRepo
UpdatedDate time.Time `json:"updated-date"`
FlavorList []Flavor `json:"flavor-list"`
HasReleaseJSON bool `json:"has-release-json"`
LastSeenDate *time.Time `json:"last-seen-date,omitempty"`
}
func ProjectCSVHeader() []string {
return []string{
"id",
"name",
"full_name",
"url",
"description",
"last_updated",
"flavors",
"curse_id",
"wago_id",
"wowi_id",
"has_release_json",
"last_seen",
}
}
// read a Project struct `p` and return a csv row.
func project_to_csv_row(p Project) []string {
return []string{
strconv.Itoa(p.ID),
p.Name,
p.FullName,
p.URL,
p.Description,
p.UpdatedDate.Format(time.RFC3339),
strings.Join(p.FlavorList, ","),
p.ProjectIDMap["x-curse-project-id"],
p.ProjectIDMap["x-wago-id"],
p.ProjectIDMap["x-wowi-id"],
title_case(fmt.Sprintf("%v", p.HasReleaseJSON)),
p.LastSeenDate.Format(time.RFC3339),
}
}
// convenience wrapper around a `http.Response`.
type ResponseWrapper struct {
*http.Response
Bytes []byte
Text string
}
// --- http utils
// returns `true` if given `resp` was throttled.
func throttled(resp ResponseWrapper) bool {
return resp.StatusCode == 403
}
// inspects `resp` and determines how long to wait. then waits.
func wait(resp ResponseWrapper) {
default_pause := float64(60) // seconds.
pause := default_pause
// inspect cache to see an example of this value
val := resp.Header.Get("X-RateLimit-Reset")
if val == "" {
slog.Debug("rate limited but no 'X-RateLimit-Reset' header present.", "headers", resp.Header)
} else {
int_val, err := strconv.ParseInt(val, 10, 64)
if err != nil {
slog.Error("failed to convert value of 'X-RateLimit-Reset' header to an integer", "val", val)
} else {
pause = math.Ceil(time.Until(time.Unix(int_val, 0)).Seconds())
if pause > 120 {
slog.Warn("received unusual wait time, using default instead", "X-RateLimit-Reset", val, "wait-time", pause, "default-wait-time", default_pause)
pause = default_pause
}
}
}
if pause > 0 {
slog.Info("throttled", "pause", pause)
time.Sleep(time.Duration(pause) * time.Second)
}
}
// logs whether the HTTP request's underlying TCP connection was re-used.
func trace_context() context.Context {
client_tracer := &httptrace.ClientTrace{
GotConn: func(info httptrace.GotConnInfo) {
slog.Debug("HTTP connection reuse", "reused", info.Reused, "remote", info.Conn.RemoteAddr())
},
}
return httptrace.WithClientTrace(context.Background(), client_tracer)
}
// --- caching
// returns a path to the cache directory.
func cache_dir() string {
return filepath.Join(STATE.CWD, "output") // "/current/working/dir/output"
}
// returns a path to the given `cache_key`.
func cache_path(cache_key string) string {
return filepath.Join(cache_dir(), cache_key) // "/current/working/dir/output/711f20df1f76da140218e51445a6fc47"
}
// returns a list of cache keys found in the cache directory.
// each key in list can be read with `read_cache_key`.
func cache_entry_list() []string {
empty_response := []string{}
dir_entry_list, err := os.ReadDir(cache_dir())
if err != nil {
slog.Error("failed to list cache directory", "error", err)
return empty_response
}
file_list := []string{}
for _, dir_entry := range dir_entry_list {
if !dir_entry.IsDir() {
file_list = append(file_list, dir_entry.Name())
}
}
return file_list
}
// creates a key that is unique to the given `req` URL (including query parameters),
// hashed to an MD5 string and prefixed, suffixed.
// the result can be safely used as a filename.
func make_cache_key(req *http.Request) string {
// inconsistent case and url params etc will cause cache misses
key := req.URL.String()
md5sum := md5.Sum([]byte(key))
cache_key := hex.EncodeToString(md5sum[:]) // fb9f36f59023fbb3681a895823ae9ba0
if strings.HasPrefix(req.URL.Path, "/search") {
return cache_key + "-search" // fb9f36f59023fbb3681a895823ae9ba0-search
}
if strings.HasSuffix(req.URL.Path, ".zip") {
return cache_key + "-zip"
}
if strings.HasSuffix(req.URL.Path, "/release.json") {
return cache_key + "-release.json"
}
return cache_key
}
// reads the cached response as if it were the result of `httputil.Dumpresponse`,
// a status code, followed by a series of headers, followed by the response body.
func read_cache_entry(cache_key string) (*http.Response, error) {
fh, err := os.Open(cache_path(cache_key))
if err != nil {
return nil, err
}
return http.ReadResponse(bufio.NewReader(fh), nil)
}
// zipfile caches are JSON maps of zipfile-entry-filenames => base64-encoded-bytes.
// todo: remove zipped_file_filter
func read_zip_cache_entry(zip_cache_key string, zipped_file_filter func(string) bool) (map[string][]byte, error) {
empty_response := map[string][]byte{}
data, err := os.ReadFile(cache_path(zip_cache_key))
if err != nil {
return empty_response, err
}
cached_zip_file_contents := map[string]string{}
err = json.Unmarshal(data, &cached_zip_file_contents)
if err != nil {
return empty_response, err
}
result := map[string][]byte{}
//placeholder := []byte{0x66, 0xFC, 0x72}
for zipfile_entry_filename, zipfile_entry_encoded_bytes := range cached_zip_file_contents {
decoded_bytes, err := base64.StdEncoding.DecodeString(zipfile_entry_encoded_bytes)
if err != nil {
return empty_response, err
}
if zipped_file_filter(zipfile_entry_filename) {
result[zipfile_entry_filename] = decoded_bytes
}
}
return result, nil
}
func write_zip_cache_entry(zip_cache_key string, zip_file_contents map[string][]byte) error {
cached_zip_file_contents := map[string]string{}
for zipfile_entry, zipfile_entry_bytes := range zip_file_contents {
cached_zip_file_contents[zipfile_entry] = base64.StdEncoding.EncodeToString(zipfile_entry_bytes)
}
json_data, err := json.Marshal(cached_zip_file_contents)
if err != nil {
return err
}
return os.WriteFile(cache_path(zip_cache_key), json_data, 0644)
}
// deletes a cache entry from the cache directory using the given `cache_key`.
func remove_cache_entry(cache_key string) error {
return os.Remove(cache_path(cache_key))
}
// returns true if the given `path` hasn't been modified for a certain duration.
// different paths have different durations.
// assumes `path` exists.
// returns `true` when an error occurs stat'ing `path`.
func cache_expired(path string) bool {
if STATE.Flags.ScrapeCommand.UseExpiredCache {
return false
}
bits := strings.Split(filepath.Base(path), "-")
suffix := ""
if len(bits) == 2 {
suffix = bits[1]
}
var cache_duration_hrs int
switch suffix {
case "-search":
cache_duration_hrs = CACHE_DURATION_SEARCH
case "-zip":
cache_duration_hrs = CACHE_DURATION_ZIP
case "-release.json":
cache_duration_hrs = CACHE_DURATION_RELEASE_JSON
default:
cache_duration_hrs = CACHE_DURATION
}
if cache_duration_hrs == -1 {
return false // cache at given `path` never expires
}
stat, err := os.Stat(path)
if err != nil {
slog.Warn("failed to stat cache file, assuming missing/bad cache file", "cache-path", path, "expired", true)
return true
}
diff := STATE.RunStart.Sub(stat.ModTime())
hours := int(math.Floor(diff.Hours()))
return hours >= cache_duration_hrs
}
type FileCachingRequest struct{}
func (x FileCachingRequest) RoundTrip(req *http.Request) (*http.Response, error) {
// don't handle zip files at all,
// their caching is handled differently.
// see: `read_zip_cache_entry` and `write_zip_cache_entry`.
if strings.HasSuffix(req.URL.String(), ".zip") {
resp, err := http.DefaultTransport.RoundTrip(req)
return resp, err
}
cache_key := make_cache_key(req) // "711f20df1f76da140218e51445a6fc47"
cache_path := cache_path(cache_key) // "/current/working/dir/output/711f20df1f76da140218e51445a6fc47"
cached_resp, err := read_cache_entry(cache_key)
if err == nil && !cache_expired(cache_path) {
// a cache entry was found and it's still valid, use that.
slog.Debug("HTTP GET cache HIT", "url", req.URL, "cache-path", cache_path)
return cached_resp, nil
}
slog.Debug("HTTP GET cache MISS", "url", req.URL, "cache-path", cache_path, "error", err)
take_http_token()
defer release_http_token()
resp, err := http.DefaultTransport.RoundTrip(req)
if err != nil {
// do not cache error responses
slog.Error("error with transport", "url", req.URL)
return resp, err
}
if resp.StatusCode == 301 || resp.StatusCode == 302 {
// we've been redirected to another location.
// follow the redirect and save it's response under the original cache key.
// .zip files bypass caching so this should only affect `release.json` files.
new_url, err := resp.Location()
if err != nil {
slog.Error("error with redirect request, no location given", "resp", resp)
return resp, err
}
slog.Debug("request redirected", "requested-url", req.URL, "redirected-to", new_url)
// make another request, update the `resp`, cache as normal.
// this allows us to cache regular file like `release.json`.
// but what happens when the redirect is also redirected?
// the `client` below isn't attached to this `RoundTrip` transport,
// so it will keep following redirects.
// the downside is it will probably create a new connection.
client := http.Client{}
resp, err = client.Get(new_url.String())
if err != nil {
slog.Error("error with transport handling redirect", "requested-url", req.URL, "redirected-to", new_url, "error", err)
return resp, err
}
}
if resp.StatusCode > 299 {
// non-2xx response, skip cache
bdy, _ := io.ReadAll(resp.Body)
slog.Debug("request unsuccessful, skipping cache", "code", resp.StatusCode, "body", string(bdy))
return resp, nil
}
fh, err := os.Create(cache_path)
if err != nil {
slog.Warn("failed to open cache file for writing", "error", err)
return resp, nil
}
defer fh.Close()
dumped_bytes, err := httputil.DumpResponse(resp, true)
if err != nil {
slog.Warn("failed to dump response to bytes", "error", err)
return resp, nil
}
_, err = fh.Write(dumped_bytes)
if err != nil {
slog.Warn("failed to write all bytes in response to cache file", "error", err)
return resp, nil
}
cached_resp, err = read_cache_entry(cache_key)
if err != nil {
slog.Warn("failed to read cache file", "error", err)
return resp, nil
}
return cached_resp, nil
}
func user_agent() string {
return fmt.Sprintf("github-wow-addon-catalogue-go/%v (%v)", APP_VERSION, APP_LOC)
}
func download(url string, headers map[string]string) (ResponseWrapper, error) {
slog.Debug("HTTP GET", "url", url)
empty_response := ResponseWrapper{}
// ---
req, err := http.NewRequestWithContext(trace_context(), http.MethodGet, url, nil)
if err != nil {
return empty_response, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("User-Agent", user_agent())
for header, header_val := range headers {
req.Header.Set(header, header_val)
}
// ---
client := STATE.Client
resp, err := client.Do(req)
if err != nil {
return empty_response, fmt.Errorf("failed to fetch '%s': %w", url, err)
}
defer resp.Body.Close()
// ---
content_bytes, err := io.ReadAll(resp.Body)
if err != nil {
return empty_response, fmt.Errorf("failed to read response body: %w", err)
}
return ResponseWrapper{
Response: resp,
Bytes: content_bytes,
Text: string(content_bytes),
}, nil
}
// just like `download` but adds an 'authorization' header to the request.
func github_download(url string) (ResponseWrapper, error) {
headers := map[string]string{
"Authorization": "token " + STATE.GithubToken,
}
return download(url, headers)
}
// returns a map of zipped-filename => uncompressed-bytes of files within a zipfile at `url`
// whose filenames match `zipped_file_filter`.
func download_zip(url string, headers map[string]string, zipped_file_filter func(string) bool) (map[string][]byte, error) {
slog.Debug("HTTP GET .zip", "url", url)
empty_response := map[string][]byte{}
req, err := http.NewRequestWithContext(trace_context(), http.MethodGet, url, nil)
if err != nil {
return empty_response, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("User-Agent", user_agent())
for header, header_val := range headers {
req.Header.Set(header, header_val)
}
// ---
cache_key := make_cache_key(req)
cached_zip_file, err := read_zip_cache_entry(cache_key, zipped_file_filter)
if err == nil {
slog.Debug("HTTP GET .zip cache HIT", "url", url, "cache-path", cache_path(cache_key))
return cached_zip_file, nil
}
slog.Debug("HTTP GET .zip cache MISS", "url", url, "cache-path", cache_path(cache_key))
// ---
client := STATE.Client
// a 'readerat' is an implementation of the built-in Go interface `io.ReaderAt`,
// that provides a means to jump around within the bytes of a remote file using
// HTTP Range requests.
http_readerat, err := httpreaderat.New(client, req, nil)
if err != nil {
return empty_response, fmt.Errorf("failed to create a HTTPReaderAt: %w", err)
}
// a 'buffered readerat' remembers the bytes read of a `io.ReaderAt` implementation,
// reducing the number of future reads when the bytes have already been read..
// in our case it's unlikely to be useful but it also doesn't hurt.
buffer_size := 1024 * 1024 // 1MiB
buffered_http_readerat := bufra.NewBufReaderAt(http_readerat, buffer_size)
zip_rdr, err := zip.NewReader(buffered_http_readerat, http_readerat.Size())
if err != nil {
return empty_response, fmt.Errorf("failed to create a zip reader: %w", err)
}
file_bytes := map[string][]byte{}
for _, zipped_file_entry := range zip_rdr.File {
if zipped_file_filter(zipped_file_entry.Name) {
slog.Debug("found zip file entry name match", "filename", zipped_file_entry.Name)
fh, err := zipped_file_entry.Open()
if err != nil {
// this file is probably busted, stop trying to read it altogether.
return empty_response, fmt.Errorf("failed to open zip file entry: %w", err)
}
defer fh.Close()
bl, err := io.ReadAll(fh)
if err != nil {
// again, file is probably busted, abort.
return empty_response, fmt.Errorf("failed to read zip file entry: %w", err)
}
file_bytes[zipped_file_entry.Name] = bl
}
}
write_zip_cache_entry(cache_key, file_bytes)
return file_bytes, nil
}
func github_zip_download(url string, zipped_file_filter func(string) bool) (map[string][]byte, error) {
headers := map[string]string{
"Authorization": "token " + STATE.GithubToken,
}
return download_zip(url, headers, zipped_file_filter)
}
func github_download_with_retries_and_backoff(url string) (ResponseWrapper, error) {
var resp ResponseWrapper
var err error
num_attempts := 5
for i := 1; i <= num_attempts; i++ {
resp, err = github_download(url)
if err != nil {
return ResponseWrapper{}, err
}
if resp.StatusCode == 404 {
return ResponseWrapper{}, errors.New("not found")
}
if throttled(resp) {
wait(resp)
continue
}
if resp.StatusCode != 200 {
slog.Warn("unsuccessful response from github, waiting and trying again", "url", url, "response", resp.StatusCode, "attempt", i)
wait(resp)
continue
}
return resp, nil
}
slog.Error("failed to download url after a number of attempts", "url", url, "num-attempts", num_attempts, "last-resp", resp.StatusCode)
return ResponseWrapper{}, errors.New("failed to download url: " + url)
}
// ---
// simplified .toc file parsing.
// keys are lowercased.
// does not handle duplicate keys, last key wins.
func parse_toc_file(filename string, toc_bytes []byte) (map[string]string, error) {
slog.Info("parsing .toc", "filename", filename)
toc_bytes, err := elide_bom(toc_bytes)
if err != nil {
slog.Warn("failed detecting/eliding BOM in toc file", "filename", filename, "error", err)
}
line_list := strings.Split(strings.ReplaceAll(string(toc_bytes), "\r\n", "\n"), "\n")
interesting_lines := map[string]string{}
for _, line := range line_list {
if strings.HasPrefix(line, "##") {
bits := strings.SplitN(line, ":", 2)
if len(bits) != 2 {
slog.Debug("ignoring line in .toc file, key has no value", "filename", filename, "line", line)
continue
}
key, val := bits[0], bits[1]
key = strings.TrimPrefix(key, "##") // "##Interface:", "## Interface:"
key = strings.TrimSuffix(key, ":") // "Interface", " Interface"
key = strings.TrimSpace(key) // "Interface"
key = strings.ToLower(key) // "interface"
val = strings.TrimSpace(val) // "100206"
slog.Debug("toc", "key", key, "val", val, "filename", filename)
interesting_lines[key] = val
}
}
return interesting_lines, nil
}
// returns a regular expression that matches against any known flavor.
// ignores word boundaries.
func flavor_regexp() *regexp.Regexp {
flavor_list := []string{}
for _, flavor := range FLAVOR_LIST {
flavor_list = append(flavor_list, string(flavor))
}
for flavor_alias := range FLAVOR_ALIAS_MAP {
flavor_list = append(flavor_list, flavor_alias)
}
flavors := strings.Join(flavor_list, "|") // "mainline|wrath|somealias"
pattern := fmt.Sprintf(`(?i)(?P<flavor>%s)`, flavors)
return regexp.MustCompile(pattern)
}
// searches given string `v` for a game track.
// it's pretty unsophisticated, be careful.
// returns the flavor that was matched and it's canonical value.
func guess_game_track(v string) (string, Flavor) {
matches := FLAVOR_REGEXP.FindStringSubmatch(v)
if len(matches) == 2 {
// "Foo-Vanilla" => [Foo-Vanilla Vanilla]
flavor := strings.ToLower(matches[1])
actual_flavor, is_alias := FLAVOR_ALIAS_MAP[flavor]
if is_alias {
return matches[1], actual_flavor
}
return matches[1], Flavor(flavor)
}
return "", ""
}
var FLAVOR_REGEXP = flavor_regexp()
// builds a regular expression to match .toc filenames and extract known flavors and aliases.
func toc_filename_regexp() *regexp.Regexp {
flavor_list := []string{}
for _, flavor := range FLAVOR_LIST {
flavor_list = append(flavor_list, string(flavor))
}
for flavor_alias := range FLAVOR_ALIAS_MAP {
flavor_list = append(flavor_list, flavor_alias)
}
flavors := strings.Join(flavor_list, "|") // "mainline|wrath|somealias"
pattern := fmt.Sprintf(`(?i)^(?P<name>[\w!'-_. ]+?)(?:[-_](?P<flavor>%s))?\.toc$`, flavors)
return regexp.MustCompile(pattern)
}
var TOC_FILENAME_REGEXP = toc_filename_regexp()
// parses the given `filename`,
// extracting the filename sans extension and any flavors,
// returning a pair of (filename, flavor).
// matching is case insensitive and flavor, if any, are returned lowercase.
// when flavor is absent, the second value is empty.
// when filename cannot be parsed, both values are empty.
func parse_toc_filename(filename string) (string, Flavor) {
matches := TOC_FILENAME_REGEXP.FindStringSubmatch(filename)
if len(matches) == 2 {
// "Bar.toc" => [Bar.toc Bar]
return matches[1], ""
}
if len(matches) == 3 {
// "Bar-wrath.toc" => [Bar-wrath.toc, Bar, wrath]
flavor := strings.ToLower(matches[2])
actual_flavor, is_alias := FLAVOR_ALIAS_MAP[flavor]
if is_alias {
return matches[1], actual_flavor
}
return matches[1], flavor
}
return "", ""
}
// parses the given `zip_file_entry` 'filename',
// that we expect to look like: 'AddonName/AddonName.toc' or 'AddonName/AddonName-flavor.toc',
// returning `true` when both the dirname and filename sans ext are equal
// and the flavor, if present, is valid.
func is_toc_file(zip_file_entry string) bool {
// golang doesn't support backreferences, so we can't use ?P= to match previous captures:
// fmt.Sprintf(`^(?P<name>[^/]+)[/](?P=name)(?:[-_](?P<flavor>%s%s))?\.toc$`, ids, aliases)
// instead we'll split on the first path delimiter and match against the rest of the path,
// ensuring the prefix matches the 'name' capture group.
bits := strings.SplitN(zip_file_entry, "/", 2)
if len(bits) != 2 {
return false
}
prefix, rest := bits[0], bits[1] // "Bar/Bar.toc" => ["Bar", "Bar.toc"]
filename, flavor := parse_toc_filename(rest) // "Bar.toc" => "Bar", "Bar-Wrath.toc" => "Bar", "wrath"
slog.Debug("zip file entry", "name", zip_file_entry, "prefix", prefix, "rest", rest, "toc-match", filename, "flavor", flavor)
if filename != "" {
if prefix == filename {
// perfect
return true
} else {
if strings.EqualFold(prefix, filename) {
// less perfect
slog.Debug("mixed filename casing", "prefix", prefix, "filename", filename)
return true
}
// edge cases: bundles, where a release contains multiple other addons but none it's own.
// WOWRainbowUI/RainbowUI-Era
// WOWRainbowUI/RainbowUI-Retail