-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
309 lines (257 loc) · 7.43 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
package main
import (
"html/template"
"net/http"
"os"
"os/signal"
"runtime"
"strings"
"syscall"
"time"
"popplio/api"
poplapps "popplio/apps"
"popplio/config"
"popplio/constants"
"popplio/notifications/votereminders"
"popplio/routes/alerts"
"popplio/routes/apps"
"popplio/routes/assets"
"popplio/routes/auth"
"popplio/routes/blogs"
"popplio/routes/bots"
"popplio/routes/diagnostics"
"popplio/routes/list"
notifrouter "popplio/routes/notifications"
"popplio/routes/packs"
"popplio/routes/payments"
"popplio/routes/platform"
"popplio/routes/reminders"
"popplio/routes/reviews"
"popplio/routes/servers"
"popplio/routes/staff"
"popplio/routes/tasks"
"popplio/routes/teams"
"popplio/routes/tickets"
"popplio/routes/users"
"popplio/routes/vanity"
"popplio/routes/votes"
"popplio/routes/webhooks"
"popplio/state"
"popplio/state/bp"
"popplio/types"
poplhooks "popplio/webhooks"
"github.com/cloudflare/tableflip"
docs "github.com/infinitybotlist/eureka/doclib"
"github.com/infinitybotlist/eureka/jsonimpl"
"github.com/infinitybotlist/eureka/uapi"
"go.uber.org/zap"
"github.com/infinitybotlist/eureka/zapchi"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
_ "embed"
)
//go:embed data/docs.html
var docsHTML string
var openapi []byte
// Simple middleware to handle CORS
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// limit body to 10mb
r.Body = http.MaxBytesReader(w, r.Body, 50*1024*1024)
if r.Header.Get("User-Auth") != "" {
if strings.HasPrefix(r.Header.Get("User-Auth"), "User ") {
r.Header.Set("Authorization", r.Header.Get("User-Auth"))
} else {
r.Header.Set("Authorization", "User "+r.Header.Get("User-Auth"))
}
} else if r.Header.Get("Bot-Auth") != "" {
if strings.HasPrefix(r.Header.Get("Bot-Auth"), "Bot ") {
r.Header.Set("Authorization", r.Header.Get("Bot-Auth"))
}
r.Header.Set("Authorization", "Bot "+r.Header.Get("Bot-Auth"))
}
origin := r.Header.Get("Origin")
if origin == "" {
origin = state.Config.Sites.Frontend.Parse()
}
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Headers", "X-Client, Content-Type, Authorization")
w.Header().Set("Access-Control-Expose-Headers", "X-Session-Invalid, Retry-After")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
if r.Method == "OPTIONS" {
w.Write([]byte{})
return
}
w.Header().Set("Content-Type", "application/json")
next.ServeHTTP(w, r)
})
}
func main() {
state.Setup()
var err error
state.BaseDovewingState.Middlewares = append(state.BaseDovewingState.Middlewares, bp.DovewingMiddleware)
docs.DocsSetupData = &docs.SetupData{
URL: state.Config.Sites.API.Parse(),
ErrorStruct: types.ApiError{},
Info: docs.Info{
Title: "Infinity Bot List API",
TermsOfService: "https://infinitybotlist.com/terms",
Version: "7.0",
Description: "",
Contact: docs.Contact{
Name: "Infinity Bot List",
URL: "https://infinitybotlist.com",
Email: "support@infinitybots.gg",
},
License: docs.License{
Name: "MIT",
URL: "https://opensource.org/licenses/MIT",
},
},
}
docs.Setup()
poplhooks.Setup()
poplapps.Setup()
docs.AddSecuritySchema("User", "User-Auth", "Requires a user token. Should be prefixed with `User ` in `Authorization` header.")
docs.AddSecuritySchema("Bot", "Bot-Auth", "Requires a bot token. Should be prefixed with `Bot ` in `Authorization` header.")
api.Setup()
r := chi.NewRouter()
r.Use(
middleware.Recoverer,
middleware.RealIP,
middleware.CleanPath,
corsMiddleware,
zapchi.Logger(state.Logger, "api"),
middleware.Timeout(30*time.Second),
)
routers := []uapi.APIRouter{
// Use same order as routes folder
alerts.Router{},
apps.Router{},
assets.Router{},
auth.Router{},
blogs.Router{},
bots.Router{},
diagnostics.Router{},
list.Router{},
notifrouter.Router{},
packs.Router{},
payments.Router{},
platform.Router{},
reminders.Router{},
reviews.Router{},
servers.Router{},
staff.Router{},
tasks.Router{},
teams.Router{},
tickets.Router{},
users.Router{},
vanity.Router{},
votes.Router{},
webhooks.Router{},
}
for _, router := range routers {
name, desc := router.Tag()
if name != "" {
docs.AddTag(name, desc)
uapi.State.SetCurrentTag(name)
} else {
panic("Router tag name cannot be empty")
}
router.Routes(r)
}
r.Get("/openapi", func(w http.ResponseWriter, r *http.Request) {
w.Write(openapi)
})
docsTempl := template.Must(template.New("docs").Parse(docsHTML))
r.Get("/docs", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/docs/popplio", http.StatusFound)
})
r.Get("/docs/{srv}", func(w http.ResponseWriter, r *http.Request) {
var docMap map[string]string
if config.CurrentEnv == "staging" {
docMap = map[string]string{
"popplio": "/openapi",
"arcadia": "https://staging--panel-api.infinitybots.gg/openapi",
"infernoplex": "https://infernoplex-staging.infinitybots.gg/openapi",
}
} else {
docMap = map[string]string{
"popplio": "/openapi",
"arcadia": "https://prod--panel-api.infinitybots.gg/openapi",
"infernoplex": "https://infernoplex.infinitybots.gg/openapi",
}
}
srv := chi.URLParam(r, "srv")
if srv == "" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Invalid service name"))
return
}
v, ok := docMap[srv]
if !ok {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Invalid service"))
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
docsTempl.Execute(w, map[string]string{
"url": v,
})
})
// Load openapi here to avoid large marshalling in every request
openapi, err = jsonimpl.Marshal(docs.GetSchema())
if err != nil {
panic(err)
}
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(constants.EndpointNotFound))
})
r.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte(constants.MethodNotAllowed))
})
go votereminders.VrLoop()
// If GOOS is windows, do normal http server
if runtime.GOOS == "linux" || runtime.GOOS == "darwin" {
upg, _ := tableflip.New(tableflip.Options{})
defer upg.Stop()
go func() {
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGHUP)
for range sig {
state.Logger.Info("Received SIGHUP, upgrading server")
upg.Upgrade()
}
}()
// Listen must be called before Ready
ln, err := upg.Listen("tcp", state.Config.Meta.Port.Parse())
if err != nil {
state.Logger.Fatal("Error binding to socket", zap.Error(err))
}
defer ln.Close()
server := http.Server{
ReadTimeout: 30 * time.Second,
Handler: r,
}
go func() {
err := server.Serve(ln)
if err != http.ErrServerClosed {
state.Logger.Error("Server failed due to unexpected error", zap.Error(err))
}
}()
if err := upg.Ready(); err != nil {
state.Logger.Fatal("Error calling upg.Ready", zap.Error(err))
}
<-upg.Exit()
} else {
// Tableflip not supported
state.Logger.Warn("Tableflip not supported on this platform, this is not a production-capable server.")
err = http.ListenAndServe(state.Config.Meta.Port.Parse(), r)
if err != nil {
state.Logger.Fatal("Error binding to socket", zap.Error(err))
}
}
}