[feature] add paging to account follows, followers and follow requests endpoints (#2186)

This commit is contained in:
kim 2023-09-12 14:00:35 +01:00 committed by GitHub
commit 7293d6029b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
51 changed files with 2281 additions and 641 deletions

View file

@ -22,6 +22,7 @@ import (
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
"github.com/superseriousbusiness/gotosocial/internal/media"
"github.com/superseriousbusiness/gotosocial/internal/oauth"
"github.com/superseriousbusiness/gotosocial/internal/processing/common"
"github.com/superseriousbusiness/gotosocial/internal/state"
"github.com/superseriousbusiness/gotosocial/internal/text"
"github.com/superseriousbusiness/gotosocial/internal/typeutils"
@ -32,6 +33,9 @@ import (
//
// It also contains logic for actions towards accounts such as following, blocking, seeing follows, etc.
type Processor struct {
// common processor logic
c *common.Processor
state *state.State
tc typeutils.TypeConverter
mediaManager *media.Manager
@ -44,6 +48,7 @@ type Processor struct {
// New returns a new account processor.
func New(
common *common.Processor,
state *state.State,
tc typeutils.TypeConverter,
mediaManager *media.Manager,
@ -53,6 +58,7 @@ func New(
parseMention gtsmodel.ParseMentionFunc,
) Processor {
return Processor{
c: common,
state: state,
tc: tc,
mediaManager: mediaManager,

View file

@ -30,6 +30,7 @@ import (
"github.com/superseriousbusiness/gotosocial/internal/oauth"
"github.com/superseriousbusiness/gotosocial/internal/processing"
"github.com/superseriousbusiness/gotosocial/internal/processing/account"
"github.com/superseriousbusiness/gotosocial/internal/processing/common"
"github.com/superseriousbusiness/gotosocial/internal/state"
"github.com/superseriousbusiness/gotosocial/internal/storage"
"github.com/superseriousbusiness/gotosocial/internal/transport"
@ -113,7 +114,8 @@ func (suite *AccountStandardTestSuite) SetupTest() {
suite.emailSender = testrig.NewEmailSender("../../../web/template/", suite.sentEmails)
filter := visibility.NewFilter(&suite.state)
suite.accountProcessor = account.New(&suite.state, suite.tc, suite.mediaManager, suite.oauthServer, suite.federator, filter, processing.GetParseMentionFunc(suite.db, suite.federator))
common := common.New(&suite.state, suite.tc, suite.federator, filter)
suite.accountProcessor = account.New(&common, &suite.state, suite.tc, suite.mediaManager, suite.oauthServer, suite.federator, filter, processing.GetParseMentionFunc(suite.db, suite.federator))
testrig.StandardDBSetup(suite.db, nil)
testrig.StandardStorageSetup(suite.storage, "../../../testrig/media")
}

View file

@ -28,8 +28,11 @@ import (
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
"github.com/superseriousbusiness/gotosocial/internal/id"
"github.com/superseriousbusiness/gotosocial/internal/log"
"github.com/superseriousbusiness/gotosocial/internal/messages"
"github.com/superseriousbusiness/gotosocial/internal/paging"
"github.com/superseriousbusiness/gotosocial/internal/uris"
"github.com/superseriousbusiness/gotosocial/internal/util"
)
// BlockCreate handles the creation of a block from requestingAccount to targetAccountID, either remote or local.
@ -128,6 +131,53 @@ func (p *Processor) BlockRemove(ctx context.Context, requestingAccount *gtsmodel
return p.RelationshipGet(ctx, requestingAccount, targetAccountID)
}
// BlocksGet ...
func (p *Processor) BlocksGet(
ctx context.Context,
requestingAccount *gtsmodel.Account,
page *paging.Page,
) (*apimodel.PageableResponse, gtserror.WithCode) {
blocks, err := p.state.DB.GetAccountBlocks(ctx,
requestingAccount.ID,
page,
)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
return nil, gtserror.NewErrorInternalError(err)
}
// Check for empty response.
count := len(blocks)
if len(blocks) == 0 {
return util.EmptyPageableResponse(), nil
}
items := make([]interface{}, 0, count)
for _, block := range blocks {
// Convert target account to frontend API model. (target will never be nil)
account, err := p.tc.AccountToAPIAccountBlocked(ctx, block.TargetAccount)
if err != nil {
log.Errorf(ctx, "error converting account to public api account: %v", err)
continue
}
// Append target to return items.
items = append(items, account)
}
// Get the lowest and highest
// ID values, used for paging.
lo := blocks[count-1].ID
hi := blocks[0].ID
return paging.PackageResponse(paging.ResponseParams{
Items: items,
Path: "/api/v1/blocks",
Next: page.Next(lo, hi),
Prev: page.Prev(lo, hi),
}), nil
}
func (p *Processor) getBlockTarget(ctx context.Context, requestingAccount *gtsmodel.Account, targetAccountID string) (*gtsmodel.Account, *gtsmodel.Block, gtserror.WithCode) {
// Account should not block or unblock itself.
if requestingAccount.ID == targetAccountID {

View file

@ -160,7 +160,7 @@ func (p *Processor) deleteUserAndTokensForAccount(ctx context.Context, account *
// - Follow requests created by account.
func (p *Processor) deleteAccountFollows(ctx context.Context, account *gtsmodel.Account) error {
// Delete follows targeting this account.
followedBy, err := p.state.DB.GetAccountFollowers(ctx, account.ID)
followedBy, err := p.state.DB.GetAccountFollowers(ctx, account.ID, nil)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
return gtserror.Newf("db error getting follows targeting account %s: %w", account.ID, err)
}
@ -172,7 +172,7 @@ func (p *Processor) deleteAccountFollows(ctx context.Context, account *gtsmodel.
}
// Delete follow requests targeting this account.
followRequestedBy, err := p.state.DB.GetAccountFollowRequests(ctx, account.ID)
followRequestedBy, err := p.state.DB.GetAccountFollowRequests(ctx, account.ID, nil)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
return gtserror.Newf("db error getting follow requests targeting account %s: %w", account.ID, err)
}
@ -193,7 +193,7 @@ func (p *Processor) deleteAccountFollows(ctx context.Context, account *gtsmodel.
)
// Delete follows originating from this account.
following, err := p.state.DB.GetAccountFollows(ctx, account.ID)
following, err := p.state.DB.GetAccountFollows(ctx, account.ID, nil)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
return gtserror.Newf("db error getting follows owned by account %s: %w", account.ID, err)
}
@ -211,7 +211,7 @@ func (p *Processor) deleteAccountFollows(ctx context.Context, account *gtsmodel.
}
// Delete follow requests originating from this account.
followRequesting, err := p.state.DB.GetAccountFollowRequesting(ctx, account.ID)
followRequesting, err := p.state.DB.GetAccountFollowRequesting(ctx, account.ID, nil)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
return gtserror.Newf("db error getting follow requests owned by account %s: %w", account.ID, err)
}

View file

@ -20,7 +20,6 @@ package account
import (
"context"
"errors"
"fmt"
"github.com/superseriousbusiness/gotosocial/internal/ap"
apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
@ -35,7 +34,7 @@ import (
// FollowCreate handles a follow request to an account, either remote or local.
func (p *Processor) FollowCreate(ctx context.Context, requestingAccount *gtsmodel.Account, form *apimodel.AccountFollowRequest) (*apimodel.Relationship, gtserror.WithCode) {
targetAccount, errWithCode := p.getFollowTarget(ctx, requestingAccount.ID, form.ID)
targetAccount, errWithCode := p.getFollowTarget(ctx, requestingAccount, form.ID)
if errWithCode != nil {
return nil, errWithCode
}
@ -46,7 +45,7 @@ func (p *Processor) FollowCreate(ctx context.Context, requestingAccount *gtsmode
requestingAccount.ID,
targetAccount.ID,
); err != nil && !errors.Is(err, db.ErrNoEntries) {
err = fmt.Errorf("FollowCreate: db error checking existing follow: %w", err)
err = gtserror.Newf("db error checking existing follow: %w", err)
return nil, gtserror.NewErrorInternalError(err)
} else if follow != nil {
// Already follows, update if necessary + return relationship.
@ -66,7 +65,7 @@ func (p *Processor) FollowCreate(ctx context.Context, requestingAccount *gtsmode
requestingAccount.ID,
targetAccount.ID,
); err != nil && !errors.Is(err, db.ErrNoEntries) {
err = fmt.Errorf("FollowCreate: db error checking existing follow request: %w", err)
err = gtserror.Newf("db error checking existing follow request: %w", err)
return nil, gtserror.NewErrorInternalError(err)
} else if followRequest != nil {
// Already requested, update if necessary + return relationship.
@ -100,7 +99,7 @@ func (p *Processor) FollowCreate(ctx context.Context, requestingAccount *gtsmode
}
if err := p.state.DB.PutFollowRequest(ctx, fr); err != nil {
err = fmt.Errorf("FollowCreate: error creating follow request in db: %s", err)
err = gtserror.Newf("error creating follow request in db: %s", err)
return nil, gtserror.NewErrorInternalError(err)
}
@ -112,7 +111,7 @@ func (p *Processor) FollowCreate(ctx context.Context, requestingAccount *gtsmode
// Because we know the requestingAccount is also
// local, we don't need to federate the accept out.
if _, err := p.state.DB.AcceptFollowRequest(ctx, requestingAccount.ID, form.ID); err != nil {
err = fmt.Errorf("FollowCreate: error accepting follow request for local unlocked account: %w", err)
err = gtserror.Newf("error accepting follow request for local unlocked account: %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
} else if targetAccount.IsRemote() {
@ -132,7 +131,7 @@ func (p *Processor) FollowCreate(ctx context.Context, requestingAccount *gtsmode
// FollowRemove handles the removal of a follow/follow request to an account, either remote or local.
func (p *Processor) FollowRemove(ctx context.Context, requestingAccount *gtsmodel.Account, targetAccountID string) (*apimodel.Relationship, gtserror.WithCode) {
targetAccount, errWithCode := p.getFollowTarget(ctx, requestingAccount.ID, targetAccountID)
targetAccount, errWithCode := p.getFollowTarget(ctx, requestingAccount, targetAccountID)
if errWithCode != nil {
return nil, errWithCode
}
@ -140,7 +139,7 @@ func (p *Processor) FollowRemove(ctx context.Context, requestingAccount *gtsmode
// Unfollow and deal with side effects.
msgs, err := p.unfollow(ctx, requestingAccount, targetAccount)
if err != nil {
return nil, gtserror.NewErrorNotFound(fmt.Errorf("FollowRemove: account %s not found in the db: %s", targetAccountID, err))
return nil, gtserror.NewErrorNotFound(gtserror.Newf("account %s not found in the db: %s", targetAccountID, err))
}
// Batch queue accreted client api messages.
@ -166,7 +165,6 @@ func (p *Processor) updateFollow(
currentNotify *bool,
update func(...string) error,
) (*apimodel.Relationship, gtserror.WithCode) {
if form.Reblogs == nil && form.Notify == nil {
// There's nothing to update.
return p.RelationshipGet(ctx, requestingAccount, form.ID)
@ -192,7 +190,7 @@ func (p *Processor) updateFollow(
}
if err := update(columns...); err != nil {
err = fmt.Errorf("updateFollow: error updating existing follow (request): %w", err)
err = gtserror.Newf("error updating existing follow (request): %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
@ -201,38 +199,23 @@ func (p *Processor) updateFollow(
// getFollowTarget is a convenience function which:
// - Checks if account is trying to follow/unfollow itself.
// - Returns not found if there's a block in place between accounts.
// - Returns not found if target should not be visible to requester.
// - Returns target account according to its id.
func (p *Processor) getFollowTarget(ctx context.Context, requestingAccountID string, targetAccountID string) (*gtsmodel.Account, gtserror.WithCode) {
func (p *Processor) getFollowTarget(ctx context.Context, requester *gtsmodel.Account, targetID string) (*gtsmodel.Account, gtserror.WithCode) {
// Check for requester.
if requester == nil {
err := errors.New("no authorized user")
return nil, gtserror.NewErrorUnauthorized(err)
}
// Account can't follow or unfollow itself.
if requestingAccountID == targetAccountID {
if requester.ID == targetID {
err := errors.New("account can't follow or unfollow itself")
return nil, gtserror.NewErrorNotAcceptable(err)
}
// Do nothing if a block exists in either direction between accounts.
if blocked, err := p.state.DB.IsEitherBlocked(ctx, requestingAccountID, targetAccountID); err != nil {
err = fmt.Errorf("db error checking block between accounts: %w", err)
return nil, gtserror.NewErrorInternalError(err)
} else if blocked {
err = errors.New("block exists between accounts")
return nil, gtserror.NewErrorNotFound(err)
}
// Ensure target account retrievable.
targetAccount, err := p.state.DB.GetAccountByID(ctx, targetAccountID)
if err != nil {
if !errors.Is(err, db.ErrNoEntries) {
// Real db error.
err = fmt.Errorf("db error looking for target account %s: %w", targetAccountID, err)
return nil, gtserror.NewErrorInternalError(err)
}
// Account not found.
err = fmt.Errorf("target account %s not found in the db", targetAccountID)
return nil, gtserror.NewErrorNotFound(err, err.Error())
}
return targetAccount, nil
// Fetch the target account for requesting user account.
return p.c.GetVisibleTargetAccount(ctx, requester, targetID)
}
// unfollow is a convenience function for having requesting account
@ -248,7 +231,7 @@ func (p *Processor) unfollow(ctx context.Context, requestingAccount *gtsmodel.Ac
// Get follow from requesting account to target account.
follow, err := p.state.DB.GetFollow(ctx, requestingAccount.ID, targetAccount.ID)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
err = fmt.Errorf("unfollow: error getting follow from %s targeting %s: %w", requestingAccount.ID, targetAccount.ID, err)
err = gtserror.Newf("error getting follow from %s targeting %s: %w", requestingAccount.ID, targetAccount.ID, err)
return nil, err
}
@ -257,7 +240,7 @@ func (p *Processor) unfollow(ctx context.Context, requestingAccount *gtsmodel.Ac
err = p.state.DB.DeleteFollowByID(ctx, follow.ID)
if err != nil {
if !errors.Is(err, db.ErrNoEntries) {
err = fmt.Errorf("unfollow: error deleting request from %s targeting %s: %w", requestingAccount.ID, targetAccount.ID, err)
err = gtserror.Newf("error deleting request from %s targeting %s: %w", requestingAccount.ID, targetAccount.ID, err)
return nil, err
}
@ -284,7 +267,7 @@ func (p *Processor) unfollow(ctx context.Context, requestingAccount *gtsmodel.Ac
// Get follow request from requesting account to target account.
followReq, err := p.state.DB.GetFollowRequest(ctx, requestingAccount.ID, targetAccount.ID)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
err = fmt.Errorf("unfollow: error getting follow request from %s targeting %s: %w", requestingAccount.ID, targetAccount.ID, err)
err = gtserror.Newf("error getting follow request from %s targeting %s: %w", requestingAccount.ID, targetAccount.ID, err)
return nil, err
}
@ -293,7 +276,7 @@ func (p *Processor) unfollow(ctx context.Context, requestingAccount *gtsmodel.Ac
err = p.state.DB.DeleteFollowRequestByID(ctx, followReq.ID)
if err != nil {
if !errors.Is(err, db.ErrNoEntries) {
err = fmt.Errorf("unfollow: error deleting follow request from %s targeting %s: %w", requestingAccount.ID, targetAccount.ID, err)
err = gtserror.Newf("error deleting follow request from %s targeting %s: %w", requestingAccount.ID, targetAccount.ID, err)
return nil, err
}

View file

@ -0,0 +1,119 @@
// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package account
import (
"context"
"errors"
"github.com/superseriousbusiness/gotosocial/internal/ap"
apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
"github.com/superseriousbusiness/gotosocial/internal/db"
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
"github.com/superseriousbusiness/gotosocial/internal/messages"
"github.com/superseriousbusiness/gotosocial/internal/paging"
)
// FollowRequestAccept handles the accepting of a follow request from the sourceAccountID to the requestingAccount (the currently authorized account).
func (p *Processor) FollowRequestAccept(ctx context.Context, requestingAccount *gtsmodel.Account, sourceAccountID string) (*apimodel.Relationship, gtserror.WithCode) {
follow, err := p.state.DB.AcceptFollowRequest(ctx, sourceAccountID, requestingAccount.ID)
if err != nil {
return nil, gtserror.NewErrorNotFound(err)
}
if follow.Account != nil {
// Only enqueue work in the case we have a request creating account stored.
// NOTE: due to how AcceptFollowRequest works, the inverse shouldn't be possible.
p.state.Workers.EnqueueClientAPI(ctx, messages.FromClientAPI{
APObjectType: ap.ActivityFollow,
APActivityType: ap.ActivityAccept,
GTSModel: follow,
OriginAccount: follow.Account,
TargetAccount: follow.TargetAccount,
})
}
return p.RelationshipGet(ctx, requestingAccount, sourceAccountID)
}
// FollowRequestReject handles the rejection of a follow request from the sourceAccountID to the requestingAccount (the currently authorized account).
func (p *Processor) FollowRequestReject(ctx context.Context, requestingAccount *gtsmodel.Account, sourceAccountID string) (*apimodel.Relationship, gtserror.WithCode) {
followRequest, err := p.state.DB.GetFollowRequest(ctx, sourceAccountID, requestingAccount.ID)
if err != nil {
return nil, gtserror.NewErrorNotFound(err)
}
err = p.state.DB.RejectFollowRequest(ctx, sourceAccountID, requestingAccount.ID)
if err != nil {
return nil, gtserror.NewErrorNotFound(err)
}
if followRequest.Account != nil {
// Only enqueue work in the case we have a request creating account stored.
// NOTE: due to how GetFollowRequest works, the inverse shouldn't be possible.
p.state.Workers.EnqueueClientAPI(ctx, messages.FromClientAPI{
APObjectType: ap.ActivityFollow,
APActivityType: ap.ActivityReject,
GTSModel: followRequest,
OriginAccount: followRequest.Account,
TargetAccount: followRequest.TargetAccount,
})
}
return p.RelationshipGet(ctx, requestingAccount, sourceAccountID)
}
// FollowRequestsGet fetches a list of the accounts that are follow requesting the given requestingAccount (the currently authorized account).
func (p *Processor) FollowRequestsGet(ctx context.Context, requestingAccount *gtsmodel.Account, page *paging.Page) (*apimodel.PageableResponse, gtserror.WithCode) {
// Fetch follow requests targeting the given requesting account model.
followRequests, err := p.state.DB.GetAccountFollowRequests(ctx, requestingAccount.ID, page)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
return nil, gtserror.NewErrorInternalError(err)
}
// Check for empty response.
count := len(followRequests)
if count == 0 {
return paging.EmptyResponse(), nil
}
// Get the lowest and highest
// ID values, used for paging.
lo := followRequests[count-1].ID
hi := followRequests[0].ID
// Func to fetch follow source at index.
getIdx := func(i int) *gtsmodel.Account {
return followRequests[i].Account
}
// Get a filtered slice of public API account models.
items := p.c.GetVisibleAPIAccountsPaged(ctx,
requestingAccount,
getIdx,
count,
)
return paging.PackageResponse(paging.ResponseParams{
Items: items,
Path: "/api/v1/follow_requests",
Next: page.Next(lo, hi),
Prev: page.Prev(lo, hi),
}), nil
}

View file

@ -20,128 +20,120 @@ package account
import (
"context"
"errors"
"fmt"
apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
"github.com/superseriousbusiness/gotosocial/internal/db"
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
"github.com/superseriousbusiness/gotosocial/internal/log"
"github.com/superseriousbusiness/gotosocial/internal/paging"
)
// FollowersGet fetches a list of the target account's followers.
func (p *Processor) FollowersGet(ctx context.Context, requestingAccount *gtsmodel.Account, targetAccountID string) ([]apimodel.Account, gtserror.WithCode) {
if blocked, err := p.state.DB.IsEitherBlocked(ctx, requestingAccount.ID, targetAccountID); err != nil {
err = fmt.Errorf("FollowersGet: db error checking block: %w", err)
func (p *Processor) FollowersGet(ctx context.Context, requestingAccount *gtsmodel.Account, targetAccountID string, page *paging.Page) (*apimodel.PageableResponse, gtserror.WithCode) {
// Fetch target account to check it exists, and visibility of requester->target.
_, errWithCode := p.c.GetVisibleTargetAccount(ctx, requestingAccount, targetAccountID)
if errWithCode != nil {
return nil, errWithCode
}
follows, err := p.state.DB.GetAccountFollowers(ctx, targetAccountID, page)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
err = gtserror.Newf("db error getting followers: %w", err)
return nil, gtserror.NewErrorInternalError(err)
} else if blocked {
err = errors.New("FollowersGet: block exists between accounts")
return nil, gtserror.NewErrorNotFound(err)
}
follows, err := p.state.DB.GetAccountFollowers(ctx, targetAccountID)
if err != nil {
if !errors.Is(err, db.ErrNoEntries) {
err = fmt.Errorf("FollowersGet: db error getting followers: %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
return []apimodel.Account{}, nil
// Check for empty response.
count := len(follows)
if count == 0 {
return paging.EmptyResponse(), nil
}
return p.accountsFromFollows(ctx, follows, requestingAccount.ID)
// Get the lowest and highest
// ID values, used for paging.
lo := follows[count-1].ID
hi := follows[0].ID
// Func to fetch follow source at index.
getIdx := func(i int) *gtsmodel.Account {
return follows[i].Account
}
// Get a filtered slice of public API account models.
items := p.c.GetVisibleAPIAccountsPaged(ctx,
requestingAccount,
getIdx,
len(follows),
)
return paging.PackageResponse(paging.ResponseParams{
Items: items,
Path: "/api/v1/accounts/" + targetAccountID + "/followers",
Next: page.Next(lo, hi),
Prev: page.Prev(lo, hi),
}), nil
}
// FollowingGet fetches a list of the accounts that target account is following.
func (p *Processor) FollowingGet(ctx context.Context, requestingAccount *gtsmodel.Account, targetAccountID string) ([]apimodel.Account, gtserror.WithCode) {
if blocked, err := p.state.DB.IsEitherBlocked(ctx, requestingAccount.ID, targetAccountID); err != nil {
err = fmt.Errorf("FollowingGet: db error checking block: %w", err)
func (p *Processor) FollowingGet(ctx context.Context, requestingAccount *gtsmodel.Account, targetAccountID string, page *paging.Page) (*apimodel.PageableResponse, gtserror.WithCode) {
// Fetch target account to check it exists, and visibility of requester->target.
_, errWithCode := p.c.GetVisibleTargetAccount(ctx, requestingAccount, targetAccountID)
if errWithCode != nil {
return nil, errWithCode
}
// Fetch known accounts that follow given target account ID.
follows, err := p.state.DB.GetAccountFollows(ctx, targetAccountID, page)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
err = gtserror.Newf("db error getting followers: %w", err)
return nil, gtserror.NewErrorInternalError(err)
} else if blocked {
err = errors.New("FollowingGet: block exists between accounts")
return nil, gtserror.NewErrorNotFound(err)
}
follows, err := p.state.DB.GetAccountFollows(ctx, targetAccountID)
if err != nil {
if !errors.Is(err, db.ErrNoEntries) {
err = fmt.Errorf("FollowingGet: db error getting followers: %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
return []apimodel.Account{}, nil
// Check for empty response.
count := len(follows)
if count == 0 {
return paging.EmptyResponse(), nil
}
return p.targetAccountsFromFollows(ctx, follows, requestingAccount.ID)
// Get the lowest and highest
// ID values, used for paging.
lo := follows[count-1].ID
hi := follows[0].ID
// Func to fetch follow source at index.
getIdx := func(i int) *gtsmodel.Account {
return follows[i].TargetAccount
}
// Get a filtered slice of public API account models.
items := p.c.GetVisibleAPIAccountsPaged(ctx,
requestingAccount,
getIdx,
len(follows),
)
return paging.PackageResponse(paging.ResponseParams{
Items: items,
Path: "/api/v1/accounts/" + targetAccountID + "/following",
Next: page.Next(lo, hi),
Prev: page.Prev(lo, hi),
}), nil
}
// RelationshipGet returns a relationship model describing the relationship of the targetAccount to the Authed account.
func (p *Processor) RelationshipGet(ctx context.Context, requestingAccount *gtsmodel.Account, targetAccountID string) (*apimodel.Relationship, gtserror.WithCode) {
if requestingAccount == nil {
return nil, gtserror.NewErrorForbidden(errors.New("not authed"))
return nil, gtserror.NewErrorForbidden(gtserror.New("not authed"))
}
gtsR, err := p.state.DB.GetRelationship(ctx, requestingAccount.ID, targetAccountID)
if err != nil {
return nil, gtserror.NewErrorInternalError(fmt.Errorf("error getting relationship: %s", err))
return nil, gtserror.NewErrorInternalError(gtserror.Newf("error getting relationship: %s", err))
}
r, err := p.tc.RelationshipToAPIRelationship(ctx, gtsR)
if err != nil {
return nil, gtserror.NewErrorInternalError(fmt.Errorf("error converting relationship: %s", err))
return nil, gtserror.NewErrorInternalError(gtserror.Newf("error converting relationship: %s", err))
}
return r, nil
}
func (p *Processor) accountsFromFollows(ctx context.Context, follows []*gtsmodel.Follow, requestingAccountID string) ([]apimodel.Account, gtserror.WithCode) {
accounts := make([]apimodel.Account, 0, len(follows))
for _, follow := range follows {
if follow.Account == nil {
// No account set for some reason; just skip.
log.WithContext(ctx).WithField("follow", follow).Warn("follow had no associated account")
continue
}
if blocked, err := p.state.DB.IsEitherBlocked(ctx, requestingAccountID, follow.AccountID); err != nil {
err = fmt.Errorf("accountsFromFollows: db error checking block: %w", err)
return nil, gtserror.NewErrorInternalError(err)
} else if blocked {
continue
}
account, err := p.tc.AccountToAPIAccountPublic(ctx, follow.Account)
if err != nil {
err = fmt.Errorf("accountsFromFollows: error converting account to api account: %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
accounts = append(accounts, *account)
}
return accounts, nil
}
func (p *Processor) targetAccountsFromFollows(ctx context.Context, follows []*gtsmodel.Follow, requestingAccountID string) ([]apimodel.Account, gtserror.WithCode) {
accounts := make([]apimodel.Account, 0, len(follows))
for _, follow := range follows {
if follow.TargetAccount == nil {
// No account set for some reason; just skip.
log.WithContext(ctx).WithField("follow", follow).Warn("follow had no associated target account")
continue
}
if blocked, err := p.state.DB.IsEitherBlocked(ctx, requestingAccountID, follow.TargetAccountID); err != nil {
err = fmt.Errorf("targetAccountsFromFollows: db error checking block: %w", err)
return nil, gtserror.NewErrorInternalError(err)
} else if blocked {
continue
}
account, err := p.tc.AccountToAPIAccountPublic(ctx, follow.TargetAccount)
if err != nil {
err = fmt.Errorf("targetAccountsFromFollows: error converting account to api account: %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
accounts = append(accounts, *account)
}
return accounts, nil
}

View file

@ -1,86 +0,0 @@
// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package processing
import (
"context"
"errors"
apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
"github.com/superseriousbusiness/gotosocial/internal/db"
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
"github.com/superseriousbusiness/gotosocial/internal/log"
"github.com/superseriousbusiness/gotosocial/internal/paging"
"github.com/superseriousbusiness/gotosocial/internal/util"
)
// BlocksGet ...
func (p *Processor) BlocksGet(
ctx context.Context,
requestingAccount *gtsmodel.Account,
page *paging.Page,
) (*apimodel.PageableResponse, gtserror.WithCode) {
blocks, err := p.state.DB.GetAccountBlocks(ctx,
requestingAccount.ID,
page,
)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
return nil, gtserror.NewErrorInternalError(err)
}
// Check for zero length.
count := len(blocks)
if len(blocks) == 0 {
return util.EmptyPageableResponse(), nil
}
var (
items = make([]interface{}, 0, count)
// Set next + prev values before API converting
// so the caller can still page even on error.
nextMaxIDValue = blocks[count-1].ID
prevMinIDValue = blocks[0].ID
)
for _, block := range blocks {
if block.TargetAccount == nil {
// All models should be populated at this point.
log.Warnf(ctx, "block target account was nil: %v", err)
continue
}
// Convert target account to frontend API model.
account, err := p.tc.AccountToAPIAccountBlocked(ctx, block.TargetAccount)
if err != nil {
log.Errorf(ctx, "error converting account to public api account: %v", err)
continue
}
// Append target to return items.
items = append(items, account)
}
return paging.PackageResponse(paging.ResponseParams{
Items: items,
Path: "/api/v1/blocks",
Next: page.Next(nextMaxIDValue),
Prev: page.Prev(prevMinIDValue),
}), nil
}

View file

@ -0,0 +1,238 @@
// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package common
import (
"context"
"errors"
apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
"github.com/superseriousbusiness/gotosocial/internal/db"
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
"github.com/superseriousbusiness/gotosocial/internal/log"
)
// GetTargetAccountBy fetches the target account with db load function, given the authorized (or, nil) requester's
// account. This returns an approprate gtserror.WithCode accounting (ha) for not found and visibility to requester.
func (p *Processor) GetTargetAccountBy(
ctx context.Context,
requester *gtsmodel.Account,
getTargetFromDB func() (*gtsmodel.Account, error),
) (
account *gtsmodel.Account,
visible bool,
errWithCode gtserror.WithCode,
) {
// Fetch the target account from db.
target, err := getTargetFromDB()
if err != nil && !errors.Is(err, db.ErrNoEntries) {
return nil, false, gtserror.NewErrorInternalError(err)
}
if target == nil {
// DB loader could not find account in database.
err := errors.New("target account not found")
return nil, false, gtserror.NewErrorNotFound(err)
}
// Check whether target account is visible to requesting account.
visible, err = p.filter.AccountVisible(ctx, requester, target)
if err != nil {
return nil, false, gtserror.NewErrorInternalError(err)
}
if requester != nil && visible {
// Ensure the account is up-to-date.
p.federator.RefreshAccountAsync(ctx,
requester.Username,
target,
nil,
false,
)
}
return target, visible, nil
}
// GetTargetAccountByID is a call-through to GetTargetAccountBy() using the db GetAccountByID() function.
func (p *Processor) GetTargetAccountByID(
ctx context.Context,
requester *gtsmodel.Account,
targetID string,
) (
account *gtsmodel.Account,
visible bool,
errWithCode gtserror.WithCode,
) {
return p.GetTargetAccountBy(ctx, requester, func() (*gtsmodel.Account, error) {
return p.state.DB.GetAccountByID(ctx, targetID)
})
}
// GetVisibleTargetAccount calls GetTargetAccountByID(),
// but converts a non-visible result to not-found error.
func (p *Processor) GetVisibleTargetAccount(
ctx context.Context,
requester *gtsmodel.Account,
targetID string,
) (
account *gtsmodel.Account,
errWithCode gtserror.WithCode,
) {
// Fetch the target account by ID from the database.
target, visible, errWithCode := p.GetTargetAccountByID(ctx,
requester,
targetID,
)
if errWithCode != nil {
return nil, errWithCode
}
if !visible {
// Pretend account doesn't exist if not visible.
err := errors.New("target account not found")
return nil, gtserror.NewErrorNotFound(err)
}
return target, nil
}
// GetAPIAccount fetches the appropriate API account model depending on whether requester = target.
func (p *Processor) GetAPIAccount(
ctx context.Context,
requester *gtsmodel.Account,
target *gtsmodel.Account,
) (
apiAcc *apimodel.Account,
errWithCode gtserror.WithCode,
) {
var err error
if requester != nil && requester.ID == target.ID {
// Only return sensitive account model _if_ requester = target.
apiAcc, err = p.converter.AccountToAPIAccountSensitive(ctx, target)
} else {
// Else, fall back to returning the public account model.
apiAcc, err = p.converter.AccountToAPIAccountPublic(ctx, target)
}
if err != nil {
err := gtserror.Newf("error converting account: %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
return apiAcc, nil
}
// GetAPIAccountBlocked fetches the limited "blocked" account model for given target.
func (p *Processor) GetAPIAccountBlocked(
ctx context.Context,
targetAcc *gtsmodel.Account,
) (
apiAcc *apimodel.Account,
errWithCode gtserror.WithCode,
) {
apiAccount, err := p.converter.AccountToAPIAccountBlocked(ctx, targetAcc)
if err != nil {
err = gtserror.Newf("error converting account: %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
return apiAccount, nil
}
// GetVisibleAPIAccounts converts an array of gtsmodel.Accounts (inputted by next function) into
// public API model accounts, checking first for visibility. Please note that all errors will be
// logged at ERROR level, but will not be returned. Callers are likely to run into show-stopping
// errors in the lead-up to this function, whereas calling this should not be a show-stopper.
func (p *Processor) GetVisibleAPIAccounts(
ctx context.Context,
requester *gtsmodel.Account,
next func(int) *gtsmodel.Account,
length int,
) []*apimodel.Account {
return p.getVisibleAPIAccounts(ctx, 3, requester, next, length)
}
// GetVisibleAPIAccountsPaged is functionally equivalent to GetVisibleAPIAccounts(),
// except the accounts are returned as a converted slice of accounts as interface{}.
func (p *Processor) GetVisibleAPIAccountsPaged(
ctx context.Context,
requester *gtsmodel.Account,
next func(int) *gtsmodel.Account,
length int,
) []interface{} {
accounts := p.getVisibleAPIAccounts(ctx, 3, requester, next, length)
if len(accounts) == 0 {
return nil
}
items := make([]interface{}, len(accounts))
for i, account := range accounts {
items[i] = account
}
return items
}
func (p *Processor) getVisibleAPIAccounts(
ctx context.Context,
calldepth int, // used to skip wrapping func above these's names
requester *gtsmodel.Account,
next func(int) *gtsmodel.Account,
length int,
) []*apimodel.Account {
// Start new log entry with
// the above calling func's name.
l := log.
WithContext(ctx).
WithField("caller", log.Caller(calldepth+1))
// Preallocate slice according to expected length.
accounts := make([]*apimodel.Account, 0, length)
for i := 0; i < length; i++ {
// Get next account.
account := next(i)
if account == nil {
continue
}
// Check whether this account is visible to requesting account.
visible, err := p.filter.AccountVisible(ctx, requester, account)
if err != nil {
l.Errorf("error checking account visibility: %v", err)
continue
}
if !visible {
// Not visible to requester.
continue
}
// Convert the account to a public API model representation.
apiAcc, err := p.converter.AccountToAPIAccountPublic(ctx, account)
if err != nil {
l.Errorf("error converting account: %v", err)
continue
}
// Append API model to return slice.
accounts = append(accounts, apiAcc)
}
return accounts
}

View file

@ -0,0 +1,50 @@
// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package common
import (
"github.com/superseriousbusiness/gotosocial/internal/federation"
"github.com/superseriousbusiness/gotosocial/internal/state"
"github.com/superseriousbusiness/gotosocial/internal/typeutils"
"github.com/superseriousbusiness/gotosocial/internal/visibility"
)
// Processor provides a processor with logic
// common to multiple logical domains of the
// processing subsection of the codebase.
type Processor struct {
state *state.State
converter typeutils.TypeConverter
federator federation.Federator
filter *visibility.Filter
}
// New returns a new Processor instance.
func New(
state *state.State,
converter typeutils.TypeConverter,
federator federation.Federator,
filter *visibility.Filter,
) Processor {
return Processor{
state: state,
converter: converter,
federator: federator,
filter: filter,
}
}

View file

@ -0,0 +1,248 @@
// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package common
import (
"context"
"errors"
apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
"github.com/superseriousbusiness/gotosocial/internal/db"
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
"github.com/superseriousbusiness/gotosocial/internal/log"
)
// GetTargetStatusBy fetches the target status with db load function, given the authorized (or, nil) requester's
// account. This returns an approprate gtserror.WithCode accounting for not found and visibility to requester.
func (p *Processor) GetTargetStatusBy(
ctx context.Context,
requester *gtsmodel.Account,
getTargetFromDB func() (*gtsmodel.Status, error),
) (
status *gtsmodel.Status,
visible bool,
errWithCode gtserror.WithCode,
) {
// Fetch the target status from db.
target, err := getTargetFromDB()
if err != nil && !errors.Is(err, db.ErrNoEntries) {
return nil, false, gtserror.NewErrorInternalError(err)
}
if target == nil {
// DB loader could not find status in database.
err := errors.New("target status not found")
return nil, false, gtserror.NewErrorNotFound(err)
}
// Check whether target status is visible to requesting account.
visible, err = p.filter.StatusVisible(ctx, requester, target)
if err != nil {
return nil, false, gtserror.NewErrorInternalError(err)
}
if requester != nil && visible {
// Ensure remote status is up-to-date.
p.federator.RefreshStatusAsync(ctx,
requester.Username,
target,
nil,
false,
)
}
return target, visible, nil
}
// GetTargetStatusByID is a call-through to GetTargetStatus() using the db GetStatusByID() function.
func (p *Processor) GetTargetStatusByID(
ctx context.Context,
requester *gtsmodel.Account,
targetID string,
) (
status *gtsmodel.Status,
visible bool,
errWithCode gtserror.WithCode,
) {
return p.GetTargetStatusBy(ctx, requester, func() (*gtsmodel.Status, error) {
return p.state.DB.GetStatusByID(ctx, targetID)
})
}
// GetVisibleTargetStatus calls GetTargetStatusByID(),
// but converts a non-visible result to not-found error.
func (p *Processor) GetVisibleTargetStatus(
ctx context.Context,
requester *gtsmodel.Account,
targetID string,
) (
status *gtsmodel.Status,
errWithCode gtserror.WithCode,
) {
// Fetch the target status by ID from the database.
target, visible, errWithCode := p.GetTargetStatusByID(ctx,
requester,
targetID,
)
if errWithCode != nil {
return nil, errWithCode
}
if !visible {
// Target should not be seen by requester.
err := errors.New("target status not found")
return nil, gtserror.NewErrorNotFound(err)
}
return target, nil
}
// GetAPIStatus fetches the appropriate API status model for target.
func (p *Processor) GetAPIStatus(
ctx context.Context,
requester *gtsmodel.Account,
target *gtsmodel.Status,
) (
apiStatus *apimodel.Status,
errWithCode gtserror.WithCode,
) {
apiStatus, err := p.converter.StatusToAPIStatus(ctx, target, requester)
if err != nil {
err = gtserror.Newf("error converting status: %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
return apiStatus, nil
}
// GetVisibleAPIStatuses converts an array of gtsmodel.Status (inputted by next function) into
// API model statuses, checking first for visibility. Please note that all errors will be
// logged at ERROR level, but will not be returned. Callers are likely to run into show-stopping
// errors in the lead-up to this function, whereas calling this should not be a show-stopper.
func (p *Processor) GetVisibleAPIStatuses(
ctx context.Context,
requester *gtsmodel.Account,
next func(int) *gtsmodel.Status,
length int,
) []*apimodel.Status {
return p.getVisibleAPIStatuses(ctx, 3, requester, next, length)
}
// GetVisibleAPIStatusesPaged is functionally equivalent to GetVisibleAPIStatuses(),
// except the statuses are returned as a converted slice of statuses as interface{}.
func (p *Processor) GetVisibleAPIStatusesPaged(
ctx context.Context,
requester *gtsmodel.Account,
next func(int) *gtsmodel.Status,
length int,
) []interface{} {
statuses := p.getVisibleAPIStatuses(ctx, 3, requester, next, length)
if len(statuses) == 0 {
return nil
}
items := make([]interface{}, len(statuses))
for i, status := range statuses {
items[i] = status
}
return items
}
func (p *Processor) getVisibleAPIStatuses(
ctx context.Context,
calldepth int, // used to skip wrapping func above these's names
requester *gtsmodel.Account,
next func(int) *gtsmodel.Status,
length int,
) []*apimodel.Status {
// Start new log entry with
// the above calling func's name.
l := log.
WithContext(ctx).
WithField("caller", log.Caller(calldepth+1))
// Preallocate slice according to expected length.
statuses := make([]*apimodel.Status, 0, length)
for i := 0; i < length; i++ {
// Get next status.
status := next(i)
if status == nil {
continue
}
// Check whether this status is visible to requesting account.
visible, err := p.filter.StatusVisible(ctx, requester, status)
if err != nil {
l.Errorf("error checking status visibility: %v", err)
continue
}
if !visible {
// Not visible to requester.
continue
}
// Convert the status to an API model representation.
apiStatus, err := p.converter.StatusToAPIStatus(ctx, status, requester)
if err != nil {
l.Errorf("error converting status: %v", err)
continue
}
// Append API model to return slice.
statuses = append(statuses, apiStatus)
}
return statuses
}
// InvalidateTimelinedStatus is a shortcut function for invalidating the cached
// representation one status in the home timeline and all list timelines of the
// given accountID. It should only be called in cases where a status update
// does *not* need to be passed into the processor via the worker queue, since
// such invalidation will, in that case, be handled by the processor instead.
func (p *Processor) InvalidateTimelinedStatus(ctx context.Context, accountID string, statusID string) error {
// Get lists first + bail if this fails.
lists, err := p.state.DB.GetListsForAccountID(ctx, accountID)
if err != nil {
return gtserror.Newf("db error getting lists for account %s: %w", accountID, err)
}
// Start new log entry with
// the above calling func's name.
l := log.
WithContext(ctx).
WithField("caller", log.Caller(3)).
WithField("accountID", accountID).
WithField("statusID", statusID)
// Unprepare item from home + list timelines, just log
// if something goes wrong since this is not a showstopper.
if err := p.state.Timelines.Home.UnprepareItem(ctx, accountID, statusID); err != nil {
l.Errorf("error unpreparing item from home timeline: %v", err)
}
for _, list := range lists {
if err := p.state.Timelines.List.UnprepareItem(ctx, list.ID, statusID); err != nil {
l.Errorf("error unpreparing item from list timeline %s: %v", list.ID, err)
}
}
return nil
}

View file

@ -1,123 +0,0 @@
// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package processing
import (
"context"
"errors"
"github.com/superseriousbusiness/gotosocial/internal/ap"
apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
"github.com/superseriousbusiness/gotosocial/internal/db"
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
"github.com/superseriousbusiness/gotosocial/internal/log"
"github.com/superseriousbusiness/gotosocial/internal/messages"
"github.com/superseriousbusiness/gotosocial/internal/oauth"
)
func (p *Processor) FollowRequestsGet(ctx context.Context, auth *oauth.Auth) ([]apimodel.Account, gtserror.WithCode) {
followRequests, err := p.state.DB.GetAccountFollowRequests(ctx, auth.Account.ID)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
return nil, gtserror.NewErrorInternalError(err)
}
accts := make([]apimodel.Account, 0, len(followRequests))
for _, followRequest := range followRequests {
if followRequest.Account == nil {
// The creator of the follow doesn't exist,
// just skip this one.
log.WithContext(ctx).WithField("followRequest", followRequest).Warn("follow request had no associated account")
continue
}
apiAcct, err := p.tc.AccountToAPIAccountPublic(ctx, followRequest.Account)
if err != nil {
return nil, gtserror.NewErrorInternalError(err)
}
accts = append(accts, *apiAcct)
}
return accts, nil
}
func (p *Processor) FollowRequestAccept(ctx context.Context, auth *oauth.Auth, accountID string) (*apimodel.Relationship, gtserror.WithCode) {
follow, err := p.state.DB.AcceptFollowRequest(ctx, accountID, auth.Account.ID)
if err != nil {
return nil, gtserror.NewErrorNotFound(err)
}
if follow.Account == nil {
// The creator of the follow doesn't exist,
// so we can't do further processing.
log.WithContext(ctx).WithField("follow", follow).Warn("follow had no associated account")
return p.relationship(ctx, auth.Account.ID, accountID)
}
p.state.Workers.EnqueueClientAPI(ctx, messages.FromClientAPI{
APObjectType: ap.ActivityFollow,
APActivityType: ap.ActivityAccept,
GTSModel: follow,
OriginAccount: follow.Account,
TargetAccount: follow.TargetAccount,
})
return p.relationship(ctx, auth.Account.ID, accountID)
}
func (p *Processor) FollowRequestReject(ctx context.Context, auth *oauth.Auth, accountID string) (*apimodel.Relationship, gtserror.WithCode) {
followRequest, err := p.state.DB.GetFollowRequest(ctx, accountID, auth.Account.ID)
if err != nil {
return nil, gtserror.NewErrorNotFound(err)
}
err = p.state.DB.RejectFollowRequest(ctx, accountID, auth.Account.ID)
if err != nil {
return nil, gtserror.NewErrorNotFound(err)
}
if followRequest.Account == nil {
// The creator of the request doesn't exist,
// so we can't do further processing.
return p.relationship(ctx, auth.Account.ID, accountID)
}
p.state.Workers.EnqueueClientAPI(ctx, messages.FromClientAPI{
APObjectType: ap.ActivityFollow,
APActivityType: ap.ActivityReject,
GTSModel: followRequest,
OriginAccount: followRequest.Account,
TargetAccount: followRequest.TargetAccount,
})
return p.relationship(ctx, auth.Account.ID, accountID)
}
func (p *Processor) relationship(ctx context.Context, accountID string, targetAccountID string) (*apimodel.Relationship, gtserror.WithCode) {
relationship, err := p.state.DB.GetRelationship(ctx, accountID, targetAccountID)
if err != nil {
return nil, gtserror.NewErrorInternalError(err)
}
apiRelationship, err := p.tc.RelationshipToAPIRelationship(ctx, relationship)
if err != nil {
return nil, gtserror.NewErrorInternalError(err)
}
return apiRelationship, nil
}

View file

@ -30,35 +30,57 @@ import (
"github.com/superseriousbusiness/gotosocial/testrig"
)
// TODO: move this to the "internal/processing/account" pkg
type FollowRequestTestSuite struct {
ProcessingStandardTestSuite
}
func (suite *FollowRequestTestSuite) TestFollowRequestAccept() {
requestingAccount := suite.testAccounts["remote_account_2"]
targetAccount := suite.testAccounts["local_account_1"]
// The authed local account we are going to use for HTTP requests
requestingAccount := suite.testAccounts["local_account_1"]
// The remote account whose follow request we are accepting
targetAccount := suite.testAccounts["remote_account_2"]
// put a follow request in the database
fr := &gtsmodel.FollowRequest{
ID: "01FJ1S8DX3STJJ6CEYPMZ1M0R3",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
URI: fmt.Sprintf("%s/follow/01FJ1S8DX3STJJ6CEYPMZ1M0R3", requestingAccount.URI),
AccountID: requestingAccount.ID,
TargetAccountID: targetAccount.ID,
URI: fmt.Sprintf("%s/follow/01FJ1S8DX3STJJ6CEYPMZ1M0R3", targetAccount.URI),
AccountID: targetAccount.ID,
TargetAccountID: requestingAccount.ID,
}
err := suite.db.Put(context.Background(), fr)
suite.NoError(err)
relationship, errWithCode := suite.processor.FollowRequestAccept(context.Background(), suite.testAutheds["local_account_1"], requestingAccount.ID)
relationship, errWithCode := suite.processor.Account().FollowRequestAccept(
context.Background(),
requestingAccount,
targetAccount.ID,
)
suite.NoError(errWithCode)
suite.EqualValues(&apimodel.Relationship{ID: "01FHMQX3GAABWSM0S2VZEC2SWC", Following: false, ShowingReblogs: false, Notifying: false, FollowedBy: true, Blocking: false, BlockedBy: false, Muting: false, MutingNotifications: false, Requested: false, DomainBlocking: false, Endorsed: false, Note: ""}, relationship)
suite.EqualValues(&apimodel.Relationship{
ID: "01FHMQX3GAABWSM0S2VZEC2SWC",
Following: false,
ShowingReblogs: false,
Notifying: false,
FollowedBy: true,
Blocking: false,
BlockedBy: false,
Muting: false,
MutingNotifications: false,
Requested: false,
DomainBlocking: false,
Endorsed: false,
Note: "",
}, relationship)
// accept should be sent to Some_User
var sent [][]byte
if !testrig.WaitFor(func() bool {
sentI, ok := suite.httpClient.SentMessages.Load(requestingAccount.InboxURI)
sentI, ok := suite.httpClient.SentMessages.Load(targetAccount.InboxURI)
if ok {
sent, ok = sentI.([][]byte)
if !ok {
@ -87,41 +109,45 @@ func (suite *FollowRequestTestSuite) TestFollowRequestAccept() {
err = json.Unmarshal(sent[0], accept)
suite.NoError(err)
suite.Equal(targetAccount.URI, accept.Actor)
suite.Equal(requestingAccount.URI, accept.Object.Actor)
suite.Equal(requestingAccount.URI, accept.Actor)
suite.Equal(targetAccount.URI, accept.Object.Actor)
suite.Equal(fr.URI, accept.Object.ID)
suite.Equal(targetAccount.URI, accept.Object.Object)
suite.Equal(targetAccount.URI, accept.Object.To)
suite.Equal(requestingAccount.URI, accept.Object.Object)
suite.Equal(requestingAccount.URI, accept.Object.To)
suite.Equal("Follow", accept.Object.Type)
suite.Equal(requestingAccount.URI, accept.To)
suite.Equal(targetAccount.URI, accept.To)
suite.Equal("Accept", accept.Type)
}
func (suite *FollowRequestTestSuite) TestFollowRequestReject() {
requestingAccount := suite.testAccounts["remote_account_2"]
targetAccount := suite.testAccounts["local_account_1"]
requestingAccount := suite.testAccounts["local_account_1"]
targetAccount := suite.testAccounts["remote_account_2"]
// put a follow request in the database
fr := &gtsmodel.FollowRequest{
ID: "01FJ1S8DX3STJJ6CEYPMZ1M0R3",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
URI: fmt.Sprintf("%s/follow/01FJ1S8DX3STJJ6CEYPMZ1M0R3", requestingAccount.URI),
AccountID: requestingAccount.ID,
TargetAccountID: targetAccount.ID,
URI: fmt.Sprintf("%s/follow/01FJ1S8DX3STJJ6CEYPMZ1M0R3", targetAccount.URI),
AccountID: targetAccount.ID,
TargetAccountID: requestingAccount.ID,
}
err := suite.db.Put(context.Background(), fr)
suite.NoError(err)
relationship, errWithCode := suite.processor.FollowRequestReject(context.Background(), suite.testAutheds["local_account_1"], requestingAccount.ID)
relationship, errWithCode := suite.processor.Account().FollowRequestReject(
context.Background(),
requestingAccount,
targetAccount.ID,
)
suite.NoError(errWithCode)
suite.EqualValues(&apimodel.Relationship{ID: "01FHMQX3GAABWSM0S2VZEC2SWC", Following: false, ShowingReblogs: false, Notifying: false, FollowedBy: false, Blocking: false, BlockedBy: false, Muting: false, MutingNotifications: false, Requested: false, DomainBlocking: false, Endorsed: false, Note: ""}, relationship)
// reject should be sent to Some_User
var sent [][]byte
if !testrig.WaitFor(func() bool {
sentI, ok := suite.httpClient.SentMessages.Load(requestingAccount.InboxURI)
sentI, ok := suite.httpClient.SentMessages.Load(targetAccount.InboxURI)
if ok {
sent, ok = sentI.([][]byte)
if !ok {
@ -150,13 +176,13 @@ func (suite *FollowRequestTestSuite) TestFollowRequestReject() {
err = json.Unmarshal(sent[0], reject)
suite.NoError(err)
suite.Equal(targetAccount.URI, reject.Actor)
suite.Equal(requestingAccount.URI, reject.Object.Actor)
suite.Equal(requestingAccount.URI, reject.Actor)
suite.Equal(targetAccount.URI, reject.Object.Actor)
suite.Equal(fr.URI, reject.Object.ID)
suite.Equal(targetAccount.URI, reject.Object.Object)
suite.Equal(targetAccount.URI, reject.Object.To)
suite.Equal(requestingAccount.URI, reject.Object.Object)
suite.Equal(requestingAccount.URI, reject.Object.To)
suite.Equal("Follow", reject.Object.Type)
suite.Equal(requestingAccount.URI, reject.To)
suite.Equal(targetAccount.URI, reject.To)
suite.Equal("Reject", reject.Type)
}

View file

@ -24,6 +24,7 @@ import (
"github.com/superseriousbusiness/gotosocial/internal/oauth"
"github.com/superseriousbusiness/gotosocial/internal/processing/account"
"github.com/superseriousbusiness/gotosocial/internal/processing/admin"
"github.com/superseriousbusiness/gotosocial/internal/processing/common"
"github.com/superseriousbusiness/gotosocial/internal/processing/fedi"
"github.com/superseriousbusiness/gotosocial/internal/processing/list"
"github.com/superseriousbusiness/gotosocial/internal/processing/markers"
@ -147,7 +148,8 @@ func NewProcessor(
//
// Start with sub processors that will
// be required by the workers processor.
accountProcessor := account.New(state, tc, mediaManager, oauthServer, federator, filter, parseMentionFunc)
commonProcessor := common.New(state, tc, federator, filter)
accountProcessor := account.New(&commonProcessor, state, tc, mediaManager, oauthServer, federator, filter, parseMentionFunc)
mediaProcessor := media.New(state, tc, mediaManager, federator.TransportController())
streamProcessor := stream.New(state, oauthServer)