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

umputun / tg-spam / 14315737380

07 Apr 2025 05:34PM UTC coverage: 81.465% (-0.2%) from 81.712%
14315737380

push

github

umputun
Add Arabic script detector plugin for Lua

- Added new plugin to detect usernames using Arabic script
- Added comprehensive unit tests
- Updated plugins documentation to include the new plugin
- Fixed code formatting and code style issues

5028 of 6172 relevant lines covered (81.46%)

56.84 hits per line

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

83.51
/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
        MetaUsernameSymbols     string        `json:"meta_username_symbols"`
89
        MultiLangLimit          int           `json:"multi_lang_limit"`
90
        OpenAIEnabled           bool          `json:"openai_enabled"`
91
        LuaPluginsEnabled       bool          `json:"lua_plugins_enabled"`
92
        LuaPluginsDir           string        `json:"lua_plugins_dir"`
93
        LuaEnabledPlugins       []string      `json:"lua_enabled_plugins"`
94
        LuaDynamicReload        bool          `json:"lua_dynamic_reload"`
95
        LuaAvailablePlugins     []string      `json:"lua_available_plugins"` // the list of all available Lua plugins
96
        SamplesDataPath         string        `json:"samples_data_path"`
97
        DynamicDataPath         string        `json:"dynamic_data_path"`
98
        WatchIntervalSecs       int           `json:"watch_interval_secs"`
99
        SimilarityThreshold     float64       `json:"similarity_threshold"`
100
        MinMsgLen               int           `json:"min_msg_len"`
101
        MaxEmoji                int           `json:"max_emoji"`
102
        MinSpamProbability      float64       `json:"min_spam_probability"`
103
        ParanoidMode            bool          `json:"paranoid_mode"`
104
        FirstMessagesCount      int           `json:"first_messages_count"`
105
        StartupMessageEnabled   bool          `json:"startup_message_enabled"`
106
        TrainingEnabled         bool          `json:"training_enabled"`
107
        StorageTimeout          time.Duration `json:"storage_timeout"`
108
        OpenAIVeto              bool          `json:"openai_veto"`
109
        OpenAIHistorySize       int           `json:"openai_history_size"`
110
        OpenAIModel             string        `json:"openai_model"`
111
        SoftBanEnabled          bool          `json:"soft_ban_enabled"`
112
        AbnormalSpacingEnabled  bool          `json:"abnormal_spacing_enabled"`
113
        HistorySize             int           `json:"history_size"`
114
        DebugModeEnabled        bool          `json:"debug_mode_enabled"`
115
        DryModeEnabled          bool          `json:"dry_mode_enabled"`
116
        TGDebugModeEnabled      bool          `json:"tg_debug_mode_enabled"`
117
}
118

119
// Detector is a spam detector interface.
120
type Detector interface {
121
        Check(req spamcheck.Request) (spam bool, cr []spamcheck.Response)
122
        ApprovedUsers() []approved.UserInfo
123
        AddApprovedUser(user approved.UserInfo) error
124
        RemoveApprovedUser(id string) error
125
        GetLuaPluginNames() []string // Returns the list of available Lua plugin names
126
}
127

128
// SpamFilter is a spam filter, bot interface.
129
type SpamFilter interface {
130
        UpdateSpam(msg string) error
131
        UpdateHam(msg string) error
132
        ReloadSamples() (err error)
133
        DynamicSamples() (spam, ham []string, err error)
134
        RemoveDynamicSpamSample(sample string) error
135
        RemoveDynamicHamSample(sample string) error
136
}
137

138
// Locator is a storage interface used to get user id by name and vice versa.
139
type Locator interface {
140
        UserIDByName(ctx context.Context, userName string) int64
141
        UserNameByID(ctx context.Context, userID int64) string
142
}
143

144
// DetectedSpam is a storage interface used to get detected spam messages and set added flag.
145
type DetectedSpam interface {
146
        Read(ctx context.Context) ([]storage.DetectedSpamInfo, error)
147
        SetAddedToSamplesFlag(ctx context.Context, id int64) error
148
        FindByUserID(ctx context.Context, userID int64) (*storage.DetectedSpamInfo, error)
149
}
150

151
// StorageEngine provides access to the database engine for operations like backup
152
type StorageEngine interface {
153
        Backup(ctx context.Context, w io.Writer) error
154
        Type() engine.Type
155
        BackupSqliteAsPostgres(ctx context.Context, w io.Writer) error
156
}
157

158
// NewServer creates a new web API server.
159
func NewServer(config Config) *Server {
46✔
160
        return &Server{Config: config}
46✔
161
}
46✔
162

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

3✔
173
        if s.AuthPasswd != "" || s.AuthHash != "" {
6✔
174
                log.Printf("[INFO] basic auth enabled for webapi server")
3✔
175
                if s.AuthHash != "" {
4✔
176
                        router.Use(rest.BasicAuthWithBcryptHashAndPrompt("tg-spam", s.AuthHash))
1✔
177
                } else {
3✔
178
                        router.Use(rest.BasicAuthWithPrompt("tg-spam", s.AuthPasswd))
2✔
179
                }
2✔
180
        } else {
×
181
                log.Printf("[WARN] basic auth disabled, access to webapi is not protected")
×
182
        }
×
183

184
        router = s.routes(router) // setup routes
3✔
185

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

196
        log.Printf("[INFO] start webapi server on %s", s.ListenAddr)
3✔
197
        if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
3✔
198
                return fmt.Errorf("failed to run server: %w", err)
×
199
        }
×
200
        return nil
3✔
201
}
202

203
func (s *Server) routes(router *routegroup.Bundle) *routegroup.Bundle {
5✔
204
        // auth api routes
5✔
205
        router.Route(func(authApi *routegroup.Bundle) {
10✔
206
                authApi.Use(s.authMiddleware(rest.BasicAuthWithUserPasswd("tg-spam", s.AuthPasswd)))
5✔
207
                authApi.HandleFunc("POST /check", s.checkMsgHandler)         // check a message for spam
5✔
208
                authApi.HandleFunc("GET /check/{user_id}", s.checkIDHandler) // check user id for spam
5✔
209

5✔
210
                authApi.Mount("/update").Route(func(r *routegroup.Bundle) {
10✔
211
                        // update spam/ham samples
5✔
212
                        r.HandleFunc("POST /spam", s.updateSampleHandler(s.SpamFilter.UpdateSpam)) // update spam samples
5✔
213
                        r.HandleFunc("POST /ham", s.updateSampleHandler(s.SpamFilter.UpdateHam))   // update ham samples
5✔
214
                })
5✔
215

216
                authApi.Mount("/delete").Route(func(r *routegroup.Bundle) {
10✔
217
                        // delete spam/ham samples
5✔
218
                        r.HandleFunc("POST /spam", s.deleteSampleHandler(s.SpamFilter.RemoveDynamicSpamSample))
5✔
219
                        r.HandleFunc("POST /ham", s.deleteSampleHandler(s.SpamFilter.RemoveDynamicHamSample))
5✔
220
                })
5✔
221

222
                authApi.Mount("/download").Route(func(r *routegroup.Bundle) {
10✔
223
                        r.HandleFunc("GET /spam", s.downloadSampleHandler(func(spam, _ []string) ([]string, string) {
5✔
224
                                return spam, "spam.txt"
×
225
                        }))
×
226
                        r.HandleFunc("GET /ham", s.downloadSampleHandler(func(_, ham []string) ([]string, string) {
5✔
227
                                return ham, "ham.txt"
×
228
                        }))
×
229
                        r.HandleFunc("GET /detected_spam", s.downloadDetectedSpamHandler)
5✔
230
                        r.HandleFunc("GET /backup", s.downloadBackupHandler)
5✔
231
                        r.HandleFunc("GET /export-to-postgres", s.downloadExportToPostgresHandler)
5✔
232
                })
233

234
                authApi.HandleFunc("GET /samples", s.getDynamicSamplesHandler)    // get dynamic samples
5✔
235
                authApi.HandleFunc("PUT /samples", s.reloadDynamicSamplesHandler) // reload samples
5✔
236

5✔
237
                authApi.Mount("/users").Route(func(r *routegroup.Bundle) { // manage approved users
10✔
238
                        // add user to the approved list and storage
5✔
239
                        r.HandleFunc("POST /add", s.updateApprovedUsersHandler(s.Detector.AddApprovedUser))
5✔
240
                        // remove user from an approved list and storage
5✔
241
                        r.HandleFunc("POST /delete", s.updateApprovedUsersHandler(s.removeApprovedUser))
5✔
242
                        // get approved users
5✔
243
                        r.HandleFunc("GET /", s.getApprovedUsersHandler)
5✔
244
                })
5✔
245

246
                authApi.HandleFunc("GET /settings", s.getSettingsHandler) // get application settings
5✔
247
        })
248

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

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

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

274
        return router
5✔
275
}
276

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

8✔
285
        isHtmxRequest := r.Header.Get("HX-Request") == "true"
8✔
286

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

303
        spam, cr := s.Detector.Check(req)
7✔
304
        if !isHtmxRequest {
13✔
305
                // for API request return JSON
6✔
306
                rest.RenderJSON(w, rest.JSON{"spam": spam, "checks": cr})
6✔
307
                return
6✔
308
        }
6✔
309

310
        if req.Msg == "" {
1✔
311
                w.Header().Set("HX-Retarget", "#error-message")
×
312
                fmt.Fprintln(w, "<div class='alert alert-danger'>Valid message required.</div>")
×
313
                return
×
314
        }
×
315

316
        // render result for HTMX request
317
        resultDisplay := CheckResultDisplay{
1✔
318
                Spam:   spam,
1✔
319
                Checks: cr,
1✔
320
        }
1✔
321

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

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

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

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

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

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

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

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

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

420
                err := updFn(req.Msg)
4✔
421
                if err != nil {
5✔
422
                        w.WriteHeader(http.StatusInternalServerError)
1✔
423
                        rest.RenderJSON(w, rest.JSON{"error": "can't update samples", "details": err.Error()})
1✔
424
                        return
1✔
425
                }
1✔
426

427
                if isHtmxRequest {
3✔
428
                        s.renderSamples(w, "samples_list")
×
429
                } else {
3✔
430
                        rest.RenderJSON(w, rest.JSON{"updated": true, "msg": req.Msg})
3✔
431
                }
3✔
432
        }
433
}
434

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

452
                if err := delFn(req.Msg); err != nil {
6✔
453
                        w.WriteHeader(http.StatusInternalServerError)
1✔
454
                        rest.RenderJSON(w, rest.JSON{"error": "can't delete sample", "details": err.Error()})
1✔
455
                        return
1✔
456
                }
1✔
457

458
                if isHtmxRequest {
5✔
459
                        s.renderSamples(w, "samples_list")
1✔
460
                } else {
4✔
461
                        rest.RenderJSON(w, rest.JSON{"deleted": true, "msg": req.Msg, "count": 1})
3✔
462
                }
3✔
463
        }
464
}
465

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

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

492
                // try to get userID from request and fallback to userName lookup if it's empty
493
                if req.UserID == "" {
12✔
494
                        req.UserID = strconv.FormatInt(s.Locator.UserIDByName(r.Context(), req.UserName), 10)
4✔
495
                }
4✔
496

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

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

515
                if isHtmxRequest {
8✔
516
                        users := s.Detector.ApprovedUsers()
1✔
517
                        tmplData := struct {
1✔
518
                                ApprovedUsers      []approved.UserInfo
1✔
519
                                TotalApprovedUsers int
1✔
520
                        }{
1✔
521
                                ApprovedUsers:      users,
1✔
522
                                TotalApprovedUsers: len(users),
1✔
523
                        }
1✔
524

1✔
525
                        if err := tmpl.ExecuteTemplate(w, "users_list", tmplData); err != nil {
1✔
526
                                http.Error(w, "Error executing template", http.StatusInternalServerError)
×
527
                                return
×
528
                        }
×
529

530
                } else {
6✔
531
                        rest.RenderJSON(w, rest.JSON{"updated": true, "user_id": req.UserID, "user_name": req.UserName})
6✔
532
                }
6✔
533
        }
534
}
535

536
// removeApprovedUser is adopter for updateApprovedUsersHandler updFn
537
func (s *Server) removeApprovedUser(req approved.UserInfo) error {
2✔
538
        if err := s.Detector.RemoveApprovedUser(req.UserID); err != nil {
2✔
539
                return fmt.Errorf("failed to remove approved user %s: %w", req.UserID, err)
×
540
        }
×
541
        return nil
2✔
542
}
543

544
// getApprovedUsersHandler handles GET /users request. It returns list of approved users.
545
func (s *Server) getApprovedUsersHandler(w http.ResponseWriter, _ *http.Request) {
1✔
546
        rest.RenderJSON(w, rest.JSON{"user_ids": s.Detector.ApprovedUsers()})
1✔
547
}
1✔
548

549
// getSettingsHandler returns application settings, including the list of available Lua plugins
550
func (s *Server) getSettingsHandler(w http.ResponseWriter, _ *http.Request) {
3✔
551
        // get the list of available Lua plugins before returning settings
3✔
552
        s.Settings.LuaAvailablePlugins = s.Detector.GetLuaPluginNames()
3✔
553
        rest.RenderJSON(w, s.Settings)
3✔
554
}
3✔
555

556
// htmlSpamCheckHandler handles GET / request.
557
// It returns rendered spam_check.html template with all the components.
558
func (s *Server) htmlSpamCheckHandler(w http.ResponseWriter, _ *http.Request) {
3✔
559
        tmplData := struct {
3✔
560
                Version string
3✔
561
        }{
3✔
562
                Version: s.Version,
3✔
563
        }
3✔
564

3✔
565
        if err := tmpl.ExecuteTemplate(w, "spam_check.html", tmplData); err != nil {
4✔
566
                log.Printf("[WARN] can't execute template: %v", err)
1✔
567
                http.Error(w, "Error executing template", http.StatusInternalServerError)
1✔
568
                return
1✔
569
        }
1✔
570
}
571

572
// htmlManageSamplesHandler handles GET /manage_samples request.
573
// It returns rendered manage_samples.html template with all the components.
574
func (s *Server) htmlManageSamplesHandler(w http.ResponseWriter, _ *http.Request) {
1✔
575
        s.renderSamples(w, "manage_samples.html")
1✔
576
}
1✔
577

578
func (s *Server) htmlManageUsersHandler(w http.ResponseWriter, _ *http.Request) {
3✔
579
        users := s.Detector.ApprovedUsers()
3✔
580
        tmplData := struct {
3✔
581
                ApprovedUsers      []approved.UserInfo
3✔
582
                TotalApprovedUsers int
3✔
583
        }{
3✔
584
                ApprovedUsers:      users,
3✔
585
                TotalApprovedUsers: len(users),
3✔
586
        }
3✔
587
        tmplData.TotalApprovedUsers = len(tmplData.ApprovedUsers)
3✔
588

3✔
589
        if err := tmpl.ExecuteTemplate(w, "manage_users.html", tmplData); err != nil {
4✔
590
                log.Printf("[WARN] can't execute template: %v", err)
1✔
591
                http.Error(w, "Error executing template", http.StatusInternalServerError)
1✔
592
                return
1✔
593
        }
1✔
594
}
595

596
func (s *Server) htmlDetectedSpamHandler(w http.ResponseWriter, r *http.Request) {
2✔
597
        ds, err := s.DetectedSpam.Read(r.Context())
2✔
598
        if err != nil {
3✔
599
                log.Printf("[ERROR] Failed to fetch detected spam: %v", err)
1✔
600
                http.Error(w, "Internal Server Error", http.StatusInternalServerError)
1✔
601
                return
1✔
602
        }
1✔
603

604
        // clean up detected spam entries
605
        for i, d := range ds {
3✔
606
                d.Text = strings.ReplaceAll(d.Text, "'", " ")
2✔
607
                d.Text = strings.ReplaceAll(d.Text, "\n", " ")
2✔
608
                d.Text = strings.ReplaceAll(d.Text, "\r", " ")
2✔
609
                d.Text = strings.ReplaceAll(d.Text, "\t", " ")
2✔
610
                d.Text = strings.ReplaceAll(d.Text, "\"", " ")
2✔
611
                d.Text = strings.ReplaceAll(d.Text, "\\", " ")
2✔
612
                ds[i] = d
2✔
613
        }
2✔
614

615
        // get filter from query param, default to "all"
616
        filter := r.URL.Query().Get("filter")
1✔
617
        if filter == "" {
2✔
618
                filter = "all"
1✔
619
        }
1✔
620

621
        // apply filtering
622
        var filteredDS []storage.DetectedSpamInfo
1✔
623
        switch filter {
1✔
624
        case "non-classified":
×
625
                for _, entry := range ds {
×
626
                        hasClassifierHam := false
×
627
                        for _, check := range entry.Checks {
×
628
                                if check.Name == "classifier" && !check.Spam {
×
629
                                        hasClassifierHam = true
×
630
                                        break
×
631
                                }
632
                        }
633
                        if hasClassifierHam {
×
634
                                filteredDS = append(filteredDS, entry)
×
635
                        }
×
636
                }
637
        case "openai":
×
638
                for _, entry := range ds {
×
639
                        hasOpenAI := false
×
640
                        for _, check := range entry.Checks {
×
641
                                if check.Name == "openai" {
×
642
                                        hasOpenAI = true
×
643
                                        break
×
644
                                }
645
                        }
646
                        if hasOpenAI {
×
647
                                filteredDS = append(filteredDS, entry)
×
648
                        }
×
649
                }
650
        default: // "all" or any other value
1✔
651
                filteredDS = ds
1✔
652
        }
653

654
        tmplData := struct {
1✔
655
                DetectedSpamEntries []storage.DetectedSpamInfo
1✔
656
                TotalDetectedSpam   int
1✔
657
                FilteredCount       int
1✔
658
                Filter              string
1✔
659
                OpenAIEnabled       bool
1✔
660
        }{
1✔
661
                DetectedSpamEntries: filteredDS,
1✔
662
                TotalDetectedSpam:   len(ds),
1✔
663
                FilteredCount:       len(filteredDS),
1✔
664
                Filter:              filter,
1✔
665
                OpenAIEnabled:       s.Settings.OpenAIEnabled,
1✔
666
        }
1✔
667

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

×
672
                // first render the content template
×
673
                if err := tmpl.ExecuteTemplate(&buf, "detected_spam_content", tmplData); err != nil {
×
674
                        log.Printf("[WARN] can't execute content template: %v", err)
×
675
                        http.Error(w, "Error executing template", http.StatusInternalServerError)
×
676
                        return
×
677
                }
×
678

679
                // then append OOB swap for the count display
680
                countHTML := ""
×
681
                if filter != "all" {
×
682
                        countHTML = fmt.Sprintf("(%d/%d)", len(filteredDS), len(ds))
×
683
                } else {
×
684
                        countHTML = fmt.Sprintf("(%d)", len(ds))
×
685
                }
×
686

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

×
689
                // write the combined response
×
690
                if _, err := buf.WriteTo(w); err != nil {
×
691
                        log.Printf("[WARN] failed to write response: %v", err)
×
692
                }
×
693
                return
×
694
        }
695

696
        // full page render for normal requests
697
        if err := tmpl.ExecuteTemplate(w, "detected_spam.html", tmplData); err != nil {
1✔
698
                log.Printf("[WARN] can't execute template: %v", err)
×
699
                http.Error(w, "Error executing template", http.StatusInternalServerError)
×
700
                return
×
701
        }
×
702
}
703

704
func (s *Server) htmlAddDetectedSpamHandler(w http.ResponseWriter, r *http.Request) {
5✔
705
        reportErr := func(err error, _ int) {
9✔
706
                w.Header().Set("HX-Retarget", "#error-message")
4✔
707
                fmt.Fprintf(w, "<div class='alert alert-danger'>%s</div>", err)
4✔
708
        }
4✔
709
        msg := r.FormValue("msg")
5✔
710

5✔
711
        id, err := strconv.ParseInt(r.FormValue("id"), 10, 64)
5✔
712
        if err != nil || msg == "" {
7✔
713
                log.Printf("[WARN] bad request: %v", err)
2✔
714
                reportErr(fmt.Errorf("bad request: %v", err), http.StatusBadRequest)
2✔
715
                return
2✔
716
        }
2✔
717

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

1✔
723
        }
1✔
724
        if err := s.DetectedSpam.SetAddedToSamplesFlag(r.Context(), id); err != nil {
3✔
725
                log.Printf("[WARN] failed to update detected spam: %v", err)
1✔
726
                reportErr(fmt.Errorf("can't update detected spam: %v", err), http.StatusInternalServerError)
1✔
727
                return
1✔
728
        }
1✔
729
        w.WriteHeader(http.StatusOK)
1✔
730
}
731

732
func (s *Server) htmlSettingsHandler(w http.ResponseWriter, _ *http.Request) {
4✔
733
        // get database information if StorageEngine is available
4✔
734
        var dbInfo struct {
4✔
735
                DatabaseType   string `json:"database_type"`
4✔
736
                GID            string `json:"gid"`
4✔
737
                DatabaseStatus string `json:"database_status"`
4✔
738
        }
4✔
739

4✔
740
        if s.StorageEngine != nil {
6✔
741
                // try to cast to SQL engine to get type information
2✔
742
                if sqlEngine, ok := s.StorageEngine.(*engine.SQL); ok {
2✔
743
                        dbInfo.DatabaseType = string(sqlEngine.Type())
×
744
                        dbInfo.GID = sqlEngine.GID()
×
745
                        dbInfo.DatabaseStatus = "Connected"
×
746
                } else {
2✔
747
                        dbInfo.DatabaseType = "Unknown"
2✔
748
                        dbInfo.DatabaseStatus = "Connected (unknown type)"
2✔
749
                }
2✔
750
        } else {
2✔
751
                dbInfo.DatabaseStatus = "Not connected"
2✔
752
        }
2✔
753

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

4✔
758
        // get system info - uptime since server start
4✔
759
        uptime := time.Since(startTime)
4✔
760

4✔
761
        // get the list of available Lua plugins
4✔
762
        s.Settings.LuaAvailablePlugins = s.Detector.GetLuaPluginNames()
4✔
763

4✔
764
        data := struct {
4✔
765
                Settings
4✔
766
                Version  string
4✔
767
                Database struct {
4✔
768
                        Type   string
4✔
769
                        GID    string
4✔
770
                        Status string
4✔
771
                }
4✔
772
                Backup struct {
4✔
773
                        URL      string
4✔
774
                        Filename string
4✔
775
                }
4✔
776
                System struct {
4✔
777
                        Uptime string
4✔
778
                }
4✔
779
        }{
4✔
780
                Settings: s.Settings,
4✔
781
                Version:  s.Version,
4✔
782
                Database: struct {
4✔
783
                        Type   string
4✔
784
                        GID    string
4✔
785
                        Status string
4✔
786
                }{
4✔
787
                        Type:   dbInfo.DatabaseType,
4✔
788
                        GID:    dbInfo.GID,
4✔
789
                        Status: dbInfo.DatabaseStatus,
4✔
790
                },
4✔
791
                Backup: struct {
4✔
792
                        URL      string
4✔
793
                        Filename string
4✔
794
                }{
4✔
795
                        URL:      backupURL,
4✔
796
                        Filename: backupFilename,
4✔
797
                },
4✔
798
                System: struct {
4✔
799
                        Uptime string
4✔
800
                }{
4✔
801
                        Uptime: formatDuration(uptime),
4✔
802
                },
4✔
803
        }
4✔
804

4✔
805
        if err := tmpl.ExecuteTemplate(w, "settings.html", data); err != nil {
5✔
806
                log.Printf("[WARN] can't execute template: %v", err)
1✔
807
                http.Error(w, "Error executing template", http.StatusInternalServerError)
1✔
808
                return
1✔
809
        }
1✔
810
}
811

812
// formatDuration formats a duration in a human-readable way
813
func formatDuration(d time.Duration) string {
12✔
814
        days := int(d.Hours() / 24)
12✔
815
        hours := int(d.Hours()) % 24
12✔
816
        minutes := int(d.Minutes()) % 60
12✔
817

12✔
818
        if days > 0 {
15✔
819
                return fmt.Sprintf("%dd %dh %dm", days, hours, minutes)
3✔
820
        }
3✔
821

822
        if hours > 0 {
11✔
823
                return fmt.Sprintf("%dh %dm", hours, minutes)
2✔
824
        }
2✔
825

826
        return fmt.Sprintf("%dm", minutes)
7✔
827
}
828

829
func (s *Server) downloadDetectedSpamHandler(w http.ResponseWriter, r *http.Request) {
3✔
830
        ctx := r.Context()
3✔
831
        spam, err := s.DetectedSpam.Read(ctx)
3✔
832
        if err != nil {
4✔
833
                w.WriteHeader(http.StatusInternalServerError)
1✔
834
                rest.RenderJSON(w, rest.JSON{"error": "can't get detected spam", "details": err.Error()})
1✔
835
                return
1✔
836
        }
1✔
837

838
        type jsonSpamInfo struct {
2✔
839
                ID        int64                `json:"id"`
2✔
840
                GID       string               `json:"gid"`
2✔
841
                Text      string               `json:"text"`
2✔
842
                UserID    int64                `json:"user_id"`
2✔
843
                UserName  string               `json:"user_name"`
2✔
844
                Timestamp time.Time            `json:"timestamp"`
2✔
845
                Added     bool                 `json:"added"`
2✔
846
                Checks    []spamcheck.Response `json:"checks"`
2✔
847
        }
2✔
848

2✔
849
        // convert entries to jsonl format with lowercase fields
2✔
850
        lines := make([]string, 0, len(spam))
2✔
851
        for _, entry := range spam {
5✔
852
                data, err := json.Marshal(jsonSpamInfo{
3✔
853
                        ID:        entry.ID,
3✔
854
                        GID:       entry.GID,
3✔
855
                        Text:      entry.Text,
3✔
856
                        UserID:    entry.UserID,
3✔
857
                        UserName:  entry.UserName,
3✔
858
                        Timestamp: entry.Timestamp,
3✔
859
                        Added:     entry.Added,
3✔
860
                        Checks:    entry.Checks,
3✔
861
                })
3✔
862
                if err != nil {
3✔
863
                        w.WriteHeader(http.StatusInternalServerError)
×
864
                        rest.RenderJSON(w, rest.JSON{"error": "can't marshal entry", "details": err.Error()})
×
865
                        return
×
866
                }
×
867
                lines = append(lines, string(data))
3✔
868
        }
869

870
        body := strings.Join(lines, "\n")
2✔
871
        w.Header().Set("Content-Type", "application/x-jsonlines")
2✔
872
        w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", "detected_spam.jsonl"))
2✔
873
        w.Header().Set("Content-Length", strconv.Itoa(len(body)))
2✔
874
        w.WriteHeader(http.StatusOK)
2✔
875
        _, _ = w.Write([]byte(body))
2✔
876
}
877

878
// downloadBackupHandler streams a database backup as an SQL file with gzip compression
879
// Files are always compressed and always have .gz extension to ensure consistency
880
func (s *Server) downloadBackupHandler(w http.ResponseWriter, r *http.Request) {
2✔
881
        if s.StorageEngine == nil {
3✔
882
                w.WriteHeader(http.StatusInternalServerError)
1✔
883
                rest.RenderJSON(w, rest.JSON{"error": "storage engine not available"})
1✔
884
                return
1✔
885
        }
1✔
886

887
        // set filename based on database type and timestamp
888
        dbType := "db"
1✔
889
        sqlEng, ok := s.StorageEngine.(*engine.SQL)
1✔
890
        if ok {
1✔
891
                dbType = string(sqlEng.Type())
×
892
        }
×
893
        timestamp := time.Now().Format("20060102-150405")
1✔
894

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

1✔
898
        // set headers for file download - note we're using application/octet-stream
1✔
899
        // instead of application/sql to prevent browsers from trying to interpret the file
1✔
900
        w.Header().Set("Content-Type", "application/octet-stream")
1✔
901
        w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename))
1✔
902
        w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
1✔
903
        w.Header().Set("Pragma", "no-cache")
1✔
904
        w.Header().Set("Expires", "0")
1✔
905

1✔
906
        // create a gzip writer that streams to response
1✔
907
        gzipWriter := gzip.NewWriter(w)
1✔
908
        defer func() {
2✔
909
                if err := gzipWriter.Close(); err != nil {
1✔
910
                        log.Printf("[ERROR] failed to close gzip writer: %v", err)
×
911
                }
×
912
        }()
913

914
        // stream backup directly to response through gzip
915
        if err := s.StorageEngine.Backup(r.Context(), gzipWriter); err != nil {
1✔
916
                log.Printf("[ERROR] failed to create backup: %v", err)
×
917
                // we've already started writing the response, so we can't send a proper error response
×
918
                return
×
919
        }
×
920

921
        // flush the gzip writer to ensure all data is written
922
        if err := gzipWriter.Flush(); err != nil {
1✔
923
                log.Printf("[ERROR] failed to flush gzip writer: %v", err)
×
924
        }
×
925
}
926

927
// downloadExportToPostgresHandler streams a PostgreSQL-compatible export from a SQLite database
928
func (s *Server) downloadExportToPostgresHandler(w http.ResponseWriter, r *http.Request) {
3✔
929
        if s.StorageEngine == nil {
4✔
930
                w.WriteHeader(http.StatusInternalServerError)
1✔
931
                rest.RenderJSON(w, rest.JSON{"error": "storage engine not available"})
1✔
932
                return
1✔
933
        }
1✔
934

935
        // check if the database is SQLite
936
        if s.StorageEngine.Type() != engine.Sqlite {
3✔
937
                w.WriteHeader(http.StatusBadRequest)
1✔
938
                rest.RenderJSON(w, rest.JSON{"error": "source database must be SQLite"})
1✔
939
                return
1✔
940
        }
1✔
941

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

1✔
946
        // set headers for file download
1✔
947
        w.Header().Set("Content-Type", "application/octet-stream")
1✔
948
        w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename))
1✔
949
        w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
1✔
950
        w.Header().Set("Pragma", "no-cache")
1✔
951
        w.Header().Set("Expires", "0")
1✔
952

1✔
953
        // create a gzip writer that streams to response
1✔
954
        gzipWriter := gzip.NewWriter(w)
1✔
955
        defer func() {
2✔
956
                if err := gzipWriter.Close(); err != nil {
1✔
957
                        log.Printf("[ERROR] failed to close gzip writer: %v", err)
×
958
                }
×
959
        }()
960

961
        // stream export directly to response through gzip
962
        if err := s.StorageEngine.BackupSqliteAsPostgres(r.Context(), gzipWriter); err != nil {
1✔
963
                log.Printf("[ERROR] failed to create export: %v", err)
×
964
                // we've already started writing the response, so we can't send a proper error response
×
965
                return
×
966
        }
×
967

968
        // flush the gzip writer to ensure all data is written
969
        if err := gzipWriter.Flush(); err != nil {
1✔
970
                log.Printf("[ERROR] failed to flush gzip writer: %v", err)
×
971
        }
×
972
}
973

974
func (s *Server) renderSamples(w http.ResponseWriter, tmplName string) {
6✔
975
        spam, ham, err := s.SpamFilter.DynamicSamples()
6✔
976
        if err != nil {
7✔
977
                w.WriteHeader(http.StatusInternalServerError)
1✔
978
                rest.RenderJSON(w, rest.JSON{"error": "can't fetch samples", "details": err.Error()})
1✔
979
                return
1✔
980
        }
1✔
981

982
        spam, ham = s.reverseSamples(spam, ham)
5✔
983

5✔
984
        type smpleWithID struct {
5✔
985
                ID     string
5✔
986
                Sample string
5✔
987
        }
5✔
988

5✔
989
        makeID := func(s string) string {
19✔
990
                hash := sha1.New() //nolint
14✔
991
                if _, err := hash.Write([]byte(s)); err != nil {
14✔
992
                        return fmt.Sprintf("%x", s)
×
993
                }
×
994
                return fmt.Sprintf("%x", hash.Sum(nil))
14✔
995
        }
996

997
        tmplData := struct {
5✔
998
                SpamSamples      []smpleWithID
5✔
999
                HamSamples       []smpleWithID
5✔
1000
                TotalHamSamples  int
5✔
1001
                TotalSpamSamples int
5✔
1002
        }{
5✔
1003
                TotalHamSamples:  len(ham),
5✔
1004
                TotalSpamSamples: len(spam),
5✔
1005
        }
5✔
1006
        for _, s := range spam {
12✔
1007
                tmplData.SpamSamples = append(tmplData.SpamSamples, smpleWithID{ID: makeID(s), Sample: s})
7✔
1008
        }
7✔
1009
        for _, h := range ham {
12✔
1010
                tmplData.HamSamples = append(tmplData.HamSamples, smpleWithID{ID: makeID(h), Sample: h})
7✔
1011
        }
7✔
1012

1013
        if err := tmpl.ExecuteTemplate(w, tmplName, tmplData); err != nil {
6✔
1014
                w.WriteHeader(http.StatusInternalServerError)
1✔
1015
                rest.RenderJSON(w, rest.JSON{"error": "can't execute template", "details": err.Error()})
1✔
1016
                return
1✔
1017
        }
1✔
1018
}
1019

1020
func (s *Server) authMiddleware(mw func(next http.Handler) http.Handler) func(next http.Handler) http.Handler {
10✔
1021
        if s.AuthPasswd == "" {
16✔
1022
                return func(next http.Handler) http.Handler {
105✔
1023
                        return next
99✔
1024
                }
99✔
1025
        }
1026
        return func(next http.Handler) http.Handler {
70✔
1027
                return mw(next)
66✔
1028
        }
66✔
1029
}
1030

1031
// reverseSamples returns reversed lists of spam and ham samples
1032
func (s *Server) reverseSamples(spam, ham []string) (revSpam, revHam []string) {
8✔
1033
        revSpam = make([]string, len(spam))
8✔
1034
        revHam = make([]string, len(ham))
8✔
1035

8✔
1036
        for i, j := 0, len(spam)-1; i < len(spam); i, j = i+1, j-1 {
19✔
1037
                revSpam[i] = spam[j]
11✔
1038
        }
11✔
1039
        for i, j := 0, len(ham)-1; i < len(ham); i, j = i+1, j-1 {
19✔
1040
                revHam[i] = ham[j]
11✔
1041
        }
11✔
1042
        return revSpam, revHam
8✔
1043
}
1044

1045
// staticFS is a filtered filesystem that only exposes specific static files
1046
type staticFS struct {
1047
        fs        fs.FS
1048
        urlToPath map[string]string
1049
}
1050

1051
// staticFileMapping defines a mapping between URL path and filesystem path
1052
type staticFileMapping struct {
1053
        urlPath     string
1054
        filesysPath string
1055
}
1056

1057
func newStaticFS(fsys fs.FS, files ...staticFileMapping) *staticFS {
5✔
1058
        urlToPath := make(map[string]string)
5✔
1059
        for _, f := range files {
20✔
1060
                urlToPath[f.urlPath] = f.filesysPath
15✔
1061
        }
15✔
1062

1063
        return &staticFS{
5✔
1064
                fs:        fsys,
5✔
1065
                urlToPath: urlToPath,
5✔
1066
        }
5✔
1067
}
1068

1069
func (sfs *staticFS) Open(name string) (fs.File, error) {
5✔
1070
        cleanName := path.Clean("/" + name)[1:]
5✔
1071

5✔
1072
        fsPath, ok := sfs.urlToPath[cleanName]
5✔
1073
        if !ok {
7✔
1074
                return nil, fs.ErrNotExist
2✔
1075
        }
2✔
1076

1077
        file, err := sfs.fs.Open(fsPath)
3✔
1078
        if err != nil {
3✔
1079
                return nil, fmt.Errorf("failed to open static file %s: %w", fsPath, err)
×
1080
        }
×
1081
        return file, nil
3✔
1082
}
1083

1084
// GenerateRandomPassword generates a random password of a given length
1085
func GenerateRandomPassword(length int) (string, error) {
2✔
1086
        const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+"
2✔
1087
        const charsetLen = int64(len(charset))
2✔
1088

2✔
1089
        result := make([]byte, length)
2✔
1090
        for i := 0; i < length; i++ {
66✔
1091
                n, err := rand.Int(rand.Reader, big.NewInt(charsetLen))
64✔
1092
                if err != nil {
64✔
1093
                        return "", fmt.Errorf("failed to generate random number: %w", err)
×
1094
                }
×
1095
                result[i] = charset[n.Int64()]
64✔
1096
        }
1097
        return string(result), nil
2✔
1098
}
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