diff --git a/internal/api/client/filters/v1/validate.go b/internal/api/client/filters/v1/validate.go index 9e876c8cf..9e31abb89 100644 --- a/internal/api/client/filters/v1/validate.go +++ b/internal/api/client/filters/v1/validate.go @@ -46,12 +46,11 @@ func validateNormalizeCreateUpdateFilter(form *apimodel.FilterCreateUpdateReques return errors.New("irreversible aka server-side drop filters are not supported yet") } - // Normalize filter expiry if necessary. - if form.ExpiresInI != nil { - // If we parsed this as JSON, expires_in - // may be either a float64 or a string. + // If `expires_in` was provided + // as JSON, then normalize it. + if form.ExpiresInI.IsSpecified() { var err error - form.ExpiresIn, err = apiutil.ParseDuration( + form.ExpiresIn, err = apiutil.ParseNullableDuration( form.ExpiresInI, "expires_in", ) @@ -60,10 +59,5 @@ func validateNormalizeCreateUpdateFilter(form *apimodel.FilterCreateUpdateReques } } - // Interpret zero as indefinite duration. - if form.ExpiresIn != nil && *form.ExpiresIn == 0 { - form.ExpiresIn = nil - } - return nil } diff --git a/internal/api/client/filters/v2/filterpost.go b/internal/api/client/filters/v2/filterpost.go index 632c4402f..ad6e83060 100644 --- a/internal/api/client/filters/v2/filterpost.go +++ b/internal/api/client/filters/v2/filterpost.go @@ -225,12 +225,11 @@ func validateNormalizeCreateFilter(form *apimodel.FilterCreateRequestV2) error { // Apply defaults for missing fields. form.FilterAction = util.Ptr(action) - // Normalize filter expiry if necessary. - if form.ExpiresInI != nil { - // If we parsed this as JSON, expires_in - // may be either a float64 or a string. + // If `expires_in` was provided + // as JSON, then normalize it. + if form.ExpiresInI.IsSpecified() { var err error - form.ExpiresIn, err = apiutil.ParseDuration( + form.ExpiresIn, err = apiutil.ParseNullableDuration( form.ExpiresInI, "expires_in", ) @@ -239,11 +238,6 @@ func validateNormalizeCreateFilter(form *apimodel.FilterCreateRequestV2) error { } } - // Interpret zero as indefinite duration. - if form.ExpiresIn != nil && *form.ExpiresIn == 0 { - form.ExpiresIn = nil - } - // Normalize and validate new keywords and statuses. for i, formKeyword := range form.Keywords { if err := validate.FilterKeyword(formKeyword.Keyword); err != nil { diff --git a/internal/api/client/filters/v2/filterput.go b/internal/api/client/filters/v2/filterput.go index 2b440d5ca..9c1b56dd6 100644 --- a/internal/api/client/filters/v2/filterput.go +++ b/internal/api/client/filters/v2/filterput.go @@ -18,10 +18,7 @@ package v2 import ( - "bytes" - "encoding/json" "errors" - "io" "net/http" "github.com/gin-gonic/gin" @@ -183,43 +180,12 @@ func (m *Module) FilterPUTHandler(c *gin.Context) { return } - // If the request is JSON: - // Explicitly check whether `expires_in` is a null literal (vs. not being set at all). - hasNullExpiresIn := false - if c.ContentType() == gin.MIMEJSON { - // To do this, we need to read the request body twice, once here and once below for the form, so we buffer it. - // If a filter update request is bigger than a megabyte, somebody's messing with us. - bodyBytes, err := io.ReadAll(io.LimitReader(c.Request.Body, 1024*1024)) - if err != nil { - apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGetV1) - return - } - c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes)) - - // Partially parse the body as a JSON object. - requestJSONObject := map[string]json.RawMessage{} - if err := json.Unmarshal(bodyBytes, &requestJSONObject); err != nil { - apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGetV1) - return - } - - // Try to parse the `expires_in` field as a literal null. - if raw, found := requestJSONObject["expires_in"]; found { - hasNullExpiresIn = string(raw) == "null" - } - } - form := &apimodel.FilterUpdateRequestV2{} if err := c.ShouldBind(form); err != nil { apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGetV1) return } - // Interpret a literal null `expires_in` as unsetting the expiration date. - if hasNullExpiresIn { - form.ExpiresIn = util.Ptr(0) - } - if err := validateNormalizeUpdateFilter(form); err != nil { apiutil.ErrorHandler(c, gtserror.NewErrorUnprocessableEntity(err, err.Error()), m.processor.InstanceGetV1) return @@ -303,12 +269,11 @@ func validateNormalizeUpdateFilter(form *apimodel.FilterUpdateRequestV2) error { } } - // Normalize filter expiry if necessary. - if form.ExpiresInI != nil { - // If we parsed this as JSON, expires_in - // may be either a float64 or a string. + // If `expires_in` was provided + // as JSON, then normalize it. + if form.ExpiresInI.IsSpecified() { var err error - form.ExpiresIn, err = apiutil.ParseDuration( + form.ExpiresIn, err = apiutil.ParseNullableDuration( form.ExpiresInI, "expires_in", ) diff --git a/internal/api/model/filterv1.go b/internal/api/model/filterv1.go index 1c3b5fb8e..0b092627e 100644 --- a/internal/api/model/filterv1.go +++ b/internal/api/model/filterv1.go @@ -95,5 +95,5 @@ type FilterCreateUpdateRequestV1 struct { // Number of seconds from now that the filter should expire. If omitted, filter never expires. // // Example: 86400 - ExpiresInI interface{} `json:"expires_in"` + ExpiresInI Nullable[any] `json:"expires_in"` } diff --git a/internal/api/model/filterv2.go b/internal/api/model/filterv2.go index 242c569dc..26b1b22b3 100644 --- a/internal/api/model/filterv2.go +++ b/internal/api/model/filterv2.go @@ -134,7 +134,7 @@ type FilterCreateRequestV2 struct { // Number of seconds from now that the filter should expire. If omitted, filter never expires. // // Example: 86400 - ExpiresInI interface{} `json:"expires_in"` + ExpiresInI Nullable[any] `json:"expires_in"` // Keywords to be added to the newly created filter. Keywords []FilterKeywordCreateUpdateRequest `form:"-" json:"keywords_attributes" xml:"keywords_attributes"` @@ -199,7 +199,7 @@ type FilterUpdateRequestV2 struct { // Number of seconds from now that the filter should expire. If omitted, filter never expires. // // Example: 86400 - ExpiresInI interface{} `json:"expires_in"` + ExpiresInI Nullable[any] `json:"expires_in"` // Keywords to be added to the filter, modified, or removed. Keywords []FilterKeywordCreateUpdateDeleteRequest `form:"-" json:"keywords_attributes" xml:"keywords_attributes"` diff --git a/internal/api/model/nullable.go b/internal/api/model/nullable.go new file mode 100644 index 000000000..9bd744978 --- /dev/null +++ b/internal/api/model/nullable.go @@ -0,0 +1,107 @@ +// GoToSocial +// Copyright (C) GoToSocial Authors admin@gotosocial.org +// SPDX-License-Identifier: AGPL-3.0-or-later +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +package model + +import ( + "bytes" + "encoding/json" + "errors" +) + +// Nullable is a generic type, which implements a field that can be one of three states: +// +// - field is not set in the request +// - field is explicitly set to `null` in the request +// - field is explicitly set to a valid value in the request +// +// Nullable is intended to be used with JSON unmarshalling. +// +// Adapted from https://github.com/oapi-codegen/nullable/blob/main/nullable.go +type Nullable[T any] struct { + state nullableState + value T +} + +type nullableState uint8 + +const ( + nullableStateUnspecified nullableState = 0 + nullableStateNull = 1 + nullableStateSet = 2 +) + +// Get retrieves the underlying value, if present, +// and returns an error if the value was not present. +func (t Nullable[T]) Get() (T, error) { + var empty T + if t.IsNull() { + return empty, errors.New("value is null") + } + + if !t.IsSpecified() { + return empty, errors.New("value is not specified") + } + + return t.value, nil +} + +// IsNull indicates whether the field +// was sent, and had a value of `null` +func (t Nullable[T]) IsNull() bool { + return t.state == nullableStateNull +} + +// IsSpecified indicates whether the field +// was sent either as a value or as `null`. +func (t Nullable[T]) IsSpecified() bool { + return t.state != nullableStateUnspecified +} + +// If field is unspecified, +// UnmarshalJSON won't be called. +func (t *Nullable[T]) UnmarshalJSON(data []byte) error { + // If field is specified as `null`. + if bytes.Equal(data, []byte("null")) { + t.setNull() + return nil + } + + // Otherwise, we have an + // actual value, so parse it. + var v T + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + t.set(v) + return nil +} + +// setNull indicates that the field +// was sent, and had a value of `null` +func (t *Nullable[T]) setNull() { + *t = Nullable[T]{state: nullableStateNull} +} + +// set the underlying value to given value. +func (t *Nullable[T]) set(value T) { + *t = Nullable[T]{ + state: nullableStateSet, + value: value, + } +} diff --git a/internal/api/util/parseform.go b/internal/api/util/parseform.go index 19e24189f..3eab065f2 100644 --- a/internal/api/util/parseform.go +++ b/internal/api/util/parseform.go @@ -20,12 +20,13 @@ package util import ( "fmt" "strconv" + + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + "github.com/superseriousbusiness/gotosocial/internal/util" ) -// ParseDuration parses the given raw interface belonging to +// ParseDuration parses the given raw interface belonging // the given fieldName as an integer duration. -// -// Will return nil, nil if rawI is the zero value of its type. func ParseDuration(rawI any, fieldName string) (*int, error) { var ( asInteger int @@ -60,11 +61,28 @@ func ParseDuration(rawI any, fieldName string) (*int, error) { return nil, err } - // Someone submitted 0, - // don't point to this. - if asInteger == 0 { - return nil, nil - } - return &asInteger, nil } + +// ParseNullableDuration is like ParseDuration, but +// for JSON values that may have been sent as `null`. +// +// IsSpecified should be checked and "true" on the +// given nullable before calling this function. +func ParseNullableDuration( + nullable apimodel.Nullable[any], + fieldName string, +) (*int, error) { + if nullable.IsNull() { + // Was specified as `null`, + // return pointer to zero value. + return util.Ptr(0), nil + } + + rawI, err := nullable.Get() + if err != nil { + return nil, err + } + + return ParseDuration(rawI, fieldName) +} diff --git a/internal/processing/filters/v1/create.go b/internal/processing/filters/v1/create.go index 18367dfce..86019d2a6 100644 --- a/internal/processing/filters/v1/create.go +++ b/internal/processing/filters/v1/create.go @@ -43,7 +43,7 @@ func (p *Processor) Create(ctx context.Context, account *gtsmodel.Account, form if *form.Irreversible { filter.Action = gtsmodel.FilterActionHide } - if form.ExpiresIn != nil { + if form.ExpiresIn != nil && *form.ExpiresIn != 0 { filter.ExpiresAt = time.Now().Add(time.Second * time.Duration(*form.ExpiresIn)) } for _, context := range form.Context { diff --git a/internal/processing/filters/v1/update.go b/internal/processing/filters/v1/update.go index 81340b4be..15c5de365 100644 --- a/internal/processing/filters/v1/update.go +++ b/internal/processing/filters/v1/update.go @@ -67,7 +67,7 @@ func (p *Processor) Update( action = gtsmodel.FilterActionHide } expiresAt := time.Time{} - if form.ExpiresIn != nil { + if form.ExpiresIn != nil && *form.ExpiresIn != 0 { expiresAt = time.Now().Add(time.Second * time.Duration(*form.ExpiresIn)) } contextHome := false diff --git a/internal/processing/filters/v2/create.go b/internal/processing/filters/v2/create.go index 7095a643c..60dd46f43 100644 --- a/internal/processing/filters/v2/create.go +++ b/internal/processing/filters/v2/create.go @@ -41,7 +41,7 @@ func (p *Processor) Create(ctx context.Context, account *gtsmodel.Account, form Title: form.Title, Action: typeutils.APIFilterActionToFilterAction(*form.FilterAction), } - if form.ExpiresIn != nil { + if form.ExpiresIn != nil && *form.ExpiresIn != 0 { filter.ExpiresAt = time.Now().Add(time.Second * time.Duration(*form.ExpiresIn)) } for _, context := range form.Context {