-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.go
More file actions
227 lines (204 loc) · 5.66 KB
/
Copy pathconfig.go
File metadata and controls
227 lines (204 loc) · 5.66 KB
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
// This file is part of club-1/newsletter-go.
//
// Copyright (c) 2026 CLUB1 Members <contact@club1.fr>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later
package newsletter
import (
"bufio"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"path/filepath"
"slices"
"strings"
"github.com/club-1/newsletter-go/v3/messages"
)
const (
EmailsFile string = "emails"
SecretFile string = ".secret"
SignatureFile string = "signature.txt"
SettingsFile string = "settings.json"
)
// Some error values.
var (
ErrNotSubscribed = errors.New("not subscribed")
)
type Settings struct {
Title string
DisplayName string
Language messages.Language
}
type Config struct {
Dir string
Emails []string
Secret string
Signature string
Settings Settings
}
func (c *Config) Unsubscribe(addr string) error {
index := slices.Index(c.Emails, addr)
if index == -1 {
return ErrNotSubscribed
}
c.Emails = append(c.Emails[:index], c.Emails[index+1:]...)
return c.saveEmails()
}
func (c *Config) Subscribe(addr string) error {
c.Emails = append(c.Emails, addr)
return c.saveEmails()
}
func (c *Config) saveEmails() error {
emailsFilePath := filepath.Join(c.Dir, EmailsFile)
err := writeLines(c.Emails, emailsFilePath)
if err != nil {
return fmt.Errorf("could not save emails: %w", err)
}
return nil
}
func (c *Config) SaveSignature() error {
signatureFilePath := filepath.Join(c.Dir, SignatureFile)
err := os.WriteFile(signatureFilePath, []byte(c.Signature), 0660)
if err != nil {
return fmt.Errorf("could not save signature: %w", err)
}
return nil
}
func (c *Config) SaveSettings() error {
settingsFilePath := filepath.Join(c.Dir, SettingsFile)
if err := saveSettings(settingsFilePath, c.Settings); err != nil {
return fmt.Errorf("could not save settings: %w", err)
}
return nil
}
// readLines reads a whole file into memory
// and returns a slice of its lines.
func readLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}
// writeLines writes the lines to the given file.
func writeLines(lines []string, path string) error {
content := strings.Join(lines, "\n")
err := os.WriteFile(path, []byte(content+"\n"), 0664)
if err != nil {
return fmt.Errorf("write file error: %w", err)
}
return nil
}
func randString() string {
key := make([]byte, 32)
rand.Read(key)
dst := make([]byte, base64.StdEncoding.EncodedLen(len(key)))
base64.StdEncoding.Encode(dst, key)
return string(dst)
}
func saveSettings(path string, settings Settings) error {
settingsJson, err := json.Marshal(settings)
if err != nil {
return fmt.Errorf("encode settings JSON: %w", err)
}
err = os.WriteFile(path, settingsJson, 0660)
if err != nil {
return fmt.Errorf("write settings: %w", err)
}
return nil
}
// InitConfig returns a new [*Config] loaded from the given configDir.
func InitConfig(configDir string) (*Config, error) {
err := os.MkdirAll(configDir, 0775)
if err != nil {
return nil, fmt.Errorf("init config directory: %w", err)
}
var emails []string
emailsFilePath := filepath.Join(configDir, EmailsFile)
_, err = os.Stat(emailsFilePath)
if errors.Is(err, os.ErrNotExist) {
emails = []string{}
} else {
emails, err = readLines(emailsFilePath)
if err != nil {
return nil, fmt.Errorf("get emails: %w", err)
}
}
var signature string
signatureFilePath := filepath.Join(configDir, SignatureFile)
_, err = os.Stat(signatureFilePath)
if errors.Is(err, os.ErrNotExist) {
signature = ""
} else {
signatureB, err := os.ReadFile(signatureFilePath)
if err != nil {
return nil, fmt.Errorf("get signature: %w", err)
}
signature = string(signatureB)
}
var secret string
secretFilePath := filepath.Join(configDir, SecretFile)
_, err = os.Stat(secretFilePath)
if errors.Is(err, os.ErrNotExist) {
secret = randString()
err := os.WriteFile(secretFilePath, []byte(secret+"\n"), 0660)
if err != nil {
return nil, fmt.Errorf("store generated secret: %w", err)
}
log.Print("generated secret")
} else {
secretB, err := os.ReadFile(secretFilePath)
if err != nil {
return nil, fmt.Errorf("get secret: %w", err)
}
secret = strings.TrimSpace(string(secretB))
}
var settings Settings
settingsFilePath := filepath.Join(configDir, SettingsFile)
_, err = os.Stat(settingsFilePath)
if errors.Is(err, os.ErrNotExist) {
settings = Settings{}
if err := saveSettings(settingsFilePath, settings); err != nil {
return nil, fmt.Errorf("init settings: %w", err)
}
} else {
settingsJson, err := os.ReadFile(settingsFilePath)
if err != nil {
return nil, fmt.Errorf("get settings: %w", err)
}
err = json.Unmarshal(settingsJson, &settings)
if err != nil {
return nil, fmt.Errorf("decode settings: %w", err)
}
}
return &Config{
Dir: configDir,
Emails: emails,
Signature: signature,
Secret: secret,
Settings: settings,
}, nil
}