This repository has been archived by the owner on Dec 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
http.go
227 lines (184 loc) · 5.52 KB
/
http.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
package aternos_api
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/PuerkitoBio/goquery"
"github.com/dop251/goja"
"log"
"net/http"
"net/url"
"strings"
"time"
)
// getDocument sends a GET request to the specified url and reads the response as a goquery.Document.
func (api *Api) getDocument(url string) (*goquery.Document, error) {
res, err := api.client.Get(url)
if err != nil {
return nil, err
}
defer res.Close()
document, err := goquery.NewDocumentFromReader(res.Body)
if err != nil {
return nil, err
}
return document, nil
}
// genSec generates a security token called SEC.
func (api *Api) genSec() {
key := randomString(11) + "00000"
value := randomString(11) + "00000"
api.sec = fmt.Sprintf("%s:%s", key, value)
api.client.Options.CookieJar.SetCookies(api.client.Options.FullUrl, []*http.Cookie{
{
Name: fmt.Sprintf("ATERNOS_SEC_%s", key),
Value: value,
},
})
}
// extractAjaxToken extracts and unpacks the AJAX TOKEN from given HTML document.
func (api *Api) extractAjaxToken(document *goquery.Document) error {
var script string
document.Find("script[type='text/javascript']").EachWithBreak(func(i int, selection *goquery.Selection) bool {
script = strings.TrimSpace(selection.Text())
return !strings.Contains(script, "window")
})
if script == "" {
return errors.New("failed to find token")
}
vm := goja.New()
if err := vm.Set("atob", atob); err != nil {
return err
}
window := "{document: {}, setTimeout: (f, t) => {}, setInterval: (f, i) => {}, clearTimeout: (f) => {}, clearInterval: (f) => {}, Map: () => {}}"
script = fmt.Sprintf("window = %s; %s window['AJAX_TOKEN'];", window, script)
v, err := vm.RunString(script)
if err != nil {
return err
}
api.token = v.String()
return nil
}
// GetServerInfo fetches all server information over HTTP.
func (api *Api) GetServerInfo() (ServerInfo, error) {
document, err := api.getDocument("server")
if err != nil {
return ServerInfo{}, err
}
var script string
var info ServerInfo
prefix := "var lastStatus ="
suffix := ";"
document.Find("script:not([src])").EachWithBreak(func(i int, selection *goquery.Selection) bool {
script = strings.TrimSpace(selection.Text())
return !strings.HasPrefix(script, prefix)
})
if script == "" {
return ServerInfo{}, errors.New("failed to find server info")
}
data := strings.TrimSuffix(strings.ReplaceAll(script, prefix, ""), suffix)
if err = json.Unmarshal([]byte(data), &info); err != nil {
return ServerInfo{}, err
}
api.genSec()
err = api.extractAjaxToken(document)
return info, err
}
// StartServer starts your Minecraft server over HTTP.
func (api *Api) StartServer() error {
info, err := api.GetServerInfo()
if err != nil {
return err
}
if info.Status == Online {
return ServerAlreadyStartedError
}
res, err := api.client.Get(fmt.Sprintf("ajax/server/start?headstart=false&access-credits=false&SEC=%s&TOKEN=%s", api.sec, api.token))
if err != nil {
return err
}
defer res.Close()
if res.StatusCode != 200 {
msg := fmt.Sprintf("Unexpected HTTP status code %d (%s)", res.StatusCode, res.Status)
fmt.Println(msg)
fmt.Println("Response body:")
fmt.Println(res.Text())
return errors.New(msg)
}
json, err := res.Json()
if err != nil {
return err
}
if json["success"] == false {
return errors.New("Aternos failed to start the server.")
}
return nil
}
// ConfirmServer sends a confirmation over HTTP to claim that 'you're still active'.
// You should call this function once it's your turn in queue, after the server has started.
//
// This function will run synchronously if no context is given (nil value).
//
// Delay specifies the amount of seconds to wait before submitting the next confirmation.
// Recommended to wait time is around 10 seconds.
func (api *Api) ConfirmServer(ctx context.Context, delay time.Duration) error {
isAsync := ctx != nil
if !isAsync {
ctx = context.Background()
}
for {
select {
case <-ctx.Done():
return nil
default:
info := ServerInfo{Status: Preparing}
// When the function is called asynchronously (aka as a go routine like `go ConfirmServer()`),
// we'll just assume the server is known to be in a preparing state already.
// This reduces additional and unnecessary overhead.
if !isAsync {
var err error
info, err = api.GetServerInfo()
if err != nil {
if isAsync {
log.Println("Failed to get server info while confirming server:", err)
}
return err
}
}
if info.Status != Preparing {
time.Sleep(delay)
break
}
res, err := api.client.Get(fmt.Sprintf("ajax/server/confirm?headstart=false&access-credits=false&SEC=%s&TOKEN=%s", api.sec, api.token))
if err != nil {
if isAsync {
log.Println("Failed to confirm server:", err)
}
return err
}
res.Close()
return nil
}
}
}
// StopServer stops the Minecraft server over HTTP.
// This function doesn't wait until the server is fully stopped, it only requests a shutdown.
func (api *Api) StopServer() error {
info, err := api.GetServerInfo()
if err != nil {
return err
}
if info.Status == Offline {
return ServerAlreadyStoppedError
}
_, err = api.client.Get(fmt.Sprintf("ajax/server/stop?SEC=%s&TOKEN=%s", api.sec, api.token))
return err
}
// GetCookies returns the current authentication cookies that are being used.
//
// You can use this function to export them (to for example a .txt file) so you can resume the session later.
func (api *Api) GetCookies() []*http.Cookie {
u, _ := url.Parse(api.client.Options.PrefixURL)
return api.client.Options.CookieJar.Cookies(u)
}