• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

umputun / tg-spam / 13734741277

08 Mar 2025 06:08AM UTC coverage: 81.061% (-0.6%) from 81.627%
13734741277

push

github

web-flow
Merge pull request #264 from umputun/feature/add-spam-filter

Add filtering to detected spam UI

17 of 58 new or added lines in 1 file covered. (29.31%)

4430 of 5465 relevant lines covered (81.06%)

61.6 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

83.71
/app/webapi/webapi.go
1
// Package webapi provides a web API spam detection service.
2
package webapi
3

4
import (
5
        "bytes"
6
        "compress/gzip"
7
        "context"
8
        "crypto/rand"
9
        "crypto/sha1" //nolint
10
        "embed"
11
        "encoding/json"
12
        "errors"
13
        "fmt"
14
        "html/template"
15
        "io"
16
        "io/fs"
17
        "math/big"
18
        "net/http"
19
        "path"
20
        "strconv"
21
        "strings"
22
        "time"
23

24
        "github.com/didip/tollbooth/v8"
25
        log "github.com/go-pkgz/lgr"
26
        "github.com/go-pkgz/rest"
27
        "github.com/go-pkgz/rest/logger"
28
        "github.com/go-pkgz/routegroup"
29

30
        "github.com/umputun/tg-spam/app/storage"
31
        "github.com/umputun/tg-spam/app/storage/engine"
32
        "github.com/umputun/tg-spam/lib/approved"
33
        "github.com/umputun/tg-spam/lib/spamcheck"
34
)
35

36
//go:generate moq --out mocks/detector.go --pkg mocks --with-resets --skip-ensure . Detector
37
//go:generate moq --out mocks/spam_filter.go --pkg mocks --with-resets --skip-ensure . SpamFilter
38
//go:generate moq --out mocks/locator.go --pkg mocks --with-resets --skip-ensure . Locator
39
//go:generate moq --out mocks/detected_spam.go --pkg mocks --with-resets --skip-ensure . DetectedSpam
40
//go:generate moq --out mocks/storage_engine.go --pkg mocks --with-resets --skip-ensure . StorageEngine
41

42
//go:embed assets/* assets/components/*
43
var templateFS embed.FS
44
var tmpl = template.Must(template.ParseFS(templateFS, "assets/*.html", "assets/components/*.html"))
45

46
// startTime tracks when the server started
47
var startTime = time.Now()
48

49
// Server is a web API server.
50
type Server struct {
51
        Config
52
}
53

54
// Config defines  server parameters
55
type Config struct {
56
        Version       string        // version to show in /ping
57
        ListenAddr    string        // listen address
58
        Detector      Detector      // spam detector
59
        SpamFilter    SpamFilter    // spam filter (bot)
60
        DetectedSpam  DetectedSpam  // detected spam accessor
61
        Locator       Locator       // locator for user info
62
        StorageEngine StorageEngine // database engine access for backups
63
        AuthPasswd    string        // basic auth password for user "tg-spam"
64
        AuthHash      string        // basic auth hash for user "tg-spam". If both AuthPasswd and AuthHash are provided, AuthHash is used
65
        Dbg           bool          // debug mode
66
        Settings      Settings      // application settings
67
}
68

69
// Settings contains all application settings
70
type Settings struct {
71
        InstanceID              string        `json:"instance_id"`
72
        PrimaryGroup            string        `json:"primary_group"`
73
        AdminGroup              string        `json:"admin_group"`
74
        DisableAdminSpamForward bool          `json:"disable_admin_spam_forward"`
75
        LoggerEnabled           bool          `json:"logger_enabled"`
76
        SuperUsers              []string      `json:"super_users"`
77
        NoSpamReply             bool          `json:"no_spam_reply"`
78
        CasEnabled              bool          `json:"cas_enabled"`
79
        MetaEnabled             bool          `json:"meta_enabled"`
80
        MetaLinksLimit          int           `json:"meta_links_limit"`
81
        MetaMentionsLimit       int           `json:"meta_mentions_limit"`
82
        MetaLinksOnly           bool          `json:"meta_links_only"`
83
        MetaImageOnly           bool          `json:"meta_image_only"`
84
        MetaVideoOnly           bool          `json:"meta_video_only"`
85
        MetaAudioOnly           bool          `json:"meta_audio_only"`
86
        MetaForwarded           bool          `json:"meta_forwarded"`
87
        MetaKeyboard            bool          `json:"meta_keyboard"`
88
        MultiLangLimit          int           `json:"multi_lang_limit"`
89
        OpenAIEnabled           bool          `json:"openai_enabled"`
90
        SamplesDataPath         string        `json:"samples_data_path"`
91
        DynamicDataPath         string        `json:"dynamic_data_path"`
92
        WatchIntervalSecs       int           `json:"watch_interval_secs"`
93
        SimilarityThreshold     float64       `json:"similarity_threshold"`
94
        MinMsgLen               int           `json:"min_msg_len"`
95
        MaxEmoji                int           `json:"max_emoji"`
96
        MinSpamProbability      float64       `json:"min_spam_probability"`
97
        ParanoidMode            bool          `json:"paranoid_mode"`
98
        FirstMessagesCount      int           `json:"first_messages_count"`
99
        StartupMessageEnabled   bool          `json:"startup_message_enabled"`
100
        TrainingEnabled         bool          `json:"training_enabled"`
101
        StorageTimeout          time.Duration `json:"storage_timeout"`
102
        OpenAIVeto              bool          `json:"openai_veto"`
103
        OpenAIHistorySize       int           `json:"openai_history_size"`
104
        OpenAIModel             string        `json:"openai_model"`
105
        SoftBanEnabled          bool          `json:"soft_ban_enabled"`
106
        AbnormalSpacingEnabled  bool          `json:"abnormal_spacing_enabled"`
107
        HistorySize             int           `json:"history_size"`
108
        DebugModeEnabled        bool          `json:"debug_mode_enabled"`
109
        DryModeEnabled          bool          `json:"dry_mode_enabled"`
110
        TGDebugModeEnabled      bool          `json:"tg_debug_mode_enabled"`
111
}
112

113
// Detector is a spam detector interface.
114
type Detector interface {
115
        Check(req spamcheck.Request) (spam bool, cr []spamcheck.Response)
116
        ApprovedUsers() []approved.UserInfo
117
        AddApprovedUser(user approved.UserInfo) error
118
        RemoveApprovedUser(id string) error
119
}
120

121
// SpamFilter is a spam filter, bot interface.
122
type SpamFilter interface {
123
        UpdateSpam(msg string) error
124
        UpdateHam(msg string) error
125
        ReloadSamples() (err error)
126
        DynamicSamples() (spam, ham []string, err error)
127
        RemoveDynamicSpamSample(sample string) error
128
        RemoveDynamicHamSample(sample string) error
129
}
130

131
// Locator is a storage interface used to get user id by name and vice versa.
132
type Locator interface {
133
        UserIDByName(ctx context.Context, userName string) int64
134
        UserNameByID(ctx context.Context, userID int64) string
135
}
136

137
// DetectedSpam is a storage interface used to get detected spam messages and set added flag.
138
type DetectedSpam interface {
139
        Read(ctx context.Context) ([]storage.DetectedSpamInfo, error)
140
        SetAddedToSamplesFlag(ctx context.Context, id int64) error
141
        FindByUserID(ctx context.Context, userID int64) (*storage.DetectedSpamInfo, error)
142
}
143

144
// StorageEngine provides access to the database engine for operations like backup
145
type StorageEngine interface {
146
        Backup(ctx context.Context, w io.Writer) error
147
        Type() engine.Type
148
        BackupSqliteAsPostgres(ctx context.Context, w io.Writer) error
149
}
150

151
// NewServer creates a new web API server.
152
func NewServer(config Config) *Server {
44✔
153
        return &Server{Config: config}
44✔
154
}
44✔
155

156
// Run starts server and accepts requests checking for spam messages.
157
func (s *Server) Run(ctx context.Context) error {
3✔
158
        router := routegroup.New(http.NewServeMux())
3✔
159
        router.Use(rest.Recoverer(log.Default()))
3✔
160
        router.Use(logger.New(logger.Log(log.Default()), logger.Prefix("[DEBUG]")).Handler)
3✔
161
        router.Use(rest.Throttle(1000))
3✔
162
        router.Use(rest.AppInfo("tg-spam", "umputun", s.Version), rest.Ping)
3✔
163
        router.Use(tollbooth.HTTPMiddleware(tollbooth.NewLimiter(50, nil)))
3✔
164
        router.Use(rest.SizeLimit(1024 * 1024)) // 1M max request size
3✔
165

3✔
166
        if s.AuthPasswd != "" || s.AuthHash != "" {
6✔
167
                log.Printf("[INFO] basic auth enabled for webapi server")
3✔
168
                if s.AuthHash != "" {
4✔
169
                        router.Use(rest.BasicAuthWithBcryptHashAndPrompt("tg-spam", s.AuthHash))
1✔
170
                } else {
3✔
171
                        router.Use(rest.BasicAuthWithPrompt("tg-spam", s.AuthPasswd))
2✔
172
                }
2✔
173
        } else {
×
174
                log.Printf("[WARN] basic auth disabled, access to webapi is not protected")
×
175
        }
×
176

177
        router = s.routes(router) // setup routes
3✔
178

3✔
179
        srv := &http.Server{Addr: s.ListenAddr, Handler: router, ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second}
3✔
180
        go func() {
6✔
181
                <-ctx.Done()
3✔
182
                if err := srv.Shutdown(ctx); err != nil {
3✔
183
                        log.Printf("[WARN] failed to shutdown webapi server: %v", err)
×
184
                } else {
3✔
185
                        log.Printf("[INFO] webapi server stopped")
3✔
186
                }
3✔
187
        }()
188

189
        log.Printf("[INFO] start webapi server on %s", s.ListenAddr)
3✔
190
        if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
3✔
191
                return fmt.Errorf("failed to run server: %w", err)
×
192
        }
×
193
        return nil
3✔
194
}
195

196
func (s *Server) routes(router *routegroup.Bundle) *routegroup.Bundle {
5✔
197
        // auth api routes
5✔
198
        router.Route(func(authApi *routegroup.Bundle) {
10✔
199
                authApi.Use(s.authMiddleware(rest.BasicAuthWithUserPasswd("tg-spam", s.AuthPasswd)))
5✔
200
                authApi.HandleFunc("POST /check", s.checkMsgHandler)         // check a message for spam
5✔
201
                authApi.HandleFunc("GET /check/{user_id}", s.checkIDHandler) // check user id for spam
5✔
202

5✔
203
                authApi.Mount("/update").Route(func(r *routegroup.Bundle) {
10✔
204
                        // update spam/ham samples
5✔
205
                        r.HandleFunc("POST /spam", s.updateSampleHandler(s.SpamFilter.UpdateSpam)) // update spam samples
5✔
206
                        r.HandleFunc("POST /ham", s.updateSampleHandler(s.SpamFilter.UpdateHam))   // update ham samples
5✔
207
                })
5✔
208

209
                authApi.Mount("/delete").Route(func(r *routegroup.Bundle) {
10✔
210
                        // delete spam/ham samples
5✔
211
                        r.HandleFunc("POST /spam", s.deleteSampleHandler(s.SpamFilter.RemoveDynamicSpamSample))
5✔
212
                        r.HandleFunc("POST /ham", s.deleteSampleHandler(s.SpamFilter.RemoveDynamicHamSample))
5✔
213
                })
5✔
214

215
                authApi.Mount("/download").Route(func(r *routegroup.Bundle) {
10✔
216
                        r.HandleFunc("GET /spam", s.downloadSampleHandler(func(spam, _ []string) ([]string, string) {
5✔
217
                                return spam, "spam.txt"
×
218
                        }))
×
219
                        r.HandleFunc("GET /ham", s.downloadSampleHandler(func(_, ham []string) ([]string, string) {
5✔
220
                                return ham, "ham.txt"
×
221
                        }))
×
222
                        r.HandleFunc("GET /detected_spam", s.downloadDetectedSpamHandler)
5✔
223
                        r.HandleFunc("GET /backup", s.downloadBackupHandler)
5✔
224
                        r.HandleFunc("GET /export-to-postgres", s.downloadExportToPostgresHandler)
5✔
225
                })
226

227
                authApi.HandleFunc("GET /samples", s.getDynamicSamplesHandler)    // get dynamic samples
5✔
228
                authApi.HandleFunc("PUT /samples", s.reloadDynamicSamplesHandler) // reload samples
5✔
229

5✔
230
                authApi.Mount("/users").Route(func(r *routegroup.Bundle) { // manage approved users
10✔
231
                        // add user to the approved list and storage
5✔
232
                        r.HandleFunc("POST /add", s.updateApprovedUsersHandler(s.Detector.AddApprovedUser))
5✔
233
                        // remove user from an approved list and storage
5✔
234
                        r.HandleFunc("POST /delete", s.updateApprovedUsersHandler(s.removeApprovedUser))
5✔
235
                        // get approved users
5✔
236
                        r.HandleFunc("GET /", s.getApprovedUsersHandler)
5✔
237
                })
5✔
238

239
                authApi.HandleFunc("GET /settings", func(w http.ResponseWriter, _ *http.Request) {
6✔
240
                        rest.RenderJSON(w, s.Settings)
1✔
241
                })
1✔
242
        })
243

244
        router.Route(func(webUI *routegroup.Bundle) {
10✔
245
                webUI.Use(s.authMiddleware(rest.BasicAuthWithPrompt("tg-spam", s.AuthPasswd)))
5✔
246
                webUI.HandleFunc("GET /", s.htmlSpamCheckHandler)                         // serve template for webUI UI
5✔
247
                webUI.HandleFunc("GET /manage_samples", s.htmlManageSamplesHandler)       // serve manage samples page
5✔
248
                webUI.HandleFunc("GET /manage_users", s.htmlManageUsersHandler)           // serve manage users page
5✔
249
                webUI.HandleFunc("GET /detected_spam", s.htmlDetectedSpamHandler)         // serve detected spam page
5✔
250
                webUI.HandleFunc("GET /list_settings", s.htmlSettingsHandler)             // serve settings
5✔
251
                webUI.HandleFunc("POST /detected_spam/add", s.htmlAddDetectedSpamHandler) // add detected spam to samples
5✔
252

5✔
253
                // handle logout - force Basic Auth re-authentication
5✔
254
                webUI.HandleFunc("GET /logout", func(w http.ResponseWriter, _ *http.Request) {
5✔
255
                        w.Header().Set("WWW-Authenticate", `Basic realm="tg-spam"`)
×
256
                        w.WriteHeader(http.StatusUnauthorized)
×
257
                        fmt.Fprintln(w, "Logged out successfully")
×
258
                })
×
259

260
                // serve only specific static files at root level
261
                staticFiles := newStaticFS(templateFS,
5✔
262
                        staticFileMapping{urlPath: "styles.css", filesysPath: "assets/styles.css"},
5✔
263
                        staticFileMapping{urlPath: "logo.png", filesysPath: "assets/logo.png"},
5✔
264
                        staticFileMapping{urlPath: "spinner.svg", filesysPath: "assets/spinner.svg"},
5✔
265
                )
5✔
266
                webUI.HandleFiles("/", http.FS(staticFiles))
5✔
267
        })
268

269
        return router
5✔
270
}
271

272
// checkMsgHandler handles POST /check request.
273
// it gets message text and user id from request body and returns spam status and check results.
274
func (s *Server) checkMsgHandler(w http.ResponseWriter, r *http.Request) {
7✔
275
        type CheckResultDisplay struct {
7✔
276
                Spam   bool
7✔
277
                Checks []spamcheck.Response
7✔
278
        }
7✔
279

7✔
280
        isHtmxRequest := r.Header.Get("HX-Request") == "true"
7✔
281

7✔
282
        req := spamcheck.Request{CheckOnly: true}
7✔
283
        if !isHtmxRequest {
13✔
284
                // API request
6✔
285
                if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
7✔
286
                        w.WriteHeader(http.StatusBadRequest)
1✔
287
                        rest.RenderJSON(w, rest.JSON{"error": "can't decode request", "details": err.Error()})
1✔
288
                        log.Printf("[WARN] can't decode request: %v", err)
1✔
289
                        return
1✔
290
                }
1✔
291
        } else {
1✔
292
                // for hx-request (HTMX) we need to get the values from the form
1✔
293
                req.UserID = r.FormValue("user_id")
1✔
294
                req.UserName = r.FormValue("user_name")
1✔
295
                req.Msg = r.FormValue("msg")
1✔
296
        }
1✔
297

298
        spam, cr := s.Detector.Check(req)
6✔
299
        if !isHtmxRequest {
11✔
300
                // for API request return JSON
5✔
301
                rest.RenderJSON(w, rest.JSON{"spam": spam, "checks": cr})
5✔
302
                return
5✔
303
        }
5✔
304

305
        if req.Msg == "" || req.UserID == "" || req.UserID == "0" {
1✔
306
                w.Header().Set("HX-Retarget", "#error-message")
×
307
                fmt.Fprintln(w, "<div class='alert alert-danger'>userid and valid message required.</div>")
×
308
                return
×
309
        }
×
310

311
        // render result for HTMX request
312
        resultDisplay := CheckResultDisplay{
1✔
313
                Spam:   spam,
1✔
314
                Checks: cr,
1✔
315
        }
1✔
316

1✔
317
        if err := tmpl.ExecuteTemplate(w, "check_results", resultDisplay); err != nil {
1✔
318
                log.Printf("[WARN] can't execute result template: %v", err)
×
319
                http.Error(w, "Error rendering result", http.StatusInternalServerError)
×
320
                return
×
321
        }
×
322
}
323

324
// checkIDHandler handles GET /check/{user_id} request.
325
// it returns JSON with the status "spam" or "ham" for a given user id.
326
// if user is spammer, it also returns check results.
327
func (s *Server) checkIDHandler(w http.ResponseWriter, r *http.Request) {
2✔
328
        type info struct {
2✔
329
                UserName  string               `json:"user_name,omitempty"`
2✔
330
                Message   string               `json:"message,omitempty"`
2✔
331
                Timestamp time.Time            `json:"timestamp,omitempty"`
2✔
332
                Checks    []spamcheck.Response `json:"checks,omitempty"`
2✔
333
        }
2✔
334
        resp := struct {
2✔
335
                Status string `json:"status"`
2✔
336
                Info   *info  `json:"info,omitempty"`
2✔
337
        }{
2✔
338
                Status: "ham",
2✔
339
        }
2✔
340

2✔
341
        userID, err := strconv.ParseInt(r.PathValue("user_id"), 10, 64)
2✔
342
        if err != nil {
2✔
343
                w.WriteHeader(http.StatusBadRequest)
×
344
                rest.RenderJSON(w, rest.JSON{"error": "can't parse user id", "details": err.Error()})
×
345
                return
×
346
        }
×
347

348
        si, err := s.DetectedSpam.FindByUserID(r.Context(), userID)
2✔
349
        if err != nil {
2✔
350
                w.WriteHeader(http.StatusInternalServerError)
×
351
                rest.RenderJSON(w, rest.JSON{"error": "can't get user info", "details": err.Error()})
×
352
                return
×
353
        }
×
354
        if si != nil {
3✔
355
                resp.Status = "spam"
1✔
356
                resp.Info = &info{
1✔
357
                        UserName:  si.UserName,
1✔
358
                        Message:   si.Text,
1✔
359
                        Timestamp: si.Timestamp,
1✔
360
                        Checks:    si.Checks,
1✔
361
                }
1✔
362
        }
1✔
363
        rest.RenderJSON(w, resp)
2✔
364
}
365

366
// getDynamicSamplesHandler handles GET /samples request. It returns dynamic samples both for spam and ham.
367
func (s *Server) getDynamicSamplesHandler(w http.ResponseWriter, _ *http.Request) {
2✔
368
        spam, ham, err := s.SpamFilter.DynamicSamples()
2✔
369
        if err != nil {
3✔
370
                w.WriteHeader(http.StatusInternalServerError)
1✔
371
                rest.RenderJSON(w, rest.JSON{"error": "can't get dynamic samples", "details": err.Error()})
1✔
372
                return
1✔
373
        }
1✔
374
        rest.RenderJSON(w, rest.JSON{"spam": spam, "ham": ham})
1✔
375
}
376

377
// downloadSampleHandler handles GET /download/spam|ham request. It returns dynamic samples both for spam and ham.
378
func (s *Server) downloadSampleHandler(pickFn func(spam, ham []string) ([]string, string)) func(w http.ResponseWriter, r *http.Request) {
13✔
379
        return func(w http.ResponseWriter, _ *http.Request) {
16✔
380
                spam, ham, err := s.SpamFilter.DynamicSamples()
3✔
381
                if err != nil {
4✔
382
                        w.WriteHeader(http.StatusInternalServerError)
1✔
383
                        rest.RenderJSON(w, rest.JSON{"error": "can't get dynamic samples", "details": err.Error()})
1✔
384
                        return
1✔
385
                }
1✔
386
                samples, name := pickFn(spam, ham)
2✔
387
                body := strings.Join(samples, "\n")
2✔
388
                w.Header().Set("Content-Type", "text/plain; charset=utf-8")
2✔
389
                w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", name))
2✔
390
                w.Header().Set("Content-Length", strconv.Itoa(len(body)))
2✔
391
                w.WriteHeader(http.StatusOK)
2✔
392
                _, _ = w.Write([]byte(body))
2✔
393
        }
394
}
395

396
// updateSampleHandler handles POST /update/spam|ham request. It updates dynamic samples both for spam and ham.
397
func (s *Server) updateSampleHandler(updFn func(msg string) error) func(w http.ResponseWriter, r *http.Request) {
13✔
398
        return func(w http.ResponseWriter, r *http.Request) {
18✔
399
                var req struct {
5✔
400
                        Msg string `json:"msg"`
5✔
401
                }
5✔
402

5✔
403
                isHtmxRequest := r.Header.Get("HX-Request") == "true"
5✔
404

5✔
405
                if isHtmxRequest {
5✔
406
                        req.Msg = r.FormValue("msg")
×
407
                } else {
5✔
408
                        if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
6✔
409
                                w.WriteHeader(http.StatusBadRequest)
1✔
410
                                rest.RenderJSON(w, rest.JSON{"error": "can't decode request", "details": err.Error()})
1✔
411
                                return
1✔
412
                        }
1✔
413
                }
414

415
                err := updFn(req.Msg)
4✔
416
                if err != nil {
5✔
417
                        w.WriteHeader(http.StatusInternalServerError)
1✔
418
                        rest.RenderJSON(w, rest.JSON{"error": "can't update samples", "details": err.Error()})
1✔
419
                        return
1✔
420
                }
1✔
421

422
                if isHtmxRequest {
3✔
423
                        s.renderSamples(w, "samples_list")
×
424
                } else {
3✔
425
                        rest.RenderJSON(w, rest.JSON{"updated": true, "msg": req.Msg})
3✔
426
                }
3✔
427
        }
428
}
429

430
// deleteSampleHandler handles DELETE /samples request. It deletes dynamic samples both for spam and ham.
431
func (s *Server) deleteSampleHandler(delFn func(msg string) error) func(w http.ResponseWriter, r *http.Request) {
13✔
432
        return func(w http.ResponseWriter, r *http.Request) {
18✔
433
                var req struct {
5✔
434
                        Msg string `json:"msg"`
5✔
435
                }
5✔
436
                isHtmxRequest := r.Header.Get("HX-Request") == "true"
5✔
437
                if isHtmxRequest {
6✔
438
                        req.Msg = r.FormValue("msg")
1✔
439
                } else {
5✔
440
                        if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
4✔
441
                                w.WriteHeader(http.StatusBadRequest)
×
442
                                rest.RenderJSON(w, rest.JSON{"error": "can't decode request", "details": err.Error()})
×
443
                                return
×
444
                        }
×
445
                }
446

447
                if err := delFn(req.Msg); err != nil {
6✔
448
                        w.WriteHeader(http.StatusInternalServerError)
1✔
449
                        rest.RenderJSON(w, rest.JSON{"error": "can't delete sample", "details": err.Error()})
1✔
450
                        return
1✔
451
                }
1✔
452

453
                if isHtmxRequest {
5✔
454
                        s.renderSamples(w, "samples_list")
1✔
455
                } else {
4✔
456
                        rest.RenderJSON(w, rest.JSON{"deleted": true, "msg": req.Msg, "count": 1})
3✔
457
                }
3✔
458
        }
459
}
460

461
// reloadDynamicSamplesHandler handles PUT /samples request. It reloads dynamic samples from db storage.
462
func (s *Server) reloadDynamicSamplesHandler(w http.ResponseWriter, _ *http.Request) {
2✔
463
        if err := s.SpamFilter.ReloadSamples(); err != nil {
3✔
464
                w.WriteHeader(http.StatusInternalServerError)
1✔
465
                rest.RenderJSON(w, rest.JSON{"error": "can't reload samples", "details": err.Error()})
1✔
466
                return
1✔
467
        }
1✔
468
        rest.RenderJSON(w, rest.JSON{"reloaded": true})
1✔
469
}
470

471
// updateApprovedUsersHandler handles POST /users/add and /users/delete requests, it adds or removes users from approved list.
472
func (s *Server) updateApprovedUsersHandler(updFn func(ui approved.UserInfo) error) func(w http.ResponseWriter, r *http.Request) {
14✔
473
        return func(w http.ResponseWriter, r *http.Request) {
23✔
474
                req := approved.UserInfo{}
9✔
475
                isHtmxRequest := r.Header.Get("HX-Request") == "true"
9✔
476
                if isHtmxRequest {
10✔
477
                        req.UserID = r.FormValue("user_id")
1✔
478
                        req.UserName = r.FormValue("user_name")
1✔
479
                } else {
9✔
480
                        if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
9✔
481
                                w.WriteHeader(http.StatusBadRequest)
1✔
482
                                rest.RenderJSON(w, rest.JSON{"error": "can't decode request", "details": err.Error()})
1✔
483
                                return
1✔
484
                        }
1✔
485
                }
486

487
                // try to get userID from request and fallback to userName lookup if it's empty
488
                if req.UserID == "" {
12✔
489
                        req.UserID = strconv.FormatInt(s.Locator.UserIDByName(r.Context(), req.UserName), 10)
4✔
490
                }
4✔
491

492
                if req.UserID == "" || req.UserID == "0" {
9✔
493
                        if isHtmxRequest {
1✔
494
                                w.Header().Set("HX-Retarget", "#error-message")
×
495
                                fmt.Fprintln(w, "<div class='alert alert-danger'>Either userid or valid username required.</div>")
×
496
                                return
×
497
                        }
×
498
                        w.WriteHeader(http.StatusBadRequest)
1✔
499
                        rest.RenderJSON(w, rest.JSON{"error": "user ID is required"})
1✔
500
                        return
1✔
501
                }
502

503
                // add or remove user from the approved list of detector
504
                if err := updFn(req); err != nil {
7✔
505
                        w.WriteHeader(http.StatusInternalServerError)
×
506
                        rest.RenderJSON(w, rest.JSON{"error": "can't update approved users", "details": err.Error()})
×
507
                        return
×
508
                }
×
509

510
                if isHtmxRequest {
8✔
511
                        users := s.Detector.ApprovedUsers()
1✔
512
                        tmplData := struct {
1✔
513
                                ApprovedUsers      []approved.UserInfo
1✔
514
                                TotalApprovedUsers int
1✔
515
                        }{
1✔
516
                                ApprovedUsers:      users,
1✔
517
                                TotalApprovedUsers: len(users),
1✔
518
                        }
1✔
519

1✔
520
                        if err := tmpl.ExecuteTemplate(w, "users_list", tmplData); err != nil {
1✔
521
                                http.Error(w, "Error executing template", http.StatusInternalServerError)
×
522
                                return
×
523
                        }
×
524

525
                } else {
6✔
526
                        rest.RenderJSON(w, rest.JSON{"updated": true, "user_id": req.UserID, "user_name": req.UserName})
6✔
527
                }
6✔
528
        }
529
}
530

531
// removeApprovedUser is adopter for updateApprovedUsersHandler updFn
532
func (s *Server) removeApprovedUser(req approved.UserInfo) error {
2✔
533
        return s.Detector.RemoveApprovedUser(req.UserID)
2✔
534
}
2✔
535

536
// getApprovedUsersHandler handles GET /users request. It returns list of approved users.
537
func (s *Server) getApprovedUsersHandler(w http.ResponseWriter, _ *http.Request) {
1✔
538
        rest.RenderJSON(w, rest.JSON{"user_ids": s.Detector.ApprovedUsers()})
1✔
539
}
1✔
540

541
// htmlSpamCheckHandler handles GET / request.
542
// It returns rendered spam_check.html template with all the components.
543
func (s *Server) htmlSpamCheckHandler(w http.ResponseWriter, _ *http.Request) {
3✔
544
        tmplData := struct {
3✔
545
                Version string
3✔
546
        }{
3✔
547
                Version: s.Version,
3✔
548
        }
3✔
549

3✔
550
        if err := tmpl.ExecuteTemplate(w, "spam_check.html", tmplData); err != nil {
4✔
551
                log.Printf("[WARN] can't execute template: %v", err)
1✔
552
                http.Error(w, "Error executing template", http.StatusInternalServerError)
1✔
553
                return
1✔
554
        }
1✔
555
}
556

557
// htmlManageSamplesHandler handles GET /manage_samples request.
558
// It returns rendered manage_samples.html template with all the components.
559
func (s *Server) htmlManageSamplesHandler(w http.ResponseWriter, _ *http.Request) {
1✔
560
        s.renderSamples(w, "manage_samples.html")
1✔
561
}
1✔
562

563
func (s *Server) htmlManageUsersHandler(w http.ResponseWriter, _ *http.Request) {
3✔
564
        users := s.Detector.ApprovedUsers()
3✔
565
        tmplData := struct {
3✔
566
                ApprovedUsers      []approved.UserInfo
3✔
567
                TotalApprovedUsers int
3✔
568
        }{
3✔
569
                ApprovedUsers:      users,
3✔
570
                TotalApprovedUsers: len(users),
3✔
571
        }
3✔
572
        tmplData.TotalApprovedUsers = len(tmplData.ApprovedUsers)
3✔
573

3✔
574
        if err := tmpl.ExecuteTemplate(w, "manage_users.html", tmplData); err != nil {
4✔
575
                log.Printf("[WARN] can't execute template: %v", err)
1✔
576
                http.Error(w, "Error executing template", http.StatusInternalServerError)
1✔
577
                return
1✔
578
        }
1✔
579
}
580

581
func (s *Server) htmlDetectedSpamHandler(w http.ResponseWriter, r *http.Request) {
2✔
582
        ds, err := s.DetectedSpam.Read(r.Context())
2✔
583
        if err != nil {
3✔
584
                log.Printf("[ERROR] Failed to fetch detected spam: %v", err)
1✔
585
                http.Error(w, "Internal Server Error", http.StatusInternalServerError)
1✔
586
                return
1✔
587
        }
1✔
588

589
        // clean up detected spam entries
590
        for i, d := range ds {
3✔
591
                d.Text = strings.ReplaceAll(d.Text, "'", " ")
2✔
592
                d.Text = strings.ReplaceAll(d.Text, "\n", " ")
2✔
593
                d.Text = strings.ReplaceAll(d.Text, "\r", " ")
2✔
594
                d.Text = strings.ReplaceAll(d.Text, "\t", " ")
2✔
595
                d.Text = strings.ReplaceAll(d.Text, "\"", " ")
2✔
596
                d.Text = strings.ReplaceAll(d.Text, "\\", " ")
2✔
597
                ds[i] = d
2✔
598
        }
2✔
599

600
        // get filter from query param, default to "all"
601
        filter := r.URL.Query().Get("filter")
1✔
602
        if filter == "" {
2✔
603
                filter = "all"
1✔
604
        }
1✔
605

606
        // apply filtering
607
        var filteredDS []storage.DetectedSpamInfo
1✔
608
        switch filter {
1✔
NEW
609
        case "non-classified":
×
NEW
610
                for _, entry := range ds {
×
NEW
611
                        hasClassifierHam := false
×
NEW
612
                        for _, check := range entry.Checks {
×
NEW
613
                                if check.Name == "classifier" && !check.Spam {
×
NEW
614
                                        hasClassifierHam = true
×
NEW
615
                                        break
×
616
                                }
617
                        }
NEW
618
                        if hasClassifierHam {
×
NEW
619
                                filteredDS = append(filteredDS, entry)
×
NEW
620
                        }
×
621
                }
NEW
622
        case "openai":
×
NEW
623
                for _, entry := range ds {
×
NEW
624
                        hasOpenAI := false
×
NEW
625
                        for _, check := range entry.Checks {
×
NEW
626
                                if check.Name == "openai" {
×
NEW
627
                                        hasOpenAI = true
×
NEW
628
                                        break
×
629
                                }
630
                        }
NEW
631
                        if hasOpenAI {
×
NEW
632
                                filteredDS = append(filteredDS, entry)
×
NEW
633
                        }
×
634
                }
635
        default: // "all" or any other value
1✔
636
                filteredDS = ds
1✔
637
        }
638

639
        tmplData := struct {
1✔
640
                DetectedSpamEntries []storage.DetectedSpamInfo
1✔
641
                TotalDetectedSpam   int
1✔
642
                FilteredCount       int
1✔
643
                Filter              string
1✔
644
        }{
1✔
645
                DetectedSpamEntries: filteredDS,
1✔
646
                TotalDetectedSpam:   len(ds),
1✔
647
                FilteredCount:       len(filteredDS),
1✔
648
                Filter:              filter,
1✔
649
        }
1✔
650

1✔
651
        // if it's an HTMX request, render both content and count display for OOB swap
1✔
652
        if r.Header.Get("HX-Request") == "true" {
1✔
NEW
653
                var buf bytes.Buffer
×
NEW
654

×
NEW
655
                // first render the content template
×
NEW
656
                if err := tmpl.ExecuteTemplate(&buf, "detected_spam_content", tmplData); err != nil {
×
NEW
657
                        log.Printf("[WARN] can't execute content template: %v", err)
×
NEW
658
                        http.Error(w, "Error executing template", http.StatusInternalServerError)
×
NEW
659
                        return
×
NEW
660
                }
×
661

662
                // then append OOB swap for the count display
NEW
663
                countHTML := ""
×
NEW
664
                if filter != "all" {
×
NEW
665
                        countHTML = fmt.Sprintf("(%d/%d)", len(filteredDS), len(ds))
×
NEW
666
                } else {
×
NEW
667
                        countHTML = fmt.Sprintf("(%d)", len(ds))
×
NEW
668
                }
×
669

NEW
670
                buf.WriteString(fmt.Sprintf(`<span id="count-display" hx-swap-oob="true">%s</span>`, countHTML))
×
NEW
671

×
NEW
672
                // write the combined response
×
NEW
673
                if _, err := buf.WriteTo(w); err != nil {
×
NEW
674
                        log.Printf("[WARN] failed to write response: %v", err)
×
NEW
675
                }
×
NEW
676
                return
×
677
        }
678

679
        // full page render for normal requests
680
        if err := tmpl.ExecuteTemplate(w, "detected_spam.html", tmplData); err != nil {
1✔
681
                log.Printf("[WARN] can't execute template: %v", err)
×
682
                http.Error(w, "Error executing template", http.StatusInternalServerError)
×
683
                return
×
684
        }
×
685
}
686

687
func (s *Server) htmlAddDetectedSpamHandler(w http.ResponseWriter, r *http.Request) {
5✔
688
        reportErr := func(err error, _ int) {
9✔
689
                w.Header().Set("HX-Retarget", "#error-message")
4✔
690
                fmt.Fprintf(w, "<div class='alert alert-danger'>%s</div>", err)
4✔
691
        }
4✔
692
        msg := r.FormValue("msg")
5✔
693

5✔
694
        id, err := strconv.ParseInt(r.FormValue("id"), 10, 64)
5✔
695
        if err != nil || msg == "" {
7✔
696
                log.Printf("[WARN] bad request: %v", err)
2✔
697
                reportErr(fmt.Errorf("bad request: %v", err), http.StatusBadRequest)
2✔
698
                return
2✔
699
        }
2✔
700

701
        if err := s.SpamFilter.UpdateSpam(msg); err != nil {
4✔
702
                log.Printf("[WARN] failed to update spam samples: %v", err)
1✔
703
                reportErr(fmt.Errorf("can't update spam samples: %v", err), http.StatusInternalServerError)
1✔
704
                return
1✔
705

1✔
706
        }
1✔
707
        if err := s.DetectedSpam.SetAddedToSamplesFlag(r.Context(), id); err != nil {
3✔
708
                log.Printf("[WARN] failed to update detected spam: %v", err)
1✔
709
                reportErr(fmt.Errorf("can't update detected spam: %v", err), http.StatusInternalServerError)
1✔
710
                return
1✔
711
        }
1✔
712
        w.WriteHeader(http.StatusOK)
1✔
713
}
714

715
func (s *Server) htmlSettingsHandler(w http.ResponseWriter, _ *http.Request) {
4✔
716
        // get database information if StorageEngine is available
4✔
717
        var dbInfo struct {
4✔
718
                DatabaseType   string `json:"database_type"`
4✔
719
                GID            string `json:"gid"`
4✔
720
                DatabaseStatus string `json:"database_status"`
4✔
721
        }
4✔
722

4✔
723
        if s.StorageEngine != nil {
6✔
724
                // try to cast to SQL engine to get type information
2✔
725
                if sqlEngine, ok := s.StorageEngine.(*engine.SQL); ok {
2✔
726
                        dbInfo.DatabaseType = string(sqlEngine.Type())
×
727
                        dbInfo.GID = sqlEngine.GID()
×
728
                        dbInfo.DatabaseStatus = "Connected"
×
729
                } else {
2✔
730
                        dbInfo.DatabaseType = "Unknown"
2✔
731
                        dbInfo.DatabaseStatus = "Connected (unknown type)"
2✔
732
                }
2✔
733
        } else {
2✔
734
                dbInfo.DatabaseStatus = "Not connected"
2✔
735
        }
2✔
736

737
        // get backup information
738
        backupURL := "/download/backup"
4✔
739
        backupFilename := fmt.Sprintf("tg-spam-backup-%s-%s.sql.gz", dbInfo.DatabaseType, time.Now().Format("20060102-150405"))
4✔
740

4✔
741
        // get system info - uptime since server start
4✔
742
        uptime := time.Since(startTime)
4✔
743

4✔
744
        data := struct {
4✔
745
                Settings
4✔
746
                Version  string
4✔
747
                Database struct {
4✔
748
                        Type   string
4✔
749
                        GID    string
4✔
750
                        Status string
4✔
751
                }
4✔
752
                Backup struct {
4✔
753
                        URL      string
4✔
754
                        Filename string
4✔
755
                }
4✔
756
                System struct {
4✔
757
                        Uptime string
4✔
758
                }
4✔
759
        }{
4✔
760
                Settings: s.Settings,
4✔
761
                Version:  s.Version,
4✔
762
                Database: struct {
4✔
763
                        Type   string
4✔
764
                        GID    string
4✔
765
                        Status string
4✔
766
                }{
4✔
767
                        Type:   dbInfo.DatabaseType,
4✔
768
                        GID:    dbInfo.GID,
4✔
769
                        Status: dbInfo.DatabaseStatus,
4✔
770
                },
4✔
771
                Backup: struct {
4✔
772
                        URL      string
4✔
773
                        Filename string
4✔
774
                }{
4✔
775
                        URL:      backupURL,
4✔
776
                        Filename: backupFilename,
4✔
777
                },
4✔
778
                System: struct {
4✔
779
                        Uptime string
4✔
780
                }{
4✔
781
                        Uptime: formatDuration(uptime),
4✔
782
                },
4✔
783
        }
4✔
784

4✔
785
        if err := tmpl.ExecuteTemplate(w, "settings.html", data); err != nil {
5✔
786
                log.Printf("[WARN] can't execute template: %v", err)
1✔
787
                http.Error(w, "Error executing template", http.StatusInternalServerError)
1✔
788
                return
1✔
789
        }
1✔
790
}
791

792
// formatDuration formats a duration in a human-readable way
793
func formatDuration(d time.Duration) string {
12✔
794
        days := int(d.Hours() / 24)
12✔
795
        hours := int(d.Hours()) % 24
12✔
796
        minutes := int(d.Minutes()) % 60
12✔
797

12✔
798
        if days > 0 {
15✔
799
                return fmt.Sprintf("%dd %dh %dm", days, hours, minutes)
3✔
800
        }
3✔
801

802
        if hours > 0 {
11✔
803
                return fmt.Sprintf("%dh %dm", hours, minutes)
2✔
804
        }
2✔
805

806
        return fmt.Sprintf("%dm", minutes)
7✔
807
}
808

809
func (s *Server) downloadDetectedSpamHandler(w http.ResponseWriter, r *http.Request) {
3✔
810
        ctx := r.Context()
3✔
811
        spam, err := s.DetectedSpam.Read(ctx)
3✔
812
        if err != nil {
4✔
813
                w.WriteHeader(http.StatusInternalServerError)
1✔
814
                rest.RenderJSON(w, rest.JSON{"error": "can't get detected spam", "details": err.Error()})
1✔
815
                return
1✔
816
        }
1✔
817

818
        type jsonSpamInfo struct {
2✔
819
                ID        int64                `json:"id"`
2✔
820
                GID       string               `json:"gid"`
2✔
821
                Text      string               `json:"text"`
2✔
822
                UserID    int64                `json:"user_id"`
2✔
823
                UserName  string               `json:"user_name"`
2✔
824
                Timestamp time.Time            `json:"timestamp"`
2✔
825
                Added     bool                 `json:"added"`
2✔
826
                Checks    []spamcheck.Response `json:"checks"`
2✔
827
        }
2✔
828

2✔
829
        // convert entries to jsonl format with lowercase fields
2✔
830
        lines := make([]string, 0, len(spam))
2✔
831
        for _, entry := range spam {
5✔
832
                data, err := json.Marshal(jsonSpamInfo{
3✔
833
                        ID:        entry.ID,
3✔
834
                        GID:       entry.GID,
3✔
835
                        Text:      entry.Text,
3✔
836
                        UserID:    entry.UserID,
3✔
837
                        UserName:  entry.UserName,
3✔
838
                        Timestamp: entry.Timestamp,
3✔
839
                        Added:     entry.Added,
3✔
840
                        Checks:    entry.Checks,
3✔
841
                })
3✔
842
                if err != nil {
3✔
843
                        w.WriteHeader(http.StatusInternalServerError)
×
844
                        rest.RenderJSON(w, rest.JSON{"error": "can't marshal entry", "details": err.Error()})
×
845
                        return
×
846
                }
×
847
                lines = append(lines, string(data))
3✔
848
        }
849

850
        body := strings.Join(lines, "\n")
2✔
851
        w.Header().Set("Content-Type", "application/x-jsonlines")
2✔
852
        w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", "detected_spam.jsonl"))
2✔
853
        w.Header().Set("Content-Length", strconv.Itoa(len(body)))
2✔
854
        w.WriteHeader(http.StatusOK)
2✔
855
        _, _ = w.Write([]byte(body))
2✔
856
}
857

858
// downloadBackupHandler streams a database backup as an SQL file with gzip compression
859
// Files are always compressed and always have .gz extension to ensure consistency
860
func (s *Server) downloadBackupHandler(w http.ResponseWriter, r *http.Request) {
2✔
861
        if s.StorageEngine == nil {
3✔
862
                w.WriteHeader(http.StatusInternalServerError)
1✔
863
                rest.RenderJSON(w, rest.JSON{"error": "storage engine not available"})
1✔
864
                return
1✔
865
        }
1✔
866

867
        // set filename based on database type and timestamp
868
        dbType := "db"
1✔
869
        sqlEng, ok := s.StorageEngine.(*engine.SQL)
1✔
870
        if ok {
1✔
871
                dbType = string(sqlEng.Type())
×
872
        }
×
873
        timestamp := time.Now().Format("20060102-150405")
1✔
874

1✔
875
        // always use a .gz extension as the content is always compressed
1✔
876
        filename := fmt.Sprintf("tg-spam-backup-%s-%s.sql.gz", dbType, timestamp)
1✔
877

1✔
878
        // set headers for file download - note we're using application/octet-stream
1✔
879
        // instead of application/sql to prevent browsers from trying to interpret the file
1✔
880
        w.Header().Set("Content-Type", "application/octet-stream")
1✔
881
        w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename))
1✔
882
        w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
1✔
883
        w.Header().Set("Pragma", "no-cache")
1✔
884
        w.Header().Set("Expires", "0")
1✔
885

1✔
886
        // create a gzip writer that streams to response
1✔
887
        gzipWriter := gzip.NewWriter(w)
1✔
888
        defer func() {
2✔
889
                if err := gzipWriter.Close(); err != nil {
1✔
890
                        log.Printf("[ERROR] failed to close gzip writer: %v", err)
×
891
                }
×
892
        }()
893

894
        // stream backup directly to response through gzip
895
        if err := s.StorageEngine.Backup(r.Context(), gzipWriter); err != nil {
1✔
896
                log.Printf("[ERROR] failed to create backup: %v", err)
×
897
                // we've already started writing the response, so we can't send a proper error response
×
898
                return
×
899
        }
×
900

901
        // flush the gzip writer to ensure all data is written
902
        if err := gzipWriter.Flush(); err != nil {
1✔
903
                log.Printf("[ERROR] failed to flush gzip writer: %v", err)
×
904
        }
×
905
}
906

907
// downloadExportToPostgresHandler streams a PostgreSQL-compatible export from a SQLite database
908
func (s *Server) downloadExportToPostgresHandler(w http.ResponseWriter, r *http.Request) {
3✔
909
        if s.StorageEngine == nil {
4✔
910
                w.WriteHeader(http.StatusInternalServerError)
1✔
911
                rest.RenderJSON(w, rest.JSON{"error": "storage engine not available"})
1✔
912
                return
1✔
913
        }
1✔
914

915
        // check if the database is SQLite
916
        if s.StorageEngine.Type() != engine.Sqlite {
3✔
917
                w.WriteHeader(http.StatusBadRequest)
1✔
918
                rest.RenderJSON(w, rest.JSON{"error": "source database must be SQLite"})
1✔
919
                return
1✔
920
        }
1✔
921

922
        // set filename based on timestamp
923
        timestamp := time.Now().Format("20060102-150405")
1✔
924
        filename := fmt.Sprintf("tg-spam-sqlite-to-postgres-%s.sql.gz", timestamp)
1✔
925

1✔
926
        // set headers for file download
1✔
927
        w.Header().Set("Content-Type", "application/octet-stream")
1✔
928
        w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename))
1✔
929
        w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
1✔
930
        w.Header().Set("Pragma", "no-cache")
1✔
931
        w.Header().Set("Expires", "0")
1✔
932

1✔
933
        // create a gzip writer that streams to response
1✔
934
        gzipWriter := gzip.NewWriter(w)
1✔
935
        defer func() {
2✔
936
                if err := gzipWriter.Close(); err != nil {
1✔
937
                        log.Printf("[ERROR] failed to close gzip writer: %v", err)
×
938
                }
×
939
        }()
940

941
        // stream export directly to response through gzip
942
        if err := s.StorageEngine.BackupSqliteAsPostgres(r.Context(), gzipWriter); err != nil {
1✔
943
                log.Printf("[ERROR] failed to create export: %v", err)
×
944
                // we've already started writing the response, so we can't send a proper error response
×
945
                return
×
946
        }
×
947

948
        // flush the gzip writer to ensure all data is written
949
        if err := gzipWriter.Flush(); err != nil {
1✔
950
                log.Printf("[ERROR] failed to flush gzip writer: %v", err)
×
951
        }
×
952
}
953

954
func (s *Server) renderSamples(w http.ResponseWriter, tmplName string) {
6✔
955
        spam, ham, err := s.SpamFilter.DynamicSamples()
6✔
956
        if err != nil {
7✔
957
                w.WriteHeader(http.StatusInternalServerError)
1✔
958
                rest.RenderJSON(w, rest.JSON{"error": "can't fetch samples", "details": err.Error()})
1✔
959
                return
1✔
960
        }
1✔
961

962
        spam, ham = s.reverseSamples(spam, ham)
5✔
963

5✔
964
        type smpleWithID struct {
5✔
965
                ID     string
5✔
966
                Sample string
5✔
967
        }
5✔
968

5✔
969
        makeID := func(s string) string {
19✔
970
                hash := sha1.New() //nolint
14✔
971
                if _, err := hash.Write([]byte(s)); err != nil {
14✔
972
                        return fmt.Sprintf("%x", s)
×
973
                }
×
974
                return fmt.Sprintf("%x", hash.Sum(nil))
14✔
975
        }
976

977
        tmplData := struct {
5✔
978
                SpamSamples      []smpleWithID
5✔
979
                HamSamples       []smpleWithID
5✔
980
                TotalHamSamples  int
5✔
981
                TotalSpamSamples int
5✔
982
        }{
5✔
983
                TotalHamSamples:  len(ham),
5✔
984
                TotalSpamSamples: len(spam),
5✔
985
        }
5✔
986
        for _, s := range spam {
12✔
987
                tmplData.SpamSamples = append(tmplData.SpamSamples, smpleWithID{ID: makeID(s), Sample: s})
7✔
988
        }
7✔
989
        for _, h := range ham {
12✔
990
                tmplData.HamSamples = append(tmplData.HamSamples, smpleWithID{ID: makeID(h), Sample: h})
7✔
991
        }
7✔
992

993
        if err := tmpl.ExecuteTemplate(w, tmplName, tmplData); err != nil {
6✔
994
                w.WriteHeader(http.StatusInternalServerError)
1✔
995
                rest.RenderJSON(w, rest.JSON{"error": "can't execute template", "details": err.Error()})
1✔
996
                return
1✔
997
        }
1✔
998
}
999

1000
func (s *Server) authMiddleware(mw func(next http.Handler) http.Handler) func(next http.Handler) http.Handler {
10✔
1001
        if s.AuthPasswd == "" {
16✔
1002
                return func(next http.Handler) http.Handler {
105✔
1003
                        return next
99✔
1004
                }
99✔
1005
        }
1006
        return func(next http.Handler) http.Handler {
70✔
1007
                return mw(next)
66✔
1008
        }
66✔
1009
}
1010

1011
// reverseSamples returns reversed lists of spam and ham samples
1012
func (s *Server) reverseSamples(spam, ham []string) (revSpam, revHam []string) {
8✔
1013
        revSpam = make([]string, len(spam))
8✔
1014
        revHam = make([]string, len(ham))
8✔
1015

8✔
1016
        for i, j := 0, len(spam)-1; i < len(spam); i, j = i+1, j-1 {
19✔
1017
                revSpam[i] = spam[j]
11✔
1018
        }
11✔
1019
        for i, j := 0, len(ham)-1; i < len(ham); i, j = i+1, j-1 {
19✔
1020
                revHam[i] = ham[j]
11✔
1021
        }
11✔
1022
        return revSpam, revHam
8✔
1023
}
1024

1025
// staticFS is a filtered filesystem that only exposes specific static files
1026
type staticFS struct {
1027
        fs        fs.FS
1028
        urlToPath map[string]string
1029
}
1030

1031
// staticFileMapping defines a mapping between URL path and filesystem path
1032
type staticFileMapping struct {
1033
        urlPath     string
1034
        filesysPath string
1035
}
1036

1037
func newStaticFS(fsys fs.FS, files ...staticFileMapping) *staticFS {
5✔
1038
        urlToPath := make(map[string]string)
5✔
1039
        for _, f := range files {
20✔
1040
                urlToPath[f.urlPath] = f.filesysPath
15✔
1041
        }
15✔
1042

1043
        return &staticFS{
5✔
1044
                fs:        fsys,
5✔
1045
                urlToPath: urlToPath,
5✔
1046
        }
5✔
1047
}
1048

1049
func (sfs *staticFS) Open(name string) (fs.File, error) {
5✔
1050
        name = path.Clean("/" + name)[1:]
5✔
1051
        if fsPath, ok := sfs.urlToPath[name]; ok {
8✔
1052
                return sfs.fs.Open(fsPath)
3✔
1053
        }
3✔
1054
        return nil, fs.ErrNotExist
2✔
1055
}
1056

1057
// GenerateRandomPassword generates a random password of a given length
1058
func GenerateRandomPassword(length int) (string, error) {
2✔
1059
        const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+"
2✔
1060

2✔
1061
        var password strings.Builder
2✔
1062
        charsetSize := big.NewInt(int64(len(charset)))
2✔
1063

2✔
1064
        for i := 0; i < length; i++ {
66✔
1065
                randomNumber, err := rand.Int(rand.Reader, charsetSize)
64✔
1066
                if err != nil {
64✔
1067
                        return "", err
×
1068
                }
×
1069

1070
                password.WriteByte(charset[randomNumber.Int64()])
64✔
1071
        }
1072

1073
        return password.String(), nil
2✔
1074
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc