From 26dcb34edf293cf2eccaef5422b4c66456fde5d1 Mon Sep 17 00:00:00 2001 From: Eggbertx Date: Fri, 30 Aug 2024 23:08:01 -0700 Subject: [PATCH] Apply suggestions made by DeepSource --- cmd/gochan-migration/internal/common/filters.go | 16 ++++++++++------ .../internal/gcupdate/gcupdate.go | 10 +++++----- frontend/ts/dom/postdropdown.ts | 4 ++++ pkg/gcsql/filters.go | 13 ++++--------- pkg/gcsql/initsql/init.go | 4 ++-- pkg/gcsql/tables.go | 2 +- pkg/gcsql/wordfilters.go | 16 +++++++++++----- pkg/manage/actionsModPerm.go | 6 +++--- pkg/manage/filters.go | 4 ++++ pkg/manage/handler.go | 4 +++- pkg/posting/formatting.go | 1 - 11 files changed, 47 insertions(+), 33 deletions(-) diff --git a/cmd/gochan-migration/internal/common/filters.go b/cmd/gochan-migration/internal/common/filters.go index c486ad57..efb5580f 100644 --- a/cmd/gochan-migration/internal/common/filters.go +++ b/cmd/gochan-migration/internal/common/filters.go @@ -12,8 +12,8 @@ import ( "github.com/gochan-org/gochan/pkg/gcsql" ) -// Used for db version 4 upgrade to create the filter tables from the respective SQL init file -func AddFilterTables(db *gcsql.GCDB, ctx context.Context, tx *sql.Tx, sqlConfig *config.SQLConfig) error { +// AddFilterTables is used for the db version 4 upgrade to create the filter tables from the respective SQL init file +func AddFilterTables(ctx context.Context, db *gcsql.GCDB, tx *sql.Tx, sqlConfig *config.SQLConfig) error { filePath, err := getInitFilePath("initdb_" + sqlConfig.DBtype + ".sql") if err != nil { return err @@ -37,7 +37,8 @@ func AddFilterTables(db *gcsql.GCDB, ctx context.Context, tx *sql.Tx, sqlConfig return nil } -func MigrateFileBans(db *gcsql.GCDB, ctx context.Context, tx *sql.Tx, cfg *config.SQLConfig) error { +// MigrateFileBans migrates file checksum and image fingerprint bans to the filter table +func MigrateFileBans(ctx context.Context, db *gcsql.GCDB, tx *sql.Tx, cfg *config.SQLConfig) error { rows, err := db.QueryContextSQL(ctx, nil, `SELECT board_id,staff_id,staff_note,issued_at,checksum,fingerprinter,ban_ip,ban_ip_message FROM DBPREFIXfile_ban`) if err != nil { return err @@ -103,7 +104,8 @@ func MigrateFileBans(db *gcsql.GCDB, ctx context.Context, tx *sql.Tx, cfg *confi return rows.Close() } -func MigrateFilenameBans(db *gcsql.GCDB, ctx context.Context, tx *sql.Tx, cfg *config.SQLConfig) error { +// MigrateFilenameBans migrates filename bans to the filter table +func MigrateFilenameBans(ctx context.Context, db *gcsql.GCDB, tx *sql.Tx, cfg *config.SQLConfig) error { rows, err := db.QueryContextSQL(ctx, nil, `SELECT board_id,staff_id,staff_note,issued_at,filename,match_mode FROM DBPREFIXfilename_ban`) if err != nil { return err @@ -154,7 +156,8 @@ func MigrateFilenameBans(db *gcsql.GCDB, ctx context.Context, tx *sql.Tx, cfg *c return rows.Close() } -func MigrateUsernameBans(db *gcsql.GCDB, ctx context.Context, tx *sql.Tx, cfg *config.SQLConfig) error { +// MigrateUsernameBans migrates poster name bans to the filter table +func MigrateUsernameBans(ctx context.Context, db *gcsql.GCDB, tx *sql.Tx, cfg *config.SQLConfig) error { rows, err := db.QueryContextSQL(ctx, nil, `SELECT board_id,staff_id,staff_note,issued_at,username,is_regex FROM DBPREFIXusername_ban`) if err != nil { return err @@ -206,7 +209,8 @@ func MigrateUsernameBans(db *gcsql.GCDB, ctx context.Context, tx *sql.Tx, cfg *c return rows.Close() } -func MigrateWordfilters(db *gcsql.GCDB, ctx context.Context, tx *sql.Tx, sqlConfig *config.SQLConfig) error { +// MigrateWordfilters migrates pre-filter wordfilters to the filter table +func MigrateWordfilters(ctx context.Context, db *gcsql.GCDB, tx *sql.Tx, sqlConfig *config.SQLConfig) error { rows, err := db.QueryContextSQL(ctx, nil, `SELECT board_dirs, staff_id, staff_note, issued_at, search, match_mode, change_to FROM DBPREFIXwordfilters`) if err != nil { return err diff --git a/cmd/gochan-migration/internal/gcupdate/gcupdate.go b/cmd/gochan-migration/internal/gcupdate/gcupdate.go index d969a9e9..729b6b76 100644 --- a/cmd/gochan-migration/internal/gcupdate/gcupdate.go +++ b/cmd/gochan-migration/internal/gcupdate/gcupdate.go @@ -80,19 +80,19 @@ func (dbu *GCDatabaseUpdater) MigrateDB() (bool, error) { if !filterTableExists { // DBPREFIXfilters not found, create it and migrate data from DBPREFIXfile_bans, DBPREFIXfilename_bans, and DBPREFIXusername_bans, - if err = common.AddFilterTables(dbu.db, ctx, tx, &sqlConfig); err != nil { + if err = common.AddFilterTables(ctx, dbu.db, tx, &sqlConfig); err != nil { return false, err } - if err = common.MigrateFileBans(dbu.db, ctx, tx, &sqlConfig); err != nil { + if err = common.MigrateFileBans(ctx, dbu.db, tx, &sqlConfig); err != nil { return false, err } - if err = common.MigrateFilenameBans(dbu.db, ctx, tx, &sqlConfig); err != nil { + if err = common.MigrateFilenameBans(ctx, dbu.db, tx, &sqlConfig); err != nil { return false, err } - if err = common.MigrateUsernameBans(dbu.db, ctx, tx, &sqlConfig); err != nil { + if err = common.MigrateUsernameBans(ctx, dbu.db, tx, &sqlConfig); err != nil { return false, err } - if err = common.MigrateWordfilters(dbu.db, ctx, tx, &sqlConfig); err != nil { + if err = common.MigrateWordfilters(ctx, dbu.db, tx, &sqlConfig); err != nil { return false, err } } diff --git a/frontend/ts/dom/postdropdown.ts b/frontend/ts/dom/postdropdown.ts index 04173b8f..3da1c16d 100644 --- a/frontend/ts/dom/postdropdown.ts +++ b/frontend/ts/dom/postdropdown.ts @@ -177,6 +177,10 @@ function handleActions(action: string, postIDStr: string) { case "Filter similar posts": window.open(`${webroot}manage/filters?srcpost=${postID}`); break; + default: + // this shouldn't happen under normal circumstances + alertLightbox("Unrecognized post dropdown option"); + break; } } diff --git a/pkg/gcsql/filters.go b/pkg/gcsql/filters.go index a020c0c3..f38dd21b 100644 --- a/pkg/gcsql/filters.go +++ b/pkg/gcsql/filters.go @@ -78,7 +78,7 @@ func GetAllFilters(activeFilter BooleanFilter) ([]Filter, error) { return filters, rows.Close() } -func getFiltersByBoardDir(dir string, includeAllBoards bool, activeFilter BooleanFilter, useWordFilters bool) ([]Filter, error) { +func getFiltersByBoardDirHelper(dir string, includeAllBoards bool, activeFilter BooleanFilter, useWordFilters bool) ([]Filter, error) { query := `SELECT DBPREFIXfilters.id, staff_id, staff_note, issued_at, match_action, match_detail, is_active FROM DBPREFIXfilters LEFT JOIN DBPREFIXfilter_boards ON filter_id = DBPREFIXfilters.id @@ -131,7 +131,7 @@ func getFiltersByBoardDir(dir string, includeAllBoards bool, activeFilter Boolea // not associated with a specific board. It can optionally return only the active or only the inactive filters // (or return all) func GetFiltersByBoardDir(dir string, includeAllBoards bool, show BooleanFilter) ([]Filter, error) { - return getFiltersByBoardDir(dir, includeAllBoards, show, false) + return getFiltersByBoardDirHelper(dir, includeAllBoards, show, false) } // GetFiltersByBoardID returns an array of post filters associated to the given board ID, including @@ -510,20 +510,15 @@ func (f *Filter) checkIfMatch(post *Post, upload *Upload, request *http.Request, return false, err } } - if match { - - } - return match, nil } -func (fc *FilterCondition) testCondition(post *Post, upload *Upload, request *http.Request, errEv *zerolog.Event) (bool, error) { +func (fc FilterCondition) testCondition(post *Post, upload *Upload, request *http.Request, errEv *zerolog.Event) (bool, error) { handler, ok := filterFieldHandlers[fc.Field] if !ok { return false, ErrInvalidConditionField } - match, err := handler.CheckMatch(request, post, upload, fc) - + match, err := handler.CheckMatch(request, post, upload, &fc) if err != nil { errEv.Err(err).Caller(). Str("field", fc.Field). diff --git a/pkg/gcsql/initsql/init.go b/pkg/gcsql/initsql/init.go index 150fadee..1eb3e1f0 100644 --- a/pkg/gcsql/initsql/init.go +++ b/pkg/gcsql/initsql/init.go @@ -118,7 +118,7 @@ func sectionBoardsTmplFunc(sectionID int) []gcsql.Board { } func init() { - events.RegisterEvent([]string{"reset-boards-sections"}, func(trigger string, i ...interface{}) error { + events.RegisterEvent([]string{"reset-boards-sections"}, func(_ string, _ ...interface{}) error { return gcsql.ResetBoardSectionArrays() }) gctemplates.AddTemplateFuncs(template.FuncMap{ @@ -134,7 +134,7 @@ func init() { "getBoardDefaultStyle": getBoardDefaultStyleTmplFunc, "sectionBoards": sectionBoardsTmplFunc, }) - gcsql.RegisterStringConditionHandler("ahash", func(r *http.Request, p *gcsql.Post, u *gcsql.Upload, fc *gcsql.FilterCondition) (bool, error) { + gcsql.RegisterStringConditionHandler("ahash", func(r *http.Request, _ *gcsql.Post, u *gcsql.Upload, fc *gcsql.FilterCondition) (bool, error) { if u == nil { return false, nil } diff --git a/pkg/gcsql/tables.go b/pkg/gcsql/tables.go index 79c97fad..9ee48865 100644 --- a/pkg/gcsql/tables.go +++ b/pkg/gcsql/tables.go @@ -77,7 +77,7 @@ type FilterCondition struct { Field string // sql: field } -func (fc *FilterCondition) insert(ctx context.Context, tx *sql.Tx) error { +func (fc FilterCondition) insert(ctx context.Context, tx *sql.Tx) error { _, err := ExecContextSQL(ctx, tx, `INSERT INTO DBPREFIXfilter_conditions(filter_id, match_mode, search, field) VALUES(?,?,?,?)`, fc.FilterID, fc.MatchMode, fc.Search, fc.Field, diff --git a/pkg/gcsql/wordfilters.go b/pkg/gcsql/wordfilters.go index 207a7021..9784d54a 100644 --- a/pkg/gcsql/wordfilters.go +++ b/pkg/gcsql/wordfilters.go @@ -36,6 +36,10 @@ func CreateWordFilter(from string, to string, isRegex bool, boards []string, sta defer cancel() tx, err := BeginContextTx(ctx) + if err != nil { + return nil, err + } + defer tx.Rollback() if _, err = ExecContextSQL(ctx, tx, query, staffID, staffNote, time.Now(), to); err != nil { return nil, err @@ -86,7 +90,7 @@ func CreateWordFilter(from string, to string, isRegex bool, boards []string, sta // GetWordfilters gets a list of wordfilters from the database and returns an array of them and any errors // encountered func GetWordfilters(active BooleanFilter) ([]Wordfilter, error) { - filters, err := getFiltersByBoardDir("", true, active, true) + filters, err := getFiltersByBoardDirHelper("", true, active, true) if err != nil { return nil, err } @@ -118,7 +122,7 @@ func GetWordfilterByID(id int) (*Wordfilter, error) { // GetBoardWordfilters gets an array of wordfilters associated with the given board directory func GetBoardWordfilters(board string) ([]Wordfilter, error) { - filters, err := getFiltersByBoardDir(board, true, OnlyTrue, true) + filters, err := getFiltersByBoardDirHelper(board, true, OnlyTrue, true) if err != nil { return nil, err } @@ -147,6 +151,8 @@ func (wf *Wordfilter) OnBoard(dir string, specific bool) (bool, error) { return false, nil } +// StaffName returns the username of the staff member who submitted the filter, or "?" if any errors occured or the +// staff member dose not exist func (wf *Wordfilter) StaffName() string { if wf.StaffID == nil { return "" @@ -207,8 +213,8 @@ func (wf *Wordfilter) VerifySingleCondition(conditions ...[]FilterCondition) (er return nil } -// Deprecated, use the first element in wf.Conditions() instead. This is kept here for templates. // IsRegex returns true if the wordfilter should use a regular expression. +// Deprecated: use the first element in wf.Conditions() instead. This is kept here for templates. func (wf *Wordfilter) IsRegex() bool { conditions, err := wf.Conditions() if err != nil || len(conditions) != 1 { @@ -217,8 +223,8 @@ func (wf *Wordfilter) IsRegex() bool { return conditions[0].MatchMode == RegexMatch } -// Deprecated, use the first element in wf.BoardDirs() instead. This is kept here for templates. // BoardsString returns the board directories associated with this wordfilter, joined into a string +// Deprecated: use the first element in wf.BoardDirs() instead. This is kept here for templates. func (wf *Wordfilter) BoardsString() string { dirs, err := wf.BoardDirs() if err != nil { @@ -230,8 +236,8 @@ func (wf *Wordfilter) BoardsString() string { return strings.Join(dirs, ",") } -// Deprecated, use the first element of wf.BoardDirs() instead. This is kept here for templates // Search returns the search field of the wordfilter condition +// Deprecated: use the first element of wf.BoardDirs() instead. This is kept here for templates func (wf *Wordfilter) Search() string { conditions, err := wf.Conditions() if err != nil { diff --git a/pkg/manage/actionsModPerm.go b/pkg/manage/actionsModPerm.go index ea170c2e..fe0f0763 100644 --- a/pkg/manage/actionsModPerm.go +++ b/pkg/manage/actionsModPerm.go @@ -176,8 +176,8 @@ func appealsCallback(_ http.ResponseWriter, request *http.Request, staff *gcsql. return manageAppealsBuffer.String(), err } -func filterHitsCallback(writer http.ResponseWriter, request *http.Request, staff *gcsql.Staff, wantsJSON bool, _, errEv *zerolog.Event) (output any, err error) { - params, _ := request.Context().Value("actionParams").(bunrouter.Params) +func filterHitsCallback(_ http.ResponseWriter, request *http.Request, _ *gcsql.Staff, _ bool, _, errEv *zerolog.Event) (output any, err error) { + params, _ := request.Context().Value(requestContextKey{}).(bunrouter.Params) filterIDStr := params.ByName("filterID") filterID, err := strconv.Atoi(filterIDStr) if err != nil { @@ -229,7 +229,7 @@ type filterField struct { hasSearchbox bool } -func filtersCallback(writer http.ResponseWriter, request *http.Request, staff *gcsql.Staff, wantsJSON bool, infoEv, errEv *zerolog.Event) (output any, err error) { +func filtersCallback(_ http.ResponseWriter, request *http.Request, staff *gcsql.Staff, _ bool, infoEv, errEv *zerolog.Event) (output any, err error) { if err = submitFilterFormData(request, staff, infoEv, errEv); err != nil { // submitFilterFormData logs any errors return nil, err diff --git a/pkg/manage/filters.go b/pkg/manage/filters.go index 3c0db82e..4f19a87a 100644 --- a/pkg/manage/filters.go +++ b/pkg/manage/filters.go @@ -205,6 +205,10 @@ func buildFilterFormData(request *http.Request, errEv *zerolog.Event) (data map[ return nil, err } post, err := gcsql.GetPostFromID(postID, true) + if err != nil { + errEv.Err(err).Caller().Int("postID", postID).Msg("Unable to get post from ID") + return nil, errors.New("unable to get post data from ID") + } conditions = []gcsql.FilterCondition{} if post.Name != "" { conditions = append(conditions, gcsql.FilterCondition{Field: "name", MatchMode: gcsql.SubstrMatch, Search: post.Name}) diff --git a/pkg/manage/handler.go b/pkg/manage/handler.go index 42017a61..f224bcfb 100644 --- a/pkg/manage/handler.go +++ b/pkg/manage/handler.go @@ -26,6 +26,8 @@ func (esa *ErrStaffAction) Error() string { return esa.Message } +type requestContextKey struct{} + func serveError(writer http.ResponseWriter, field string, action string, message string, isJSON bool) { server.ServeError(writer, message, isJSON, map[string]any{ "error": field, @@ -103,7 +105,7 @@ func setupManageFunction(action *Action) bunrouter.HandlerFunc { err = fmt.Errorf("action %q exists but has no defined callback", action.ID) } else { output, err = actionCB(writer, - request.WithContext(context.WithValue(request.Context(), "actionParams", req.Params())), + request.WithContext(context.WithValue(request.Context(), requestContextKey{}, req.Params())), staff, wantsJSON, infoEv, errEv) } } diff --git a/pkg/posting/formatting.go b/pkg/posting/formatting.go index 6b374cf8..52c66eab 100644 --- a/pkg/posting/formatting.go +++ b/pkg/posting/formatting.go @@ -110,7 +110,6 @@ func FormatMessage(message string, boardDir string) (template.HTML, error) { if linkParent == 0 { // board or op not found lineWords[w] = `` + word + `` - continue } else { lineWords[w] = fmt.Sprintf(`%s`, WebRoot, boardDir, linkParent, word[8:], word) }