-
Notifications
You must be signed in to change notification settings - Fork 927
/
web.go
403 lines (316 loc) · 12.2 KB
/
web.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
package web
import (
"crypto/tls"
"flag"
"html/template"
"net/http"
"strings"
"sync/atomic"
"time"
"github.com/NYTimes/gziphandler"
"github.com/golang/crypto/acme/autocert"
"github.com/jonas747/discordgo"
"github.com/jonas747/yagpdb/bot/botrest"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/common/config"
"github.com/jonas747/yagpdb/common/patreon"
yagtmpl "github.com/jonas747/yagpdb/common/templates"
"github.com/jonas747/yagpdb/web/discordblog"
"github.com/natefinch/lumberjack"
"goji.io"
"goji.io/pat"
)
var (
// Core template files
Templates *template.Template
Debug = true // Turns on debug mode
ListenAddressHTTP = ":5000"
ListenAddressHTTPS = ":5001"
// Muxers
RootMux *goji.Mux
CPMux *goji.Mux
ServerPublicMux *goji.Mux
ServerPubliAPIMux *goji.Mux
properAddresses bool
https bool
exthttps bool
acceptingRequests *int32
globalTemplateData = TemplateData(make(map[string]interface{}))
StartedAt = time.Now()
CurrentAd *Advertisement
logger = common.GetFixedPrefixLogger("web")
confAnnouncementsChannel = config.RegisterOption("yagpdb.announcements_channel", "Channel to pull announcements from and display on the control panel homepage", 0)
confAdPath = config.RegisterOption("yagpdb.ad.img_path", "The ad image ", "")
confAdLinkurl = config.RegisterOption("yagpdb.ad.link", "Link to follow when clicking on the ad", "")
confAdWidth = config.RegisterOption("yagpdb.ad.w", "Ad width", 0)
confAdHeight = config.RegisterOption("yagpdb.ad.h", "Ad Height", 0)
ConfAdVideos = config.RegisterOption("yagpdb.ad.video_paths", "Comma seperated list of video paths in different formats", "")
confDisableRequestLogging = config.RegisterOption("yagpdb.disable_request_logging", "Disable logging of http requests to web server", false)
)
type Advertisement struct {
Path template.URL
VideoUrls []template.URL
VideoTypes []string
LinkURL template.URL
Width int
Height int
}
func init() {
b := int32(1)
acceptingRequests = &b
Templates = template.New("")
Templates = Templates.Funcs(template.FuncMap{
"mTemplate": mTemplate,
"hasPerm": hasPerm,
"formatTime": prettyTime,
"roleOptions": tmplRoleDropdown,
"roleOptionsMulti": tmplRoleDropdownMutli,
"textChannelOptions": tmplChannelOpts(discordgo.ChannelTypeGuildText, "#"),
"textChannelOptionsMulti": tmplChannelOptsMulti(discordgo.ChannelTypeGuildText, "#"),
"voiceChannelOptions": tmplChannelOpts(discordgo.ChannelTypeGuildVoice, ""),
"voiceChannelOptionsMulti": tmplChannelOptsMulti(discordgo.ChannelTypeGuildVoice, ""),
"catChannelOptions": tmplChannelOpts(discordgo.ChannelTypeGuildCategory, ""),
"catChannelOptionsMulti": tmplChannelOptsMulti(discordgo.ChannelTypeGuildCategory, ""),
})
Templates = Templates.Funcs(yagtmpl.StandardFuncMap)
flag.BoolVar(&properAddresses, "pa", false, "Sets the listen addresses to 80 and 443")
flag.BoolVar(&https, "https", true, "Serve web on HTTPS. Only disable when using an HTTPS reverse proxy.")
flag.BoolVar(&exthttps, "exthttps", false, "Set if the website uses external https (through reverse proxy) but should only listen on http.")
}
func loadTemplates() {
Templates = template.Must(Templates.ParseFiles("templates/index.html", "templates/cp_main.html",
"templates/cp_nav.html", "templates/cp_selectserver.html", "templates/cp_logs.html",
"templates/status.html", "templates/cp_server_home.html", "templates/cp_core_settings.html"))
}
func BaseURL() string {
if https || exthttps {
return "https://" + common.ConfHost.GetString()
}
return "http://" + common.ConfHost.GetString()
}
func Run() {
common.RegisterPlugin(&ControlPanelPlugin{})
loadTemplates()
AddGlobalTemplateData("ClientID", common.ConfClientID.GetString())
AddGlobalTemplateData("Host", common.ConfHost.GetString())
AddGlobalTemplateData("Version", common.VERSION)
AddGlobalTemplateData("Testing", common.Testing)
if properAddresses {
ListenAddressHTTP = ":80"
ListenAddressHTTPS = ":443"
}
patreon.Run()
InitOauth()
mux := setupRoutes()
// Start monitoring the bot
go botrest.RunPinger()
go pollCommandsRan()
blogChannel := confAnnouncementsChannel.GetInt()
if blogChannel != 0 {
go discordblog.RunPoller(common.BotSession, int64(blogChannel), time.Minute)
}
LoadAd()
logger.Info("Running webservers")
runServers(mux)
}
func LoadAd() {
path := confAdPath.GetString()
linkurl := confAdLinkurl.GetString()
CurrentAd = &Advertisement{
Path: template.URL(path),
LinkURL: template.URL(linkurl),
Width: confAdWidth.GetInt(),
Height: confAdHeight.GetInt(),
}
videos := strings.Split(ConfAdVideos.GetString(), ",")
for _, v := range videos {
if v == "" {
continue
}
CurrentAd.VideoUrls = append(CurrentAd.VideoUrls, template.URL(v))
split := strings.SplitN(v, ".", 2)
if len(split) < 2 {
CurrentAd.VideoTypes = append(CurrentAd.VideoTypes, "unknown")
continue
}
CurrentAd.VideoTypes = append(CurrentAd.VideoTypes, "video/"+split[1])
}
}
func Stop() {
atomic.StoreInt32(acceptingRequests, 0)
}
func IsAcceptingRequests() bool {
return atomic.LoadInt32(acceptingRequests) != 0
}
func runServers(mainMuxer *goji.Mux) {
if !https {
logger.Info("Starting yagpdb web server http:", ListenAddressHTTP)
server := &http.Server{
Addr: ListenAddressHTTP,
Handler: mainMuxer,
IdleTimeout: time.Minute,
}
err := server.ListenAndServe()
if err != nil {
logger.Error("Failed http ListenAndServe:", err)
}
} else {
logger.Info("Starting yagpdb web server http:", ListenAddressHTTP, ", and https:", ListenAddressHTTPS)
cache := autocert.DirCache("cert")
certManager := autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(common.ConfHost.GetString(), "www."+common.ConfHost.GetString()),
Email: common.ConfEmail.GetString(),
Cache: cache,
}
// launch the redir server
go func() {
unsafeHandler := &http.Server{
Addr: ListenAddressHTTP,
Handler: certManager.HTTPHandler(http.HandlerFunc(httpsRedirHandler)),
IdleTimeout: time.Minute,
}
err := unsafeHandler.ListenAndServe()
if err != nil {
logger.Error("Failed http ListenAndServe:", err)
}
}()
tlsServer := &http.Server{
Addr: ListenAddressHTTPS,
Handler: mainMuxer,
IdleTimeout: time.Minute,
TLSConfig: &tls.Config{
GetCertificate: certManager.GetCertificate,
},
}
err := tlsServer.ListenAndServeTLS("", "")
if err != nil {
logger.Error("Failed https ListenAndServeTLS:", err)
}
}
}
func setupRoutes() *goji.Mux {
// setup the root routes and middlewares
setupRootMux()
// Guild specific public routes, does not require admin or being logged in at all
serverPublicMux := goji.SubMux()
serverPublicMux.Use(ActiveServerMW)
serverPublicMux.Use(RequireActiveServer)
serverPublicMux.Use(LoadCoreConfigMiddleware)
serverPublicMux.Use(SetGuildMemberMiddleware)
RootMux.Handle(pat.New("/public/:server"), serverPublicMux)
RootMux.Handle(pat.New("/public/:server/*"), serverPublicMux)
ServerPublicMux = serverPublicMux
// same as above but for API stuff
ServerPubliAPIMux = goji.SubMux()
ServerPubliAPIMux.Use(ActiveServerMW)
ServerPubliAPIMux.Use(RequireActiveServer)
ServerPubliAPIMux.Use(LoadCoreConfigMiddleware)
ServerPubliAPIMux.Use(SetGuildMemberMiddleware)
RootMux.Handle(pat.Get("/api/:server"), ServerPubliAPIMux)
RootMux.Handle(pat.Get("/api/:server/*"), ServerPubliAPIMux)
ServerPubliAPIMux.Handle(pat.Get("/channelperms/:channel"), RequireActiveServer(APIHandler(HandleChanenlPermissions)))
// Server selection has its own handler
RootMux.Handle(pat.Get("/manage"), RenderHandler(HandleSelectServer, "cp_selectserver"))
RootMux.Handle(pat.Get("/manage/"), RenderHandler(HandleSelectServer, "cp_selectserver"))
RootMux.Handle(pat.Get("/status"), ControllerHandler(HandleStatus, "cp_status"))
RootMux.Handle(pat.Get("/status/"), ControllerHandler(HandleStatus, "cp_status"))
RootMux.Handle(pat.Post("/shard/:shard/reconnect"), ControllerHandler(HandleReconnectShard, "cp_status"))
RootMux.Handle(pat.Post("/shard/:shard/reconnect/"), ControllerHandler(HandleReconnectShard, "cp_status"))
RootMux.HandleFunc(pat.Get("/cp"), legacyCPRedirHandler)
RootMux.HandleFunc(pat.Get("/cp/*"), legacyCPRedirHandler)
// Server control panel, requires you to be an admin for the server (owner or have server management role)
CPMux = goji.SubMux()
CPMux.Use(RequireSessionMiddleware)
CPMux.Use(ActiveServerMW)
CPMux.Use(RequireActiveServer)
CPMux.Use(LoadCoreConfigMiddleware)
CPMux.Use(SetGuildMemberMiddleware)
CPMux.Use(RequireServerAdminMiddleware)
RootMux.Handle(pat.New("/manage/:server"), CPMux)
RootMux.Handle(pat.New("/manage/:server/*"), CPMux)
CPMux.Handle(pat.Get("/cplogs"), RenderHandler(HandleCPLogs, "cp_action_logs"))
CPMux.Handle(pat.Get("/cplogs/"), RenderHandler(HandleCPLogs, "cp_action_logs"))
CPMux.Handle(pat.Get("/home"), ControllerHandler(HandleServerHome, "cp_server_home"))
CPMux.Handle(pat.Get("/home/"), ControllerHandler(HandleServerHome, "cp_server_home"))
coreSettingsHandler := RenderHandler(nil, "cp_core_settings")
CPMux.Handle(pat.Get("/core/"), coreSettingsHandler)
CPMux.Handle(pat.Get("/core"), coreSettingsHandler)
CPMux.Handle(pat.Post("/core"), ControllerPostHandler(HandlePostCoreSettings, coreSettingsHandler, CoreConfigPostForm{}, "Updated core settings"))
RootMux.Handle(pat.Get("/guild_selection"), RequireSessionMiddleware(ControllerHandler(HandleGetManagedGuilds, "cp_guild_selection")))
CPMux.Handle(pat.Get("/guild_selection"), RequireSessionMiddleware(ControllerHandler(HandleGetManagedGuilds, "cp_guild_selection")))
// Set up the routes for the per server home widgets
for _, p := range common.Plugins {
if cast, ok := p.(PluginWithServerHomeWidget); ok {
handler := GuildScopeCacheMW(p, ControllerHandler(cast.LoadServerHomeWidget, "cp_server_home_widget"))
if mwares, ok2 := p.(PluginWithServerHomeWidgetMiddlewares); ok2 {
handler = mwares.ServerHomeWidgetApplyMiddlewares(handler)
}
CPMux.Handle(pat.Get("/homewidgets/"+p.PluginInfo().SysName), handler)
}
}
for _, plugin := range common.Plugins {
if webPlugin, ok := plugin.(Plugin); ok {
webPlugin.InitWeb()
logger.Info("Initialized web plugin:", plugin.PluginInfo().Name)
}
}
return RootMux
}
func setupRootMux() {
mux := goji.NewMux()
RootMux = mux
if confDisableRequestLogging.GetBool() {
requestLogger := &lumberjack.Logger{
Filename: "access.log",
MaxSize: 10,
}
mux.Use(RequestLogger(requestLogger))
}
// Setup fileserver
mux.Handle(pat.Get("/static/*"), http.FileServer(http.Dir(".")))
mux.Handle(pat.Get("/robots.txt"), http.HandlerFunc(handleRobotsTXT))
// General middleware
mux.Use(SkipStaticMW(gziphandler.GzipHandler, ".css", ".js", ".map"))
mux.Use(SkipStaticMW(MiscMiddleware))
mux.Use(SkipStaticMW(BaseTemplateDataMiddleware))
mux.Use(SkipStaticMW(SessionMiddleware))
mux.Use(SkipStaticMW(UserInfoMiddleware))
// General handlers
mux.Handle(pat.Get("/"), ControllerHandler(HandleLandingPage, "index"))
mux.HandleFunc(pat.Get("/login"), HandleLogin)
mux.HandleFunc(pat.Get("/confirm_login"), HandleConfirmLogin)
mux.HandleFunc(pat.Get("/logout"), HandleLogout)
}
func httpsRedirHandler(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "https://"+r.Host+r.URL.String(), http.StatusMovedPermanently)
}
func AddGlobalTemplateData(key string, data interface{}) {
globalTemplateData[key] = data
}
func legacyCPRedirHandler(w http.ResponseWriter, r *http.Request) {
logger.Println("Hit cp path: ", r.RequestURI)
trimmed := strings.TrimPrefix(r.RequestURI, "/cp")
http.Redirect(w, r, "/manage"+trimmed, http.StatusMovedPermanently)
}
func LoadHTMLTemplate(pathTesting, pathProd string) {
path := pathProd
if common.Testing {
path = pathTesting
}
Templates = template.Must(Templates.ParseFiles(path))
}
const (
SidebarCategoryTopLevel = "Top"
SidebarCategoryFeeds = "Feeds"
SidebarCategoryTools = "Tools"
SidebarCategoryFun = "Fun"
)
type SidebarItem struct {
Name string
URL string
}
var sideBarItems = make(map[string][]*SidebarItem)
func AddSidebarItem(category string, sItem *SidebarItem) {
sideBarItems[category] = append(sideBarItems[category], sItem)
}