diff options
author | 2024-06-06 09:38:02 -0700 | |
---|---|---|
committer | 2024-06-06 16:38:02 +0000 | |
commit | 5e2d4fdb19eb4fcd4c0bbfb3e2f29067a58c88c8 (patch) | |
tree | 607006af6b4bb63bb625b39f3ca0fe869eb6ba95 /internal/api/client/accounts | |
parent | [bugfix] update media if more than just url changes (#2970) (diff) | |
download | gotosocial-5e2d4fdb19eb4fcd4c0bbfb3e2f29067a58c88c8.tar.xz |
[feature] User muting (#2960)
* User muting
* Address review feedback
* Rename uniqueness constraint on user_mutes to match convention
* Remove unused account_id from where clause
* Add UserMute to NewTestDB
* Update test/envparsing.sh with new and fixed cache stuff
* Address tobi's review comments
* Make compiledUserMuteListEntry.expired consistent with UserMute.Expired
* Make sure mute_expires_at is serialized as an explicit null for indefinite mutes
---------
Co-authored-by: tobi <tobi.smethurst@protonmail.com>
Diffstat (limited to 'internal/api/client/accounts')
-rw-r--r-- | internal/api/client/accounts/accounts.go | 6 | ||||
-rw-r--r-- | internal/api/client/accounts/mute.go | 170 | ||||
-rw-r--r-- | internal/api/client/accounts/mute_test.go | 173 | ||||
-rw-r--r-- | internal/api/client/accounts/unmute.go | 98 | ||||
-rw-r--r-- | internal/api/client/accounts/unmute_test.go | 136 |
5 files changed, 583 insertions, 0 deletions
diff --git a/internal/api/client/accounts/accounts.go b/internal/api/client/accounts/accounts.go index 61fdc41ad..0dbc5ea53 100644 --- a/internal/api/client/accounts/accounts.go +++ b/internal/api/client/accounts/accounts.go @@ -45,12 +45,14 @@ const ( FollowPath = BasePathWithID + "/follow" ListsPath = BasePathWithID + "/lists" LookupPath = BasePath + "/lookup" + MutePath = BasePathWithID + "/mute" NotePath = BasePathWithID + "/note" RelationshipsPath = BasePath + "/relationships" SearchPath = BasePath + "/search" StatusesPath = BasePathWithID + "/statuses" UnblockPath = BasePathWithID + "/unblock" UnfollowPath = BasePathWithID + "/unfollow" + UnmutePath = BasePathWithID + "/unmute" UpdatePath = BasePath + "/update_credentials" VerifyPath = BasePath + "/verify_credentials" MovePath = BasePath + "/move" @@ -117,6 +119,10 @@ func (m *Module) Route(attachHandler func(method string, path string, f ...gin.H // account note attachHandler(http.MethodPost, NotePath, m.AccountNotePOSTHandler) + // mute or unmute account + attachHandler(http.MethodPost, MutePath, m.AccountMutePOSTHandler) + attachHandler(http.MethodPost, UnmutePath, m.AccountUnmutePOSTHandler) + // search for accounts attachHandler(http.MethodGet, SearchPath, m.AccountSearchGETHandler) attachHandler(http.MethodGet, LookupPath, m.AccountLookupGETHandler) diff --git a/internal/api/client/accounts/mute.go b/internal/api/client/accounts/mute.go new file mode 100644 index 000000000..37cd3bbff --- /dev/null +++ b/internal/api/client/accounts/mute.go @@ -0,0 +1,170 @@ +// 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 <http://www.gnu.org/licenses/>. + +package accounts + +import ( + "errors" + "fmt" + "net/http" + "strconv" + + "github.com/gin-gonic/gin" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/internal/util" +) + +// AccountMutePOSTHandler swagger:operation POST /api/v1/accounts/{id}/mute accountMute +// +// Mute account by ID. +// +// If account was already muted, succeeds anyway. This can be used to update the details of a mute. +// +// --- +// tags: +// - accounts +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: The ID of the account to block. +// in: path +// required: true +// - +// name: notifications +// type: boolean +// description: Mute notifications as well as posts. +// in: formData +// required: false +// default: false +// - +// name: duration +// type: number +// description: How long the mute should last, in seconds. If 0 or not provided, mute lasts indefinitely. +// in: formData +// required: false +// default: 0 +// +// security: +// - OAuth2 Bearer: +// - write:mutes +// +// responses: +// '200': +// description: Your relationship to the account. +// schema: +// "$ref": "#/definitions/accountRelationship" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '403': +// description: forbidden to moved accounts +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) AccountMutePOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGetV1) + return + } + + if authed.Account.IsMoving() { + apiutil.ForbiddenAfterMove(c) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGetV1) + return + } + + targetAcctID := c.Param(IDKey) + if targetAcctID == "" { + err := errors.New("no account id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGetV1) + return + } + + form := &apimodel.UserMuteCreateUpdateRequest{} + if err := c.ShouldBind(form); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGetV1) + return + } + + if err := normalizeCreateUpdateMute(form); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnprocessableEntity(err, err.Error()), m.processor.InstanceGetV1) + return + } + + relationship, errWithCode := m.processor.Account().MuteCreate( + c.Request.Context(), + authed.Account, + targetAcctID, + form, + ) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGetV1) + return + } + + apiutil.JSON(c, http.StatusOK, relationship) +} + +func normalizeCreateUpdateMute(form *apimodel.UserMuteCreateUpdateRequest) error { + // Apply defaults for missing fields. + form.Notifications = util.Ptr(util.PtrValueOr(form.Notifications, false)) + + // Normalize mute duration if necessary. + // If we parsed this as JSON, expires_in + // may be either a float64 or a string. + if ei := form.DurationI; ei != nil { + switch e := ei.(type) { + case float64: + form.Duration = util.Ptr(int(e)) + + case string: + duration, err := strconv.Atoi(e) + if err != nil { + return fmt.Errorf("could not parse duration value %s as integer: %w", e, err) + } + + form.Duration = &duration + + default: + return fmt.Errorf("could not parse expires_in type %T as integer", ei) + } + } + + // Interpret zero as indefinite duration. + if form.Duration != nil && *form.Duration == 0 { + form.Duration = nil + } + + return nil +} diff --git a/internal/api/client/accounts/mute_test.go b/internal/api/client/accounts/mute_test.go new file mode 100644 index 000000000..d181a2e3b --- /dev/null +++ b/internal/api/client/accounts/mute_test.go @@ -0,0 +1,173 @@ +// 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 <http://www.gnu.org/licenses/>. + +package accounts_test + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/accounts" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + "github.com/superseriousbusiness/gotosocial/internal/config" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +type MuteTestSuite struct { + AccountStandardTestSuite +} + +func (suite *MuteTestSuite) postMute( + accountID string, + notifications *bool, + duration *int, + requestJson *string, + expectedHTTPStatus int, + expectedBody string, +) (*apimodel.Relationship, error) { + // instantiate recorder + test context + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauth.DBTokenToToken(suite.testTokens["local_account_1"])) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + + // create the request + ctx.Request = httptest.NewRequest(http.MethodPut, config.GetProtocol()+"://"+config.GetHost()+"/api/"+accounts.BasePath+"/"+accountID+"/mute", nil) + ctx.Request.Header.Set("accept", "application/json") + if requestJson != nil { + ctx.Request.Header.Set("content-type", "application/json") + ctx.Request.Body = io.NopCloser(strings.NewReader(*requestJson)) + } else { + ctx.Request.Form = make(url.Values) + if notifications != nil { + ctx.Request.Form["notifications"] = []string{strconv.FormatBool(*notifications)} + } + if duration != nil { + ctx.Request.Form["duration"] = []string{strconv.Itoa(*duration)} + } + } + + ctx.AddParam("id", accountID) + + // trigger the handler + suite.accountsModule.AccountMutePOSTHandler(ctx) + + // read the response + result := recorder.Result() + defer result.Body.Close() + + b, err := io.ReadAll(result.Body) + if err != nil { + return nil, err + } + + errs := gtserror.NewMultiError(2) + + // check code + body + if resultCode := recorder.Code; expectedHTTPStatus != resultCode { + errs.Appendf("expected %d got %d", expectedHTTPStatus, resultCode) + if expectedBody == "" { + return nil, errs.Combine() + } + } + + // if we got an expected body, return early + if expectedBody != "" { + if string(b) != expectedBody { + errs.Appendf("expected %s got %s", expectedBody, string(b)) + } + return nil, errs.Combine() + } + + resp := &apimodel.Relationship{} + if err := json.Unmarshal(b, resp); err != nil { + return nil, err + } + + return resp, nil +} + +func (suite *MuteTestSuite) TestPostMuteFull() { + accountID := suite.testAccounts["remote_account_1"].ID + notifications := true + duration := 86400 + relationship, err := suite.postMute(accountID, ¬ifications, &duration, nil, http.StatusOK, "") + if err != nil { + suite.FailNow(err.Error()) + } + + suite.True(relationship.Muting) + suite.Equal(notifications, relationship.MutingNotifications) +} + +func (suite *MuteTestSuite) TestPostMuteFullJSON() { + accountID := suite.testAccounts["remote_account_2"].ID + // Use a numeric literal with a fractional part to test the JSON-specific handling for non-integer "duration". + requestJson := `{ + "notifications": true, + "duration": 86400.1 + }` + relationship, err := suite.postMute(accountID, nil, nil, &requestJson, http.StatusOK, "") + if err != nil { + suite.FailNow(err.Error()) + } + + suite.True(relationship.Muting) + suite.True(relationship.MutingNotifications) +} + +func (suite *MuteTestSuite) TestPostMuteMinimal() { + accountID := suite.testAccounts["remote_account_3"].ID + relationship, err := suite.postMute(accountID, nil, nil, nil, http.StatusOK, "") + if err != nil { + suite.FailNow(err.Error()) + } + + suite.True(relationship.Muting) + suite.False(relationship.MutingNotifications) +} + +func (suite *MuteTestSuite) TestPostMuteSelf() { + accountID := suite.testAccounts["local_account_1"].ID + _, err := suite.postMute(accountID, nil, nil, nil, http.StatusNotAcceptable, `{"error":"Not Acceptable: getMuteTarget: account 01F8MH1H7YV1Z7D2C8K2730QBF cannot mute or unmute itself"}`) + if err != nil { + suite.FailNow(err.Error()) + } +} + +func (suite *MuteTestSuite) TestPostMuteNonexistentAccount() { + accountID := "not_even_a_real_ULID" + _, err := suite.postMute(accountID, nil, nil, nil, http.StatusNotFound, `{"error":"Not Found: getMuteTarget: target account not_even_a_real_ULID not found in the db"}`) + if err != nil { + suite.FailNow(err.Error()) + } +} + +func TestMuteTestSuite(t *testing.T) { + suite.Run(t, new(MuteTestSuite)) +} diff --git a/internal/api/client/accounts/unmute.go b/internal/api/client/accounts/unmute.go new file mode 100644 index 000000000..665c3908e --- /dev/null +++ b/internal/api/client/accounts/unmute.go @@ -0,0 +1,98 @@ +// 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 <http://www.gnu.org/licenses/>. + +package accounts + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// AccountUnmutePOSTHandler swagger:operation POST /api/v1/accounts/{id}/unmute accountUnmute +// +// Unmute account by ID. +// +// If account was already unmuted (or has never been muted), succeeds anyway. +// +// --- +// tags: +// - accounts +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: The ID of the account to unmute. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - write:mutes +// +// responses: +// '200': +// name: account relationship +// description: Your relationship to this account. +// schema: +// "$ref": "#/definitions/accountRelationship" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) AccountUnmutePOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGetV1) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGetV1) + return + } + + targetAcctID := c.Param(IDKey) + if targetAcctID == "" { + err := errors.New("no account id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGetV1) + return + } + + relationship, errWithCode := m.processor.Account().MuteRemove(c.Request.Context(), authed.Account, targetAcctID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGetV1) + return + } + + apiutil.JSON(c, http.StatusOK, relationship) + +} diff --git a/internal/api/client/accounts/unmute_test.go b/internal/api/client/accounts/unmute_test.go new file mode 100644 index 000000000..5a00c3610 --- /dev/null +++ b/internal/api/client/accounts/unmute_test.go @@ -0,0 +1,136 @@ +// 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 <http://www.gnu.org/licenses/>. + +package accounts_test + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + + "github.com/superseriousbusiness/gotosocial/internal/api/client/accounts" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + "github.com/superseriousbusiness/gotosocial/internal/config" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +func (suite *MuteTestSuite) postUnmute( + accountID string, + expectedHTTPStatus int, + expectedBody string, +) (*apimodel.Relationship, error) { + // instantiate recorder + test context + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauth.DBTokenToToken(suite.testTokens["local_account_1"])) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + + // create the request + ctx.Request = httptest.NewRequest(http.MethodPut, config.GetProtocol()+"://"+config.GetHost()+"/api/"+accounts.BasePath+"/"+accountID+"/unmute", nil) + ctx.Request.Header.Set("accept", "application/json") + + ctx.AddParam("id", accountID) + + // trigger the handler + suite.accountsModule.AccountUnmutePOSTHandler(ctx) + + // read the response + result := recorder.Result() + defer result.Body.Close() + + b, err := io.ReadAll(result.Body) + if err != nil { + return nil, err + } + + errs := gtserror.NewMultiError(2) + + // check code + body + if resultCode := recorder.Code; expectedHTTPStatus != resultCode { + errs.Appendf("expected %d got %d", expectedHTTPStatus, resultCode) + if expectedBody == "" { + return nil, errs.Combine() + } + } + + // if we got an expected body, return early + if expectedBody != "" { + if string(b) != expectedBody { + errs.Appendf("expected %s got %s", expectedBody, string(b)) + } + return nil, errs.Combine() + } + + resp := &apimodel.Relationship{} + if err := json.Unmarshal(b, resp); err != nil { + return nil, err + } + + return resp, nil +} + +func (suite *MuteTestSuite) TestPostUnmuteWithoutPreviousMute() { + accountID := suite.testAccounts["remote_account_4"].ID + relationship, err := suite.postUnmute(accountID, http.StatusOK, "") + if err != nil { + suite.FailNow(err.Error()) + } + + suite.False(relationship.Muting) + suite.False(relationship.MutingNotifications) +} + +func (suite *MuteTestSuite) TestPostWithPreviousMute() { + accountID := suite.testAccounts["local_account_2"].ID + + relationship, err := suite.postMute(accountID, nil, nil, nil, http.StatusOK, "") + if err != nil { + suite.FailNow(err.Error()) + } + + suite.True(relationship.Muting) + suite.False(relationship.MutingNotifications) + + relationship, err = suite.postUnmute(accountID, http.StatusOK, "") + if err != nil { + suite.FailNow(err.Error()) + } + + suite.False(relationship.Muting) + suite.False(relationship.MutingNotifications) +} + +func (suite *MuteTestSuite) TestPostUnmuteSelf() { + accountID := suite.testAccounts["local_account_1"].ID + _, err := suite.postUnmute(accountID, http.StatusNotAcceptable, `{"error":"Not Acceptable: getMuteTarget: account 01F8MH1H7YV1Z7D2C8K2730QBF cannot mute or unmute itself"}`) + if err != nil { + suite.FailNow(err.Error()) + } +} + +func (suite *MuteTestSuite) TestPostUnmuteNonexistentAccount() { + accountID := "not_even_a_real_ULID" + _, err := suite.postUnmute(accountID, http.StatusNotFound, `{"error":"Not Found: getMuteTarget: target account not_even_a_real_ULID not found in the db"}`) + if err != nil { + suite.FailNow(err.Error()) + } +} |