From c27b4d7ed02cdabac00c3ddedb8201b74f745ec6 Mon Sep 17 00:00:00 2001 From: tobi <31960611+tsmethurst@users.noreply.github.com> Date: Sat, 25 Feb 2023 13:16:30 +0100 Subject: [PATCH] [feature] Client API endpoints + v. basic web view for pinned posts (#1547) * implement status pin client api + web handler * make test names + comments more descriptive * don't use separate table for status pins * remove unused add + remove checking * tidy up + add some more tests --- docs/api/swagger.yaml | 73 +++++++ .../api/activitypub/users/inboxpost_test.go | 2 +- internal/api/client/accounts/statuses_test.go | 179 +++++++++++++++- internal/api/client/statuses/status.go | 4 + internal/api/client/statuses/statuspin.go | 103 +++++++++ .../api/client/statuses/statuspin_test.go | 198 ++++++++++++++++++ internal/api/client/statuses/statusunpin.go | 98 +++++++++ internal/db/account.go | 18 +- internal/db/bundb/account.go | 33 ++- internal/db/bundb/account_test.go | 41 +++- .../20230221150957_status_pin_client_api.go | 65 ++++++ internal/db/bundb/timeline_test.go | 1 - internal/gtsmodel/status.go | 2 +- internal/processing/account/delete.go | 2 +- internal/processing/account/statuses.go | 31 ++- internal/processing/fedi/collections.go | 2 +- internal/processing/fromclientapi_test.go | 1 - internal/processing/fromfederator_test.go | 2 +- internal/processing/status/pin.go | 140 +++++++++++++ internal/typeutils/astointernal.go | 3 +- internal/typeutils/internal.go | 2 - internal/typeutils/internaltoas_test.go | 2 +- internal/typeutils/internaltofrontend.go | 2 +- internal/typeutils/util.go | 7 + internal/validate/status_test.go | 1 - internal/web/profile.go | 31 ++- testrig/testmodels.go | 20 +- web/source/css/profile.css | 2 +- web/template/profile.tmpl | 12 ++ 29 files changed, 1015 insertions(+), 62 deletions(-) create mode 100644 internal/api/client/statuses/statuspin.go create mode 100644 internal/api/client/statuses/statuspin_test.go create mode 100644 internal/api/client/statuses/statusunpin.go create mode 100644 internal/db/bundb/migrations/20230221150957_status_pin_client_api.go create mode 100644 internal/processing/status/pin.go diff --git a/docs/api/swagger.yaml b/docs/api/swagger.yaml index 293c7a443..c9ab00b86 100644 --- a/docs/api/swagger.yaml +++ b/docs/api/swagger.yaml @@ -5096,6 +5096,45 @@ paths: summary: View accounts that have faved/starred/liked the target status. tags: - statuses + /api/v1/statuses/{id}/pin: + post: + description: |- + You can only pin original posts (not reblogs) that you authored yourself. + + Supported privacy levels for pinned posts are public, unlisted, and private/followers-only, + but only public posts will appear on the web version of your profile. + operationId: statusPin + parameters: + - description: Target status ID. + in: path + name: id + required: true + type: string + produces: + - application/json + responses: + "200": + description: The status. + schema: + $ref: '#/definitions/status' + "400": + description: bad request + "401": + description: unauthorized + "403": + description: forbidden + "404": + description: not found + "406": + description: not acceptable + "500": + description: internal server error + security: + - OAuth2 Bearer: + - write:accounts + summary: Pin a status to the top of your profile, and add it to your Featured ActivityPub collection. + tags: + - statuses /api/v1/statuses/{id}/reblog: post: description: |- @@ -5233,6 +5272,40 @@ paths: summary: Unstar/unlike/unfavourite the given status. tags: - statuses + /api/v1/statuses/{id}/unpin: + post: + operationId: statusUnpin + parameters: + - description: Target status ID. + in: path + name: id + required: true + type: string + produces: + - application/json + responses: + "200": + description: The status. + schema: + $ref: '#/definitions/status' + "400": + description: bad request + "401": + description: unauthorized + "403": + description: forbidden + "404": + description: not found + "406": + description: not acceptable + "500": + description: internal server error + security: + - OAuth2 Bearer: + - write:accounts + summary: Unpin one of your pinned statuses. + tags: + - statuses /api/v1/statuses/{id}/unreblog: post: operationId: statusUnreblog diff --git a/internal/api/activitypub/users/inboxpost_test.go b/internal/api/activitypub/users/inboxpost_test.go index e43532e80..0ad63abf7 100644 --- a/internal/api/activitypub/users/inboxpost_test.go +++ b/internal/api/activitypub/users/inboxpost_test.go @@ -481,7 +481,7 @@ func (suite *InboxPostTestSuite) TestPostDelete() { } // no statuses from foss satan should be left in the database - dbStatuses, err := suite.db.GetAccountStatuses(ctx, deletedAccount.ID, 0, false, false, "", "", false, false, false) + dbStatuses, err := suite.db.GetAccountStatuses(ctx, deletedAccount.ID, 0, false, false, "", "", false, false) suite.ErrorIs(err, db.ErrNoEntries) suite.Empty(dbStatuses) diff --git a/internal/api/client/accounts/statuses_test.go b/internal/api/client/accounts/statuses_test.go index 5676d79e0..fdf2efac3 100644 --- a/internal/api/client/accounts/statuses_test.go +++ b/internal/api/client/accounts/statuses_test.go @@ -27,10 +27,10 @@ import ( "testing" "github.com/gin-gonic/gin" - "github.com/stretchr/testify/assert" "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/oauth" ) type AccountStatusesTestSuite struct { @@ -62,7 +62,7 @@ func (suite *AccountStatusesTestSuite) TestGetStatusesPublicOnly() { // check the response b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) + suite.NoError(err) // unmarshal the returned statuses apimodelStatuses := []*apimodel.Status{} @@ -74,7 +74,7 @@ func (suite *AccountStatusesTestSuite) TestGetStatusesPublicOnly() { suite.Equal(apimodel.VisibilityPublic, s.Visibility) } - suite.Equal(`; rel="next", ; rel="prev"`, result.Header.Get("link")) + suite.Equal(`; rel="next", ; rel="prev"`, result.Header.Get("link")) } func (suite *AccountStatusesTestSuite) TestGetStatusesPublicOnlyMediaOnly() { @@ -102,7 +102,7 @@ func (suite *AccountStatusesTestSuite) TestGetStatusesPublicOnlyMediaOnly() { // check the response b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) + suite.NoError(err) // unmarshal the returned statuses apimodelStatuses := []*apimodel.Status{} @@ -115,7 +115,176 @@ func (suite *AccountStatusesTestSuite) TestGetStatusesPublicOnlyMediaOnly() { suite.Equal(apimodel.VisibilityPublic, s.Visibility) } - suite.Equal(`; rel="next", ; rel="prev"`, result.Header.Get("link")) + suite.Equal(`; rel="next", ; rel="prev"`, result.Header.Get("link")) +} + +func (suite *AccountStatusesTestSuite) TestGetStatusesPinnedOnlyPublicPins() { + // admin has a couple statuses pinned + // we're getting pinned statuses of admin, as local account 1 + targetAccount := suite.testAccounts["admin_account"] + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodGet, nil, fmt.Sprintf("/api/v1/accounts/%s/statuses?pinned=true", targetAccount.ID), "") + ctx.Params = gin.Params{ + gin.Param{ + Key: accounts.IDKey, + Value: targetAccount.ID, + }, + } + + // call the handler + suite.accountsModule.AccountStatusesGETHandler(ctx) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusOK, recorder.Code) + + // 2. we should have no error message in the result body + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + // unmarshal the returned statuses + apimodelStatuses := []*apimodel.Status{} + err = json.Unmarshal(b, &apimodelStatuses) + suite.NoError(err) + suite.Len(apimodelStatuses, 2) + suite.Empty(result.Header.Get("link")) + + for _, s := range apimodelStatuses { + // Requesting account doesn't own these + // statuses, so pinned should be false. + suite.False(s.Pinned) + } +} + +func (suite *AccountStatusesTestSuite) TestGetStatusesPinnedOnlyNotFollowing() { + // local account 2 has a followers-only status pinned + // we're getting pinned statuses of local account 2 with an account that doesn't follow it + targetAccount := suite.testAccounts["local_account_2"] + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodGet, nil, fmt.Sprintf("/api/v1/accounts/%s/statuses?pinned=true", targetAccount.ID), "") + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["admin_account"]) + ctx.Set(oauth.SessionAuthorizedToken, oauth.DBTokenToToken(suite.testTokens["admin_account"])) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["admin_account"]) + ctx.Params = gin.Params{ + gin.Param{ + Key: accounts.IDKey, + Value: targetAccount.ID, + }, + } + + // call the handler + suite.accountsModule.AccountStatusesGETHandler(ctx) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusOK, recorder.Code) + + // 2. we should have no error message in the result body + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + // unmarshal the returned statuses + apimodelStatuses := []*apimodel.Status{} + err = json.Unmarshal(b, &apimodelStatuses) + suite.NoError(err) + suite.Empty(apimodelStatuses) + suite.Empty(result.Header.Get("link")) +} + +func (suite *AccountStatusesTestSuite) TestGetStatusesPinnedOnlyFollowing() { + // local account 2 has a followers-only status pinned + // we're getting pinned statuses of local account 2 with an account that *DOES* follow it + targetAccount := suite.testAccounts["local_account_2"] + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodGet, nil, fmt.Sprintf("/api/v1/accounts/%s/statuses?pinned=true", targetAccount.ID), "") + 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"]) + ctx.Params = gin.Params{ + gin.Param{ + Key: accounts.IDKey, + Value: targetAccount.ID, + }, + } + + // call the handler + suite.accountsModule.AccountStatusesGETHandler(ctx) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusOK, recorder.Code) + + // 2. we should have no error message in the result body + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + // unmarshal the returned statuses + apimodelStatuses := []*apimodel.Status{} + err = json.Unmarshal(b, &apimodelStatuses) + suite.NoError(err) + suite.Len(apimodelStatuses, 1) + suite.Empty(result.Header.Get("link")) + + for _, s := range apimodelStatuses { + // Requesting account doesn't own these + // statuses, so pinned should be false. + suite.False(s.Pinned) + } +} + +func (suite *AccountStatusesTestSuite) TestGetStatusesPinnedOnlyGetOwn() { + // local account 2 has a followers-only status pinned + // we're getting pinned statuses of local account 2 with local account 2! + targetAccount := suite.testAccounts["local_account_2"] + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodGet, nil, fmt.Sprintf("/api/v1/accounts/%s/statuses?pinned=true", targetAccount.ID), "") + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_2"]) + ctx.Set(oauth.SessionAuthorizedToken, oauth.DBTokenToToken(suite.testTokens["local_account_2"])) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_2"]) + ctx.Params = gin.Params{ + gin.Param{ + Key: accounts.IDKey, + Value: targetAccount.ID, + }, + } + + // call the handler + suite.accountsModule.AccountStatusesGETHandler(ctx) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusOK, recorder.Code) + + // 2. we should have no error message in the result body + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + // unmarshal the returned statuses + apimodelStatuses := []*apimodel.Status{} + err = json.Unmarshal(b, &apimodelStatuses) + suite.NoError(err) + suite.Len(apimodelStatuses, 1) + suite.Empty(result.Header.Get("link")) + + for _, s := range apimodelStatuses { + // Requesting account owns pinned statuses. + suite.True(s.Pinned) + } } func TestAccountStatusesTestSuite(t *testing.T) { diff --git a/internal/api/client/statuses/status.go b/internal/api/client/statuses/status.go index 380846ed4..d709d80ea 100644 --- a/internal/api/client/statuses/status.go +++ b/internal/api/client/statuses/status.go @@ -88,6 +88,10 @@ func (m *Module) Route(attachHandler func(method string, path string, f ...gin.H attachHandler(http.MethodPost, UnfavouritePath, m.StatusUnfavePOSTHandler) attachHandler(http.MethodGet, FavouritedPath, m.StatusFavedByGETHandler) + // pin stuff + attachHandler(http.MethodPost, PinPath, m.StatusPinPOSTHandler) + attachHandler(http.MethodPost, UnpinPath, m.StatusUnpinPOSTHandler) + // reblog stuff attachHandler(http.MethodPost, ReblogPath, m.StatusBoostPOSTHandler) attachHandler(http.MethodPost, UnreblogPath, m.StatusUnboostPOSTHandler) diff --git a/internal/api/client/statuses/statuspin.go b/internal/api/client/statuses/statuspin.go new file mode 100644 index 000000000..54508f51a --- /dev/null +++ b/internal/api/client/statuses/statuspin.go @@ -0,0 +1,103 @@ +/* + GoToSocial + Copyright (C) 2021-2023 GoToSocial Authors admin@gotosocial.org + + 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 statuses + +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" +) + +// StatusPinPOSTHandler swagger:operation POST /api/v1/statuses/{id}/pin statusPin +// +// Pin a status to the top of your profile, and add it to your Featured ActivityPub collection. +// +// You can only pin original posts (not reblogs) that you authored yourself. +// +// Supported privacy levels for pinned posts are public, unlisted, and private/followers-only, +// but only public posts will appear on the web version of your profile. +// +// --- +// tags: +// - statuses +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: Target status ID. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - write:accounts +// +// responses: +// '200': +// name: status +// description: The status. +// schema: +// "$ref": "#/definitions/status" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '403': +// description: forbidden +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) StatusPinPOSTHandler(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 + } + + targetStatusID := c.Param(IDKey) + if targetStatusID == "" { + err := errors.New("no status id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGetV1) + return + } + + apiStatus, errWithCode := m.processor.Status().PinCreate(c.Request.Context(), authed.Account, targetStatusID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGetV1) + return + } + + c.JSON(http.StatusOK, apiStatus) +} diff --git a/internal/api/client/statuses/statuspin_test.go b/internal/api/client/statuses/statuspin_test.go new file mode 100644 index 000000000..69cf34eff --- /dev/null +++ b/internal/api/client/statuses/statuspin_test.go @@ -0,0 +1,198 @@ +/* + GoToSocial + Copyright (C) 2021-2023 GoToSocial Authors admin@gotosocial.org + + 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 statuses_test + +import ( + "context" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "strconv" + "testing" + "time" + + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/ap" + "github.com/superseriousbusiness/gotosocial/internal/api/client/statuses" + 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/gtsmodel" + "github.com/superseriousbusiness/gotosocial/internal/id" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +type StatusPinTestSuite struct { + StatusStandardTestSuite +} + +func (suite *StatusPinTestSuite) createPin( + expectedHTTPStatus int, + expectedBody string, + targetStatusID string, +) (*apimodel.Status, 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.MethodPost, config.GetProtocol()+"://"+config.GetHost()+"/api/"+statuses.BasePath+"/"+targetStatusID+"/pin", nil) + ctx.Request.Header.Set("accept", "application/json") + ctx.AddParam(statuses.IDKey, targetStatusID) + + // trigger the handler + suite.statusModule.StatusPinPOSTHandler(ctx) + + // read the response + result := recorder.Result() + defer result.Body.Close() + + b, err := ioutil.ReadAll(result.Body) + if err != nil { + return nil, err + } + + errs := gtserror.MultiError{} + + // check code + body + if resultCode := recorder.Code; expectedHTTPStatus != resultCode { + errs = append(errs, fmt.Sprintf("expected %d got %d", expectedHTTPStatus, resultCode)) + } + + // if we got an expected body, return early + if expectedBody != "" && string(b) != expectedBody { + errs = append(errs, fmt.Sprintf("expected %s got %s", expectedBody, string(b))) + } + + if len(errs) > 0 { + return nil, errs.Combine() + } + + resp := &apimodel.Status{} + if err := json.Unmarshal(b, resp); err != nil { + return nil, err + } + + return resp, nil +} + +func (suite *StatusPinTestSuite) TestPinStatusPublicOK() { + // Pin an unpinned public status that this account owns. + targetStatus := suite.testStatuses["local_account_1_status_1"] + + resp, err := suite.createPin(http.StatusOK, "", targetStatus.ID) + if err != nil { + suite.FailNow(err.Error()) + } + + suite.True(resp.Pinned) +} + +func (suite *StatusPinTestSuite) TestPinStatusFollowersOnlyOK() { + // Pin an unpinned followers only status that this account owns. + targetStatus := suite.testStatuses["local_account_1_status_5"] + + resp, err := suite.createPin(http.StatusOK, "", targetStatus.ID) + if err != nil { + suite.FailNow(err.Error()) + } + + suite.True(resp.Pinned) +} + +func (suite *StatusPinTestSuite) TestPinStatusTwiceError() { + // Try to pin a status that's already been pinned. + targetStatus := >smodel.Status{} + *targetStatus = *suite.testStatuses["local_account_1_status_5"] + targetStatus.PinnedAt = time.Now() + + if err := suite.db.UpdateStatus(context.Background(), targetStatus); err != nil { + suite.FailNow(err.Error()) + } + + if _, err := suite.createPin( + http.StatusUnprocessableEntity, + `{"error":"Unprocessable Entity: status already pinned"}`, + targetStatus.ID, + ); err != nil { + suite.FailNow(err.Error()) + } +} + +func (suite *StatusPinTestSuite) TestPinStatusOtherAccountError() { + // Try to pin a status that doesn't belong to us. + targetStatus := suite.testStatuses["admin_account_status_1"] + + if _, err := suite.createPin( + http.StatusUnprocessableEntity, + `{"error":"Unprocessable Entity: status 01F8MH75CBF9JFX4ZAD54N0W0R does not belong to account 01F8MH1H7YV1Z7D2C8K2730QBF"}`, + targetStatus.ID, + ); err != nil { + suite.FailNow(err.Error()) + } +} + +func (suite *StatusPinTestSuite) TestPinStatusTooManyPins() { + // Test pinning too many statuses. + testAccount := suite.testAccounts["local_account_1"] + + // Spam 10 pinned statuses into the database. + ctx := context.Background() + for i := range make([]interface{}, 10) { + status := >smodel.Status{ + ID: id.NewULID(), + PinnedAt: time.Now(), + URL: "stub " + strconv.Itoa(i), + URI: "stub " + strconv.Itoa(i), + Local: testrig.TrueBool(), + AccountID: testAccount.ID, + AccountURI: testAccount.URI, + Visibility: gtsmodel.VisibilityPublic, + Federated: testrig.TrueBool(), + Boostable: testrig.TrueBool(), + Replyable: testrig.TrueBool(), + Likeable: testrig.TrueBool(), + ActivityStreamsType: ap.ObjectNote, + } + if err := suite.db.PutStatus(ctx, status); err != nil { + suite.FailNow(err.Error()) + } + } + + // Try to pin one more status as a treat. + targetStatus := suite.testStatuses["local_account_1_status_1"] + if _, err := suite.createPin( + http.StatusUnprocessableEntity, + `{"error":"Unprocessable Entity: status pin limit exceeded, you've already pinned 10 status(es) out of 10"}`, + targetStatus.ID, + ); err != nil { + suite.FailNow(err.Error()) + } +} + +func TestStatusPinTestSuite(t *testing.T) { + suite.Run(t, new(StatusPinTestSuite)) +} diff --git a/internal/api/client/statuses/statusunpin.go b/internal/api/client/statuses/statusunpin.go new file mode 100644 index 000000000..6a14b109e --- /dev/null +++ b/internal/api/client/statuses/statusunpin.go @@ -0,0 +1,98 @@ +/* + GoToSocial + Copyright (C) 2021-2023 GoToSocial Authors admin@gotosocial.org + + 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 statuses + +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" +) + +// StatusUnpinPOSTHandler swagger:operation POST /api/v1/statuses/{id}/unpin statusUnpin +// +// Unpin one of your pinned statuses. +// +// --- +// tags: +// - statuses +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: Target status ID. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - write:accounts +// +// responses: +// '200': +// name: status +// description: The status. +// schema: +// "$ref": "#/definitions/status" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '403': +// description: forbidden +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) StatusUnpinPOSTHandler(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 + } + + targetStatusID := c.Param(IDKey) + if targetStatusID == "" { + err := errors.New("no status id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGetV1) + return + } + + apiStatus, errWithCode := m.processor.Status().PinRemove(c.Request.Context(), authed.Account, targetStatusID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGetV1) + return + } + + c.JSON(http.StatusOK, apiStatus) +} diff --git a/internal/db/account.go b/internal/db/account.go index 42a8c62b0..7989b9838 100644 --- a/internal/db/account.go +++ b/internal/db/account.go @@ -62,15 +62,29 @@ type Account interface { // GetAccountStatusesCount is a shortcut for the common action of counting statuses produced by accountID. CountAccountStatuses(ctx context.Context, accountID string) (int, Error) + // CountAccountPinned returns the total number of pinned statuses owned by account with the given id. + CountAccountPinned(ctx context.Context, accountID string) (int, Error) + // GetAccountStatuses is a shortcut for getting the most recent statuses. accountID is optional, if not provided // then all statuses will be returned. If limit is set to 0, the size of the returned slice will not be limited. This can // be very memory intensive so you probably shouldn't do this! - // In case of no entries, a 'no entries' error will be returned - GetAccountStatuses(ctx context.Context, accountID string, limit int, excludeReplies bool, excludeReblogs bool, maxID string, minID string, pinnedOnly bool, mediaOnly bool, publicOnly bool) ([]*gtsmodel.Status, Error) + // + // In the case of no statuses, this function will return db.ErrNoEntries. + GetAccountStatuses(ctx context.Context, accountID string, limit int, excludeReplies bool, excludeReblogs bool, maxID string, minID string, mediaOnly bool, publicOnly bool) ([]*gtsmodel.Status, Error) + + // GetAccountPinnedStatuses returns ONLY statuses owned by the give accountID for which a corresponding StatusPin + // exists in the database. Statuses which are not pinned will not be returned by this function. + // + // Statuses will be returned in the order in which they were pinned, from latest pinned to oldest pinned (descending). + // + // In the case of no statuses, this function will return db.ErrNoEntries. + GetAccountPinnedStatuses(ctx context.Context, accountID string) ([]*gtsmodel.Status, Error) // GetAccountWebStatuses is similar to GetAccountStatuses, but it's specifically for returning statuses that // should be visible via the web view of an account. So, only public, federated statuses that aren't boosts // or replies. + // + // In the case of no statuses, this function will return db.ErrNoEntries. GetAccountWebStatuses(ctx context.Context, accountID string, limit int, maxID string) ([]*gtsmodel.Status, Error) GetBookmarks(ctx context.Context, accountID string, limit int, maxID string, minID string) ([]*gtsmodel.StatusBookmark, Error) diff --git a/internal/db/bundb/account.go b/internal/db/bundb/account.go index 937f4ba23..26959001f 100644 --- a/internal/db/bundb/account.go +++ b/internal/db/bundb/account.go @@ -350,7 +350,16 @@ func (a *accountDB) CountAccountStatuses(ctx context.Context, accountID string) Count(ctx) } -func (a *accountDB) GetAccountStatuses(ctx context.Context, accountID string, limit int, excludeReplies bool, excludeReblogs bool, maxID string, minID string, pinnedOnly bool, mediaOnly bool, publicOnly bool) ([]*gtsmodel.Status, db.Error) { +func (a *accountDB) CountAccountPinned(ctx context.Context, accountID string) (int, db.Error) { + return a.conn. + NewSelect(). + TableExpr("? AS ?", bun.Ident("statuses"), bun.Ident("status")). + Where("? = ?", bun.Ident("status.account_id"), accountID). + Where("? IS NOT NULL", bun.Ident("status.pinned_at")). + Count(ctx) +} + +func (a *accountDB) GetAccountStatuses(ctx context.Context, accountID string, limit int, excludeReplies bool, excludeReblogs bool, maxID string, minID string, mediaOnly bool, publicOnly bool) ([]*gtsmodel.Status, db.Error) { statusIDs := []string{} q := a.conn. @@ -390,10 +399,6 @@ func (a *accountDB) GetAccountStatuses(ctx context.Context, accountID string, li q = q.Where("? > ?", bun.Ident("status.id"), minID) } - if pinnedOnly { - q = q.Where("? = ?", bun.Ident("status.pinned"), true) - } - if mediaOnly { // attachments are stored as a json object; // this implementation differs between sqlite and postgres, @@ -429,6 +434,24 @@ func (a *accountDB) GetAccountStatuses(ctx context.Context, accountID string, li return a.statusesFromIDs(ctx, statusIDs) } +func (a *accountDB) GetAccountPinnedStatuses(ctx context.Context, accountID string) ([]*gtsmodel.Status, db.Error) { + statusIDs := []string{} + + q := a.conn. + NewSelect(). + TableExpr("? AS ?", bun.Ident("statuses"), bun.Ident("status")). + Column("status.id"). + Where("? = ?", bun.Ident("status.account_id"), accountID). + Where("? IS NOT NULL", bun.Ident("status.pinned_at")). + Order("status.pinned_at DESC") + + if err := q.Scan(ctx, &statusIDs); err != nil { + return nil, a.conn.ProcessError(err) + } + + return a.statusesFromIDs(ctx, statusIDs) +} + func (a *accountDB) GetAccountWebStatuses(ctx context.Context, accountID string, limit int, maxID string) ([]*gtsmodel.Status, db.Error) { statusIDs := []string{} diff --git a/internal/db/bundb/account_test.go b/internal/db/bundb/account_test.go index 13bdba20d..a510e2152 100644 --- a/internal/db/bundb/account_test.go +++ b/internal/db/bundb/account_test.go @@ -28,6 +28,7 @@ import ( "github.com/stretchr/testify/suite" "github.com/superseriousbusiness/gotosocial/internal/ap" + "github.com/superseriousbusiness/gotosocial/internal/db" "github.com/superseriousbusiness/gotosocial/internal/db/bundb" "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" "github.com/uptrace/bun" @@ -38,25 +39,25 @@ type AccountTestSuite struct { } func (suite *AccountTestSuite) TestGetAccountStatuses() { - statuses, err := suite.db.GetAccountStatuses(context.Background(), suite.testAccounts["local_account_1"].ID, 20, false, false, "", "", false, false, false) + statuses, err := suite.db.GetAccountStatuses(context.Background(), suite.testAccounts["local_account_1"].ID, 20, false, false, "", "", false, false) suite.NoError(err) suite.Len(statuses, 5) } func (suite *AccountTestSuite) TestGetAccountStatusesExcludeRepliesAndReblogs() { - statuses, err := suite.db.GetAccountStatuses(context.Background(), suite.testAccounts["local_account_1"].ID, 20, true, true, "", "", false, false, false) + statuses, err := suite.db.GetAccountStatuses(context.Background(), suite.testAccounts["local_account_1"].ID, 20, true, true, "", "", false, false) suite.NoError(err) suite.Len(statuses, 5) } func (suite *AccountTestSuite) TestGetAccountStatusesExcludeRepliesAndReblogsPublicOnly() { - statuses, err := suite.db.GetAccountStatuses(context.Background(), suite.testAccounts["local_account_1"].ID, 20, true, true, "", "", false, false, true) + statuses, err := suite.db.GetAccountStatuses(context.Background(), suite.testAccounts["local_account_1"].ID, 20, true, true, "", "", false, true) suite.NoError(err) suite.Len(statuses, 1) } func (suite *AccountTestSuite) TestGetAccountStatusesMediaOnly() { - statuses, err := suite.db.GetAccountStatuses(context.Background(), suite.testAccounts["local_account_1"].ID, 20, false, false, "", "", false, true, false) + statuses, err := suite.db.GetAccountStatuses(context.Background(), suite.testAccounts["local_account_1"].ID, 20, false, false, "", "", true, false) suite.NoError(err) suite.Len(statuses, 1) } @@ -214,6 +215,38 @@ func (suite *AccountTestSuite) TestGettingBookmarksWithNoAccount() { suite.Nil(statuses) } +func (suite *AccountTestSuite) TestGetAccountPinnedStatusesSomeResults() { + testAccount := suite.testAccounts["admin_account"] + + statuses, err := suite.db.GetAccountPinnedStatuses(context.Background(), testAccount.ID) + suite.NoError(err) + suite.Len(statuses, 2) // This account has 2 statuses pinned. +} + +func (suite *AccountTestSuite) TestGetAccountPinnedStatusesNothingPinned() { + testAccount := suite.testAccounts["local_account_1"] + + statuses, err := suite.db.GetAccountPinnedStatuses(context.Background(), testAccount.ID) + suite.ErrorIs(err, db.ErrNoEntries) + suite.Empty(statuses) // This account has nothing pinned. +} + +func (suite *AccountTestSuite) TestCountAccountPinnedSomeResults() { + testAccount := suite.testAccounts["admin_account"] + + pinned, err := suite.db.CountAccountPinned(context.Background(), testAccount.ID) + suite.NoError(err) + suite.Equal(pinned, 2) // This account has 2 statuses pinned. +} + +func (suite *AccountTestSuite) TestCountAccountPinnedNothingPinned() { + testAccount := suite.testAccounts["local_account_1"] + + pinned, err := suite.db.CountAccountPinned(context.Background(), testAccount.ID) + suite.NoError(err) + suite.Equal(pinned, 0) // This account has nothing pinned. +} + func TestAccountTestSuite(t *testing.T) { suite.Run(t, new(AccountTestSuite)) } diff --git a/internal/db/bundb/migrations/20230221150957_status_pin_client_api.go b/internal/db/bundb/migrations/20230221150957_status_pin_client_api.go new file mode 100644 index 000000000..b2464fe30 --- /dev/null +++ b/internal/db/bundb/migrations/20230221150957_status_pin_client_api.go @@ -0,0 +1,65 @@ +/* + GoToSocial + Copyright (C) 2021-2023 GoToSocial Authors admin@gotosocial.org + + 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 migrations + +import ( + "context" + "strings" + + "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" + "github.com/uptrace/bun" +) + +func init() { + up := func(ctx context.Context, db *bun.DB) error { + return db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { + // Drop the now unused 'pinned' column in statuses. + if _, err := tx.ExecContext(ctx, "ALTER TABLE ? DROP COLUMN ?", bun.Ident("statuses"), bun.Ident("pinned")); err != nil && + !(strings.Contains(err.Error(), "no such column") || strings.Contains(err.Error(), "does not exist") || strings.Contains(err.Error(), "SQLSTATE 42703")) { + return err + } + + // Create new (more useful) pinned_at column. + if _, err := tx.NewAddColumn().Model(>smodel.Status{}).ColumnExpr("? TIMESTAMPTZ", bun.Ident("pinned_at")).Exec(ctx); err != nil && + !(strings.Contains(err.Error(), "already exists") || strings.Contains(err.Error(), "duplicate column name") || strings.Contains(err.Error(), "SQLSTATE 42701")) { + return err + } + + // Index new column appropriately. + if _, err := tx. + NewCreateIndex(). + Model(>smodel.Status{}). + Index("statuses_account_id_pinned_at_idx"). + Column("account_id", "pinned_at"). + Exec(ctx); err != nil { + return err + } + + return nil + }) + } + + down := func(ctx context.Context, db *bun.DB) error { + return nil + } + + if err := Migrations.Register(up, down); err != nil { + panic(err) + } +} diff --git a/internal/db/bundb/timeline_test.go b/internal/db/bundb/timeline_test.go index 91a4fef15..3b98de45d 100644 --- a/internal/db/bundb/timeline_test.go +++ b/internal/db/bundb/timeline_test.go @@ -113,7 +113,6 @@ func getFutureStatus() *gtsmodel.Status { Sensitive: testrig.FalseBool(), Language: "en", CreatedWithApplicationID: "01F8MGXQRHYF5QPMTMXP78QC2F", - Pinned: testrig.FalseBool(), Federated: testrig.TrueBool(), Boostable: testrig.TrueBool(), Replyable: testrig.TrueBool(), diff --git a/internal/gtsmodel/status.go b/internal/gtsmodel/status.go index 2ace42da7..a2f1b4869 100644 --- a/internal/gtsmodel/status.go +++ b/internal/gtsmodel/status.go @@ -27,6 +27,7 @@ type Status struct { ID string `validate:"required,ulid" bun:"type:CHAR(26),pk,nullzero,notnull,unique"` // id of this item in the database CreatedAt time.Time `validate:"-" bun:"type:timestamptz,nullzero,notnull,default:current_timestamp"` // when was item created UpdatedAt time.Time `validate:"-" bun:"type:timestamptz,nullzero,notnull,default:current_timestamp"` // when was item last updated + PinnedAt time.Time `validate:"-" bun:"type:timestamptz,nullzero"` // Status was pinned by owning account at this time. URI string `validate:"required,url" bun:",unique,nullzero,notnull"` // activitypub URI of this status URL string `validate:"url" bun:",nullzero"` // web url for viewing this status Content string `validate:"-" bun:""` // content of this status; likely html-formatted but not guaranteed @@ -59,7 +60,6 @@ type Status struct { CreatedWithApplication *Application `validate:"-" bun:"rel:belongs-to"` // application corresponding to createdWithApplicationID ActivityStreamsType string `validate:"required" bun:",nullzero,notnull"` // What is the activitystreams type of this status? See: https://www.w3.org/TR/activitystreams-vocabulary/#object-types. Will probably almost always be Note but who knows!. Text string `validate:"-" bun:""` // Original text of the status without formatting - Pinned *bool `validate:"-" bun:",nullzero,notnull,default:false"` // Has this status been pinned by its owner? Federated *bool `validate:"-" bun:",notnull"` // This status will be federated beyond the local timeline(s) Boostable *bool `validate:"-" bun:",notnull"` // This status can be boosted/reblogged Replyable *bool `validate:"-" bun:",notnull"` // This status can be replied to diff --git a/internal/processing/account/delete.go b/internal/processing/account/delete.go index 7a31b45d4..58a967337 100644 --- a/internal/processing/account/delete.go +++ b/internal/processing/account/delete.go @@ -129,7 +129,7 @@ func (p *Processor) Delete(ctx context.Context, account *gtsmodel.Account, origi for { // Fetch next block of account statuses from database - statuses, err := p.db.GetAccountStatuses(ctx, account.ID, 20, false, false, maxID, "", false, false, false) + statuses, err := p.db.GetAccountStatuses(ctx, account.ID, 20, false, false, maxID, "", false, false) if err != nil { if !errors.Is(err, db.ErrNoEntries) { // an actual error has occurred diff --git a/internal/processing/account/statuses.go b/internal/processing/account/statuses.go index 29833086d..7ff6de2ff 100644 --- a/internal/processing/account/statuses.go +++ b/internal/processing/account/statuses.go @@ -31,7 +31,7 @@ import ( // StatusesGet fetches a number of statuses (in time descending order) from the given account, filtered by visibility for // the account given in authed. -func (p *Processor) StatusesGet(ctx context.Context, requestingAccount *gtsmodel.Account, targetAccountID string, limit int, excludeReplies bool, excludeReblogs bool, maxID string, minID string, pinnedOnly bool, mediaOnly bool, publicOnly bool) (*apimodel.PageableResponse, gtserror.WithCode) { +func (p *Processor) StatusesGet(ctx context.Context, requestingAccount *gtsmodel.Account, targetAccountID string, limit int, excludeReplies bool, excludeReblogs bool, maxID string, minID string, pinned bool, mediaOnly bool, publicOnly bool) (*apimodel.PageableResponse, gtserror.WithCode) { if requestingAccount != nil { if blocked, err := p.db.IsBlocked(ctx, requestingAccount.ID, targetAccountID, true); err != nil { return nil, gtserror.NewErrorInternalError(err) @@ -40,7 +40,17 @@ func (p *Processor) StatusesGet(ctx context.Context, requestingAccount *gtsmodel } } - statuses, err := p.db.GetAccountStatuses(ctx, targetAccountID, limit, excludeReplies, excludeReblogs, maxID, minID, pinnedOnly, mediaOnly, publicOnly) + var ( + statuses []*gtsmodel.Status + err error + ) + if pinned { + // Get *ONLY* pinned statuses. + statuses, err = p.db.GetAccountPinnedStatuses(ctx, targetAccountID) + } else { + // Get account statuses which *may* include pinned ones. + statuses, err = p.db.GetAccountStatuses(ctx, targetAccountID, limit, excludeReplies, excludeReblogs, maxID, minID, mediaOnly, publicOnly) + } if err != nil { if err == db.ErrNoEntries { return util.EmptyPageableResponse(), nil @@ -48,7 +58,9 @@ func (p *Processor) StatusesGet(ctx context.Context, requestingAccount *gtsmodel return nil, gtserror.NewErrorInternalError(err) } - var filtered []*gtsmodel.Status + // Filtering + serialization process is the same for + // either pinned status queries or 'normal' ones. + filtered := make([]*gtsmodel.Status, 0, len(statuses)) for _, s := range statuses { visible, err := p.filter.StatusVisible(ctx, s, requestingAccount) if err == nil && visible { @@ -57,12 +69,11 @@ func (p *Processor) StatusesGet(ctx context.Context, requestingAccount *gtsmodel } count := len(filtered) - if count == 0 { return util.EmptyPageableResponse(), nil } - items := []interface{}{} + items := make([]interface{}, 0, count) nextMaxIDValue := "" prevMinIDValue := "" for i, s := range filtered { @@ -82,6 +93,14 @@ func (p *Processor) StatusesGet(ctx context.Context, requestingAccount *gtsmodel items = append(items, item) } + if pinned { + // We don't page on pinned status responses, + // so we can save some work + just return items. + return &apimodel.PageableResponse{ + Items: items, + }, nil + } + return util.PackagePageableResponse(util.PageableResponseParams{ Items: items, Path: fmt.Sprintf("/api/v1/accounts/%s/statuses", targetAccountID), @@ -91,7 +110,7 @@ func (p *Processor) StatusesGet(ctx context.Context, requestingAccount *gtsmodel ExtraQueryParams: []string{ fmt.Sprintf("exclude_replies=%t", excludeReplies), fmt.Sprintf("exclude_reblogs=%t", excludeReblogs), - fmt.Sprintf("pinned_only=%t", pinnedOnly), + fmt.Sprintf("pinned=%t", pinned), fmt.Sprintf("only_media=%t", mediaOnly), fmt.Sprintf("only_public=%t", publicOnly), }, diff --git a/internal/processing/fedi/collections.go b/internal/processing/fedi/collections.go index 62fc9d7b8..33d1b64e9 100644 --- a/internal/processing/fedi/collections.go +++ b/internal/processing/fedi/collections.go @@ -192,7 +192,7 @@ func (p *Processor) OutboxGet(ctx context.Context, requestedUsername string, pag // scenario 2 -- get the requested page // limit pages to 30 entries per page - publicStatuses, err := p.db.GetAccountStatuses(ctx, requestedAccount.ID, 30, true, true, maxID, minID, false, false, true) + publicStatuses, err := p.db.GetAccountStatuses(ctx, requestedAccount.ID, 30, true, true, maxID, minID, false, true) if err != nil && err != db.ErrNoEntries { return nil, gtserror.NewErrorInternalError(err) } diff --git a/internal/processing/fromclientapi_test.go b/internal/processing/fromclientapi_test.go index 2349febf5..438c6a3ce 100644 --- a/internal/processing/fromclientapi_test.go +++ b/internal/processing/fromclientapi_test.go @@ -76,7 +76,6 @@ func (suite *FromClientAPITestSuite) TestProcessStreamNewStatus() { Sensitive: testrig.FalseBool(), Language: "en", CreatedWithApplicationID: "01F8MGXQRHYF5QPMTMXP78QC2F", - Pinned: testrig.FalseBool(), Federated: testrig.FalseBool(), Boostable: testrig.TrueBool(), Replyable: testrig.TrueBool(), diff --git a/internal/processing/fromfederator_test.go b/internal/processing/fromfederator_test.go index 9999c7054..6913b22af 100644 --- a/internal/processing/fromfederator_test.go +++ b/internal/processing/fromfederator_test.go @@ -369,7 +369,7 @@ func (suite *FromFederatorTestSuite) TestProcessAccountDelete() { // no statuses from foss satan should be left in the database if !testrig.WaitFor(func() bool { - s, err := suite.db.GetAccountStatuses(ctx, deletedAccount.ID, 0, false, false, "", "", false, false, false) + s, err := suite.db.GetAccountStatuses(ctx, deletedAccount.ID, 0, false, false, "", "", false, false) return s == nil && err == db.ErrNoEntries }) { suite.FailNow("timeout waiting for statuses to be deleted") diff --git a/internal/processing/status/pin.go b/internal/processing/status/pin.go new file mode 100644 index 000000000..addd2515b --- /dev/null +++ b/internal/processing/status/pin.go @@ -0,0 +1,140 @@ +/* + GoToSocial + Copyright (C) 2021-2023 GoToSocial Authors admin@gotosocial.org + + 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 status + +import ( + "context" + "errors" + "fmt" + "time" + + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" +) + +const allowedPinnedCount = 10 + +// getPinnableStatus fetches targetStatusID status and ensures that requestingAccountID +// can pin or unpin it. +// +// It checks: +// - Status belongs to requesting account. +// - Status is public, unlisted, or followers-only. +// - Status is not a boost. +func (p *Processor) getPinnableStatus(ctx context.Context, targetStatusID string, requestingAccountID string) (*gtsmodel.Status, gtserror.WithCode) { + targetStatus, err := p.db.GetStatusByID(ctx, targetStatusID) + if err != nil { + err = fmt.Errorf("error fetching status %s: %w", targetStatusID, err) + return nil, gtserror.NewErrorNotFound(err) + } + + if targetStatus.AccountID != requestingAccountID { + err = fmt.Errorf("status %s does not belong to account %s", targetStatusID, requestingAccountID) + return nil, gtserror.NewErrorUnprocessableEntity(err, err.Error()) + } + + if targetStatus.Visibility == gtsmodel.VisibilityDirect { + err = errors.New("cannot pin direct messages") + return nil, gtserror.NewErrorUnprocessableEntity(err, err.Error()) + } + + if targetStatus.BoostOfID != "" { + err = errors.New("cannot pin boosts") + return nil, gtserror.NewErrorUnprocessableEntity(err, err.Error()) + } + + return targetStatus, nil +} + +// PinCreate pins the target status to the top of requestingAccount's profile, if possible. +// +// Conditions for a pin to work: +// - Status belongs to requesting account. +// - Status is public, unlisted, or followers-only. +// - Status is not a boost. +// - Status is not already pinnd. +// - Limit of pinned statuses not yet met or exceeded. +// +// If the conditions can't be met, then code 422 Unprocessable Entity will be returned. +func (p *Processor) PinCreate(ctx context.Context, requestingAccount *gtsmodel.Account, targetStatusID string) (*apimodel.Status, gtserror.WithCode) { + targetStatus, errWithCode := p.getPinnableStatus(ctx, targetStatusID, requestingAccount.ID) + if errWithCode != nil { + return nil, errWithCode + } + + if !targetStatus.PinnedAt.IsZero() { + err := errors.New("status already pinned") + return nil, gtserror.NewErrorUnprocessableEntity(err, err.Error()) + } + + pinnedCount, err := p.db.CountAccountPinned(ctx, requestingAccount.ID) + if err != nil { + return nil, gtserror.NewErrorInternalError(fmt.Errorf("error checking number of pinned statuses: %w", err)) + } + + if pinnedCount >= allowedPinnedCount { + err = fmt.Errorf("status pin limit exceeded, you've already pinned %d status(es) out of %d", pinnedCount, allowedPinnedCount) + return nil, gtserror.NewErrorUnprocessableEntity(err, err.Error()) + } + + targetStatus.PinnedAt = time.Now() + if err := p.db.UpdateStatus(ctx, targetStatus); err != nil { + return nil, gtserror.NewErrorInternalError(fmt.Errorf("db error pinning status: %w", err)) + } + + apiStatus, err := p.tc.StatusToAPIStatus(ctx, targetStatus, requestingAccount) + if err != nil { + return nil, gtserror.NewErrorInternalError(fmt.Errorf("error converting status %s to frontend representation: %w", targetStatus.ID, err)) + } + + return apiStatus, nil +} + +// PinRemove unpins the target status from the top of requestingAccount's profile, if possible. +// +// Conditions for an unpin to work: +// - Status belongs to requesting account. +// - Status is public, unlisted, or followers-only. +// - Status is not a boost. +// +// If the conditions can't be met, then code 422 Unprocessable Entity will be returned. +// +// Unlike with PinCreate, statuses that are already unpinned will not return 422, but just do +// nothing and return the api model representation of the status, to conform to the masto API. +func (p *Processor) PinRemove(ctx context.Context, requestingAccount *gtsmodel.Account, targetStatusID string) (*apimodel.Status, gtserror.WithCode) { + targetStatus, errWithCode := p.getPinnableStatus(ctx, targetStatusID, requestingAccount.ID) + if errWithCode != nil { + return nil, errWithCode + } + + if targetStatus.PinnedAt.IsZero() { + targetStatus.PinnedAt = time.Time{} + if err := p.db.UpdateStatus(ctx, targetStatus); err != nil { + return nil, gtserror.NewErrorInternalError(fmt.Errorf("db error unpinning status: %w", err)) + } + } + + apiStatus, err := p.tc.StatusToAPIStatus(ctx, targetStatus, requestingAccount) + if err != nil { + return nil, gtserror.NewErrorInternalError(fmt.Errorf("error converting status %s to frontend representation: %w", targetStatus.ID, err)) + } + + return apiStatus, nil +} diff --git a/internal/typeutils/astointernal.go b/internal/typeutils/astointernal.go index 459f3402d..11633ad4e 100644 --- a/internal/typeutils/astointernal.go +++ b/internal/typeutils/astointernal.go @@ -346,17 +346,16 @@ func (c *converter) ASStatusToStatus(ctx context.Context, statusable ap.Statusab // advanced visibility for this status // TODO: a lot of work to be done here -- a new type needs to be created for this in go-fed/activity using ASTOOL // for now we just set everything to true - pinned := false federated := true boostable := true replyable := true likeable := true - status.Pinned = &pinned status.Federated = &federated status.Boostable = &boostable status.Replyable = &replyable status.Likeable = &likeable + // sensitive sensitive := ap.ExtractSensitive(statusable) status.Sensitive = &sensitive diff --git a/internal/typeutils/internal.go b/internal/typeutils/internal.go index 62e43f8c7..cf490e88d 100644 --- a/internal/typeutils/internal.go +++ b/internal/typeutils/internal.go @@ -37,7 +37,6 @@ func (c *converter) StatusToBoost(ctx context.Context, s *gtsmodel.Status, boost } sensitive := *s.Sensitive - pinned := false // can't pin a boost federated := *s.Federated boostable := *s.Boostable replyable := *s.Replyable @@ -75,7 +74,6 @@ func (c *converter) StatusToBoost(ctx context.Context, s *gtsmodel.Status, boost BoostOfID: s.ID, BoostOfAccountID: s.AccountID, Visibility: s.Visibility, - Pinned: &pinned, Federated: &federated, Boostable: &boostable, Replyable: &replyable, diff --git a/internal/typeutils/internaltoas_test.go b/internal/typeutils/internaltoas_test.go index 0bbb80dac..2ea393db3 100644 --- a/internal/typeutils/internaltoas_test.go +++ b/internal/typeutils/internaltoas_test.go @@ -433,7 +433,7 @@ func (suite *InternalToASTestSuite) TestStatusesToASOutboxPage() { ctx := context.Background() // get public statuses from testaccount - statuses, err := suite.db.GetAccountStatuses(ctx, testAccount.ID, 30, true, true, "", "", false, false, true) + statuses, err := suite.db.GetAccountStatuses(ctx, testAccount.ID, 30, true, true, "", "", false, true) suite.NoError(err) page, err := suite.typeconverter.StatusesToASOutboxPage(ctx, testAccount.OutboxURI, "", "", statuses) diff --git a/internal/typeutils/internaltofrontend.go b/internal/typeutils/internaltofrontend.go index 40837ad6b..ebea023cf 100644 --- a/internal/typeutils/internaltofrontend.go +++ b/internal/typeutils/internaltofrontend.go @@ -628,7 +628,7 @@ func (c *converter) StatusToAPIStatus(ctx context.Context, s *gtsmodel.Status, r Bookmarked: interacts.Bookmarked, Muted: interacts.Muted, Reblogged: interacts.Reblogged, - Pinned: *s.Pinned, + Pinned: interacts.Pinned, Content: s.Content, Reblog: nil, Application: apiApplication, diff --git a/internal/typeutils/util.go b/internal/typeutils/util.go index 40001e913..d11cccb2c 100644 --- a/internal/typeutils/util.go +++ b/internal/typeutils/util.go @@ -32,6 +32,7 @@ type statusInteractions struct { Muted bool Bookmarked bool Reblogged bool + Pinned bool } func (c *converter) interactionsWithStatusForAccount(ctx context.Context, s *gtsmodel.Status, requestingAccount *gtsmodel.Account) (*statusInteractions, error) { @@ -61,6 +62,12 @@ func (c *converter) interactionsWithStatusForAccount(ctx context.Context, s *gts return nil, fmt.Errorf("error checking if requesting account has bookmarked status: %s", err) } si.Bookmarked = bookmarked + + // The only time 'pinned' should be true is if the + // requesting account is looking at its OWN status. + if s.AccountID == requestingAccount.ID { + si.Pinned = !s.PinnedAt.IsZero() + } } return si, nil } diff --git a/internal/validate/status_test.go b/internal/validate/status_test.go index 2abda7777..31a2294d1 100644 --- a/internal/validate/status_test.go +++ b/internal/validate/status_test.go @@ -70,7 +70,6 @@ func happyStatus() *gtsmodel.Status { Likeable: testrig.TrueBool(), ActivityStreamsType: ap.ObjectNote, Text: "Test status! #hello", - Pinned: testrig.FalseBool(), } } diff --git a/internal/web/profile.go b/internal/web/profile.go index 2319e5dc9..a5816901e 100644 --- a/internal/web/profile.go +++ b/internal/web/profile.go @@ -91,15 +91,17 @@ func (m *Module) profileGETHandler(c *gin.Context) { robotsMeta = robotsMetaAllowSome } - // we should only show the 'back to top' button if the - // profile visitor is paging through statuses - showBackToTop := false + // We need to change our response slightly if the + // profile visitor is paging through statuses. + var ( + paging bool + pinnedResp = &apimodel.PageableResponse{} + maxStatusID string + ) - maxStatusID := "" - maxStatusIDString := c.Query(MaxStatusIDKey) - if maxStatusIDString != "" { + if maxStatusIDString := c.Query(MaxStatusIDKey); maxStatusIDString != "" { maxStatusID = maxStatusIDString - showBackToTop = true + paging = true } statusResp, errWithCode := m.processor.Account().WebStatusesGet(ctx, account.ID, maxStatusID) @@ -108,6 +110,18 @@ func (m *Module) profileGETHandler(c *gin.Context) { return } + // If we're not paging, then the profile visitor + // is currently just opening the bare profile, so + // load pinned statuses so we can show them at the + // top of the profile. + if !paging { + pinnedResp, errWithCode = m.processor.Account().StatusesGet(ctx, authed.Account, account.ID, 0, false, false, "", "", true, false, false) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, instanceGet) + return + } + } + stylesheets := []string{ assetsPathPrefix + "/Fork-Awesome/css/fork-awesome.min.css", distPathPrefix + "/status.css", @@ -125,7 +139,8 @@ func (m *Module) profileGETHandler(c *gin.Context) { "robotsMeta": robotsMeta, "statuses": statusResp.Items, "statuses_next": statusResp.NextLink, - "show_back_to_top": showBackToTop, + "pinned_statuses": pinnedResp.Items, + "show_back_to_top": paging, "stylesheets": stylesheets, "javascript": []string{distPathPrefix + "/frontend.js"}, }) diff --git a/testrig/testmodels.go b/testrig/testmodels.go index e5fe45d9e..776265813 100644 --- a/testrig/testmodels.go +++ b/testrig/testmodels.go @@ -1263,6 +1263,7 @@ func NewTestStatuses() map[string]*gtsmodel.Status { return map[string]*gtsmodel.Status{ "admin_account_status_1": { ID: "01F8MH75CBF9JFX4ZAD54N0W0R", + PinnedAt: TimeMustParse("2022-05-14T13:21:09+02:00"), URI: "http://localhost:8080/users/admin/statuses/01F8MH75CBF9JFX4ZAD54N0W0R", URL: "http://localhost:8080/@admin/statuses/01F8MH75CBF9JFX4ZAD54N0W0R", Content: "hello world! #welcome ! first post on the instance :rainbow: !", @@ -1283,7 +1284,6 @@ func NewTestStatuses() map[string]*gtsmodel.Status { Sensitive: FalseBool(), Language: "en", CreatedWithApplicationID: "01F8MGXQRHYF5QPMTMXP78QC2F", - Pinned: FalseBool(), Federated: TrueBool(), Boostable: TrueBool(), Replyable: TrueBool(), @@ -1292,6 +1292,7 @@ func NewTestStatuses() map[string]*gtsmodel.Status { }, "admin_account_status_2": { ID: "01F8MHAAY43M6RJ473VQFCVH37", + PinnedAt: TimeMustParse("2022-05-14T14:21:09+02:00"), URI: "http://localhost:8080/users/admin/statuses/01F8MHAAY43M6RJ473VQFCVH37", URL: "http://localhost:8080/@admin/statuses/01F8MHAAY43M6RJ473VQFCVH37", Content: "🐕🐕🐕🐕🐕", @@ -1308,7 +1309,6 @@ func NewTestStatuses() map[string]*gtsmodel.Status { Sensitive: TrueBool(), Language: "en", CreatedWithApplicationID: "01F8MGXQRHYF5QPMTMXP78QC2F", - Pinned: FalseBool(), Federated: TrueBool(), Boostable: TrueBool(), Replyable: TrueBool(), @@ -1335,7 +1335,6 @@ func NewTestStatuses() map[string]*gtsmodel.Status { Sensitive: FalseBool(), Language: "en", CreatedWithApplicationID: "01F8MGXQRHYF5QPMTMXP78QC2F", - Pinned: FalseBool(), Federated: TrueBool(), Boostable: TrueBool(), Replyable: TrueBool(), @@ -1363,7 +1362,6 @@ func NewTestStatuses() map[string]*gtsmodel.Status { Sensitive: TrueBool(), Language: "en", CreatedWithApplicationID: "01F8MGXQRHYF5QPMTMXP78QC2F", - Pinned: FalseBool(), Federated: TrueBool(), Boostable: TrueBool(), Replyable: TrueBool(), @@ -1388,7 +1386,6 @@ func NewTestStatuses() map[string]*gtsmodel.Status { Sensitive: TrueBool(), Language: "en", CreatedWithApplicationID: "01F8MGY43H3N2C8EWPR2FPYEXG", - Pinned: FalseBool(), Federated: TrueBool(), Boostable: TrueBool(), Replyable: TrueBool(), @@ -1413,7 +1410,6 @@ func NewTestStatuses() map[string]*gtsmodel.Status { Sensitive: FalseBool(), Language: "en", CreatedWithApplicationID: "01F8MGY43H3N2C8EWPR2FPYEXG", - Pinned: FalseBool(), Federated: FalseBool(), Boostable: TrueBool(), Replyable: TrueBool(), @@ -1438,7 +1434,6 @@ func NewTestStatuses() map[string]*gtsmodel.Status { Sensitive: FalseBool(), Language: "en", CreatedWithApplicationID: "01F8MGY43H3N2C8EWPR2FPYEXG", - Pinned: FalseBool(), Federated: TrueBool(), Boostable: FalseBool(), Replyable: FalseBool(), @@ -1464,7 +1459,6 @@ func NewTestStatuses() map[string]*gtsmodel.Status { Sensitive: FalseBool(), Language: "en", CreatedWithApplicationID: "01F8MGY43H3N2C8EWPR2FPYEXG", - Pinned: FalseBool(), Federated: TrueBool(), Boostable: TrueBool(), Replyable: TrueBool(), @@ -1490,7 +1484,6 @@ func NewTestStatuses() map[string]*gtsmodel.Status { Sensitive: FalseBool(), Language: "en", CreatedWithApplicationID: "01F8MGY43H3N2C8EWPR2FPYEXG", - Pinned: FalseBool(), Federated: TrueBool(), Boostable: TrueBool(), Replyable: TrueBool(), @@ -1515,7 +1508,6 @@ func NewTestStatuses() map[string]*gtsmodel.Status { Sensitive: TrueBool(), Language: "en", CreatedWithApplicationID: "01F8MGYG9E893WRHW0TAEXR8GJ", - Pinned: FalseBool(), Federated: TrueBool(), Boostable: TrueBool(), Replyable: TrueBool(), @@ -1540,7 +1532,6 @@ func NewTestStatuses() map[string]*gtsmodel.Status { Sensitive: TrueBool(), Language: "en", CreatedWithApplicationID: "01F8MGYG9E893WRHW0TAEXR8GJ", - Pinned: FalseBool(), Federated: TrueBool(), Boostable: TrueBool(), Replyable: FalseBool(), @@ -1565,7 +1556,6 @@ func NewTestStatuses() map[string]*gtsmodel.Status { Sensitive: TrueBool(), Language: "en", CreatedWithApplicationID: "01F8MGYG9E893WRHW0TAEXR8GJ", - Pinned: FalseBool(), Federated: TrueBool(), Boostable: TrueBool(), Replyable: FalseBool(), @@ -1590,7 +1580,6 @@ func NewTestStatuses() map[string]*gtsmodel.Status { Sensitive: TrueBool(), Language: "en", CreatedWithApplicationID: "01F8MGYG9E893WRHW0TAEXR8GJ", - Pinned: FalseBool(), Federated: FalseBool(), Boostable: FalseBool(), Replyable: TrueBool(), @@ -1619,7 +1608,6 @@ func NewTestStatuses() map[string]*gtsmodel.Status { Sensitive: FalseBool(), Language: "en", CreatedWithApplicationID: "01F8MGYG9E893WRHW0TAEXR8GJ", - Pinned: FalseBool(), Federated: TrueBool(), Boostable: TrueBool(), Replyable: TrueBool(), @@ -1647,7 +1635,6 @@ func NewTestStatuses() map[string]*gtsmodel.Status { Sensitive: FalseBool(), Language: "en", CreatedWithApplicationID: "01F8MGYG9E893WRHW0TAEXR8GJ", - Pinned: FalseBool(), Federated: TrueBool(), Boostable: TrueBool(), Replyable: TrueBool(), @@ -1656,6 +1643,7 @@ func NewTestStatuses() map[string]*gtsmodel.Status { }, "local_account_2_status_7": { ID: "01G20ZM733MGN8J344T4ZDDFY1", + PinnedAt: TimeMustParse("2021-03-18T09:13:55+02:00"), URI: "http://localhost:8080/users/1happyturtle/statuses/01G20ZM733MGN8J344T4ZDDFY1", URL: "http://localhost:8080/@1happyturtle/statuses/01G20ZM733MGN8J344T4ZDDFY1", Content: "🐢 hi followers! did u know i'm a turtle? 🐢", @@ -1673,7 +1661,6 @@ func NewTestStatuses() map[string]*gtsmodel.Status { Sensitive: FalseBool(), Language: "en", CreatedWithApplicationID: "01F8MGYG9E893WRHW0TAEXR8GJ", - Pinned: FalseBool(), Federated: TrueBool(), Boostable: TrueBool(), Replyable: TrueBool(), @@ -1701,7 +1688,6 @@ func NewTestStatuses() map[string]*gtsmodel.Status { Sensitive: FalseBool(), Language: "en", CreatedWithApplicationID: "", - Pinned: FalseBool(), Federated: TrueBool(), Boostable: TrueBool(), Replyable: TrueBool(), diff --git a/web/source/css/profile.css b/web/source/css/profile.css index 288ca6955..0065f6015 100644 --- a/web/source/css/profile.css +++ b/web/source/css/profile.css @@ -271,7 +271,7 @@ main { box-shadow: $boxshadow; } -#recent { +#recent, #pinned { display: flex; flex-direction: row; align-items: center; diff --git a/web/template/profile.tmpl b/web/template/profile.tmpl index d584676a6..f567998a4 100644 --- a/web/template/profile.tmpl +++ b/web/template/profile.tmpl @@ -53,6 +53,18 @@ + {{ if .pinned_statuses }} +

+ Pinned toots +

+
+ {{ range .pinned_statuses }} +
+ {{ template "status.tmpl" .}} +
+ {{ end }} +
+ {{ end }}

Latest public toots {{ if .rssFeed }}