[feature] Interaction requests client api + settings panel (#3215)

* [feature] Interaction requests client api + settings panel

* test accept / reject

* fmt

* don't pin rejected interaction

* use single db model for interaction accept, reject, and request

* swaggor

* env sharting

* append errors

* remove ErrNoEntries checks

* change intReqID to reqID

* rename "pend" to "request"

* markIntsPending -> mark interactionsPending

* use log instead of returning error when rejecting interaction

* empty migration

* jolly renaming

* make interactionURI unique again

* swag grr

* remove unnecessary locks

* invalidate as last step
This commit is contained in:
tobi
2024-08-24 11:49:37 +02:00
committed by GitHub
parent 8e5a72ac5c
commit f23f04e0b1
72 changed files with 4446 additions and 663 deletions

View File

@@ -0,0 +1,239 @@
// 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 interactionrequests
import (
"context"
"time"
"github.com/superseriousbusiness/gotosocial/internal/ap"
apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
"github.com/superseriousbusiness/gotosocial/internal/messages"
"github.com/superseriousbusiness/gotosocial/internal/uris"
"github.com/superseriousbusiness/gotosocial/internal/util"
)
// Accept accepts an interaction request with the given ID,
// on behalf of the given account (whose post it must target).
func (p *Processor) Accept(
ctx context.Context,
acct *gtsmodel.Account,
reqID string,
) (*apimodel.InteractionRequest, gtserror.WithCode) {
req, err := p.state.DB.GetInteractionRequestByID(ctx, reqID)
if err != nil {
err := gtserror.Newf("db error getting interaction request: %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
if req.TargetAccountID != acct.ID {
err := gtserror.Newf(
"interaction request %s does not belong to account %s",
reqID, acct.ID,
)
return nil, gtserror.NewErrorNotFound(err)
}
if !req.IsPending() {
err := gtserror.Newf(
"interaction request %s has already been handled",
reqID,
)
return nil, gtserror.NewErrorNotFound(err)
}
// Lock on the interaction req URI to
// ensure nobody else is modifying it rn.
unlock := p.state.ProcessingLocks.Lock(req.InteractionURI)
defer unlock()
// Mark the request as accepted
// and generate a URI for it.
req.AcceptedAt = time.Now()
req.URI = uris.GenerateURIForAccept(acct.Username, req.ID)
if err := p.state.DB.UpdateInteractionRequest(
ctx,
req,
"accepted_at",
"uri",
); err != nil {
err := gtserror.Newf("db error updating interaction request: %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
switch req.InteractionType {
case gtsmodel.InteractionLike:
if errWithCode := p.acceptLike(ctx, req); errWithCode != nil {
return nil, errWithCode
}
case gtsmodel.InteractionReply:
if errWithCode := p.acceptReply(ctx, req); errWithCode != nil {
return nil, errWithCode
}
case gtsmodel.InteractionAnnounce:
if errWithCode := p.acceptAnnounce(ctx, req); errWithCode != nil {
return nil, errWithCode
}
default:
err := gtserror.Newf("unknown interaction type for interaction request %s", reqID)
return nil, gtserror.NewErrorInternalError(err)
}
// Return the now-accepted req to the caller so
// they can do something with it if they need to.
apiReq, err := p.converter.InteractionReqToAPIInteractionReq(
ctx,
req,
acct,
)
if err != nil {
err := gtserror.Newf("error converting interaction request: %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
return apiReq, nil
}
// Package-internal convenience
// function to accept a like.
func (p *Processor) acceptLike(
ctx context.Context,
req *gtsmodel.InteractionRequest,
) gtserror.WithCode {
// If the Like is missing, that means it's
// probably already been undone by someone,
// so there's nothing to actually accept.
if req.Like == nil {
err := gtserror.Newf("no Like found for interaction request %s", req.ID)
return gtserror.NewErrorNotFound(err)
}
// Update the Like.
req.Like.PendingApproval = util.Ptr(false)
req.Like.PreApproved = false
req.Like.ApprovedByURI = req.URI
if err := p.state.DB.UpdateStatusFave(
ctx,
req.Like,
"pending_approval",
"approved_by_uri",
); err != nil {
err := gtserror.Newf("db error updating status fave: %w", err)
return gtserror.NewErrorInternalError(err)
}
// Send the accepted request off through the
// client API processor to handle side effects.
p.state.Workers.Client.Queue.Push(&messages.FromClientAPI{
APObjectType: ap.ActivityLike,
APActivityType: ap.ActivityAccept,
GTSModel: req,
Origin: req.TargetAccount,
Target: req.InteractingAccount,
})
return nil
}
// Package-internal convenience
// function to accept a reply.
func (p *Processor) acceptReply(
ctx context.Context,
req *gtsmodel.InteractionRequest,
) gtserror.WithCode {
// If the Reply is missing, that means it's
// probably already been undone by someone,
// so there's nothing to actually accept.
if req.Reply == nil {
err := gtserror.Newf("no Reply found for interaction request %s", req.ID)
return gtserror.NewErrorNotFound(err)
}
// Update the Reply.
req.Reply.PendingApproval = util.Ptr(false)
req.Reply.PreApproved = false
req.Reply.ApprovedByURI = req.URI
if err := p.state.DB.UpdateStatus(
ctx,
req.Reply,
"pending_approval",
"approved_by_uri",
); err != nil {
err := gtserror.Newf("db error updating status reply: %w", err)
return gtserror.NewErrorInternalError(err)
}
// Send the accepted request off through the
// client API processor to handle side effects.
p.state.Workers.Client.Queue.Push(&messages.FromClientAPI{
APObjectType: ap.ObjectNote,
APActivityType: ap.ActivityAccept,
GTSModel: req,
Origin: req.TargetAccount,
Target: req.InteractingAccount,
})
return nil
}
// Package-internal convenience
// function to accept an announce.
func (p *Processor) acceptAnnounce(
ctx context.Context,
req *gtsmodel.InteractionRequest,
) gtserror.WithCode {
// If the Announce is missing, that means it's
// probably already been undone by someone,
// so there's nothing to actually accept.
if req.Reply == nil {
err := gtserror.Newf("no Announce found for interaction request %s", req.ID)
return gtserror.NewErrorNotFound(err)
}
// Update the Announce.
req.Announce.PendingApproval = util.Ptr(false)
req.Announce.PreApproved = false
req.Announce.ApprovedByURI = req.URI
if err := p.state.DB.UpdateStatus(
ctx,
req.Announce,
"pending_approval",
"approved_by_uri",
); err != nil {
err := gtserror.Newf("db error updating status announce: %w", err)
return gtserror.NewErrorInternalError(err)
}
// Send the accepted request off through the
// client API processor to handle side effects.
p.state.Workers.Client.Queue.Push(&messages.FromClientAPI{
APObjectType: ap.ActivityAnnounce,
APActivityType: ap.ActivityAccept,
GTSModel: req,
Origin: req.TargetAccount,
Target: req.InteractingAccount,
})
return nil
}

View File

@@ -0,0 +1,89 @@
// 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 interactionrequests_test
import (
"context"
"testing"
"github.com/stretchr/testify/suite"
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
"github.com/superseriousbusiness/gotosocial/internal/processing/interactionrequests"
"github.com/superseriousbusiness/gotosocial/testrig"
)
type AcceptTestSuite struct {
InteractionRequestsTestSuite
}
func (suite *AcceptTestSuite) TestAccept() {
testStructs := testrig.SetupTestStructs(rMediaPath, rTemplatePath)
defer testrig.TearDownTestStructs(testStructs)
var (
ctx = context.Background()
state = testStructs.State
acct = suite.testAccounts["local_account_2"]
intReq = suite.testInteractionRequests["admin_account_reply_turtle"]
)
// Create interaction reqs processor.
p := interactionrequests.New(
testStructs.Common,
testStructs.State,
testStructs.TypeConverter,
)
apiReq, errWithCode := p.Accept(ctx, acct, intReq.ID)
if errWithCode != nil {
suite.FailNow(errWithCode.Error())
}
// Get db interaction request.
dbReq, err := state.DB.GetInteractionRequestByID(ctx, apiReq.ID)
if err != nil {
suite.FailNow(err.Error())
}
suite.True(dbReq.IsAccepted())
// Interacting status
// should now be approved.
dbStatus, err := state.DB.GetStatusByURI(ctx, dbReq.InteractionURI)
if err != nil {
suite.FailNow(err.Error())
}
suite.False(*dbStatus.PendingApproval)
suite.Equal(dbReq.URI, dbStatus.ApprovedByURI)
// Wait for a notification
// for interacting status.
testrig.WaitFor(func() bool {
notif, err := state.DB.GetNotification(
ctx,
gtsmodel.NotificationMention,
dbStatus.InReplyToAccountID,
dbStatus.AccountID,
dbStatus.ID,
)
return notif != nil && err == nil
})
}
func TestAcceptTestSuite(t *testing.T) {
suite.Run(t, new(AcceptTestSuite))
}

View File

@@ -0,0 +1,141 @@
// 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 interactionrequests
import (
"context"
"errors"
"net/url"
"strconv"
apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util"
"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"
)
// GetPage returns a page of interaction requests targeting
// the requester and (optionally) the given status ID.
func (p *Processor) GetPage(
ctx context.Context,
requester *gtsmodel.Account,
statusID string,
likes bool,
replies bool,
boosts bool,
page *paging.Page,
) (*apimodel.PageableResponse, gtserror.WithCode) {
reqs, err := p.state.DB.GetInteractionsRequestsForAcct(
ctx,
requester.ID,
statusID,
likes,
replies,
boosts,
page,
)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
err := gtserror.Newf("db error getting interaction requests: %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
count := len(reqs)
if count == 0 {
return paging.EmptyResponse(), nil
}
var (
// Get the lowest and highest
// ID values, used for paging.
lo = reqs[count-1].ID
hi = reqs[0].ID
// Best-guess items length.
items = make([]interface{}, 0, count)
)
for _, req := range reqs {
apiReq, err := p.converter.InteractionReqToAPIInteractionReq(
ctx, req, requester,
)
if err != nil {
log.Errorf(ctx, "error converting interaction req to api req: %v", err)
continue
}
// Append req to return items.
items = append(items, apiReq)
}
// Build extra query params to return in Link header.
extraParams := make(url.Values, 4)
extraParams.Set(apiutil.InteractionFavouritesKey, strconv.FormatBool(likes))
extraParams.Set(apiutil.InteractionRepliesKey, strconv.FormatBool(replies))
extraParams.Set(apiutil.InteractionReblogsKey, strconv.FormatBool(boosts))
if statusID != "" {
extraParams.Set(apiutil.InteractionStatusIDKey, statusID)
}
return paging.PackageResponse(paging.ResponseParams{
Items: items,
Path: "/api/v1/interaction_requests",
Next: page.Next(lo, hi),
Prev: page.Prev(lo, hi),
Query: extraParams,
}), nil
}
// GetOne returns one interaction
// request with the given ID.
func (p *Processor) GetOne(
ctx context.Context,
requester *gtsmodel.Account,
id string,
) (*apimodel.InteractionRequest, gtserror.WithCode) {
req, err := p.state.DB.GetInteractionRequestByID(ctx, id)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
err := gtserror.Newf("db error getting interaction request: %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
if req == nil {
err := gtserror.New("interaction request not found")
return nil, gtserror.NewErrorNotFound(err)
}
if req.TargetAccountID != requester.ID {
err := gtserror.Newf(
"interaction request %s does not target account %s",
req.ID, requester.ID,
)
return nil, gtserror.NewErrorNotFound(err)
}
apiReq, err := p.converter.InteractionReqToAPIInteractionReq(
ctx, req, requester,
)
if err != nil {
err := gtserror.Newf("error converting interaction req to api req: %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
return apiReq, nil
}

View File

@@ -0,0 +1,47 @@
// 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 interactionrequests
import (
"github.com/superseriousbusiness/gotosocial/internal/processing/common"
"github.com/superseriousbusiness/gotosocial/internal/state"
"github.com/superseriousbusiness/gotosocial/internal/typeutils"
)
// Processor wraps functionality for getting,
// accepting, and rejecting interaction requests.
type Processor struct {
// common processor logic
c *common.Processor
state *state.State
converter *typeutils.Converter
}
// New returns a new interaction requests processor.
func New(
common *common.Processor,
state *state.State,
converter *typeutils.Converter,
) Processor {
return Processor{
c: common,
state: state,
converter: converter,
}
}

View File

@@ -0,0 +1,45 @@
// 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 interactionrequests_test
import (
"github.com/stretchr/testify/suite"
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
"github.com/superseriousbusiness/gotosocial/testrig"
)
const (
rMediaPath = "../../../testrig/media"
rTemplatePath = "../../../web/template"
)
type InteractionRequestsTestSuite struct {
suite.Suite
testAccounts map[string]*gtsmodel.Account
testStatuses map[string]*gtsmodel.Status
testInteractionRequests map[string]*gtsmodel.InteractionRequest
}
func (suite *InteractionRequestsTestSuite) SetupTest() {
testrig.InitTestConfig()
testrig.InitTestLog()
suite.testAccounts = testrig.NewTestAccounts()
suite.testStatuses = testrig.NewTestStatuses()
suite.testInteractionRequests = testrig.NewTestInteractionRequests()
}

View File

@@ -0,0 +1,133 @@
// 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 interactionrequests
import (
"context"
"time"
"github.com/superseriousbusiness/gotosocial/internal/ap"
apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
"github.com/superseriousbusiness/gotosocial/internal/messages"
"github.com/superseriousbusiness/gotosocial/internal/uris"
)
// Reject rejects an interaction request with the given ID,
// on behalf of the given account (whose post it must target).
func (p *Processor) Reject(
ctx context.Context,
acct *gtsmodel.Account,
reqID string,
) (*apimodel.InteractionRequest, gtserror.WithCode) {
req, err := p.state.DB.GetInteractionRequestByID(ctx, reqID)
if err != nil {
err := gtserror.Newf("db error getting interaction request: %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
if req.TargetAccountID != acct.ID {
err := gtserror.Newf(
"interaction request %s does not belong to account %s",
reqID, acct.ID,
)
return nil, gtserror.NewErrorNotFound(err)
}
if !req.IsPending() {
err := gtserror.Newf(
"interaction request %s has already been handled",
reqID,
)
return nil, gtserror.NewErrorNotFound(err)
}
// Lock on the interaction req URI to
// ensure nobody else is modifying it rn.
unlock := p.state.ProcessingLocks.Lock(req.InteractionURI)
defer unlock()
// Mark the request as rejected
// and generate a URI for it.
req.RejectedAt = time.Now()
req.URI = uris.GenerateURIForReject(acct.Username, req.ID)
if err := p.state.DB.UpdateInteractionRequest(
ctx,
req,
"rejected_at",
"uri",
); err != nil {
err := gtserror.Newf("db error updating interaction request: %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
switch req.InteractionType {
case gtsmodel.InteractionLike:
// Send the rejected request off through the
// client API processor to handle side effects.
p.state.Workers.Client.Queue.Push(&messages.FromClientAPI{
APObjectType: ap.ActivityLike,
APActivityType: ap.ActivityReject,
GTSModel: req,
Origin: req.TargetAccount,
Target: req.InteractingAccount,
})
case gtsmodel.InteractionReply:
// Send the rejected request off through the
// client API processor to handle side effects.
p.state.Workers.Client.Queue.Push(&messages.FromClientAPI{
APObjectType: ap.ObjectNote,
APActivityType: ap.ActivityReject,
GTSModel: req,
Origin: req.TargetAccount,
Target: req.InteractingAccount,
})
case gtsmodel.InteractionAnnounce:
// Send the rejected request off through the
// client API processor to handle side effects.
p.state.Workers.Client.Queue.Push(&messages.FromClientAPI{
APObjectType: ap.ActivityAnnounce,
APActivityType: ap.ActivityReject,
GTSModel: req,
Origin: req.TargetAccount,
Target: req.InteractingAccount,
})
default:
err := gtserror.Newf("unknown interaction type for interaction request %s", reqID)
return nil, gtserror.NewErrorInternalError(err)
}
// Return the now-rejected req to the caller so
// they can do something with it if they need to.
apiReq, err := p.converter.InteractionReqToAPIInteractionReq(
ctx,
req,
acct,
)
if err != nil {
err := gtserror.Newf("error converting interaction request: %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
return apiReq, nil
}

View File

@@ -0,0 +1,78 @@
// 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 interactionrequests_test
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/suite"
"github.com/superseriousbusiness/gotosocial/internal/db"
"github.com/superseriousbusiness/gotosocial/internal/gtscontext"
"github.com/superseriousbusiness/gotosocial/internal/processing/interactionrequests"
"github.com/superseriousbusiness/gotosocial/testrig"
)
type RejectTestSuite struct {
InteractionRequestsTestSuite
}
func (suite *RejectTestSuite) TestReject() {
testStructs := testrig.SetupTestStructs(rMediaPath, rTemplatePath)
defer testrig.TearDownTestStructs(testStructs)
var (
ctx = context.Background()
state = testStructs.State
acct = suite.testAccounts["local_account_2"]
intReq = suite.testInteractionRequests["admin_account_reply_turtle"]
)
// Create int reqs processor.
p := interactionrequests.New(
testStructs.Common,
testStructs.State,
testStructs.TypeConverter,
)
apiReq, errWithCode := p.Reject(ctx, acct, intReq.ID)
if errWithCode != nil {
suite.FailNow(errWithCode.Error())
}
// Get db interaction rejection.
dbReq, err := state.DB.GetInteractionRequestByID(ctx, apiReq.ID)
if err != nil {
suite.FailNow(err.Error())
}
suite.True(dbReq.IsRejected())
// Wait for interacting status to be deleted.
testrig.WaitFor(func() bool {
status, err := state.DB.GetStatusByURI(
gtscontext.SetBarebones(ctx),
dbReq.InteractionURI,
)
return status == nil && errors.Is(err, db.ErrNoEntries)
})
}
func TestRejectTestSuite(t *testing.T) {
suite.Run(t, new(RejectTestSuite))
}