forked from jlelse/GoBlog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
576 lines (527 loc) · 18.1 KB
/
config.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
package main
import (
"errors"
"log"
"net/http"
"net/url"
"strings"
"sync"
"github.com/samber/lo"
"github.com/spf13/viper"
)
type config struct {
Server *configServer `mapstructure:"server"`
Db *configDb `mapstructure:"database"`
Cache *configCache `mapstructure:"cache"`
DefaultBlog string `mapstructure:"defaultblog"`
Blogs map[string]*configBlog `mapstructure:"blogs"`
User *configUser `mapstructure:"user"`
Hooks *configHooks `mapstructure:"hooks"`
Plugins []*configPlugin `mapstructure:"plugins"`
Micropub *configMicropub `mapstructure:"micropub"`
PathRedirects []*configRegexRedirect `mapstructure:"pathRedirects"`
ActivityPub *configActivityPub `mapstructure:"activityPub"`
Webmention *configWebmention `mapstructure:"webmention"`
Notifications *configNotifications `mapstructure:"notifications"`
PrivateMode *configPrivateMode `mapstructure:"privateMode"`
IndexNow *configIndexNow `mapstructure:"indexNow"`
EasterEgg *configEasterEgg `mapstructure:"easterEgg"`
MapTiles *configMapTiles `mapstructure:"mapTiles"`
TTS *configTTS `mapstructure:"tts"`
Reactions *configReactions `mapstructure:"reactions"`
Pprof *configPprof `mapstructure:"pprof"`
Debug bool `mapstructure:"debug"`
initialized bool
}
type configServer struct {
Logging bool `mapstructure:"logging"`
LogFile string `mapstructure:"logFile"`
Port int `mapstructure:"port"`
PublicAddress string `mapstructure:"publicAddress"`
ShortPublicAddress string `mapstructure:"shortPublicAddress"`
MediaAddress string `mapstructure:"mediaAddress"`
PublicHTTPS bool `mapstructure:"publicHttps"`
AcmeDir string `mapstructure:"acmeDir"`
AcmeEabKid string `mapstructure:"acmeEabKid"`
AcmeEabKey string `mapstructure:"acmeEabKey"`
TailscaleHTTPS bool `mapstructure:"tailscaleHttps"`
Tailscale *configTailscale `mapstructure:"tailscale"`
Tor bool `mapstructure:"tor"`
TorSingleHop bool `mapstructure:"torSingleHop"`
SecurityHeaders bool `mapstructure:"securityHeaders"`
CSPDomains []string `mapstructure:"cspDomains"`
publicHostname string
shortPublicHostname string
mediaHostname string
}
type configTailscale struct {
Enabled bool `mapstructure:"enabled"`
AuthKey string `mapstructure:"authKey"`
Hostname string `mapstructure:"Hostname"`
}
type configDb struct {
File string `mapstructure:"file"`
DumpFile string `mapstructure:"dumpFile"`
Debug bool `mapstructure:"debug"`
}
type configCache struct {
Enable bool `mapstructure:"enable"`
Expiration int `mapstructure:"expiration"`
}
type configBlog struct {
Path string `mapstructure:"path"`
Lang string `mapstructure:"lang"`
Title string `mapstructure:"title"`
Description string `mapstructure:"description"`
Pagination int `mapstructure:"pagination"`
DefaultSection string `mapstructure:"defaultsection"`
Sections map[string]*configSection `mapstructure:"sections"`
Taxonomies []*configTaxonomy `mapstructure:"taxonomies"`
Menus map[string]*configMenu `mapstructure:"menus"`
Photos *configPhotos `mapstructure:"photos"`
Search *configSearch `mapstructure:"search"`
BlogStats *configBlogStats `mapstructure:"blogStats"`
Blogroll *configBlogroll `mapstructure:"blogroll"`
Telegram *configTelegram `mapstructure:"telegram"`
PostAsHome bool `mapstructure:"postAsHome"`
RandomPost *configRandomPost `mapstructure:"randomPost"`
OnThisDay *configOnThisDay `mapstructure:"onThisDay"`
Comments *configComments `mapstructure:"comments"`
Map *configGeoMap `mapstructure:"map"`
Contact *configContact `mapstructure:"contact"`
Announcement *configAnnouncement `mapstructure:"announcement"`
// Configs read from database
hideOldContentWarning bool
hideShareButton bool
hideTranslateButton bool
// Editor state WebSockets
esws sync.Map
esm sync.Mutex
}
type configSection struct {
Title string `mapstructure:"title"`
Description string `mapstructure:"description"`
PathTemplate string `mapstructure:"pathtemplate"`
ShowFull bool `mapstructure:"showFull"`
Name string
}
type configTaxonomy struct {
Name string `mapstructure:"name"`
Title string `mapstructure:"title"`
Description string `mapstructure:"description"`
}
type configMenu struct {
Items []*configMenuItem `mapstructure:"items"`
}
type configMenuItem struct {
Title string `mapstructure:"title"`
Link string `mapstructure:"link"`
}
type configPhotos struct {
Enabled bool `mapstructure:"enabled"`
Path string `mapstructure:"path"`
Title string `mapstructure:"title"`
Description string `mapstructure:"description"`
}
type configSearch struct {
Enabled bool `mapstructure:"enabled"`
Path string `mapstructure:"path"`
Title string `mapstructure:"title"`
Description string `mapstructure:"description"`
Placeholder string `mapstructure:"placeholder"`
}
type configBlogStats struct {
Enabled bool `mapstructure:"enabled"`
Path string `mapstructure:"path"`
Title string `mapstructure:"title"`
Description string `mapstructure:"description"`
}
type configBlogroll struct {
Enabled bool `mapstructure:"enabled"`
Path string `mapstructure:"path"`
Opml string `mapstructure:"opml"`
AuthHeader string `mapstructure:"authHeader"`
AuthValue string `mapstructure:"authValue"`
Categories []string `mapstructure:"categories"`
Title string `mapstructure:"title"`
Description string `mapstructure:"description"`
}
type configRandomPost struct {
Enabled bool `mapstructure:"enabled"`
Path string `mapstructure:"path"`
}
type configOnThisDay struct {
Enabled bool `mapstructure:"enabled"`
Path string `mapstructure:"path"`
}
type configComments struct {
Enabled bool `mapstructure:"enabled"`
}
type configGeoMap struct {
Enabled bool `mapstructure:"enabled"`
Path string `mapstructure:"path"`
}
type configContact struct {
Enabled bool `mapstructure:"enabled"`
Path string `mapstructure:"path"`
Title string `mapstructure:"title"`
Description string `mapstructure:"description"`
PrivacyPolicy string `mapstructure:"privacyPolicy"`
SMTPHost string `mapstructure:"smtpHost"`
SMTPPort int `mapstructure:"smtpPort"`
SMTPUser string `mapstructure:"smtpUser"`
SMTPPassword string `mapstructure:"smtpPassword"`
EmailFrom string `mapstructure:"emailFrom"`
EmailTo string `mapstructure:"emailTo"`
EmailSubject string `mapstructure:"emailSubject"`
}
type configAnnouncement struct {
Text string `mapstructure:"text"`
}
type configUser struct {
Nick string `mapstructure:"nick"`
Name string `mapstructure:"name"`
Password string `mapstructure:"password"`
TOTP string `mapstructure:"totp"`
AppPasswords []*configAppPassword `mapstructure:"appPasswords"`
Picture string `mapstructure:"picture"`
Email string `mapstructure:"email"`
Link string `mapstructure:"link"`
Identities []string `mapstructure:"identities"`
}
type configAppPassword struct {
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
}
type configHooks struct {
Shell string `mapstructure:"shell"`
Hourly []string `mapstructure:"hourly"`
PreStart []string `mapstructure:"prestart"`
// Can use template
PostPost []string `mapstructure:"postpost"`
PostUpdate []string `mapstructure:"postupdate"`
PostDelete []string `mapstructure:"postdelete"`
PostUndelete []string `mapstructure:"postundelete"`
}
type configMicropub struct {
CategoryParam string `mapstructure:"categoryParam"`
ReplyParam string `mapstructure:"replyParam"`
ReplyTitleParam string `mapstructure:"replyTitleParam"`
LikeParam string `mapstructure:"likeParam"`
LikeTitleParam string `mapstructure:"likeTitleParam"`
BookmarkParam string `mapstructure:"bookmarkParam"`
AudioParam string `mapstructure:"audioParam"`
PhotoParam string `mapstructure:"photoParam"`
PhotoDescriptionParam string `mapstructure:"photoDescriptionParam"`
LocationParam string `mapstructure:"locationParam"`
MediaStorage *configMicropubMedia `mapstructure:"mediaStorage"`
}
type configMicropubMedia struct {
MediaURL string `mapstructure:"mediaUrl"`
// BunnyCDN
BunnyStorageKey string `mapstructure:"bunnyStorageKey"`
BunnyStorageName string `mapstructure:"bunnyStorageName"`
BunnyStorageRegion string `mapstructure:"bunnyStorageRegion"`
// FTP
FTPAddress string `mapstructure:"ftpAddress"`
FTPUser string `mapstructure:"ftpUser"`
FTPPassword string `mapstructure:"ftpPassword"`
// Tinify
TinifyKey string `mapstructure:"tinifyKey"`
// Cloudflare
CloudflareCompressionEnabled bool `mapstructure:"cloudflareCompressionEnabled"`
// Local
LocalCompressionEnabled bool `mapstructure:"localCompressionEnabled"`
}
type configRegexRedirect struct {
From string `mapstructure:"from"`
To string `mapstructure:"to"`
Type int `mapstructure:"type"`
}
type configActivityPub struct {
Enabled bool `mapstructure:"enabled"`
TagsTaxonomies []string `mapstructure:"tagsTaxonomies"`
}
type configNotifications struct {
Ntfy *configNtfy `mapstructure:"ntfy"`
Telegram *configTelegram `mapstructure:"telegram"`
}
type configNtfy struct {
Enabled bool `mapstructure:"enabled"`
Topic string `mapstructure:"topic"`
Server string `mapstructure:"server"`
User string `mapstructure:"user"`
Pass string `mapstructure:"pass"`
Email string `mapstructure:"email"`
}
type configTelegram struct {
Enabled bool `mapstructure:"enabled"`
ChatID string `mapstructure:"chatId"`
BotToken string `mapstructure:"botToken"`
InstantViewHash string `mapstructure:"instantViewHash"`
}
type configPrivateMode struct {
Enabled bool `mapstructure:"enabled"`
}
type configIndexNow struct {
Enabled bool `mapstructure:"enabled"`
}
type configEasterEgg struct {
Enabled bool `mapstructure:"enabled"`
}
type configWebmention struct {
DisableSending bool `mapstructure:"disableSending"`
DisableReceiving bool `mapstructure:"disableReceiving"`
}
type configMapTiles struct {
Source string `mapstructure:"source"`
Attribution string `mapstructure:"attribution"`
MinZoom int `mapstructure:"minZoom"`
MaxZoom int `mapstructure:"maxZoom"`
}
type configTTS struct {
Enabled bool `mapstructure:"enabled"`
GoogleAPIKey string `mapstructure:"googleApiKey"`
}
type configReactions struct {
Enabled bool `mapstructure:"enabled"`
}
type configPprof struct {
Enabled bool `mapstructure:"enabled"`
Address string `mapstructure:"address"`
}
type configPlugin struct {
Path string `mapstructure:"path"`
Type string `mapstructure:"type"`
Import string `mapstructure:"import"`
Config map[string]any `mapstructure:"config"`
}
func (a *goBlog) loadConfigFile(file string) error {
// Use viper to load the config file
v := viper.New()
if file != "" {
// Use config file from the flag
v.SetConfigFile(file)
} else {
// Search in default locations
v.SetConfigName("config")
v.AddConfigPath("./config/")
}
// Read config
if err := v.ReadInConfig(); err != nil {
return err
}
// Unmarshal config
a.cfg = createDefaultConfig()
return v.Unmarshal(a.cfg)
}
func (a *goBlog) initConfig(logging bool) error {
if a.cfg == nil {
a.cfg = createDefaultConfig()
}
if a.cfg.initialized {
return nil
}
// Init database
if err := a.initDatabase(logging); err != nil {
return err
}
// Check config
// Parse addresses and hostnames
if a.cfg.Server.PublicAddress == "" {
return errors.New("no public address configured")
}
publicURL, err := url.Parse(a.cfg.Server.PublicAddress)
if err != nil {
return errors.New("Invalid public address: " + err.Error())
}
a.cfg.Server.publicHostname = publicURL.Hostname()
if sa := a.cfg.Server.ShortPublicAddress; sa != "" {
shortPublicURL, err := url.Parse(sa)
if err != nil {
return errors.New("Invalid short public address: " + err.Error())
}
a.cfg.Server.shortPublicHostname = shortPublicURL.Hostname()
}
if ma := a.cfg.Server.MediaAddress; ma != "" {
mediaUrl, err := url.Parse(ma)
if err != nil {
return errors.New("Invalid media address: " + err.Error())
}
a.cfg.Server.mediaHostname = mediaUrl.Hostname()
}
// Check if any blog is configured
if a.cfg.Blogs == nil || len(a.cfg.Blogs) == 0 {
a.cfg.Blogs = map[string]*configBlog{
"default": createDefaultBlog(),
}
}
// Check if default blog is set
if a.cfg.DefaultBlog == "" {
// Set default blog to the only blog that is configured
a.cfg.DefaultBlog = lo.Keys(a.cfg.Blogs)[0]
}
// Check if default blog exists
if a.cfg.Blogs[a.cfg.DefaultBlog] == nil {
return errors.New("default blog does not exist")
}
// Check media storage config
if ms := a.cfg.Micropub.MediaStorage; ms != nil && ms.MediaURL != "" {
ms.MediaURL = strings.TrimSuffix(ms.MediaURL, "/")
}
// Check if webmention receiving is disabled
if wm := a.cfg.Webmention; wm != nil && wm.DisableReceiving {
// Disable comments for all blogs
for _, b := range a.cfg.Blogs {
b.Comments = &configComments{Enabled: false}
}
}
// Check if sections already migrated to db
const sectionMigrationKey = "sections_migrated"
if val, err := a.getSettingValue(sectionMigrationKey); err != nil {
return err
} else if val == "" {
if err = a.saveAllSections(); err != nil {
return err
}
if err = a.saveSettingValue(sectionMigrationKey, "1"); err != nil {
return err
}
}
// Load db sections
if err = a.loadSections(); err != nil {
return err
}
// Check config for each blog
for blog, bc := range a.cfg.Blogs {
// Check sections and add section if none exists
if len(bc.Sections) == 0 {
bc.Sections = createDefaultSections()
if err = a.saveAllSections(); err != nil {
return err
}
}
// Check default section
if defaultSection, err := a.getSettingValue(settingNameWithBlog(blog, defaultSectionSetting)); err != nil {
// Failed to read value
return err
} else if defaultSection == "" {
// No value defined in database
if _, ok := bc.Sections[bc.DefaultSection]; !ok {
bc.DefaultSection = lo.Keys(bc.Sections)[0]
}
// Save to database
if err = a.saveSettingValue(settingNameWithBlog(blog, defaultSectionSetting), bc.DefaultSection); err != nil {
return err
}
} else {
// Set value from database
bc.DefaultSection = defaultSection
}
// Check if language is set
if bc.Lang == "" {
bc.Lang = "en"
}
// Blogroll
if br := bc.Blogroll; br != nil && br.Enabled && br.Opml == "" {
br.Enabled = false
}
// Load other settings from database
bc.hideOldContentWarning, err = a.getBooleanSettingValue(settingNameWithBlog(blog, hideOldContentWarningSetting), false)
if err != nil {
return err
}
bc.hideShareButton, err = a.getBooleanSettingValue(settingNameWithBlog(blog, hideShareButtonSetting), false)
if err != nil {
return err
}
bc.hideTranslateButton, err = a.getBooleanSettingValue(settingNameWithBlog(blog, hideTranslateButtonSetting), false)
if err != nil {
return err
}
}
// Log success
a.cfg.initialized = true
log.Println("Initialized configuration")
return nil
}
func createDefaultConfig() *config {
return &config{
Server: &configServer{
Port: 8080,
PublicAddress: "http://localhost:8080",
LogFile: "data/access.log",
},
Db: &configDb{
File: "data/db.sqlite",
},
Cache: &configCache{
Enable: true,
Expiration: 600,
},
User: &configUser{
Nick: "admin",
Password: "secret",
},
Hooks: &configHooks{
Shell: "/bin/bash",
},
Micropub: &configMicropub{
CategoryParam: "tags",
ReplyParam: "replylink",
ReplyTitleParam: "replytitle",
LikeParam: "likelink",
LikeTitleParam: "liketitle",
BookmarkParam: "link",
AudioParam: "audio",
PhotoParam: "images",
PhotoDescriptionParam: "imagealts",
LocationParam: "location",
},
ActivityPub: &configActivityPub{
TagsTaxonomies: []string{"tags"},
},
}
}
func createDefaultBlog() *configBlog {
return &configBlog{
Path: "/",
Lang: "en",
Title: "My Blog",
Description: "Welcome to my blog.",
Taxonomies: []*configTaxonomy{
{
Name: "tags",
Title: "Tags",
},
},
}
}
func createDefaultSections() map[string]*configSection {
return map[string]*configSection{
"posts": {
Title: "Posts",
},
}
}
func (a *goBlog) httpsConfigured(checkAddress bool) bool {
return a.cfg.Server.PublicHTTPS ||
a.cfg.Server.TailscaleHTTPS ||
a.cfg.Server.SecurityHeaders ||
(checkAddress && strings.HasPrefix(a.cfg.Server.PublicAddress, "https"))
}
func (a *goBlog) getBlog(r *http.Request) (string, *configBlog) {
if r == nil {
return a.cfg.DefaultBlog, a.cfg.Blogs[a.cfg.DefaultBlog]
}
blog := a.cfg.DefaultBlog
if ctxBlog := r.Context().Value(blogKey); ctxBlog != nil {
if ctxBlogString, ok := ctxBlog.(string); ok {
blog = ctxBlogString
}
}
return blog, a.cfg.Blogs[blog]
}
func (a *goBlog) getBlogFromPost(p *post) *configBlog {
return a.cfg.Blogs[defaultIfEmpty(p.Blog, a.cfg.DefaultBlog)]
}