...
1 package data
2
3 import (
4 "context"
5 "fmt"
6 "log"
7 "os"
8 "time"
9
10 "go.formulabun.club/functional/array"
11 "go.formulabun.club/srb2kart/addons"
12 "go.formulabun.club/srb2kart/conversion"
13 client "go.formulabun.club/translator/client"
14 )
15
16 var c *client.APIClient
17
18 func Init(ctx context.Context) *SiteData {
19 res := SiteData{nil, nil, []string{}, []string{}, []string{}, []string{}}
20 cfg := client.NewConfiguration()
21 c = client.NewAPIClient(cfg)
22
23 updateData(&res, ctx)
24
25 return &res
26 }
27
28 func updateData(d *SiteData, ctx context.Context) {
29 go updateServer(d, ctx)
30 go updatePlayers(d, ctx)
31 go updateFiles(d, ctx)
32 }
33
34 func updateServer(d *SiteData, ctx context.Context) {
35 l := log.New(os.Stdout, "server: ", log.LstdFlags)
36 for range initTick(time.Second) {
37 cctx, _ := context.WithTimeout(ctx, time.Second)
38 req := c.DefaultApi.ServerinfoGet(cctx)
39 info, _, err := req.Execute()
40 if err != nil {
41 l.Print(err)
42 continue
43 }
44 if info == nil || !info.HasLevelTime() {
45 continue
46 }
47 d.ServerInfo = &ServerInfo{
48 info.MapTitle,
49 fmt.Sprintf("%s", conversion.FramesToTime(uint(*info.LevelTime)).Round(time.Second)),
50 }
51 }
52 }
53
54 func updatePlayers(d *SiteData, ctx context.Context) {
55 l := log.New(os.Stdout, "players: ", log.LstdFlags)
56 for range initTick(time.Second) {
57 cctx, _ := context.WithTimeout(ctx, time.Second*10)
58 req := c.DefaultApi.PlayerinfoGet(cctx)
59 players, _, err := req.Execute()
60 if err != nil {
61 l.Print(err)
62 continue
63 }
64 if players == nil {
65 continue
66 }
67 d.Players = array.Map(players,
68 func(pl client.PlayerInfoEntry) Player {
69 todo := "todo"
70 return Player{pl.Name, &todo, pl.Score, *(pl.Team) > 0}
71 })
72 }
73 }
74
75 func updateFiles(d *SiteData, ctx context.Context) {
76 l := log.New(os.Stdout, "files: ", log.LstdFlags)
77 for range initTick(time.Minute * 5) {
78 cctx, _ := context.WithTimeout(ctx, time.Minute*1)
79 req := c.DefaultApi.FilesGet(cctx)
80 files, _, err := req.Execute()
81 if err != nil {
82 l.Print(err)
83 continue
84 }
85 d.Maps = []string{}
86 d.Characters = []string{}
87 d.Mods = []string{}
88 d.Other = []string{}
89 for _, f := range files {
90 t := addons.GetAddonType(f)
91 switch {
92 case t&(addons.RaceFlag|addons.BattleFlag) > 0:
93 d.Maps = append(d.Maps, f)
94 case t&addons.CharFlag > 0:
95 d.Characters = append(d.Characters, f)
96 case t&addons.LuaFlag > 0:
97 d.Mods = append(d.Mods, f)
98 default:
99 d.Other = append(d.Other, f)
100 }
101 }
102 }
103 }
104
105 func initTick(d time.Duration) <-chan time.Time {
106 ch := make(chan time.Time)
107 go func() {
108 ch <- time.Now()
109 for t := range time.Tick(d) {
110 ch <- t
111 }
112 }()
113 return ch
114 }
115
View as plain text