summaryrefslogtreecommitdiff
path: root/internal/api
diff options
context:
space:
mode:
authorLibravatar kim <89579420+NyaaaWhatsUpDoc@users.noreply.github.com>2023-09-12 14:00:35 +0100
committerLibravatar GitHub <noreply@github.com>2023-09-12 14:00:35 +0100
commit7293d6029b43db693fd170c0c087394339da0677 (patch)
tree09063243faf1b178fde35973486e311f66b1ca33 /internal/api
parent[feature] Allow admins to expire remote public keys; refetch expired keys on ... (diff)
downloadgotosocial-7293d6029b43db693fd170c0c087394339da0677.tar.xz
[feature] add paging to account follows, followers and follow requests endpoints (#2186)
Diffstat (limited to 'internal/api')
-rw-r--r--internal/api/client/accounts/follow_test.go411
-rw-r--r--internal/api/client/accounts/followers.go62
-rw-r--r--internal/api/client/accounts/following.go62
-rw-r--r--internal/api/client/blocks/blocksget.go43
-rw-r--r--internal/api/client/followrequests/authorize.go2
-rw-r--r--internal/api/client/followrequests/get.go59
-rw-r--r--internal/api/client/followrequests/get_test.go220
-rw-r--r--internal/api/client/followrequests/reject.go2
8 files changed, 835 insertions, 26 deletions
diff --git a/internal/api/client/accounts/follow_test.go b/internal/api/client/accounts/follow_test.go
index 9660acd4f..47526da1d 100644
--- a/internal/api/client/accounts/follow_test.go
+++ b/internal/api/client/accounts/follow_test.go
@@ -18,21 +18,33 @@
package accounts_test
import (
+ "context"
+ "encoding/json"
"fmt"
"io/ioutil"
+ "math/rand"
"net/http"
"net/http/httptest"
+ "net/url"
+ "strconv"
"strings"
"testing"
+ "time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
"github.com/superseriousbusiness/gotosocial/internal/api/client/accounts"
+ "github.com/superseriousbusiness/gotosocial/internal/api/model"
+ "github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
"github.com/superseriousbusiness/gotosocial/internal/oauth"
"github.com/superseriousbusiness/gotosocial/testrig"
+ "github.com/tomnomnom/linkheader"
)
+// random reader according to current-time source seed.
+var randRd = rand.New(rand.NewSource(time.Now().Unix()))
+
type FollowTestSuite struct {
AccountStandardTestSuite
}
@@ -69,6 +81,405 @@ func (suite *FollowTestSuite) TestFollowSelf() {
assert.NoError(suite.T(), err)
}
+func (suite *FollowTestSuite) TestGetFollowersPageBackwardLimit2() {
+ suite.testGetFollowersPage(2, "backward")
+}
+
+func (suite *FollowTestSuite) TestGetFollowersPageBackwardLimit4() {
+ suite.testGetFollowersPage(4, "backward")
+}
+
+func (suite *FollowTestSuite) TestGetFollowersPageBackwardLimit6() {
+ suite.testGetFollowersPage(6, "backward")
+}
+
+func (suite *FollowTestSuite) TestGetFollowersPageForwardLimit2() {
+ suite.testGetFollowersPage(2, "forward")
+}
+
+func (suite *FollowTestSuite) TestGetFollowersPageForwardLimit4() {
+ suite.testGetFollowersPage(4, "forward")
+}
+
+func (suite *FollowTestSuite) TestGetFollowersPageForwardLimit6() {
+ suite.testGetFollowersPage(6, "forward")
+}
+
+func (suite *FollowTestSuite) testGetFollowersPage(limit int, direction string) {
+ ctx := context.Background()
+
+ // The authed local account we are going to use for HTTP requests
+ requestingAccount := suite.testAccounts["local_account_1"]
+ suite.clearAccountRelations(requestingAccount.ID)
+
+ // Get current time.
+ now := time.Now()
+
+ var i int
+
+ for _, targetAccount := range suite.testAccounts {
+ if targetAccount.ID == requestingAccount.ID {
+ // we cannot be our own target...
+ continue
+ }
+
+ // Get next simple ID.
+ id := strconv.Itoa(i)
+ i++
+
+ // put a follow in the database
+ err := suite.db.PutFollow(ctx, &gtsmodel.Follow{
+ ID: id,
+ CreatedAt: now,
+ UpdatedAt: now,
+ URI: fmt.Sprintf("%s/follow/%s", targetAccount.URI, id),
+ AccountID: targetAccount.ID,
+ TargetAccountID: requestingAccount.ID,
+ })
+ suite.NoError(err)
+
+ // Bump now by 1 second.
+ now = now.Add(time.Second)
+ }
+
+ // Get _ALL_ follows we expect to see without any paging (this filters invisible).
+ apiRsp, err := suite.processor.Account().FollowersGet(ctx, requestingAccount, requestingAccount.ID, nil)
+ suite.NoError(err)
+ expectAccounts := apiRsp.Items // interfaced{} account slice
+
+ // Iteratively set
+ // link query string.
+ var query string
+
+ switch direction {
+ case "backward":
+ // Set the starting query to page backward from newest.
+ acc := expectAccounts[0].(*model.Account)
+ newest, _ := suite.db.GetFollow(ctx, acc.ID, requestingAccount.ID)
+ expectAccounts = expectAccounts[1:]
+ query = fmt.Sprintf("limit=%d&max_id=%s", limit, newest.ID)
+
+ case "forward":
+ // Set the starting query to page forward from the oldest.
+ acc := expectAccounts[len(expectAccounts)-1].(*model.Account)
+ oldest, _ := suite.db.GetFollow(ctx, acc.ID, requestingAccount.ID)
+ expectAccounts = expectAccounts[:len(expectAccounts)-1]
+ query = fmt.Sprintf("limit=%d&min_id=%s", limit, oldest.ID)
+ }
+
+ for p := 0; ; p++ {
+ // Prepare new request for endpoint
+ recorder := httptest.NewRecorder()
+ endpoint := fmt.Sprintf("/api/v1/accounts/%s/followers", requestingAccount.ID)
+ ctx := suite.newContext(recorder, http.MethodGet, []byte{}, endpoint, "")
+ ctx.Params = gin.Params{{Key: "id", Value: requestingAccount.ID}}
+ ctx.Request.URL.RawQuery = query // setting provided next query value
+
+ // call the handler and check for valid response code.
+ suite.T().Logf("direction=%q page=%d query=%q", direction, p, query)
+ suite.accountsModule.AccountFollowersGETHandler(ctx)
+ suite.Equal(http.StatusOK, recorder.Code)
+
+ var accounts []*model.Account
+
+ // Decode response body into API account models
+ result := recorder.Result()
+ dec := json.NewDecoder(result.Body)
+ err := dec.Decode(&accounts)
+ suite.NoError(err)
+ _ = result.Body.Close()
+
+ var (
+
+ // start provides the starting index for loop in accounts.
+ start func([]*model.Account) int
+
+ // iter performs the loop iter step with index.
+ iter func(int) int
+
+ // check performs the loop conditional check against index and accounts.
+ check func(int, []*model.Account) bool
+
+ // expect pulls the next account to check against from expectAccounts.
+ expect func([]interface{}) interface{}
+
+ // trunc drops the last checked account from expectAccounts.
+ trunc func([]interface{}) []interface{}
+ )
+
+ switch direction {
+ case "backward":
+ // When paging backwards (DESC) we:
+ // - iter from end of received accounts
+ // - iterate backward through received accounts
+ // - stop when we reach last index of received accounts
+ // - compare each received with the first index of expected accounts
+ // - after each compare, drop the first index of expected accounts
+ start = func([]*model.Account) int { return 0 }
+ iter = func(i int) int { return i + 1 }
+ check = func(idx int, i []*model.Account) bool { return idx < len(i) }
+ expect = func(i []interface{}) interface{} { return i[0] }
+ trunc = func(i []interface{}) []interface{} { return i[1:] }
+
+ case "forward":
+ // When paging forwards (ASC) we:
+ // - iter from end of received accounts
+ // - iterate backward through received accounts
+ // - stop when we reach first index of received accounts
+ // - compare each received with the last index of expected accounts
+ // - after each compare, drop the last index of expected accounts
+ start = func(i []*model.Account) int { return len(i) - 1 }
+ iter = func(i int) int { return i - 1 }
+ check = func(idx int, i []*model.Account) bool { return idx >= 0 }
+ expect = func(i []interface{}) interface{} { return i[len(i)-1] }
+ trunc = func(i []interface{}) []interface{} { return i[:len(i)-1] }
+ }
+
+ for i := start(accounts); check(i, accounts); i = iter(i) {
+ // Get next expected account.
+ iface := expect(expectAccounts)
+
+ // Check that expected account matches received.
+ expectAccID := iface.(*model.Account).ID
+ receivdAccID := accounts[i].ID
+ suite.Equal(expectAccID, receivdAccID, "unexpected account at position in response on page=%d", p)
+
+ // Drop checked from expected accounts.
+ expectAccounts = trunc(expectAccounts)
+ }
+
+ if len(expectAccounts) == 0 {
+ // Reached end.
+ break
+ }
+
+ // Parse response link header values.
+ values := result.Header.Values("Link")
+ links := linkheader.ParseMultiple(values)
+ filteredLinks := links.FilterByRel("next")
+ suite.NotEmpty(filteredLinks, "no next link provided with more remaining accounts on page=%d", p)
+
+ // A ref link header was set.
+ link := filteredLinks[0]
+
+ // Parse URI from URI string.
+ uri, err := url.Parse(link.URL)
+ suite.NoError(err)
+
+ // Set next raw query value.
+ query = uri.RawQuery
+ }
+}
+
+func (suite *FollowTestSuite) TestGetFollowingPageBackwardLimit2() {
+ suite.testGetFollowingPage(2, "backward")
+}
+
+func (suite *FollowTestSuite) TestGetFollowingPageBackwardLimit4() {
+ suite.testGetFollowingPage(4, "backward")
+}
+
+func (suite *FollowTestSuite) TestGetFollowingPageBackwardLimit6() {
+ suite.testGetFollowingPage(6, "backward")
+}
+
+func (suite *FollowTestSuite) TestGetFollowingPageForwardLimit2() {
+ suite.testGetFollowingPage(2, "forward")
+}
+
+func (suite *FollowTestSuite) TestGetFollowingPageForwardLimit4() {
+ suite.testGetFollowingPage(4, "forward")
+}
+
+func (suite *FollowTestSuite) TestGetFollowingPageForwardLimit6() {
+ suite.testGetFollowingPage(6, "forward")
+}
+
+func (suite *FollowTestSuite) testGetFollowingPage(limit int, direction string) {
+ ctx := context.Background()
+
+ // The authed local account we are going to use for HTTP requests
+ requestingAccount := suite.testAccounts["local_account_1"]
+ suite.clearAccountRelations(requestingAccount.ID)
+
+ // Get current time.
+ now := time.Now()
+
+ var i int
+
+ for _, targetAccount := range suite.testAccounts {
+ if targetAccount.ID == requestingAccount.ID {
+ // we cannot be our own target...
+ continue
+ }
+
+ // Get next simple ID.
+ id := strconv.Itoa(i)
+ i++
+
+ // put a follow in the database
+ err := suite.db.PutFollow(ctx, &gtsmodel.Follow{
+ ID: id,
+ CreatedAt: now,
+ UpdatedAt: now,
+ URI: fmt.Sprintf("%s/follow/%s", requestingAccount.URI, id),
+ AccountID: requestingAccount.ID,
+ TargetAccountID: targetAccount.ID,
+ })
+ suite.NoError(err)
+
+ // Bump now by 1 second.
+ now = now.Add(time.Second)
+ }
+
+ // Get _ALL_ follows we expect to see without any paging (this filters invisible).
+ apiRsp, err := suite.processor.Account().FollowingGet(ctx, requestingAccount, requestingAccount.ID, nil)
+ suite.NoError(err)
+ expectAccounts := apiRsp.Items // interfaced{} account slice
+
+ // Iteratively set
+ // link query string.
+ var query string
+
+ switch direction {
+ case "backward":
+ // Set the starting query to page backward from newest.
+ acc := expectAccounts[0].(*model.Account)
+ newest, _ := suite.db.GetFollow(ctx, requestingAccount.ID, acc.ID)
+ expectAccounts = expectAccounts[1:]
+ query = fmt.Sprintf("limit=%d&max_id=%s", limit, newest.ID)
+
+ case "forward":
+ // Set the starting query to page forward from the oldest.
+ acc := expectAccounts[len(expectAccounts)-1].(*model.Account)
+ oldest, _ := suite.db.GetFollow(ctx, requestingAccount.ID, acc.ID)
+ expectAccounts = expectAccounts[:len(expectAccounts)-1]
+ query = fmt.Sprintf("limit=%d&min_id=%s", limit, oldest.ID)
+ }
+
+ for p := 0; ; p++ {
+ // Prepare new request for endpoint
+ recorder := httptest.NewRecorder()
+ endpoint := fmt.Sprintf("/api/v1/accounts/%s/following", requestingAccount.ID)
+ ctx := suite.newContext(recorder, http.MethodGet, []byte{}, endpoint, "")
+ ctx.Params = gin.Params{{Key: "id", Value: requestingAccount.ID}}
+ ctx.Request.URL.RawQuery = query // setting provided next query value
+
+ // call the handler and check for valid response code.
+ suite.T().Logf("direction=%q page=%d query=%q", direction, p, query)
+ suite.accountsModule.AccountFollowingGETHandler(ctx)
+ suite.Equal(http.StatusOK, recorder.Code)
+
+ var accounts []*model.Account
+
+ // Decode response body into API account models
+ result := recorder.Result()
+ dec := json.NewDecoder(result.Body)
+ err := dec.Decode(&accounts)
+ suite.NoError(err)
+ _ = result.Body.Close()
+
+ var (
+ // start provides the starting index for loop in accounts.
+ start func([]*model.Account) int
+
+ // iter performs the loop iter step with index.
+ iter func(int) int
+
+ // check performs the loop conditional check against index and accounts.
+ check func(int, []*model.Account) bool
+
+ // expect pulls the next account to check against from expectAccounts.
+ expect func([]interface{}) interface{}
+
+ // trunc drops the last checked account from expectAccounts.
+ trunc func([]interface{}) []interface{}
+ )
+
+ switch direction {
+ case "backward":
+ // When paging backwards (DESC) we:
+ // - iter from end of received accounts
+ // - iterate backward through received accounts
+ // - stop when we reach last index of received accounts
+ // - compare each received with the first index of expected accounts
+ // - after each compare, drop the first index of expected accounts
+ start = func([]*model.Account) int { return 0 }
+ iter = func(i int) int { return i + 1 }
+ check = func(idx int, i []*model.Account) bool { return idx < len(i) }
+ expect = func(i []interface{}) interface{} { return i[0] }
+ trunc = func(i []interface{}) []interface{} { return i[1:] }
+
+ case "forward":
+ // When paging forwards (ASC) we:
+ // - iter from end of received accounts
+ // - iterate backward through received accounts
+ // - stop when we reach first index of received accounts
+ // - compare each received with the last index of expected accounts
+ // - after each compare, drop the last index of expected accounts
+ start = func(i []*model.Account) int { return len(i) - 1 }
+ iter = func(i int) int { return i - 1 }
+ check = func(idx int, i []*model.Account) bool { return idx >= 0 }
+ expect = func(i []interface{}) interface{} { return i[len(i)-1] }
+ trunc = func(i []interface{}) []interface{} { return i[:len(i)-1] }
+ }
+
+ for i := start(accounts); check(i, accounts); i = iter(i) {
+ // Get next expected account.
+ iface := expect(expectAccounts)
+
+ // Check that expected account matches received.
+ expectAccID := iface.(*model.Account).ID
+ receivdAccID := accounts[i].ID
+ suite.Equal(expectAccID, receivdAccID, "unexpected account at position in response on page=%d", p)
+
+ // Drop checked from expected accounts.
+ expectAccounts = trunc(expectAccounts)
+ }
+
+ if len(expectAccounts) == 0 {
+ // Reached end.
+ break
+ }
+
+ // Parse response link header values.
+ values := result.Header.Values("Link")
+ links := linkheader.ParseMultiple(values)
+ filteredLinks := links.FilterByRel("next")
+ suite.NotEmpty(filteredLinks, "no next link provided with more remaining accounts on page=%d", p)
+
+ // A ref link header was set.
+ link := filteredLinks[0]
+
+ // Parse URI from URI string.
+ uri, err := url.Parse(link.URL)
+ suite.NoError(err)
+
+ // Set next raw query value.
+ query = uri.RawQuery
+ }
+}
+
+func (suite *FollowTestSuite) clearAccountRelations(id string) {
+ // Esnure no account blocks exist between accounts.
+ _ = suite.db.DeleteAccountBlocks(
+ context.Background(),
+ id,
+ )
+
+ // Ensure no account follows exist between accounts.
+ _ = suite.db.DeleteAccountFollows(
+ context.Background(),
+ id,
+ )
+
+ // Ensure no account follow_requests exist between accounts.
+ _ = suite.db.DeleteAccountFollowRequests(
+ context.Background(),
+ id,
+ )
+}
+
func TestFollowTestSuite(t *testing.T) {
suite.Run(t, new(FollowTestSuite))
}
diff --git a/internal/api/client/accounts/followers.go b/internal/api/client/accounts/followers.go
index 96b034877..2448bc50a 100644
--- a/internal/api/client/accounts/followers.go
+++ b/internal/api/client/accounts/followers.go
@@ -25,12 +25,20 @@ import (
apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util"
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
"github.com/superseriousbusiness/gotosocial/internal/oauth"
+ "github.com/superseriousbusiness/gotosocial/internal/paging"
)
// AccountFollowersGETHandler swagger:operation GET /api/v1/accounts/{id}/followers accountFollowers
//
// See followers of account with given id.
//
+// The next and previous queries can be parsed from the returned Link header.
+// Example:
+//
+// ```
+// <https://example.org/api/v1/accounts/0657WMDEC3KQDTD6NZ4XJZBK4M/followers?limit=80&max_id=01FC0SKA48HNSVR6YKZCQGS2V8>; rel="next", <https://example.org/api/v1/accounts/0657WMDEC3KQDTD6NZ4XJZBK4M/followers?limit=80&min_id=01FC0SKW5JK2Q4EVAV2B462YY0>; rel="prev"
+// ````
+//
// ---
// tags:
// - accounts
@@ -45,6 +53,42 @@ import (
// description: Account ID.
// in: path
// required: true
+// -
+// name: max_id
+// type: string
+// description: >-
+// Return only follower accounts *OLDER* than the given max ID.
+// The follower account with the specified ID will not be included in the response.
+// NOTE: the ID is of the internal follow, NOT any of the returned accounts.
+// in: query
+// required: false
+// -
+// name: since_id
+// type: string
+// description: >-
+// Return only follower accounts *NEWER* than the given since ID.
+// The follower account with the specified ID will not be included in the response.
+// NOTE: the ID is of the internal follow, NOT any of the returned accounts.
+// in: query
+// required: false
+// -
+// name: min_id
+// type: string
+// description: >-
+// Return only follower accounts *IMMEDIATELY NEWER* than the given min ID.
+// The follower account with the specified ID will not be included in the response.
+// NOTE: the ID is of the internal follow, NOT any of the returned accounts.
+// in: query
+// required: false
+// -
+// name: limit
+// type: integer
+// description: Number of follower accounts to return.
+// default: 40
+// minimum: 1
+// maximum: 80
+// in: query
+// required: false
//
// security:
// - OAuth2 Bearer:
@@ -87,11 +131,25 @@ func (m *Module) AccountFollowersGETHandler(c *gin.Context) {
return
}
- followers, errWithCode := m.processor.Account().FollowersGet(c.Request.Context(), authed.Account, targetAcctID)
+ page, errWithCode := paging.ParseIDPage(c,
+ 1, // min limit
+ 80, // max limit
+ 40, // default limit
+ )
+ if errWithCode != nil {
+ apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGetV1)
+ return
+ }
+
+ resp, errWithCode := m.processor.Account().FollowersGet(c.Request.Context(), authed.Account, targetAcctID, page)
if errWithCode != nil {
apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGetV1)
return
}
- c.JSON(http.StatusOK, followers)
+ if resp.LinkHeader != "" {
+ c.Header("Link", resp.LinkHeader)
+ }
+
+ c.JSON(http.StatusOK, resp.Items)
}
diff --git a/internal/api/client/accounts/following.go b/internal/api/client/accounts/following.go
index 122a12a6e..d106d6ea6 100644
--- a/internal/api/client/accounts/following.go
+++ b/internal/api/client/accounts/following.go
@@ -25,12 +25,20 @@ import (
apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util"
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
"github.com/superseriousbusiness/gotosocial/internal/oauth"
+ "github.com/superseriousbusiness/gotosocial/internal/paging"
)
// AccountFollowingGETHandler swagger:operation GET /api/v1/accounts/{id}/following accountFollowing
//
// See accounts followed by given account id.
//
+// The next and previous queries can be parsed from the returned Link header.
+// Example:
+//
+// ```
+// <https://example.org/api/v1/accounts/0657WMDEC3KQDTD6NZ4XJZBK4M/following?limit=80&max_id=01FC0SKA48HNSVR6YKZCQGS2V8>; rel="next", <https://example.org/api/v1/accounts/0657WMDEC3KQDTD6NZ4XJZBK4M/following?limit=80&min_id=01FC0SKW5JK2Q4EVAV2B462YY0>; rel="prev"
+// ````
+//
// ---
// tags:
// - accounts
@@ -45,6 +53,42 @@ import (
// description: Account ID.
// in: path
// required: true
+// -
+// name: max_id
+// type: string
+// description: >-
+// Return only following accounts *OLDER* than the given max ID.
+// The following account with the specified ID will not be included in the response.
+// NOTE: the ID is of the internal follow, NOT any of the returned accounts.
+// in: query
+// required: false
+// -
+// name: since_id
+// type: string
+// description: >-
+// Return only following accounts *NEWER* than the given since ID.
+// The following account with the specified ID will not be included in the response.
+// NOTE: the ID is of the internal follow, NOT any of the returned accounts.
+// in: query
+// required: false
+// -
+// name: min_id
+// type: string
+// description: >-
+// Return only following accounts *IMMEDIATELY NEWER* than the given min ID.
+// The following account with the specified ID will not be included in the response.
+// NOTE: the ID is of the internal follow, NOT any of the returned accounts.
+// in: query
+// required: false
+// -
+// name: limit
+// type: integer
+// description: Number of following accounts to return.
+// default: 40
+// minimum: 1
+// maximum: 80
+// in: query
+// required: false
//
// security:
// - OAuth2 Bearer:
@@ -87,11 +131,25 @@ func (m *Module) AccountFollowingGETHandler(c *gin.Context) {
return
}
- following, errWithCode := m.processor.Account().FollowingGet(c.Request.Context(), authed.Account, targetAcctID)
+ page, errWithCode := paging.ParseIDPage(c,
+ 1, // min limit
+ 80, // max limit
+ 40, // default limit
+ )
+ if errWithCode != nil {
+ apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGetV1)
+ return
+ }
+
+ resp, errWithCode := m.processor.Account().FollowingGet(c.Request.Context(), authed.Account, targetAcctID, page)
if errWithCode != nil {
apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGetV1)
return
}
- c.JSON(http.StatusOK, following)
+ if resp.LinkHeader != "" {
+ c.Header("Link", resp.LinkHeader)
+ }
+
+ c.JSON(http.StatusOK, resp.Items)
}
diff --git a/internal/api/client/blocks/blocksget.go b/internal/api/client/blocks/blocksget.go
index dcf70e9cf..0761160bc 100644
--- a/internal/api/client/blocks/blocksget.go
+++ b/internal/api/client/blocks/blocksget.go
@@ -47,25 +47,40 @@ import (
//
// parameters:
// -
-// name: limit
-// type: integer
-// description: Number of blocks to return.
-// default: 20
-// in: query
-// -
// name: max_id
// type: string
// description: >-
-// Return only blocks *OLDER* than the given block ID.
-// The block with the specified ID will not be included in the response.
+// Return only blocked accounts *OLDER* than the given max ID.
+// The blocked account with the specified ID will not be included in the response.
+// NOTE: the ID is of the internal block, NOT any of the returned accounts.
// in: query
+// required: false
// -
// name: since_id
// type: string
// description: >-
-// Return only blocks *NEWER* than the given block ID.
-// The block with the specified ID will not be included in the response.
+// Return only blocked accounts *NEWER* than the given since ID.
+// The blocked account with the specified ID will not be included in the response.
+// NOTE: the ID is of the internal block, NOT any of the returned accounts.
+// in: query
+// -
+// name: min_id
+// type: string
+// description: >-
+// Return only blocked accounts *IMMEDIATELY NEWER* than the given min ID.
+// The blocked account with the specified ID will not be included in the response.
+// NOTE: the ID is of the internal block, NOT any of the returned accounts.
+// in: query
+// required: false
+// -
+// name: limit
+// type: integer
+// description: Number of blocked accounts to return.
+// default: 40
+// minimum: 1
+// maximum: 80
// in: query
+// required: false
//
// security:
// - OAuth2 Bearer:
@@ -104,16 +119,16 @@ func (m *Module) BlocksGETHandler(c *gin.Context) {
}
page, errWithCode := paging.ParseIDPage(c,
- 1, // min limit
- 100, // max limit
- 20, // default limit
+ 1, // min limit
+ 80, // max limit
+ 40, // default limit
)
if errWithCode != nil {
apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGetV1)
return
}
- resp, errWithCode := m.processor.BlocksGet(
+ resp, errWithCode := m.processor.Account().BlocksGet(
c.Request.Context(),
authed.Account,
page,
diff --git a/internal/api/client/followrequests/authorize.go b/internal/api/client/followrequests/authorize.go
index 7a19c0f86..707d3db26 100644
--- a/internal/api/client/followrequests/authorize.go
+++ b/internal/api/client/followrequests/authorize.go
@@ -87,7 +87,7 @@ func (m *Module) FollowRequestAuthorizePOSTHandler(c *gin.Context) {
return
}
- relationship, errWithCode := m.processor.FollowRequestAccept(c.Request.Context(), authed, originAccountID)
+ relationship, errWithCode := m.processor.Account().FollowRequestAccept(c.Request.Context(), authed.Account, originAccountID)
if errWithCode != nil {
apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGetV1)
return
diff --git a/internal/api/client/followrequests/get.go b/internal/api/client/followrequests/get.go
index 628e3b807..af2f3741c 100644
--- a/internal/api/client/followrequests/get.go
+++ b/internal/api/client/followrequests/get.go
@@ -24,12 +24,19 @@ import (
apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util"
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
"github.com/superseriousbusiness/gotosocial/internal/oauth"
+ "github.com/superseriousbusiness/gotosocial/internal/paging"
)
// FollowRequestGETHandler swagger:operation GET /api/v1/follow_requests getFollowRequests
//
// Get an array of accounts that have requested to follow you.
-// Accounts will be sorted in order of follow request date descending (newest first).
+//
+// The next and previous queries can be parsed from the returned Link header.
+// Example:
+//
+// ```
+// <https://example.org/api/v1/follow_requests?limit=80&max_id=01FC0SKA48HNSVR6YKZCQGS2V8>; rel="next", <https://example.org/api/v1/follow_requests?limit=80&min_id=01FC0SKW5JK2Q4EVAV2B462YY0>; rel="prev"
+// ````
//
// ---
// tags:
@@ -40,11 +47,41 @@ import (
//
// parameters:
// -
+// name: max_id
+// type: string
+// description: >-
+// Return only follow requesting accounts *OLDER* than the given max ID.
+// The follow requester with the specified ID will not be included in the response.
+// NOTE: the ID is of the internal follow request, NOT any of the returned accounts.
+// in: query
+// required: false
+// -
+// name: since_id
+// type: string
+// description: >-
+// Return only follow requesting accounts *NEWER* than the given since ID.
+// The follow requester with the specified ID will not be included in the response.
+// NOTE: the ID is of the internal follow request, NOT any of the returned accounts.
+// in: query
+// required: false
+// -
+// name: min_id
+// type: string
+// description: >-
+// Return only follow requesting accounts *IMMEDIATELY NEWER* than the given min ID.
+// The follow requester with the specified ID will not be included in the response.
+// NOTE: the ID is of the internal follow request, NOT any of the returned accounts.
+// in: query
+// required: false
+// -
// name: limit
// type: integer
-// description: Number of accounts to return.
+// description: Number of follow requesting accounts to return.
// default: 40
+// minimum: 1
+// maximum: 80
// in: query
+// required: false
//
// security:
// - OAuth2 Bearer:
@@ -82,11 +119,25 @@ func (m *Module) FollowRequestGETHandler(c *gin.Context) {
return
}
- accts, errWithCode := m.processor.FollowRequestsGet(c.Request.Context(), authed)
+ page, errWithCode := paging.ParseIDPage(c,
+ 1, // min limit
+ 80, // max limit
+ 40, // default limit
+ )
if errWithCode != nil {
apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGetV1)
return
}
- c.JSON(http.StatusOK, accts)
+ resp, errWithCode := m.processor.Account().FollowRequestsGet(c.Request.Context(), authed.Account, page)
+ if errWithCode != nil {
+ apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGetV1)
+ return
+ }
+
+ if resp.LinkHeader != "" {
+ c.Header("Link", resp.LinkHeader)
+ }
+
+ c.JSON(http.StatusOK, resp.Items)
}
diff --git a/internal/api/client/followrequests/get_test.go b/internal/api/client/followrequests/get_test.go
index d95c9878c..f2fa832a1 100644
--- a/internal/api/client/followrequests/get_test.go
+++ b/internal/api/client/followrequests/get_test.go
@@ -22,17 +22,25 @@ import (
"context"
"encoding/json"
"fmt"
- "io/ioutil"
+ "io"
+ "math/rand"
"net/http"
"net/http/httptest"
+ "net/url"
+ "strconv"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
+ "github.com/superseriousbusiness/gotosocial/internal/api/model"
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
+ "github.com/tomnomnom/linkheader"
)
+// random reader according to current-time source seed.
+var randRd = rand.New(rand.NewSource(time.Now().Unix()))
+
type GetTestSuite struct {
FollowRequestStandardTestSuite
}
@@ -68,7 +76,7 @@ func (suite *GetTestSuite) TestGet() {
defer result.Body.Close()
// check the response
- b, err := ioutil.ReadAll(result.Body)
+ b, err := io.ReadAll(result.Body)
assert.NoError(suite.T(), err)
dst := new(bytes.Buffer)
err = json.Indent(dst, b, "", " ")
@@ -99,6 +107,214 @@ func (suite *GetTestSuite) TestGet() {
]`, dst.String())
}
+func (suite *GetTestSuite) TestGetPageBackwardLimit2() {
+ suite.testGetPage(2, "backward")
+}
+
+func (suite *GetTestSuite) TestGetPageBackwardLimit4() {
+ suite.testGetPage(4, "backward")
+}
+
+func (suite *GetTestSuite) TestGetPageBackwardLimit6() {
+ suite.testGetPage(6, "backward")
+}
+
+func (suite *GetTestSuite) TestGetPageForwardLimit2() {
+ suite.testGetPage(2, "forward")
+}
+
+func (suite *GetTestSuite) TestGetPageForwardLimit4() {
+ suite.testGetPage(4, "forward")
+}
+
+func (suite *GetTestSuite) TestGetPageForwardLimit6() {
+ suite.testGetPage(6, "forward")
+}
+
+func (suite *GetTestSuite) testGetPage(limit int, direction string) {
+ ctx := context.Background()
+
+ // The authed local account we are going to use for HTTP requests
+ requestingAccount := suite.testAccounts["local_account_1"]
+ suite.clearAccountRelations(requestingAccount.ID)
+
+ // Get current time.
+ now := time.Now()
+
+ var i int
+
+ for _, targetAccount := range suite.testAccounts {
+ if targetAccount.ID == requestingAccount.ID {
+ // we cannot be our own target...
+ continue
+ }
+
+ // Get next simple ID.
+ id := strconv.Itoa(i)
+ i++
+
+ // put a follow request in the database
+ err := suite.db.PutFollowRequest(ctx, &gtsmodel.FollowRequest{
+ ID: id,
+ CreatedAt: now,
+ UpdatedAt: now,
+ URI: fmt.Sprintf("%s/follow/%s", targetAccount.URI, id),
+ AccountID: targetAccount.ID,
+ TargetAccountID: requestingAccount.ID,
+ })
+ suite.NoError(err)
+
+ // Bump now by 1 second.
+ now = now.Add(time.Second)
+ }
+
+ // Get _ALL_ follow requests we expect to see without any paging (this filters invisible).
+ apiRsp, err := suite.processor.Account().FollowRequestsGet(ctx, requestingAccount, nil)
+ suite.NoError(err)
+ expectAccounts := apiRsp.Items // interfaced{} account slice
+
+ // Iteratively set
+ // link query string.
+ var query string
+
+ switch direction {
+ case "backward":
+ // Set the starting query to page backward from newest.
+ acc := expectAccounts[0].(*model.Account)
+ newest, _ := suite.db.GetFollowRequest(ctx, acc.ID, requestingAccount.ID)
+ expectAccounts = expectAccounts[1:]
+ query = fmt.Sprintf("limit=%d&max_id=%s", limit, newest.ID)
+
+ case "forward":
+ // Set the starting query to page forward from the oldest.
+ acc := expectAccounts[len(expectAccounts)-1].(*model.Account)
+ oldest, _ := suite.db.GetFollowRequest(ctx, acc.ID, requestingAccount.ID)
+ expectAccounts = expectAccounts[:len(expectAccounts)-1]
+ query = fmt.Sprintf("limit=%d&min_id=%s", limit, oldest.ID)
+ }
+
+ for p := 0; ; p++ {
+ // Prepare new request for endpoint
+ recorder := httptest.NewRecorder()
+ ctx := suite.newContext(recorder, http.MethodGet, []byte{}, "/api/v1/follow_requests", "")
+ ctx.Request.URL.RawQuery = query // setting provided next query value
+
+ // call the handler and check for valid response code.
+ suite.T().Logf("direction=%q page=%d query=%q", direction, p, query)
+ suite.followRequestModule.FollowRequestGETHandler(ctx)
+ suite.Equal(http.StatusOK, recorder.Code)
+
+ var accounts []*model.Account
+
+ // Decode response body into API account models
+ result := recorder.Result()
+ dec := json.NewDecoder(result.Body)
+ err := dec.Decode(&accounts)
+ suite.NoError(err)
+ _ = result.Body.Close()
+
+ var (
+
+ // start provides the starting index for loop in accounts.
+ start func([]*model.Account) int
+
+ // iter performs the loop iter step with index.
+ iter func(int) int
+
+ // check performs the loop conditional check against index and accounts.
+ check func(int, []*model.Account) bool
+
+ // expect pulls the next account to check against from expectAccounts.
+ expect func([]interface{}) interface{}
+
+ // trunc drops the last checked account from expectAccounts.
+ trunc func([]interface{}) []interface{}
+ )
+
+ switch direction {
+ case "backward":
+ // When paging backwards (DESC) we:
+ // - iter from end of received accounts
+ // - iterate backward through received accounts
+ // - stop when we reach last index of received accounts
+ // - compare each received with the first index of expected accounts
+ // - after each compare, drop the first index of expected accounts
+ start = func([]*model.Account) int { return 0 }
+ iter = func(i int) int { return i + 1 }
+ check = func(idx int, i []*model.Account) bool { return idx < len(i) }
+ expect = func(i []interface{}) interface{} { return i[0] }
+ trunc = func(i []interface{}) []interface{} { return i[1:] }
+
+ case "forward":
+ // When paging forwards (ASC) we:
+ // - iter from end of received accounts
+ // - iterate backward through received accounts
+ // - stop when we reach first index of received accounts
+ // - compare each received with the last index of expected accounts
+ // - after each compare, drop the last index of expected accounts
+ start = func(i []*model.Account) int { return len(i) - 1 }
+ iter = func(i int) int { return i - 1 }
+ check = func(idx int, i []*model.Account) bool { return idx >= 0 }
+ expect = func(i []interface{}) interface{} { return i[len(i)-1] }
+ trunc = func(i []interface{}) []interface{} { return i[:len(i)-1] }
+ }
+
+ for i := start(accounts); check(i, accounts); i = iter(i) {
+ // Get next expected account.
+ iface := expect(expectAccounts)
+
+ // Check that expected account matches received.
+ expectAccID := iface.(*model.Account).ID
+ receivdAccID := accounts[i].ID
+ suite.Equal(expectAccID, receivdAccID, "unexpected account at position in response on page=%d", p)
+
+ // Drop checked from expected accounts.
+ expectAccounts = trunc(expectAccounts)
+ }
+
+ if len(expectAccounts) == 0 {
+ // Reached end.
+ break
+ }
+
+ // Parse response link header values.
+ values := result.Header.Values("Link")
+ links := linkheader.ParseMultiple(values)
+ filteredLinks := links.FilterByRel("next")
+ suite.NotEmpty(filteredLinks, "no next link provided with more remaining accounts on page=%d", p)
+
+ // A ref link header was set.
+ link := filteredLinks[0]
+
+ // Parse URI from URI string.
+ uri, err := url.Parse(link.URL)
+ suite.NoError(err)
+
+ // Set next raw query value.
+ query = uri.RawQuery
+ }
+}
+
+func (suite *GetTestSuite) clearAccountRelations(id string) {
+ // Esnure no account blocks exist between accounts.
+ _ = suite.db.DeleteAccountBlocks(
+ context.Background(),
+ id,
+ )
+
+ // Ensure no account follows exist between accounts.
+ _ = suite.db.DeleteAccountFollows(
+ context.Background(),
+ id,
+ )
+
+ // Ensure no account follow_requests exist between accounts.
+ _ = suite.db.DeleteAccountFollowRequests(
+ context.Background(),
+ id,
+ )
+}
+
func TestGetTestSuite(t *testing.T) {
suite.Run(t, &GetTestSuite{})
}
diff --git a/internal/api/client/followrequests/reject.go b/internal/api/client/followrequests/reject.go
index 3f75facba..6514a615e 100644
--- a/internal/api/client/followrequests/reject.go
+++ b/internal/api/client/followrequests/reject.go
@@ -85,7 +85,7 @@ func (m *Module) FollowRequestRejectPOSTHandler(c *gin.Context) {
return
}
- relationship, errWithCode := m.processor.FollowRequestReject(c.Request.Context(), authed, originAccountID)
+ relationship, errWithCode := m.processor.Account().FollowRequestReject(c.Request.Context(), authed.Account, originAccountID)
if errWithCode != nil {
apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGetV1)
return