[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
This commit is contained in:
tobi 2023-02-25 13:16:30 +01:00 committed by GitHub
parent ecdc8379fa
commit c27b4d7ed0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
29 changed files with 1015 additions and 62 deletions

View file

@ -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

View file

@ -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)

View file

@ -27,10 +27,10 @@
"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(`<http://localhost:8080/api/v1/accounts/01F8MH17FWEB39HZJ76B6VXSKF/statuses?limit=20&max_id=01F8MH75CBF9JFX4ZAD54N0W0R&exclude_replies=false&exclude_reblogs=false&pinned_only=false&only_media=false&only_public=true>; rel="next", <http://localhost:8080/api/v1/accounts/01F8MH17FWEB39HZJ76B6VXSKF/statuses?limit=20&min_id=01G36SF3V6Y6V5BF9P4R7PQG7G&exclude_replies=false&exclude_reblogs=false&pinned_only=false&only_media=false&only_public=true>; rel="prev"`, result.Header.Get("link"))
suite.Equal(`<http://localhost:8080/api/v1/accounts/01F8MH17FWEB39HZJ76B6VXSKF/statuses?limit=20&max_id=01F8MH75CBF9JFX4ZAD54N0W0R&exclude_replies=false&exclude_reblogs=false&pinned=false&only_media=false&only_public=true>; rel="next", <http://localhost:8080/api/v1/accounts/01F8MH17FWEB39HZJ76B6VXSKF/statuses?limit=20&min_id=01G36SF3V6Y6V5BF9P4R7PQG7G&exclude_replies=false&exclude_reblogs=false&pinned=false&only_media=false&only_public=true>; 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(`<http://localhost:8080/api/v1/accounts/01F8MH17FWEB39HZJ76B6VXSKF/statuses?limit=20&max_id=01F8MH75CBF9JFX4ZAD54N0W0R&exclude_replies=false&exclude_reblogs=false&pinned_only=false&only_media=true&only_public=true>; rel="next", <http://localhost:8080/api/v1/accounts/01F8MH17FWEB39HZJ76B6VXSKF/statuses?limit=20&min_id=01F8MH75CBF9JFX4ZAD54N0W0R&exclude_replies=false&exclude_reblogs=false&pinned_only=false&only_media=true&only_public=true>; rel="prev"`, result.Header.Get("link"))
suite.Equal(`<http://localhost:8080/api/v1/accounts/01F8MH17FWEB39HZJ76B6VXSKF/statuses?limit=20&max_id=01F8MH75CBF9JFX4ZAD54N0W0R&exclude_replies=false&exclude_reblogs=false&pinned=false&only_media=true&only_public=true>; rel="next", <http://localhost:8080/api/v1/accounts/01F8MH17FWEB39HZJ76B6VXSKF/statuses?limit=20&min_id=01F8MH75CBF9JFX4ZAD54N0W0R&exclude_replies=false&exclude_reblogs=false&pinned=false&only_media=true&only_public=true>; 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) {

View file

@ -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)

View file

@ -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 <http://www.gnu.org/licenses/>.
*/
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)
}

View file

@ -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 <http://www.gnu.org/licenses/>.
*/
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 := &gtsmodel.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 := &gtsmodel.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))
}

View file

@ -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 <http://www.gnu.org/licenses/>.
*/
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)
}

View file

@ -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)

View file

@ -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{}

View file

@ -28,6 +28,7 @@
"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))
}

View file

@ -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 <http://www.gnu.org/licenses/>.
*/
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(&gtsmodel.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(&gtsmodel.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)
}
}

View file

@ -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(),

View file

@ -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

View file

@ -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

View file

@ -31,7 +31,7 @@
// 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),
},

View file

@ -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)
}

View file

@ -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(),

View file

@ -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")

View file

@ -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 <http://www.gnu.org/licenses/>.
*/
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
}

View file

@ -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

View file

@ -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,

View file

@ -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)

View file

@ -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,

View file

@ -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
}

View file

@ -70,7 +70,6 @@ func happyStatus() *gtsmodel.Status {
Likeable: testrig.TrueBool(),
ActivityStreamsType: ap.ObjectNote,
Text: "Test status! #hello",
Pinned: testrig.FalseBool(),
}
}

View file

@ -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"},
})

View file

@ -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(),

View file

@ -271,7 +271,7 @@ main {
box-shadow: $boxshadow;
}
#recent {
#recent, #pinned {
display: flex;
flex-direction: row;
align-items: center;

View file

@ -53,6 +53,18 @@
</div>
</div>
</div>
{{ if .pinned_statuses }}
<h2 id="pinned">
<span>Pinned toots</span>
</h2>
<div class="thread">
{{ range .pinned_statuses }}
<div class="toot expanded">
{{ template "status.tmpl" .}}
</div>
{{ end }}
</div>
{{ end }}
<h2 id="recent">
<span>Latest public toots</span>
{{ if .rssFeed }}