From 941893a774c83802afdc4cc76e1d30c59b6c5585 Mon Sep 17 00:00:00 2001 From: tobi <31960611+tsmethurst@users.noreply.github.com> Date: Mon, 2 Jan 2023 13:10:50 +0100 Subject: [chore] The Big Middleware and API Refactor (tm) (#1250) * interim commit: start refactoring middlewares into package under router * another interim commit, this is becoming a big job * another fucking massive interim commit * refactor bookmarks to new style * ambassador, wiz zeze commits you are spoiling uz * she compiles, we're getting there * we're just normal men; we're just innocent men * apiutil * whoopsie * i'm glad noone reads commit msgs haha :blob_sweat: * use that weirdo go-bytesize library for maxMultipartMemory * fix media module paths --- internal/api/client/account/account.go | 141 ------- internal/api/client/account/account_test.go | 127 ------ internal/api/client/account/accountcreate.go | 150 ------- internal/api/client/account/accountcreate_test.go | 19 - internal/api/client/account/accountdelete.go | 95 ----- internal/api/client/account/accountdelete_test.go | 101 ----- internal/api/client/account/accountget.go | 95 ----- internal/api/client/account/accountupdate.go | 216 ---------- internal/api/client/account/accountupdate_test.go | 452 --------------------- internal/api/client/account/accountverify.go | 78 ---- internal/api/client/account/accountverify_test.go | 91 ----- internal/api/client/account/block.go | 95 ----- internal/api/client/account/block_test.go | 74 ---- internal/api/client/account/follow.go | 124 ------ internal/api/client/account/follow_test.go | 75 ---- internal/api/client/account/followers.go | 98 ----- internal/api/client/account/following.go | 98 ----- internal/api/client/account/relationships.go | 93 ----- internal/api/client/account/statuses.go | 246 ----------- internal/api/client/account/statuses_test.go | 123 ------ internal/api/client/account/unblock.go | 96 ----- internal/api/client/account/unfollow.go | 96 ----- internal/api/client/accounts/account_test.go | 127 ++++++ internal/api/client/accounts/accountcreate.go | 150 +++++++ internal/api/client/accounts/accountcreate_test.go | 19 + internal/api/client/accounts/accountdelete.go | 95 +++++ internal/api/client/accounts/accountdelete_test.go | 101 +++++ internal/api/client/accounts/accountget.go | 95 +++++ internal/api/client/accounts/accounts.go | 119 ++++++ internal/api/client/accounts/accountupdate.go | 216 ++++++++++ internal/api/client/accounts/accountupdate_test.go | 452 +++++++++++++++++++++ internal/api/client/accounts/accountverify.go | 78 ++++ internal/api/client/accounts/accountverify_test.go | 91 +++++ internal/api/client/accounts/block.go | 95 +++++ internal/api/client/accounts/block_test.go | 74 ++++ internal/api/client/accounts/follow.go | 124 ++++++ internal/api/client/accounts/follow_test.go | 75 ++++ internal/api/client/accounts/followers.go | 98 +++++ internal/api/client/accounts/following.go | 98 +++++ internal/api/client/accounts/relationships.go | 93 +++++ internal/api/client/accounts/statuses.go | 246 +++++++++++ internal/api/client/accounts/statuses_test.go | 123 ++++++ internal/api/client/accounts/unblock.go | 96 +++++ internal/api/client/accounts/unfollow.go | 96 +++++ internal/api/client/admin/accountaction.go | 18 +- internal/api/client/admin/admin.go | 41 +- internal/api/client/admin/admin_test.go | 2 +- internal/api/client/admin/domainblockcreate.go | 26 +- internal/api/client/admin/domainblockdelete.go | 14 +- internal/api/client/admin/domainblockget.go | 16 +- internal/api/client/admin/domainblocksget.go | 14 +- internal/api/client/admin/emojicategoriesget.go | 12 +- internal/api/client/admin/emojicreate.go | 22 +- internal/api/client/admin/emojidelete.go | 14 +- internal/api/client/admin/emojiget.go | 14 +- internal/api/client/admin/emojisget.go | 16 +- internal/api/client/admin/emojiupdate.go | 36 +- internal/api/client/admin/mediacleanup.go | 14 +- internal/api/client/admin/mediarefetch.go | 8 +- internal/api/client/app/app.go | 48 --- internal/api/client/app/app_test.go | 21 - internal/api/client/app/appcreate.go | 126 ------ internal/api/client/apps/appcreate.go | 126 ++++++ internal/api/client/apps/apps.go | 43 ++ internal/api/client/auth/auth.go | 105 ----- internal/api/client/auth/auth_test.go | 139 ------- internal/api/client/auth/authorize.go | 335 --------------- internal/api/client/auth/authorize_test.go | 118 ------ internal/api/client/auth/callback.go | 311 -------------- internal/api/client/auth/oob.go | 111 ----- internal/api/client/auth/signin.go | 145 ------- internal/api/client/auth/token.go | 115 ------ internal/api/client/auth/token_test.go | 215 ---------- internal/api/client/auth/util.go | 31 -- internal/api/client/blocks/blocks.go | 17 +- internal/api/client/blocks/blocksget.go | 12 +- internal/api/client/bookmarks/bookmarks.go | 13 +- internal/api/client/bookmarks/bookmarks_test.go | 10 +- internal/api/client/bookmarks/bookmarksget.go | 14 +- internal/api/client/customemojis/customemojis.go | 45 ++ .../api/client/customemojis/customemojisget.go | 76 ++++ internal/api/client/emoji/emoji.go | 50 --- internal/api/client/emoji/emojisget.go | 58 --- internal/api/client/favourites/favourites.go | 17 +- internal/api/client/favourites/favourites_test.go | 2 +- internal/api/client/favourites/favouritesget.go | 12 +- internal/api/client/fileserver/fileserver.go | 64 --- internal/api/client/fileserver/fileserver_test.go | 109 ----- internal/api/client/fileserver/servefile.go | 135 ------ internal/api/client/fileserver/servefile_test.go | 272 ------------- internal/api/client/filter/filter.go | 50 --- internal/api/client/filter/filtersget.go | 25 -- internal/api/client/filters/filter.go | 45 ++ internal/api/client/filters/filtersget.go | 25 ++ internal/api/client/followrequest/authorize.go | 98 ----- .../api/client/followrequest/authorize_test.go | 115 ------ internal/api/client/followrequest/followrequest.go | 61 --- .../api/client/followrequest/followrequest_test.go | 122 ------ internal/api/client/followrequest/get.go | 93 ----- internal/api/client/followrequest/get_test.go | 78 ---- internal/api/client/followrequest/reject.go | 96 ----- internal/api/client/followrequest/reject_test.go | 87 ---- internal/api/client/followrequests/authorize.go | 98 +++++ .../api/client/followrequests/authorize_test.go | 115 ++++++ .../api/client/followrequests/followrequest.go | 56 +++ .../client/followrequests/followrequest_test.go | 122 ++++++ internal/api/client/followrequests/get.go | 93 +++++ internal/api/client/followrequests/get_test.go | 78 ++++ internal/api/client/followrequests/reject.go | 96 +++++ internal/api/client/followrequests/reject_test.go | 87 ++++ internal/api/client/instance/instance.go | 21 +- internal/api/client/instance/instance_test.go | 2 +- internal/api/client/instance/instanceget.go | 8 +- internal/api/client/instance/instancepatch.go | 22 +- internal/api/client/instance/instancepeersget.go | 12 +- internal/api/client/list/list.go | 50 --- internal/api/client/list/listsgets.go | 25 -- internal/api/client/lists/list.go | 45 ++ internal/api/client/lists/listsgets.go | 44 ++ internal/api/client/media/media.go | 27 +- internal/api/client/media/mediacreate.go | 34 +- internal/api/client/media/mediacreate_test.go | 53 +-- internal/api/client/media/mediaget.go | 18 +- internal/api/client/media/mediaupdate.go | 28 +- internal/api/client/media/mediaupdate_test.go | 31 +- internal/api/client/notification/notification.go | 66 --- .../api/client/notification/notificationsclear.go | 80 ---- .../api/client/notification/notificationsget.go | 159 -------- internal/api/client/notifications/notifications.go | 61 +++ .../api/client/notifications/notificationsclear.go | 80 ++++ .../api/client/notifications/notificationsget.go | 159 ++++++++ internal/api/client/search/search.go | 23 +- internal/api/client/search/search_test.go | 2 +- internal/api/client/search/searchget.go | 26 +- internal/api/client/status/status.go | 123 ------ internal/api/client/status/status_test.go | 98 ----- internal/api/client/status/statusbookmark.go | 98 ----- internal/api/client/status/statusbookmark_test.go | 83 ---- internal/api/client/status/statusboost.go | 101 ----- internal/api/client/status/statusboost_test.go | 247 ----------- internal/api/client/status/statusboostedby.go | 89 ---- internal/api/client/status/statusboostedby_test.go | 112 ----- internal/api/client/status/statuscontext.go | 100 ----- internal/api/client/status/statuscreate.go | 172 -------- internal/api/client/status/statuscreate_test.go | 398 ------------------ internal/api/client/status/statusdelete.go | 100 ----- internal/api/client/status/statusdelete_test.go | 91 ----- internal/api/client/status/statusfave.go | 97 ----- internal/api/client/status/statusfave_test.go | 131 ------ internal/api/client/status/statusfavedby.go | 98 ----- internal/api/client/status/statusfavedby_test.go | 88 ---- internal/api/client/status/statusget.go | 97 ----- internal/api/client/status/statusget_test.go | 33 -- internal/api/client/status/statusunbookmark.go | 98 ----- .../api/client/status/statusunbookmark_test.go | 78 ---- internal/api/client/status/statusunboost.go | 98 ----- internal/api/client/status/statusunfave.go | 97 ----- internal/api/client/status/statusunfave_test.go | 143 ------- internal/api/client/statuses/status.go | 100 +++++ internal/api/client/statuses/status_test.go | 98 +++++ internal/api/client/statuses/statusbookmark.go | 98 +++++ .../api/client/statuses/statusbookmark_test.go | 83 ++++ internal/api/client/statuses/statusboost.go | 101 +++++ internal/api/client/statuses/statusboost_test.go | 247 +++++++++++ internal/api/client/statuses/statusboostedby.go | 89 ++++ .../api/client/statuses/statusboostedby_test.go | 112 +++++ internal/api/client/statuses/statuscontext.go | 100 +++++ internal/api/client/statuses/statuscreate.go | 172 ++++++++ internal/api/client/statuses/statuscreate_test.go | 398 ++++++++++++++++++ internal/api/client/statuses/statusdelete.go | 100 +++++ internal/api/client/statuses/statusdelete_test.go | 91 +++++ internal/api/client/statuses/statusfave.go | 97 +++++ internal/api/client/statuses/statusfave_test.go | 132 ++++++ internal/api/client/statuses/statusfavedby.go | 98 +++++ internal/api/client/statuses/statusfavedby_test.go | 88 ++++ internal/api/client/statuses/statusget.go | 97 +++++ internal/api/client/statuses/statusget_test.go | 33 ++ internal/api/client/statuses/statusunbookmark.go | 98 +++++ .../api/client/statuses/statusunbookmark_test.go | 78 ++++ internal/api/client/statuses/statusunboost.go | 98 +++++ internal/api/client/statuses/statusunfave.go | 97 +++++ internal/api/client/statuses/statusunfave_test.go | 143 +++++++ internal/api/client/streaming/stream.go | 60 ++- internal/api/client/streaming/streaming.go | 19 +- internal/api/client/streaming/streaming_test.go | 2 +- internal/api/client/timeline/home.go | 176 -------- internal/api/client/timeline/public.go | 187 --------- internal/api/client/timeline/timeline.go | 65 --- internal/api/client/timelines/home.go | 176 ++++++++ internal/api/client/timelines/public.go | 187 +++++++++ internal/api/client/timelines/timeline.go | 60 +++ internal/api/client/user/passwordchange.go | 20 +- internal/api/client/user/user.go | 17 +- internal/api/client/user/user_test.go | 2 +- 194 files changed, 7904 insertions(+), 10207 deletions(-) delete mode 100644 internal/api/client/account/account.go delete mode 100644 internal/api/client/account/account_test.go delete mode 100644 internal/api/client/account/accountcreate.go delete mode 100644 internal/api/client/account/accountcreate_test.go delete mode 100644 internal/api/client/account/accountdelete.go delete mode 100644 internal/api/client/account/accountdelete_test.go delete mode 100644 internal/api/client/account/accountget.go delete mode 100644 internal/api/client/account/accountupdate.go delete mode 100644 internal/api/client/account/accountupdate_test.go delete mode 100644 internal/api/client/account/accountverify.go delete mode 100644 internal/api/client/account/accountverify_test.go delete mode 100644 internal/api/client/account/block.go delete mode 100644 internal/api/client/account/block_test.go delete mode 100644 internal/api/client/account/follow.go delete mode 100644 internal/api/client/account/follow_test.go delete mode 100644 internal/api/client/account/followers.go delete mode 100644 internal/api/client/account/following.go delete mode 100644 internal/api/client/account/relationships.go delete mode 100644 internal/api/client/account/statuses.go delete mode 100644 internal/api/client/account/statuses_test.go delete mode 100644 internal/api/client/account/unblock.go delete mode 100644 internal/api/client/account/unfollow.go create mode 100644 internal/api/client/accounts/account_test.go create mode 100644 internal/api/client/accounts/accountcreate.go create mode 100644 internal/api/client/accounts/accountcreate_test.go create mode 100644 internal/api/client/accounts/accountdelete.go create mode 100644 internal/api/client/accounts/accountdelete_test.go create mode 100644 internal/api/client/accounts/accountget.go create mode 100644 internal/api/client/accounts/accounts.go create mode 100644 internal/api/client/accounts/accountupdate.go create mode 100644 internal/api/client/accounts/accountupdate_test.go create mode 100644 internal/api/client/accounts/accountverify.go create mode 100644 internal/api/client/accounts/accountverify_test.go create mode 100644 internal/api/client/accounts/block.go create mode 100644 internal/api/client/accounts/block_test.go create mode 100644 internal/api/client/accounts/follow.go create mode 100644 internal/api/client/accounts/follow_test.go create mode 100644 internal/api/client/accounts/followers.go create mode 100644 internal/api/client/accounts/following.go create mode 100644 internal/api/client/accounts/relationships.go create mode 100644 internal/api/client/accounts/statuses.go create mode 100644 internal/api/client/accounts/statuses_test.go create mode 100644 internal/api/client/accounts/unblock.go create mode 100644 internal/api/client/accounts/unfollow.go delete mode 100644 internal/api/client/app/app.go delete mode 100644 internal/api/client/app/app_test.go delete mode 100644 internal/api/client/app/appcreate.go create mode 100644 internal/api/client/apps/appcreate.go create mode 100644 internal/api/client/apps/apps.go delete mode 100644 internal/api/client/auth/auth.go delete mode 100644 internal/api/client/auth/auth_test.go delete mode 100644 internal/api/client/auth/authorize.go delete mode 100644 internal/api/client/auth/authorize_test.go delete mode 100644 internal/api/client/auth/callback.go delete mode 100644 internal/api/client/auth/oob.go delete mode 100644 internal/api/client/auth/signin.go delete mode 100644 internal/api/client/auth/token.go delete mode 100644 internal/api/client/auth/token_test.go delete mode 100644 internal/api/client/auth/util.go create mode 100644 internal/api/client/customemojis/customemojis.go create mode 100644 internal/api/client/customemojis/customemojisget.go delete mode 100644 internal/api/client/emoji/emoji.go delete mode 100644 internal/api/client/emoji/emojisget.go delete mode 100644 internal/api/client/fileserver/fileserver.go delete mode 100644 internal/api/client/fileserver/fileserver_test.go delete mode 100644 internal/api/client/fileserver/servefile.go delete mode 100644 internal/api/client/fileserver/servefile_test.go delete mode 100644 internal/api/client/filter/filter.go delete mode 100644 internal/api/client/filter/filtersget.go create mode 100644 internal/api/client/filters/filter.go create mode 100644 internal/api/client/filters/filtersget.go delete mode 100644 internal/api/client/followrequest/authorize.go delete mode 100644 internal/api/client/followrequest/authorize_test.go delete mode 100644 internal/api/client/followrequest/followrequest.go delete mode 100644 internal/api/client/followrequest/followrequest_test.go delete mode 100644 internal/api/client/followrequest/get.go delete mode 100644 internal/api/client/followrequest/get_test.go delete mode 100644 internal/api/client/followrequest/reject.go delete mode 100644 internal/api/client/followrequest/reject_test.go create mode 100644 internal/api/client/followrequests/authorize.go create mode 100644 internal/api/client/followrequests/authorize_test.go create mode 100644 internal/api/client/followrequests/followrequest.go create mode 100644 internal/api/client/followrequests/followrequest_test.go create mode 100644 internal/api/client/followrequests/get.go create mode 100644 internal/api/client/followrequests/get_test.go create mode 100644 internal/api/client/followrequests/reject.go create mode 100644 internal/api/client/followrequests/reject_test.go delete mode 100644 internal/api/client/list/list.go delete mode 100644 internal/api/client/list/listsgets.go create mode 100644 internal/api/client/lists/list.go create mode 100644 internal/api/client/lists/listsgets.go delete mode 100644 internal/api/client/notification/notification.go delete mode 100644 internal/api/client/notification/notificationsclear.go delete mode 100644 internal/api/client/notification/notificationsget.go create mode 100644 internal/api/client/notifications/notifications.go create mode 100644 internal/api/client/notifications/notificationsclear.go create mode 100644 internal/api/client/notifications/notificationsget.go delete mode 100644 internal/api/client/status/status.go delete mode 100644 internal/api/client/status/status_test.go delete mode 100644 internal/api/client/status/statusbookmark.go delete mode 100644 internal/api/client/status/statusbookmark_test.go delete mode 100644 internal/api/client/status/statusboost.go delete mode 100644 internal/api/client/status/statusboost_test.go delete mode 100644 internal/api/client/status/statusboostedby.go delete mode 100644 internal/api/client/status/statusboostedby_test.go delete mode 100644 internal/api/client/status/statuscontext.go delete mode 100644 internal/api/client/status/statuscreate.go delete mode 100644 internal/api/client/status/statuscreate_test.go delete mode 100644 internal/api/client/status/statusdelete.go delete mode 100644 internal/api/client/status/statusdelete_test.go delete mode 100644 internal/api/client/status/statusfave.go delete mode 100644 internal/api/client/status/statusfave_test.go delete mode 100644 internal/api/client/status/statusfavedby.go delete mode 100644 internal/api/client/status/statusfavedby_test.go delete mode 100644 internal/api/client/status/statusget.go delete mode 100644 internal/api/client/status/statusget_test.go delete mode 100644 internal/api/client/status/statusunbookmark.go delete mode 100644 internal/api/client/status/statusunbookmark_test.go delete mode 100644 internal/api/client/status/statusunboost.go delete mode 100644 internal/api/client/status/statusunfave.go delete mode 100644 internal/api/client/status/statusunfave_test.go create mode 100644 internal/api/client/statuses/status.go create mode 100644 internal/api/client/statuses/status_test.go create mode 100644 internal/api/client/statuses/statusbookmark.go create mode 100644 internal/api/client/statuses/statusbookmark_test.go create mode 100644 internal/api/client/statuses/statusboost.go create mode 100644 internal/api/client/statuses/statusboost_test.go create mode 100644 internal/api/client/statuses/statusboostedby.go create mode 100644 internal/api/client/statuses/statusboostedby_test.go create mode 100644 internal/api/client/statuses/statuscontext.go create mode 100644 internal/api/client/statuses/statuscreate.go create mode 100644 internal/api/client/statuses/statuscreate_test.go create mode 100644 internal/api/client/statuses/statusdelete.go create mode 100644 internal/api/client/statuses/statusdelete_test.go create mode 100644 internal/api/client/statuses/statusfave.go create mode 100644 internal/api/client/statuses/statusfave_test.go create mode 100644 internal/api/client/statuses/statusfavedby.go create mode 100644 internal/api/client/statuses/statusfavedby_test.go create mode 100644 internal/api/client/statuses/statusget.go create mode 100644 internal/api/client/statuses/statusget_test.go create mode 100644 internal/api/client/statuses/statusunbookmark.go create mode 100644 internal/api/client/statuses/statusunbookmark_test.go create mode 100644 internal/api/client/statuses/statusunboost.go create mode 100644 internal/api/client/statuses/statusunfave.go create mode 100644 internal/api/client/statuses/statusunfave_test.go delete mode 100644 internal/api/client/timeline/home.go delete mode 100644 internal/api/client/timeline/public.go delete mode 100644 internal/api/client/timeline/timeline.go create mode 100644 internal/api/client/timelines/home.go create mode 100644 internal/api/client/timelines/public.go create mode 100644 internal/api/client/timelines/timeline.go (limited to 'internal/api/client') diff --git a/internal/api/client/account/account.go b/internal/api/client/account/account.go deleted file mode 100644 index 4205baa2c..000000000 --- a/internal/api/client/account/account.go +++ /dev/null @@ -1,141 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account - -import ( - "net/http" - "strings" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/processing" - - "github.com/superseriousbusiness/gotosocial/internal/router" -) - -const ( - // LimitKey is for setting the return amount limit for eg., requesting an account's statuses - LimitKey = "limit" - // ExcludeRepliesKey is for specifying whether to exclude replies in a list of returned statuses by an account. - ExcludeRepliesKey = "exclude_replies" - // ExcludeReblogsKey is for specifying whether to exclude reblogs in a list of returned statuses by an account. - ExcludeReblogsKey = "exclude_reblogs" - // PinnedKey is for specifying whether to include pinned statuses in a list of returned statuses by an account. - PinnedKey = "pinned" - // MaxIDKey is for specifying the maximum ID of the status to retrieve. - MaxIDKey = "max_id" - // MinIDKey is for specifying the minimum ID of the status to retrieve. - MinIDKey = "min_id" - // OnlyMediaKey is for specifying that only statuses with media should be returned in a list of returned statuses by an account. - OnlyMediaKey = "only_media" - // OnlyPublicKey is for specifying that only statuses with visibility public should be returned in a list of returned statuses by account. - OnlyPublicKey = "only_public" - - // IDKey is the key to use for retrieving account ID in requests - IDKey = "id" - // BasePath is the base API path for this module - BasePath = "/api/v1/accounts" - // BasePathWithID is the base path for this module with the ID key - BasePathWithID = BasePath + "/:" + IDKey - // VerifyPath is for verifying account credentials - VerifyPath = BasePath + "/verify_credentials" - // UpdateCredentialsPath is for updating account credentials - UpdateCredentialsPath = BasePath + "/update_credentials" - // GetStatusesPath is for showing an account's statuses - GetStatusesPath = BasePathWithID + "/statuses" - // GetFollowersPath is for showing an account's followers - GetFollowersPath = BasePathWithID + "/followers" - // GetFollowingPath is for showing account's that an account follows. - GetFollowingPath = BasePathWithID + "/following" - // GetRelationshipsPath is for showing an account's relationship with other accounts - GetRelationshipsPath = BasePath + "/relationships" - // FollowPath is for POSTing new follows to, and updating existing follows - FollowPath = BasePathWithID + "/follow" - // UnfollowPath is for POSTing an unfollow - UnfollowPath = BasePathWithID + "/unfollow" - // BlockPath is for creating a block of an account - BlockPath = BasePathWithID + "/block" - // UnblockPath is for removing a block of an account - UnblockPath = BasePathWithID + "/unblock" - // DeleteAccountPath is for deleting one's account via the API - DeleteAccountPath = BasePath + "/delete" -) - -// Module implements the ClientAPIModule interface for account-related actions -type Module struct { - processor processing.Processor -} - -// New returns a new account module -func New(processor processing.Processor) api.ClientModule { - return &Module{ - processor: processor, - } -} - -// Route attaches all routes from this module to the given router -func (m *Module) Route(r router.Router) error { - // create account - r.AttachHandler(http.MethodPost, BasePath, m.AccountCreatePOSTHandler) - - // delete account - r.AttachHandler(http.MethodPost, DeleteAccountPath, m.AccountDeletePOSTHandler) - - // get account - r.AttachHandler(http.MethodGet, BasePathWithID, m.muxHandler) - - // modify account - r.AttachHandler(http.MethodPatch, BasePathWithID, m.muxHandler) - - // get account's statuses - r.AttachHandler(http.MethodGet, GetStatusesPath, m.AccountStatusesGETHandler) - - // get following or followers - r.AttachHandler(http.MethodGet, GetFollowersPath, m.AccountFollowersGETHandler) - r.AttachHandler(http.MethodGet, GetFollowingPath, m.AccountFollowingGETHandler) - - // get relationship with account - r.AttachHandler(http.MethodGet, GetRelationshipsPath, m.AccountRelationshipsGETHandler) - - // follow or unfollow account - r.AttachHandler(http.MethodPost, FollowPath, m.AccountFollowPOSTHandler) - r.AttachHandler(http.MethodPost, UnfollowPath, m.AccountUnfollowPOSTHandler) - - // block or unblock account - r.AttachHandler(http.MethodPost, BlockPath, m.AccountBlockPOSTHandler) - r.AttachHandler(http.MethodPost, UnblockPath, m.AccountUnblockPOSTHandler) - - return nil -} - -func (m *Module) muxHandler(c *gin.Context) { - ru := c.Request.RequestURI - switch c.Request.Method { - case http.MethodGet: - if strings.HasPrefix(ru, VerifyPath) { - m.AccountVerifyGETHandler(c) - } else { - m.AccountGETHandler(c) - } - case http.MethodPatch: - if strings.HasPrefix(ru, UpdateCredentialsPath) { - m.AccountUpdateCredentialsPATCHHandler(c) - } - } -} diff --git a/internal/api/client/account/account_test.go b/internal/api/client/account/account_test.go deleted file mode 100644 index 90dbd6249..000000000 --- a/internal/api/client/account/account_test.go +++ /dev/null @@ -1,127 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account_test - -import ( - "bytes" - "fmt" - "net/http" - "net/http/httptest" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/account" - "github.com/superseriousbusiness/gotosocial/internal/concurrency" - "github.com/superseriousbusiness/gotosocial/internal/config" - "github.com/superseriousbusiness/gotosocial/internal/db" - "github.com/superseriousbusiness/gotosocial/internal/email" - "github.com/superseriousbusiness/gotosocial/internal/federation" - "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" - "github.com/superseriousbusiness/gotosocial/internal/media" - "github.com/superseriousbusiness/gotosocial/internal/messages" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/storage" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type AccountStandardTestSuite struct { - // standard suite interfaces - suite.Suite - db db.DB - storage *storage.Driver - mediaManager media.Manager - federator federation.Federator - processor processing.Processor - emailSender email.Sender - sentEmails map[string]string - - // standard suite models - testTokens map[string]*gtsmodel.Token - testClients map[string]*gtsmodel.Client - testApplications map[string]*gtsmodel.Application - testUsers map[string]*gtsmodel.User - testAccounts map[string]*gtsmodel.Account - testAttachments map[string]*gtsmodel.MediaAttachment - testStatuses map[string]*gtsmodel.Status - - // module being tested - accountModule *account.Module -} - -func (suite *AccountStandardTestSuite) SetupSuite() { - suite.testTokens = testrig.NewTestTokens() - suite.testClients = testrig.NewTestClients() - suite.testApplications = testrig.NewTestApplications() - suite.testUsers = testrig.NewTestUsers() - suite.testAccounts = testrig.NewTestAccounts() - suite.testAttachments = testrig.NewTestAttachments() - suite.testStatuses = testrig.NewTestStatuses() -} - -func (suite *AccountStandardTestSuite) SetupTest() { - testrig.InitTestConfig() - testrig.InitTestLog() - - fedWorker := concurrency.NewWorkerPool[messages.FromFederator](-1, -1) - clientWorker := concurrency.NewWorkerPool[messages.FromClientAPI](-1, -1) - - suite.db = testrig.NewTestDB() - suite.storage = testrig.NewInMemoryStorage() - suite.mediaManager = testrig.NewTestMediaManager(suite.db, suite.storage) - suite.federator = testrig.NewTestFederator(suite.db, testrig.NewTestTransportController(testrig.NewMockHTTPClient(nil, "../../../../testrig/media"), suite.db, fedWorker), suite.storage, suite.mediaManager, fedWorker) - suite.sentEmails = make(map[string]string) - suite.emailSender = testrig.NewEmailSender("../../../../web/template/", suite.sentEmails) - suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator, suite.emailSender, suite.mediaManager, clientWorker, fedWorker) - suite.accountModule = account.New(suite.processor).(*account.Module) - testrig.StandardDBSetup(suite.db, nil) - testrig.StandardStorageSetup(suite.storage, "../../../../testrig/media") - - suite.NoError(suite.processor.Start()) -} - -func (suite *AccountStandardTestSuite) TearDownTest() { - testrig.StandardDBTeardown(suite.db) - testrig.StandardStorageTeardown(suite.storage) -} - -func (suite *AccountStandardTestSuite) newContext(recorder *httptest.ResponseRecorder, requestMethod string, requestBody []byte, requestPath string, bodyContentType string) *gin.Context { - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauth.DBTokenToToken(suite.testTokens["local_account_1"])) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - - protocol := config.GetProtocol() - host := config.GetHost() - - baseURI := fmt.Sprintf("%s://%s", protocol, host) - requestURI := fmt.Sprintf("%s/%s", baseURI, requestPath) - - ctx.Request = httptest.NewRequest(http.MethodPatch, requestURI, bytes.NewReader(requestBody)) // the endpoint we're hitting - - if bodyContentType != "" { - ctx.Request.Header.Set("Content-Type", bodyContentType) - } - - ctx.Request.Header.Set("accept", "application/json") - - return ctx -} diff --git a/internal/api/client/account/accountcreate.go b/internal/api/client/account/accountcreate.go deleted file mode 100644 index e7b6c642d..000000000 --- a/internal/api/client/account/accountcreate.go +++ /dev/null @@ -1,150 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account - -import ( - "errors" - "net" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/config" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/internal/validate" -) - -// AccountCreatePOSTHandler swagger:operation POST /api/v1/accounts accountCreate -// -// Create a new account using an application token. -// -// The parameters can also be given in the body of the request, as JSON, if the content-type is set to 'application/json'. -// The parameters can also be given in the body of the request, as XML, if the content-type is set to 'application/xml'. -// -// --- -// tags: -// - accounts -// -// consumes: -// - application/json -// - application/xml -// - application/x-www-form-urlencoded -// -// produces: -// - application/json -// -// security: -// - OAuth2 Application: -// - write:accounts -// -// responses: -// '200': -// description: "An OAuth2 access token for the newly-created account." -// schema: -// "$ref": "#/definitions/oauthToken" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) AccountCreatePOSTHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, false, false) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - form := &model.AccountCreateRequest{} - if err := c.ShouldBind(form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - if err := validateCreateAccount(form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - clientIP := c.ClientIP() - signUpIP := net.ParseIP(clientIP) - if signUpIP == nil { - err := errors.New("ip address could not be parsed from request") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - form.IP = signUpIP - - ti, errWithCode := m.processor.AccountCreate(c.Request.Context(), authed, form) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, ti) -} - -// validateCreateAccount checks through all the necessary prerequisites for creating a new account, -// according to the provided account create request. If the account isn't eligible, an error will be returned. -func validateCreateAccount(form *model.AccountCreateRequest) error { - if form == nil { - return errors.New("form was nil") - } - - if !config.GetAccountsRegistrationOpen() { - return errors.New("registration is not open for this server") - } - - if err := validate.Username(form.Username); err != nil { - return err - } - - if err := validate.Email(form.Email); err != nil { - return err - } - - if err := validate.NewPassword(form.Password); err != nil { - return err - } - - if !form.Agreement { - return errors.New("agreement to terms and conditions not given") - } - - if err := validate.Language(form.Locale); err != nil { - return err - } - - if err := validate.SignUpReason(form.Reason, config.GetAccountsReasonRequired()); err != nil { - return err - } - - return nil -} diff --git a/internal/api/client/account/accountcreate_test.go b/internal/api/client/account/accountcreate_test.go deleted file mode 100644 index a4fc165bf..000000000 --- a/internal/api/client/account/accountcreate_test.go +++ /dev/null @@ -1,19 +0,0 @@ -// /* -// GoToSocial -// Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. - -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . -// */ - -package account_test diff --git a/internal/api/client/account/accountdelete.go b/internal/api/client/account/accountdelete.go deleted file mode 100644 index 53bdedd0f..000000000 --- a/internal/api/client/account/accountdelete.go +++ /dev/null @@ -1,95 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// AccountDeletePOSTHandler swagger:operation POST /api/v1/accounts/delete accountDelete -// -// Delete your account. -// -// --- -// tags: -// - accounts -// -// consumes: -// - multipart/form-data -// -// parameters: -// - -// name: password -// in: formData -// description: Password of the account user, for confirmation. -// type: string -// required: true -// -// security: -// - OAuth2 Bearer: -// - write:accounts -// -// responses: -// '202': -// description: "The account deletion has been accepted and the account will be deleted." -// '400': -// description: bad request -// '401': -// description: unauthorized -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) AccountDeletePOSTHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - form := &model.AccountDeleteRequest{} - if err := c.ShouldBind(&form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - if form.Password == "" { - err = errors.New("no password provided in account delete request") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - form.DeleteOriginID = authed.Account.ID - - if errWithCode := m.processor.AccountDeleteLocal(c.Request.Context(), authed, form); errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusAccepted, gin.H{"message": "accepted"}) -} diff --git a/internal/api/client/account/accountdelete_test.go b/internal/api/client/account/accountdelete_test.go deleted file mode 100644 index 78348eabc..000000000 --- a/internal/api/client/account/accountdelete_test.go +++ /dev/null @@ -1,101 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account_test - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/account" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type AccountDeleteTestSuite struct { - AccountStandardTestSuite -} - -func (suite *AccountDeleteTestSuite) TestAccountDeletePOSTHandler() { - // set up the request - // we're deleting zork - requestBody, w, err := testrig.CreateMultipartFormData( - "", "", - map[string]string{ - "password": "password", - }) - if err != nil { - panic(err) - } - bodyBytes := requestBody.Bytes() - recorder := httptest.NewRecorder() - ctx := suite.newContext(recorder, http.MethodPost, bodyBytes, account.DeleteAccountPath, w.FormDataContentType()) - - // call the handler - suite.accountModule.AccountDeletePOSTHandler(ctx) - - // 1. we should have Accepted because our request was valid - suite.Equal(http.StatusAccepted, recorder.Code) -} - -func (suite *AccountDeleteTestSuite) TestAccountDeletePOSTHandlerWrongPassword() { - // set up the request - // we're deleting zork - requestBody, w, err := testrig.CreateMultipartFormData( - "", "", - map[string]string{ - "password": "aaaaaaaaaaaaaaaaaaaaaaaaaaaa", - }) - if err != nil { - panic(err) - } - bodyBytes := requestBody.Bytes() - recorder := httptest.NewRecorder() - ctx := suite.newContext(recorder, http.MethodPost, bodyBytes, account.DeleteAccountPath, w.FormDataContentType()) - - // call the handler - suite.accountModule.AccountDeletePOSTHandler(ctx) - - // 1. we should have Forbidden because we supplied the wrong password - suite.Equal(http.StatusForbidden, recorder.Code) -} - -func (suite *AccountDeleteTestSuite) TestAccountDeletePOSTHandlerNoPassword() { - // set up the request - // we're deleting zork - requestBody, w, err := testrig.CreateMultipartFormData( - "", "", - map[string]string{}) - if err != nil { - panic(err) - } - bodyBytes := requestBody.Bytes() - recorder := httptest.NewRecorder() - ctx := suite.newContext(recorder, http.MethodPost, bodyBytes, account.DeleteAccountPath, w.FormDataContentType()) - - // call the handler - suite.accountModule.AccountDeletePOSTHandler(ctx) - - // 1. we should have StatusBadRequest because our request was invalid - suite.Equal(http.StatusBadRequest, recorder.Code) -} - -func TestAccountDeleteTestSuite(t *testing.T) { - suite.Run(t, new(AccountDeleteTestSuite)) -} diff --git a/internal/api/client/account/accountget.go b/internal/api/client/account/accountget.go deleted file mode 100644 index c9aae5b2b..000000000 --- a/internal/api/client/account/accountget.go +++ /dev/null @@ -1,95 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// AccountGETHandler swagger:operation GET /api/v1/accounts/{id} accountGet -// -// Get information about an account with the given ID. -// -// --- -// tags: -// - accounts -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: string -// description: The id of the requested account. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - read:accounts -// -// responses: -// '200': -// description: The requested account. -// schema: -// "$ref": "#/definitions/account" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) AccountGETHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetAcctID := c.Param(IDKey) - if targetAcctID == "" { - err := errors.New("no account id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - acctInfo, errWithCode := m.processor.AccountGet(c.Request.Context(), authed, targetAcctID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, acctInfo) -} diff --git a/internal/api/client/account/accountupdate.go b/internal/api/client/account/accountupdate.go deleted file mode 100644 index f89259a96..000000000 --- a/internal/api/client/account/accountupdate.go +++ /dev/null @@ -1,216 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account - -import ( - "errors" - "fmt" - "net/http" - "strconv" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// AccountUpdateCredentialsPATCHHandler swagger:operation PATCH /api/v1/accounts/update_credentials accountUpdate -// -// Update your account. -// -// --- -// tags: -// - accounts -// -// consumes: -// - multipart/form-data -// -// produces: -// - application/json -// -// parameters: -// - -// name: discoverable -// in: formData -// description: Account should be made discoverable and shown in the profile directory (if enabled). -// type: boolean -// - -// name: bot -// in: formData -// description: Account is flagged as a bot. -// type: boolean -// - -// name: display_name -// in: formData -// description: The display name to use for the account. -// type: string -// allowEmptyValue: true -// - -// name: note -// in: formData -// description: Bio/description of this account. -// type: string -// allowEmptyValue: true -// - -// name: avatar -// in: formData -// description: Avatar of the user. -// type: file -// - -// name: header -// in: formData -// description: Header of the user. -// type: file -// - -// name: locked -// in: formData -// description: Require manual approval of follow requests. -// type: boolean -// - -// name: source[privacy] -// in: formData -// description: Default post privacy for authored statuses. -// type: string -// - -// name: source[sensitive] -// in: formData -// description: Mark authored statuses as sensitive by default. -// type: boolean -// - -// name: source[language] -// in: formData -// description: Default language to use for authored statuses (ISO 6391). -// type: string -// - -// name: source[status_format] -// in: formData -// description: Default format to use for authored statuses (plain or markdown). -// type: string -// - -// name: custom_css -// in: formData -// description: >- -// Custom CSS to use when rendering this account's profile or statuses. -// String must be no more than 5,000 characters (~5kb). -// type: string -// - -// name: enable_rss -// in: formData -// description: Enable RSS feed for this account's Public posts at `/[username]/feed.rss` -// type: boolean -// -// security: -// - OAuth2 Bearer: -// - write:accounts -// -// responses: -// '200': -// description: "The newly updated account." -// schema: -// "$ref": "#/definitions/account" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) AccountUpdateCredentialsPATCHHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - form, err := parseUpdateAccountForm(c) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - acctSensitive, errWithCode := m.processor.AccountUpdate(c.Request.Context(), authed, form) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, acctSensitive) -} - -func parseUpdateAccountForm(c *gin.Context) (*model.UpdateCredentialsRequest, error) { - form := &model.UpdateCredentialsRequest{ - Source: &model.UpdateSource{}, - } - - if err := c.ShouldBind(&form); err != nil { - return nil, fmt.Errorf("could not parse form from request: %s", err) - } - - // parse source field-by-field - sourceMap := c.PostFormMap("source") - - if privacy, ok := sourceMap["privacy"]; ok { - form.Source.Privacy = &privacy - } - - if sensitive, ok := sourceMap["sensitive"]; ok { - sensitiveBool, err := strconv.ParseBool(sensitive) - if err != nil { - return nil, fmt.Errorf("error parsing form source[sensitive]: %s", err) - } - form.Source.Sensitive = &sensitiveBool - } - - if language, ok := sourceMap["language"]; ok { - form.Source.Language = &language - } - - if statusFormat, ok := sourceMap["status_format"]; ok { - form.Source.StatusFormat = &statusFormat - } - - if form == nil || - (form.Discoverable == nil && - form.Bot == nil && - form.DisplayName == nil && - form.Note == nil && - form.Avatar == nil && - form.Header == nil && - form.Locked == nil && - form.Source.Privacy == nil && - form.Source.Sensitive == nil && - form.Source.Language == nil && - form.Source.StatusFormat == nil && - form.FieldsAttributes == nil && - form.CustomCSS == nil && - form.EnableRSS == nil) { - return nil, errors.New("empty form submitted") - } - - return form, nil -} diff --git a/internal/api/client/account/accountupdate_test.go b/internal/api/client/account/accountupdate_test.go deleted file mode 100644 index 259bb69e9..000000000 --- a/internal/api/client/account/accountupdate_test.go +++ /dev/null @@ -1,452 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account_test - -import ( - "context" - "encoding/json" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/account" - apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type AccountUpdateTestSuite struct { - AccountStandardTestSuite -} - -func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandler() { - // set up the request - // we're updating the note of zork - newBio := "this is my new bio read it and weep" - requestBody, w, err := testrig.CreateMultipartFormData( - "", "", - map[string]string{ - "note": newBio, - }) - if err != nil { - panic(err) - } - bodyBytes := requestBody.Bytes() - recorder := httptest.NewRecorder() - ctx := suite.newContext(recorder, http.MethodPatch, bodyBytes, account.UpdateCredentialsPath, w.FormDataContentType()) - - // call the handler - suite.accountModule.AccountUpdateCredentialsPATCHHandler(ctx) - - // 1. we should have OK because our request was valid - suite.Equal(http.StatusOK, recorder.Code) - - // 2. we should have no error message in the result body - result := recorder.Result() - defer result.Body.Close() - - // check the response - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - // unmarshal the returned account - apimodelAccount := &apimodel.Account{} - err = json.Unmarshal(b, apimodelAccount) - suite.NoError(err) - - // check the returned api model account - // fields should be updated - suite.Equal("

this is my new bio read it and weep

", apimodelAccount.Note) - suite.Equal(newBio, apimodelAccount.Source.Note) -} - -func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandlerUnlockLock() { - // set up the first request - requestBody1, w1, err := testrig.CreateMultipartFormData( - "", "", - map[string]string{ - "locked": "false", - }) - if err != nil { - panic(err) - } - bodyBytes1 := requestBody1.Bytes() - recorder1 := httptest.NewRecorder() - ctx1 := suite.newContext(recorder1, http.MethodPatch, bodyBytes1, account.UpdateCredentialsPath, w1.FormDataContentType()) - - // call the handler - suite.accountModule.AccountUpdateCredentialsPATCHHandler(ctx1) - - // 1. we should have OK because our request was valid - suite.Equal(http.StatusOK, recorder1.Code) - - // 2. we should have no error message in the result body - result1 := recorder1.Result() - defer result1.Body.Close() - - // check the response - b1, err := ioutil.ReadAll(result1.Body) - suite.NoError(err) - - // unmarshal the returned account - apimodelAccount1 := &apimodel.Account{} - err = json.Unmarshal(b1, apimodelAccount1) - suite.NoError(err) - - // check the returned api model account - // fields should be updated - suite.False(apimodelAccount1.Locked) - - // set up the first request - requestBody2, w2, err := testrig.CreateMultipartFormData( - "", "", - map[string]string{ - "locked": "true", - }) - if err != nil { - panic(err) - } - bodyBytes2 := requestBody2.Bytes() - recorder2 := httptest.NewRecorder() - ctx2 := suite.newContext(recorder2, http.MethodPatch, bodyBytes2, account.UpdateCredentialsPath, w2.FormDataContentType()) - - // call the handler - suite.accountModule.AccountUpdateCredentialsPATCHHandler(ctx2) - - // 1. we should have OK because our request was valid - suite.Equal(http.StatusOK, recorder1.Code) - - // 2. we should have no error message in the result body - result2 := recorder2.Result() - defer result2.Body.Close() - - // check the response - b2, err := ioutil.ReadAll(result2.Body) - suite.NoError(err) - - // unmarshal the returned account - apimodelAccount2 := &apimodel.Account{} - err = json.Unmarshal(b2, apimodelAccount2) - suite.NoError(err) - - // check the returned api model account - // fields should be updated - suite.True(apimodelAccount2.Locked) -} - -func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandlerGetAccountFirst() { - // get the account first to make sure it's in the database cache -- when the account is updated via - // the PATCH handler, it should invalidate the cache and not return the old version - _, err := suite.db.GetAccountByID(context.Background(), suite.testAccounts["local_account_1"].ID) - suite.NoError(err) - - // set up the request - // we're updating the note of zork - newBio := "this is my new bio read it and weep" - requestBody, w, err := testrig.CreateMultipartFormData( - "", "", - map[string]string{ - "note": newBio, - }) - if err != nil { - panic(err) - } - bodyBytes := requestBody.Bytes() - recorder := httptest.NewRecorder() - ctx := suite.newContext(recorder, http.MethodPatch, bodyBytes, account.UpdateCredentialsPath, w.FormDataContentType()) - - // call the handler - suite.accountModule.AccountUpdateCredentialsPATCHHandler(ctx) - - // 1. we should have OK because our request was valid - suite.Equal(http.StatusOK, recorder.Code) - - // 2. we should have no error message in the result body - result := recorder.Result() - defer result.Body.Close() - - // check the response - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - // unmarshal the returned account - apimodelAccount := &apimodel.Account{} - err = json.Unmarshal(b, apimodelAccount) - suite.NoError(err) - - // check the returned api model account - // fields should be updated - suite.Equal("

this is my new bio read it and weep

", apimodelAccount.Note) - suite.Equal(newBio, apimodelAccount.Source.Note) -} - -func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandlerTwoFields() { - // set up the request - // we're updating the note of zork, and setting locked to true - newBio := "this is my new bio read it and weep :rainbow:" - requestBody, w, err := testrig.CreateMultipartFormData( - "", "", - map[string]string{ - "note": newBio, - "locked": "true", - }) - if err != nil { - panic(err) - } - bodyBytes := requestBody.Bytes() - recorder := httptest.NewRecorder() - ctx := suite.newContext(recorder, http.MethodPatch, bodyBytes, account.UpdateCredentialsPath, w.FormDataContentType()) - - // call the handler - suite.accountModule.AccountUpdateCredentialsPATCHHandler(ctx) - - // 1. we should have OK because our request was valid - suite.Equal(http.StatusOK, recorder.Code) - - // 2. we should have no error message in the result body - result := recorder.Result() - defer result.Body.Close() - - // check the response - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - // unmarshal the returned account - apimodelAccount := &apimodel.Account{} - err = json.Unmarshal(b, apimodelAccount) - suite.NoError(err) - - // check the returned api model account - // fields should be updated - suite.Equal("

this is my new bio read it and weep :rainbow:

", apimodelAccount.Note) - suite.Equal(newBio, apimodelAccount.Source.Note) - suite.True(apimodelAccount.Locked) - suite.NotEmpty(apimodelAccount.Emojis) - suite.Equal(apimodelAccount.Emojis[0].Shortcode, "rainbow") - - // check the account in the database - dbZork, err := suite.db.GetAccountByID(context.Background(), apimodelAccount.ID) - suite.NoError(err) - suite.Equal(newBio, dbZork.NoteRaw) - suite.Equal("

this is my new bio read it and weep :rainbow:

", dbZork.Note) - suite.True(*dbZork.Locked) - suite.NotEmpty(dbZork.EmojiIDs) -} - -func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandlerWithMedia() { - // set up the request - // we're updating the header image, the display name, and the locked status of zork - // we're removing the note/bio - requestBody, w, err := testrig.CreateMultipartFormData( - "header", "../../../../testrig/media/test-jpeg.jpg", - map[string]string{ - "display_name": "updated zork display name!!!", - "note": "", - "locked": "true", - }) - if err != nil { - panic(err) - } - bodyBytes := requestBody.Bytes() - recorder := httptest.NewRecorder() - ctx := suite.newContext(recorder, http.MethodPatch, bodyBytes, account.UpdateCredentialsPath, w.FormDataContentType()) - - // call the handler - suite.accountModule.AccountUpdateCredentialsPATCHHandler(ctx) - - // 1. we should have OK because our request was valid - suite.Equal(http.StatusOK, recorder.Code) - - // 2. we should have no error message in the result body - result := recorder.Result() - defer result.Body.Close() - - // check the response - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - // unmarshal the returned account - apimodelAccount := &apimodel.Account{} - err = json.Unmarshal(b, apimodelAccount) - suite.NoError(err) - - // check the returned api model account - // fields should be updated - suite.Equal("updated zork display name!!!", apimodelAccount.DisplayName) - suite.True(apimodelAccount.Locked) - suite.Empty(apimodelAccount.Note) - suite.Empty(apimodelAccount.Source.Note) - - // header values... - // should be set - suite.NotEmpty(apimodelAccount.Header) - suite.NotEmpty(apimodelAccount.HeaderStatic) - - // should be different from the values set before - suite.NotEqual("http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/header/original/01PFPMWK2FF0D9WMHEJHR07C3Q.jpeg", apimodelAccount.Header) - suite.NotEqual("http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/header/small/01PFPMWK2FF0D9WMHEJHR07C3Q.jpeg", apimodelAccount.HeaderStatic) -} - -func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandlerEmptyForm() { - // set up the request - bodyBytes := []byte{} - recorder := httptest.NewRecorder() - ctx := suite.newContext(recorder, http.MethodPatch, bodyBytes, account.UpdateCredentialsPath, "") - - // call the handler - suite.accountModule.AccountUpdateCredentialsPATCHHandler(ctx) - - // 1. we should have OK because our request was valid - suite.Equal(http.StatusBadRequest, recorder.Code) - - // 2. we should have no error message in the result body - result := recorder.Result() - defer result.Body.Close() - - // check the response - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - suite.Equal(`{"error":"Bad Request: empty form submitted"}`, string(b)) -} - -func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandlerUpdateSource() { - // set up the request - // we're updating the language of zork - newLanguage := "de" - requestBody, w, err := testrig.CreateMultipartFormData( - "", "", - map[string]string{ - "source[privacy]": string(apimodel.VisibilityPrivate), - "source[language]": "de", - "source[sensitive]": "true", - "locked": "true", - }) - if err != nil { - panic(err) - } - bodyBytes := requestBody.Bytes() - recorder := httptest.NewRecorder() - ctx := suite.newContext(recorder, http.MethodPatch, bodyBytes, account.UpdateCredentialsPath, w.FormDataContentType()) - - // call the handler - suite.accountModule.AccountUpdateCredentialsPATCHHandler(ctx) - - // 1. we should have OK because our request was valid - suite.Equal(http.StatusOK, recorder.Code) - - // 2. we should have no error message in the result body - result := recorder.Result() - defer result.Body.Close() - - // check the response - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - // unmarshal the returned account - apimodelAccount := &apimodel.Account{} - err = json.Unmarshal(b, apimodelAccount) - suite.NoError(err) - - // check the returned api model account - // fields should be updated - suite.Equal(newLanguage, apimodelAccount.Source.Language) - suite.EqualValues(apimodel.VisibilityPrivate, apimodelAccount.Source.Privacy) - suite.True(apimodelAccount.Source.Sensitive) - suite.True(apimodelAccount.Locked) -} - -func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandlerUpdateStatusFormatOK() { - // set up the request - // we're updating the language of zork - requestBody, w, err := testrig.CreateMultipartFormData( - "", "", - map[string]string{ - "source[status_format]": "markdown", - }) - if err != nil { - panic(err) - } - bodyBytes := requestBody.Bytes() - recorder := httptest.NewRecorder() - ctx := suite.newContext(recorder, http.MethodPatch, bodyBytes, account.UpdateCredentialsPath, w.FormDataContentType()) - - // call the handler - suite.accountModule.AccountUpdateCredentialsPATCHHandler(ctx) - - // 1. we should have OK because our request was valid - suite.Equal(http.StatusOK, recorder.Code) - - // 2. we should have no error message in the result body - result := recorder.Result() - defer result.Body.Close() - - // check the response - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - // unmarshal the returned account - apimodelAccount := &apimodel.Account{} - err = json.Unmarshal(b, apimodelAccount) - suite.NoError(err) - - // check the returned api model account - // fields should be updated - suite.Equal("markdown", apimodelAccount.Source.StatusFormat) - - dbAccount, err := suite.db.GetAccountByID(context.Background(), suite.testAccounts["local_account_1"].ID) - if err != nil { - suite.FailNow(err.Error()) - } - suite.Equal(dbAccount.StatusFormat, "markdown") -} - -func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandlerUpdateStatusFormatBad() { - // set up the request - // we're updating the language of zork - requestBody, w, err := testrig.CreateMultipartFormData( - "", "", - map[string]string{ - "source[status_format]": "peepeepoopoo", - }) - if err != nil { - panic(err) - } - bodyBytes := requestBody.Bytes() - recorder := httptest.NewRecorder() - ctx := suite.newContext(recorder, http.MethodPatch, bodyBytes, account.UpdateCredentialsPath, w.FormDataContentType()) - - // call the handler - suite.accountModule.AccountUpdateCredentialsPATCHHandler(ctx) - - suite.Equal(http.StatusBadRequest, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - - // check the response - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - suite.Equal(`{"error":"Bad Request: status format 'peepeepoopoo' was not recognized, valid options are 'plain', 'markdown'"}`, string(b)) -} - -func TestAccountUpdateTestSuite(t *testing.T) { - suite.Run(t, new(AccountUpdateTestSuite)) -} diff --git a/internal/api/client/account/accountverify.go b/internal/api/client/account/accountverify.go deleted file mode 100644 index 916d0a322..000000000 --- a/internal/api/client/account/accountverify.go +++ /dev/null @@ -1,78 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account - -import ( - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// AccountVerifyGETHandler swagger:operation GET /api/v1/accounts/verify_credentials accountVerify -// -// Verify a token by returning account details pertaining to it. -// -// --- -// tags: -// - accounts -// -// produces: -// - application/json -// -// security: -// - OAuth2 Bearer: -// - read:accounts -// -// responses: -// '200': -// schema: -// "$ref": "#/definitions/account" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) AccountVerifyGETHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - acctSensitive, errWithCode := m.processor.AccountGet(c.Request.Context(), authed, authed.Account.ID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, acctSensitive) -} diff --git a/internal/api/client/account/accountverify_test.go b/internal/api/client/account/accountverify_test.go deleted file mode 100644 index 886272865..000000000 --- a/internal/api/client/account/accountverify_test.go +++ /dev/null @@ -1,91 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account_test - -import ( - "encoding/json" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/account" - apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" -) - -type AccountVerifyTestSuite struct { - AccountStandardTestSuite -} - -func (suite *AccountVerifyTestSuite) TestAccountVerifyGet() { - testAccount := suite.testAccounts["local_account_1"] - - // set up the request - recorder := httptest.NewRecorder() - ctx := suite.newContext(recorder, http.MethodGet, nil, account.VerifyPath, "") - - // call the handler - suite.accountModule.AccountVerifyGETHandler(ctx) - - // 1. we should have OK because our request was valid - suite.Equal(http.StatusOK, recorder.Code) - - // 2. we should have no error message in the result body - result := recorder.Result() - defer result.Body.Close() - - // check the response - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - - // unmarshal the returned account - apimodelAccount := &apimodel.Account{} - err = json.Unmarshal(b, apimodelAccount) - suite.NoError(err) - - createdAt, err := time.Parse(time.RFC3339, apimodelAccount.CreatedAt) - suite.NoError(err) - - suite.Equal(testAccount.ID, apimodelAccount.ID) - suite.Equal(testAccount.Username, apimodelAccount.Username) - suite.Equal(testAccount.Username, apimodelAccount.Acct) - suite.Equal(testAccount.DisplayName, apimodelAccount.DisplayName) - suite.Equal(*testAccount.Locked, apimodelAccount.Locked) - suite.Equal(*testAccount.Bot, apimodelAccount.Bot) - suite.WithinDuration(testAccount.CreatedAt, createdAt, 30*time.Second) // we lose a bit of accuracy serializing so fuzz this a bit - suite.Equal(testAccount.URL, apimodelAccount.URL) - suite.Equal("http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/avatar/original/01F8MH58A357CV5K7R7TJMSH6S.jpeg", apimodelAccount.Avatar) - suite.Equal("http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/avatar/small/01F8MH58A357CV5K7R7TJMSH6S.jpeg", apimodelAccount.AvatarStatic) - suite.Equal("http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/header/original/01PFPMWK2FF0D9WMHEJHR07C3Q.jpeg", apimodelAccount.Header) - suite.Equal("http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/header/small/01PFPMWK2FF0D9WMHEJHR07C3Q.jpeg", apimodelAccount.HeaderStatic) - suite.Equal(2, apimodelAccount.FollowersCount) - suite.Equal(2, apimodelAccount.FollowingCount) - suite.Equal(5, apimodelAccount.StatusesCount) - suite.EqualValues(gtsmodel.VisibilityPublic, apimodelAccount.Source.Privacy) - suite.Equal(testAccount.Language, apimodelAccount.Source.Language) - suite.Equal(testAccount.NoteRaw, apimodelAccount.Source.Note) -} - -func TestAccountVerifyTestSuite(t *testing.T) { - suite.Run(t, new(AccountVerifyTestSuite)) -} diff --git a/internal/api/client/account/block.go b/internal/api/client/account/block.go deleted file mode 100644 index 9840c96ab..000000000 --- a/internal/api/client/account/block.go +++ /dev/null @@ -1,95 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// AccountBlockPOSTHandler swagger:operation POST /api/v1/accounts/{id}/block accountBlock -// -// Block account with id. -// -// --- -// tags: -// - accounts -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: string -// description: The id of the account to block. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - write:blocks -// -// responses: -// '200': -// description: Your relationship to the account. -// schema: -// "$ref": "#/definitions/accountRelationship" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) AccountBlockPOSTHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetAcctID := c.Param(IDKey) - if targetAcctID == "" { - err := errors.New("no account id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - relationship, errWithCode := m.processor.AccountBlockCreate(c.Request.Context(), authed, targetAcctID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, relationship) -} diff --git a/internal/api/client/account/block_test.go b/internal/api/client/account/block_test.go deleted file mode 100644 index 9c75330aa..000000000 --- a/internal/api/client/account/block_test.go +++ /dev/null @@ -1,74 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account_test - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/account" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type BlockTestSuite struct { - AccountStandardTestSuite -} - -func (suite *BlockTestSuite) TestBlockSelf() { - testAcct := suite.testAccounts["local_account_1"] - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedAccount, testAcct) - ctx.Set(oauth.SessionAuthorizedToken, oauth.DBTokenToToken(suite.testTokens["local_account_1"])) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(account.BlockPath, ":id", testAcct.ID, 1)), nil) - - ctx.Params = gin.Params{ - gin.Param{ - Key: account.IDKey, - Value: testAcct.ID, - }, - } - - suite.accountModule.AccountBlockPOSTHandler(ctx) - - // 1. status should be Not Acceptable due to attempted self-block - suite.Equal(http.StatusNotAcceptable, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - - // check the response - b, err := ioutil.ReadAll(result.Body) - _ = b - assert.NoError(suite.T(), err) -} - -func TestBlockTestSuite(t *testing.T) { - suite.Run(t, new(BlockTestSuite)) -} diff --git a/internal/api/client/account/follow.go b/internal/api/client/account/follow.go deleted file mode 100644 index cc523a7f8..000000000 --- a/internal/api/client/account/follow.go +++ /dev/null @@ -1,124 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// AccountFollowPOSTHandler swagger:operation POST /api/v1/accounts/{id}/follow accountFollow -// -// Follow account with id. -// -// The parameters can also be given in the body of the request, as JSON, if the content-type is set to 'application/json'. -// The parameters can also be given in the body of the request, as XML, if the content-type is set to 'application/xml'. -// -// --- -// tags: -// - accounts -// -// consumes: -// - application/json -// - application/xml -// - application/x-www-form-urlencoded -// -// parameters: -// - -// name: id -// required: true -// in: path -// description: ID of the account to follow. -// type: string -// - -// name: reblogs -// type: boolean -// default: true -// description: Show reblogs from this account. -// in: formData -// - -// default: false -// description: Notify when this account posts. -// in: formData -// name: notify -// type: boolean -// -// produces: -// - application/json -// -// security: -// - OAuth2 Bearer: -// - write:follows -// -// responses: -// '200': -// name: account relationship -// description: Your relationship to this account. -// schema: -// "$ref": "#/definitions/accountRelationship" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) AccountFollowPOSTHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetAcctID := c.Param(IDKey) - if targetAcctID == "" { - err := errors.New("no account id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - form := &model.AccountFollowRequest{} - if err := c.ShouldBind(form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - form.ID = targetAcctID - - relationship, errWithCode := m.processor.AccountFollowCreate(c.Request.Context(), authed, form) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, relationship) -} diff --git a/internal/api/client/account/follow_test.go b/internal/api/client/account/follow_test.go deleted file mode 100644 index fad67b185..000000000 --- a/internal/api/client/account/follow_test.go +++ /dev/null @@ -1,75 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account_test - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/account" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type FollowTestSuite struct { - AccountStandardTestSuite -} - -func (suite *FollowTestSuite) TestFollowSelf() { - testAcct := suite.testAccounts["local_account_1"] - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedAccount, testAcct) - ctx.Set(oauth.SessionAuthorizedToken, oauth.DBTokenToToken(suite.testTokens["local_account_1"])) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(account.FollowPath, ":id", testAcct.ID, 1)), nil) - - ctx.Params = gin.Params{ - gin.Param{ - Key: account.IDKey, - Value: testAcct.ID, - }, - } - - // call the handler - suite.accountModule.AccountFollowPOSTHandler(ctx) - - // 1. status should be Not Acceptable due to self-follow attempt - suite.Equal(http.StatusNotAcceptable, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - - // check the response - b, err := ioutil.ReadAll(result.Body) - _ = b - assert.NoError(suite.T(), err) -} - -func TestFollowTestSuite(t *testing.T) { - suite.Run(t, new(FollowTestSuite)) -} diff --git a/internal/api/client/account/followers.go b/internal/api/client/account/followers.go deleted file mode 100644 index cb2f4bfa6..000000000 --- a/internal/api/client/account/followers.go +++ /dev/null @@ -1,98 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// AccountFollowersGETHandler swagger:operation GET /api/v1/accounts/{id}/followers accountFollowers -// -// See followers of account with given id. -// -// --- -// tags: -// - accounts -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: string -// description: Account ID. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - read:accounts -// -// responses: -// '200': -// name: accounts -// description: Array of accounts that follow this account. -// schema: -// type: array -// items: -// "$ref": "#/definitions/account" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) AccountFollowersGETHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetAcctID := c.Param(IDKey) - if targetAcctID == "" { - err := errors.New("no account id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - followers, errWithCode := m.processor.AccountFollowersGet(c.Request.Context(), authed, targetAcctID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, followers) -} diff --git a/internal/api/client/account/following.go b/internal/api/client/account/following.go deleted file mode 100644 index 3d69739c3..000000000 --- a/internal/api/client/account/following.go +++ /dev/null @@ -1,98 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// AccountFollowingGETHandler swagger:operation GET /api/v1/accounts/{id}/following accountFollowing -// -// See accounts followed by given account id. -// -// --- -// tags: -// - accounts -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: string -// description: Account ID. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - read:accounts -// -// responses: -// '200': -// name: accounts -// description: Array of accounts that are followed by this account. -// schema: -// type: array -// items: -// "$ref": "#/definitions/account" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) AccountFollowingGETHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetAcctID := c.Param(IDKey) - if targetAcctID == "" { - err := errors.New("no account id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - following, errWithCode := m.processor.AccountFollowingGet(c.Request.Context(), authed, targetAcctID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, following) -} diff --git a/internal/api/client/account/relationships.go b/internal/api/client/account/relationships.go deleted file mode 100644 index 56159d48e..000000000 --- a/internal/api/client/account/relationships.go +++ /dev/null @@ -1,93 +0,0 @@ -package account - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// AccountRelationshipsGETHandler swagger:operation GET /api/v1/accounts/relationships accountRelationships -// -// See your account's relationships with the given account IDs. -// -// --- -// tags: -// - accounts -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: array -// items: -// type: string -// description: Account IDs. -// in: query -// required: true -// -// security: -// - OAuth2 Bearer: -// - read:accounts -// -// responses: -// '200': -// name: account relationships -// description: Array of account relationships. -// schema: -// type: array -// items: -// "$ref": "#/definitions/accountRelationship" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) AccountRelationshipsGETHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetAccountIDs := c.QueryArray("id[]") - if len(targetAccountIDs) == 0 { - // check fallback -- let's be generous and see if maybe it's just set as 'id'? - id := c.Query("id") - if id == "" { - err = errors.New("no account id(s) specified in query") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - targetAccountIDs = append(targetAccountIDs, id) - } - - relationships := []model.Relationship{} - - for _, targetAccountID := range targetAccountIDs { - r, errWithCode := m.processor.AccountRelationshipGet(c.Request.Context(), authed, targetAccountID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - relationships = append(relationships, *r) - } - - c.JSON(http.StatusOK, relationships) -} diff --git a/internal/api/client/account/statuses.go b/internal/api/client/account/statuses.go deleted file mode 100644 index 7ecf3ba9f..000000000 --- a/internal/api/client/account/statuses.go +++ /dev/null @@ -1,246 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account - -import ( - "errors" - "fmt" - "net/http" - "strconv" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// AccountStatusesGETHandler swagger:operation GET /api/v1/accounts/{id}/statuses accountStatuses -// -// See statuses posted by the requested account. -// -// The statuses will be returned in descending chronological order (newest first), with sequential IDs (bigger = newer). -// -// --- -// tags: -// - accounts -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: string -// description: Account ID. -// in: path -// required: true -// - -// name: limit -// type: integer -// description: Number of statuses to return. -// default: 30 -// in: query -// required: false -// - -// name: exclude_replies -// type: boolean -// description: Exclude statuses that are a reply to another status. -// default: false -// in: query -// required: false -// - -// name: exclude_reblogs -// type: boolean -// description: Exclude statuses that are a reblog/boost of another status. -// default: false -// in: query -// required: false -// - -// name: max_id -// type: string -// description: >- -// Return only statuses *OLDER* than the given max status ID. -// The status with the specified ID will not be included in the response. -// in: query -// - -// name: min_id -// type: string -// description: >- -// Return only statuses *NEWER* than the given min status ID. -// The status with the specified ID will not be included in the response. -// in: query -// required: false -// - -// name: pinned_only -// type: boolean -// description: Show only pinned statuses. In other words, exclude statuses that are not pinned to the given account ID. -// default: false -// in: query -// required: false -// - -// name: only_media -// type: boolean -// description: Show only statuses with media attachments. -// default: false -// in: query -// required: false -// - -// name: only_public -// type: boolean -// description: Show only statuses with a privacy setting of 'public'. -// default: false -// in: query -// required: false -// -// security: -// - OAuth2 Bearer: -// - read:accounts -// -// responses: -// '200': -// name: statuses -// description: Array of statuses. -// schema: -// type: array -// items: -// "$ref": "#/definitions/status" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) AccountStatusesGETHandler(c *gin.Context) { - authed, err := oauth.Authed(c, false, false, false, false) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetAcctID := c.Param(IDKey) - if targetAcctID == "" { - err := errors.New("no account id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - limit := 30 - limitString := c.Query(LimitKey) - if limitString != "" { - i, err := strconv.ParseInt(limitString, 10, 32) - if err != nil { - err := fmt.Errorf("error parsing %s: %s", LimitKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - limit = int(i) - } - - excludeReplies := false - excludeRepliesString := c.Query(ExcludeRepliesKey) - if excludeRepliesString != "" { - i, err := strconv.ParseBool(excludeRepliesString) - if err != nil { - err := fmt.Errorf("error parsing %s: %s", ExcludeRepliesKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - excludeReplies = i - } - - excludeReblogs := false - excludeReblogsString := c.Query(ExcludeReblogsKey) - if excludeReblogsString != "" { - i, err := strconv.ParseBool(excludeReblogsString) - if err != nil { - err := fmt.Errorf("error parsing %s: %s", ExcludeReblogsKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - excludeReblogs = i - } - - maxID := "" - maxIDString := c.Query(MaxIDKey) - if maxIDString != "" { - maxID = maxIDString - } - - minID := "" - minIDString := c.Query(MinIDKey) - if minIDString != "" { - minID = minIDString - } - - pinnedOnly := false - pinnedString := c.Query(PinnedKey) - if pinnedString != "" { - i, err := strconv.ParseBool(pinnedString) - if err != nil { - err := fmt.Errorf("error parsing %s: %s", PinnedKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - pinnedOnly = i - } - - mediaOnly := false - mediaOnlyString := c.Query(OnlyMediaKey) - if mediaOnlyString != "" { - i, err := strconv.ParseBool(mediaOnlyString) - if err != nil { - err := fmt.Errorf("error parsing %s: %s", OnlyMediaKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - mediaOnly = i - } - - publicOnly := false - publicOnlyString := c.Query(OnlyPublicKey) - if publicOnlyString != "" { - i, err := strconv.ParseBool(publicOnlyString) - if err != nil { - err := fmt.Errorf("error parsing %s: %s", OnlyPublicKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - publicOnly = i - } - - resp, errWithCode := m.processor.AccountStatusesGet(c.Request.Context(), authed, targetAcctID, limit, excludeReplies, excludeReblogs, maxID, minID, pinnedOnly, mediaOnly, publicOnly) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - if resp.LinkHeader != "" { - c.Header("Link", resp.LinkHeader) - } - c.JSON(http.StatusOK, resp.Items) -} diff --git a/internal/api/client/account/statuses_test.go b/internal/api/client/account/statuses_test.go deleted file mode 100644 index 1f935896c..000000000 --- a/internal/api/client/account/statuses_test.go +++ /dev/null @@ -1,123 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account_test - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/account" - apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" -) - -type AccountStatusesTestSuite struct { - AccountStandardTestSuite -} - -func (suite *AccountStatusesTestSuite) TestGetStatusesPublicOnly() { - // set up the request - // we're getting statuses of admin - targetAccount := suite.testAccounts["admin_account"] - recorder := httptest.NewRecorder() - ctx := suite.newContext(recorder, http.MethodGet, nil, fmt.Sprintf("/api/v1/accounts/%s/statuses?limit=20&only_media=false&only_public=true", targetAccount.ID), "") - ctx.Params = gin.Params{ - gin.Param{ - Key: account.IDKey, - Value: targetAccount.ID, - }, - } - - // call the handler - suite.accountModule.AccountStatusesGETHandler(ctx) - - // 1. we should have OK because our request was valid - suite.Equal(http.StatusOK, recorder.Code) - - // 2. we should have no error message in the result body - result := recorder.Result() - defer result.Body.Close() - - // check the response - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - - // unmarshal the returned statuses - apimodelStatuses := []*apimodel.Status{} - err = json.Unmarshal(b, &apimodelStatuses) - suite.NoError(err) - suite.NotEmpty(apimodelStatuses) - - for _, s := range apimodelStatuses { - suite.Equal(apimodel.VisibilityPublic, s.Visibility) - } - - suite.Equal(`; rel="next", ; rel="prev"`, result.Header.Get("link")) -} - -func (suite *AccountStatusesTestSuite) TestGetStatusesPublicOnlyMediaOnly() { - // set up the request - // we're getting statuses of admin - targetAccount := suite.testAccounts["admin_account"] - recorder := httptest.NewRecorder() - ctx := suite.newContext(recorder, http.MethodGet, nil, fmt.Sprintf("/api/v1/accounts/%s/statuses?limit=20&only_media=true&only_public=true", targetAccount.ID), "") - ctx.Params = gin.Params{ - gin.Param{ - Key: account.IDKey, - Value: targetAccount.ID, - }, - } - - // call the handler - suite.accountModule.AccountStatusesGETHandler(ctx) - - // 1. we should have OK because our request was valid - suite.Equal(http.StatusOK, recorder.Code) - - // 2. we should have no error message in the result body - result := recorder.Result() - defer result.Body.Close() - - // check the response - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - - // unmarshal the returned statuses - apimodelStatuses := []*apimodel.Status{} - err = json.Unmarshal(b, &apimodelStatuses) - suite.NoError(err) - suite.NotEmpty(apimodelStatuses) - - for _, s := range apimodelStatuses { - suite.NotEmpty(s.MediaAttachments) - suite.Equal(apimodel.VisibilityPublic, s.Visibility) - } - - suite.Equal(`; rel="next", ; rel="prev"`, result.Header.Get("link")) -} - -func TestAccountStatusesTestSuite(t *testing.T) { - suite.Run(t, new(AccountStatusesTestSuite)) -} diff --git a/internal/api/client/account/unblock.go b/internal/api/client/account/unblock.go deleted file mode 100644 index 451b7fd27..000000000 --- a/internal/api/client/account/unblock.go +++ /dev/null @@ -1,96 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// AccountUnblockPOSTHandler swagger:operation POST /api/v1/accounts/{id}/unblock accountUnblock -// -// Unblock account with ID. -// -// --- -// tags: -// - accounts -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: string -// description: The id of the account to unblock. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - write:blocks -// -// responses: -// '200': -// name: account relationship -// description: Your relationship to this account. -// schema: -// "$ref": "#/definitions/accountRelationship" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) AccountUnblockPOSTHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetAcctID := c.Param(IDKey) - if targetAcctID == "" { - err := errors.New("no account id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - relationship, errWithCode := m.processor.AccountBlockRemove(c.Request.Context(), authed, targetAcctID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, relationship) -} diff --git a/internal/api/client/account/unfollow.go b/internal/api/client/account/unfollow.go deleted file mode 100644 index fafba99fd..000000000 --- a/internal/api/client/account/unfollow.go +++ /dev/null @@ -1,96 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// AccountUnfollowPOSTHandler swagger:operation POST /api/v1/accounts/{id}/unfollow accountUnfollow -// -// Unfollow account with id. -// -// --- -// tags: -// - accounts -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: string -// description: The id of the account to unfollow. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - write:follows -// -// responses: -// '200': -// name: account relationship -// description: Your relationship to this account. -// schema: -// "$ref": "#/definitions/accountRelationship" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) AccountUnfollowPOSTHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetAcctID := c.Param(IDKey) - if targetAcctID == "" { - err := errors.New("no account id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - relationship, errWithCode := m.processor.AccountFollowRemove(c.Request.Context(), authed, targetAcctID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, relationship) -} diff --git a/internal/api/client/accounts/account_test.go b/internal/api/client/accounts/account_test.go new file mode 100644 index 000000000..57d1e6c04 --- /dev/null +++ b/internal/api/client/accounts/account_test.go @@ -0,0 +1,127 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts_test + +import ( + "bytes" + "fmt" + "net/http" + "net/http/httptest" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/accounts" + "github.com/superseriousbusiness/gotosocial/internal/concurrency" + "github.com/superseriousbusiness/gotosocial/internal/config" + "github.com/superseriousbusiness/gotosocial/internal/db" + "github.com/superseriousbusiness/gotosocial/internal/email" + "github.com/superseriousbusiness/gotosocial/internal/federation" + "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" + "github.com/superseriousbusiness/gotosocial/internal/media" + "github.com/superseriousbusiness/gotosocial/internal/messages" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/internal/processing" + "github.com/superseriousbusiness/gotosocial/internal/storage" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +type AccountStandardTestSuite struct { + // standard suite interfaces + suite.Suite + db db.DB + storage *storage.Driver + mediaManager media.Manager + federator federation.Federator + processor processing.Processor + emailSender email.Sender + sentEmails map[string]string + + // standard suite models + testTokens map[string]*gtsmodel.Token + testClients map[string]*gtsmodel.Client + testApplications map[string]*gtsmodel.Application + testUsers map[string]*gtsmodel.User + testAccounts map[string]*gtsmodel.Account + testAttachments map[string]*gtsmodel.MediaAttachment + testStatuses map[string]*gtsmodel.Status + + // module being tested + accountsModule *accounts.Module +} + +func (suite *AccountStandardTestSuite) SetupSuite() { + suite.testTokens = testrig.NewTestTokens() + suite.testClients = testrig.NewTestClients() + suite.testApplications = testrig.NewTestApplications() + suite.testUsers = testrig.NewTestUsers() + suite.testAccounts = testrig.NewTestAccounts() + suite.testAttachments = testrig.NewTestAttachments() + suite.testStatuses = testrig.NewTestStatuses() +} + +func (suite *AccountStandardTestSuite) SetupTest() { + testrig.InitTestConfig() + testrig.InitTestLog() + + fedWorker := concurrency.NewWorkerPool[messages.FromFederator](-1, -1) + clientWorker := concurrency.NewWorkerPool[messages.FromClientAPI](-1, -1) + + suite.db = testrig.NewTestDB() + suite.storage = testrig.NewInMemoryStorage() + suite.mediaManager = testrig.NewTestMediaManager(suite.db, suite.storage) + suite.federator = testrig.NewTestFederator(suite.db, testrig.NewTestTransportController(testrig.NewMockHTTPClient(nil, "../../../../testrig/media"), suite.db, fedWorker), suite.storage, suite.mediaManager, fedWorker) + suite.sentEmails = make(map[string]string) + suite.emailSender = testrig.NewEmailSender("../../../../web/template/", suite.sentEmails) + suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator, suite.emailSender, suite.mediaManager, clientWorker, fedWorker) + suite.accountsModule = accounts.New(suite.processor) + testrig.StandardDBSetup(suite.db, nil) + testrig.StandardStorageSetup(suite.storage, "../../../../testrig/media") + + suite.NoError(suite.processor.Start()) +} + +func (suite *AccountStandardTestSuite) TearDownTest() { + testrig.StandardDBTeardown(suite.db) + testrig.StandardStorageTeardown(suite.storage) +} + +func (suite *AccountStandardTestSuite) newContext(recorder *httptest.ResponseRecorder, requestMethod string, requestBody []byte, requestPath string, bodyContentType string) *gin.Context { + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauth.DBTokenToToken(suite.testTokens["local_account_1"])) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + + protocol := config.GetProtocol() + host := config.GetHost() + + baseURI := fmt.Sprintf("%s://%s", protocol, host) + requestURI := fmt.Sprintf("%s/%s", baseURI, requestPath) + + ctx.Request = httptest.NewRequest(http.MethodPatch, requestURI, bytes.NewReader(requestBody)) // the endpoint we're hitting + + if bodyContentType != "" { + ctx.Request.Header.Set("Content-Type", bodyContentType) + } + + ctx.Request.Header.Set("accept", "application/json") + + return ctx +} diff --git a/internal/api/client/accounts/accountcreate.go b/internal/api/client/accounts/accountcreate.go new file mode 100644 index 000000000..041ca7fc4 --- /dev/null +++ b/internal/api/client/accounts/accountcreate.go @@ -0,0 +1,150 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts + +import ( + "errors" + "net" + "net/http" + + "github.com/gin-gonic/gin" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/config" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/internal/validate" +) + +// AccountCreatePOSTHandler swagger:operation POST /api/v1/accounts accountCreate +// +// Create a new account using an application token. +// +// The parameters can also be given in the body of the request, as JSON, if the content-type is set to 'application/json'. +// The parameters can also be given in the body of the request, as XML, if the content-type is set to 'application/xml'. +// +// --- +// tags: +// - accounts +// +// consumes: +// - application/json +// - application/xml +// - application/x-www-form-urlencoded +// +// produces: +// - application/json +// +// security: +// - OAuth2 Application: +// - write:accounts +// +// responses: +// '200': +// description: "An OAuth2 access token for the newly-created account." +// schema: +// "$ref": "#/definitions/oauthToken" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) AccountCreatePOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, false, false) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + form := &apimodel.AccountCreateRequest{} + if err := c.ShouldBind(form); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + if err := validateCreateAccount(form); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + clientIP := c.ClientIP() + signUpIP := net.ParseIP(clientIP) + if signUpIP == nil { + err := errors.New("ip address could not be parsed from request") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + form.IP = signUpIP + + ti, errWithCode := m.processor.AccountCreate(c.Request.Context(), authed, form) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, ti) +} + +// validateCreateAccount checks through all the necessary prerequisites for creating a new account, +// according to the provided account create request. If the account isn't eligible, an error will be returned. +func validateCreateAccount(form *apimodel.AccountCreateRequest) error { + if form == nil { + return errors.New("form was nil") + } + + if !config.GetAccountsRegistrationOpen() { + return errors.New("registration is not open for this server") + } + + if err := validate.Username(form.Username); err != nil { + return err + } + + if err := validate.Email(form.Email); err != nil { + return err + } + + if err := validate.NewPassword(form.Password); err != nil { + return err + } + + if !form.Agreement { + return errors.New("agreement to terms and conditions not given") + } + + if err := validate.Language(form.Locale); err != nil { + return err + } + + if err := validate.SignUpReason(form.Reason, config.GetAccountsReasonRequired()); err != nil { + return err + } + + return nil +} diff --git a/internal/api/client/accounts/accountcreate_test.go b/internal/api/client/accounts/accountcreate_test.go new file mode 100644 index 000000000..b2b8c715f --- /dev/null +++ b/internal/api/client/accounts/accountcreate_test.go @@ -0,0 +1,19 @@ +// /* +// GoToSocial +// Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. + +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . +// */ + +package accounts_test diff --git a/internal/api/client/accounts/accountdelete.go b/internal/api/client/accounts/accountdelete.go new file mode 100644 index 000000000..f1b95e95a --- /dev/null +++ b/internal/api/client/accounts/accountdelete.go @@ -0,0 +1,95 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// AccountDeletePOSTHandler swagger:operation POST /api/v1/accounts/delete accountDelete +// +// Delete your account. +// +// --- +// tags: +// - accounts +// +// consumes: +// - multipart/form-data +// +// parameters: +// - +// name: password +// in: formData +// description: Password of the account user, for confirmation. +// type: string +// required: true +// +// security: +// - OAuth2 Bearer: +// - write:accounts +// +// responses: +// '202': +// description: "The account deletion has been accepted and the account will be deleted." +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) AccountDeletePOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + form := &apimodel.AccountDeleteRequest{} + if err := c.ShouldBind(&form); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + if form.Password == "" { + err = errors.New("no password provided in account delete request") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + form.DeleteOriginID = authed.Account.ID + + if errWithCode := m.processor.AccountDeleteLocal(c.Request.Context(), authed, form); errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusAccepted, gin.H{"message": "accepted"}) +} diff --git a/internal/api/client/accounts/accountdelete_test.go b/internal/api/client/accounts/accountdelete_test.go new file mode 100644 index 000000000..31559d59a --- /dev/null +++ b/internal/api/client/accounts/accountdelete_test.go @@ -0,0 +1,101 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts_test + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/accounts" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +type AccountDeleteTestSuite struct { + AccountStandardTestSuite +} + +func (suite *AccountDeleteTestSuite) TestAccountDeletePOSTHandler() { + // set up the request + // we're deleting zork + requestBody, w, err := testrig.CreateMultipartFormData( + "", "", + map[string]string{ + "password": "password", + }) + if err != nil { + panic(err) + } + bodyBytes := requestBody.Bytes() + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodPost, bodyBytes, accounts.DeleteAccountPath, w.FormDataContentType()) + + // call the handler + suite.accountsModule.AccountDeletePOSTHandler(ctx) + + // 1. we should have Accepted because our request was valid + suite.Equal(http.StatusAccepted, recorder.Code) +} + +func (suite *AccountDeleteTestSuite) TestAccountDeletePOSTHandlerWrongPassword() { + // set up the request + // we're deleting zork + requestBody, w, err := testrig.CreateMultipartFormData( + "", "", + map[string]string{ + "password": "aaaaaaaaaaaaaaaaaaaaaaaaaaaa", + }) + if err != nil { + panic(err) + } + bodyBytes := requestBody.Bytes() + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodPost, bodyBytes, accounts.DeleteAccountPath, w.FormDataContentType()) + + // call the handler + suite.accountsModule.AccountDeletePOSTHandler(ctx) + + // 1. we should have Forbidden because we supplied the wrong password + suite.Equal(http.StatusForbidden, recorder.Code) +} + +func (suite *AccountDeleteTestSuite) TestAccountDeletePOSTHandlerNoPassword() { + // set up the request + // we're deleting zork + requestBody, w, err := testrig.CreateMultipartFormData( + "", "", + map[string]string{}) + if err != nil { + panic(err) + } + bodyBytes := requestBody.Bytes() + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodPost, bodyBytes, accounts.DeleteAccountPath, w.FormDataContentType()) + + // call the handler + suite.accountsModule.AccountDeletePOSTHandler(ctx) + + // 1. we should have StatusBadRequest because our request was invalid + suite.Equal(http.StatusBadRequest, recorder.Code) +} + +func TestAccountDeleteTestSuite(t *testing.T) { + suite.Run(t, new(AccountDeleteTestSuite)) +} diff --git a/internal/api/client/accounts/accountget.go b/internal/api/client/accounts/accountget.go new file mode 100644 index 000000000..1a6354490 --- /dev/null +++ b/internal/api/client/accounts/accountget.go @@ -0,0 +1,95 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// AccountGETHandler swagger:operation GET /api/v1/accounts/{id} accountGet +// +// Get information about an account with the given ID. +// +// --- +// tags: +// - accounts +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: The id of the requested account. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - read:accounts +// +// responses: +// '200': +// description: The requested account. +// schema: +// "$ref": "#/definitions/account" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) AccountGETHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetAcctID := c.Param(IDKey) + if targetAcctID == "" { + err := errors.New("no account id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + acctInfo, errWithCode := m.processor.AccountGet(c.Request.Context(), authed, targetAcctID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, acctInfo) +} diff --git a/internal/api/client/accounts/accounts.go b/internal/api/client/accounts/accounts.go new file mode 100644 index 000000000..54c6c5f22 --- /dev/null +++ b/internal/api/client/accounts/accounts.go @@ -0,0 +1,119 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "github.com/superseriousbusiness/gotosocial/internal/processing" +) + +const ( + // LimitKey is for setting the return amount limit for eg., requesting an account's statuses + LimitKey = "limit" + // ExcludeRepliesKey is for specifying whether to exclude replies in a list of returned statuses by an account. + ExcludeRepliesKey = "exclude_replies" + // ExcludeReblogsKey is for specifying whether to exclude reblogs in a list of returned statuses by an account. + ExcludeReblogsKey = "exclude_reblogs" + // PinnedKey is for specifying whether to include pinned statuses in a list of returned statuses by an account. + PinnedKey = "pinned" + // MaxIDKey is for specifying the maximum ID of the status to retrieve. + MaxIDKey = "max_id" + // MinIDKey is for specifying the minimum ID of the status to retrieve. + MinIDKey = "min_id" + // OnlyMediaKey is for specifying that only statuses with media should be returned in a list of returned statuses by an account. + OnlyMediaKey = "only_media" + // OnlyPublicKey is for specifying that only statuses with visibility public should be returned in a list of returned statuses by account. + OnlyPublicKey = "only_public" + + // IDKey is the key to use for retrieving account ID in requests + IDKey = "id" + // BasePath is the base API path for this module, excluding the 'api' prefix + BasePath = "/v1/accounts" + // BasePathWithID is the base path for this module with the ID key + BasePathWithID = BasePath + "/:" + IDKey + // VerifyPath is for verifying account credentials + VerifyPath = BasePath + "/verify_credentials" + // UpdateCredentialsPath is for updating account credentials + UpdateCredentialsPath = BasePath + "/update_credentials" + // GetStatusesPath is for showing an account's statuses + GetStatusesPath = BasePathWithID + "/statuses" + // GetFollowersPath is for showing an account's followers + GetFollowersPath = BasePathWithID + "/followers" + // GetFollowingPath is for showing account's that an account follows. + GetFollowingPath = BasePathWithID + "/following" + // GetRelationshipsPath is for showing an account's relationship with other accounts + GetRelationshipsPath = BasePath + "/relationships" + // FollowPath is for POSTing new follows to, and updating existing follows + FollowPath = BasePathWithID + "/follow" + // UnfollowPath is for POSTing an unfollow + UnfollowPath = BasePathWithID + "/unfollow" + // BlockPath is for creating a block of an account + BlockPath = BasePathWithID + "/block" + // UnblockPath is for removing a block of an account + UnblockPath = BasePathWithID + "/unblock" + // DeleteAccountPath is for deleting one's account via the API + DeleteAccountPath = BasePath + "/delete" +) + +type Module struct { + processor processing.Processor +} + +func New(processor processing.Processor) *Module { + return &Module{ + processor: processor, + } +} + +func (m *Module) Route(attachHandler func(method string, path string, f ...gin.HandlerFunc) gin.IRoutes) { + // create account + attachHandler(http.MethodPost, BasePath, m.AccountCreatePOSTHandler) + + // get account + attachHandler(http.MethodGet, BasePathWithID, m.AccountGETHandler) + + // delete account + attachHandler(http.MethodPost, DeleteAccountPath, m.AccountDeletePOSTHandler) + + // verify account + attachHandler(http.MethodGet, VerifyPath, m.AccountVerifyGETHandler) + + // modify account + attachHandler(http.MethodPatch, UpdateCredentialsPath, m.AccountUpdateCredentialsPATCHHandler) + + // get account's statuses + attachHandler(http.MethodGet, GetStatusesPath, m.AccountStatusesGETHandler) + + // get following or followers + attachHandler(http.MethodGet, GetFollowersPath, m.AccountFollowersGETHandler) + attachHandler(http.MethodGet, GetFollowingPath, m.AccountFollowingGETHandler) + + // get relationship with account + attachHandler(http.MethodGet, GetRelationshipsPath, m.AccountRelationshipsGETHandler) + + // follow or unfollow account + attachHandler(http.MethodPost, FollowPath, m.AccountFollowPOSTHandler) + attachHandler(http.MethodPost, UnfollowPath, m.AccountUnfollowPOSTHandler) + + // block or unblock account + attachHandler(http.MethodPost, BlockPath, m.AccountBlockPOSTHandler) + attachHandler(http.MethodPost, UnblockPath, m.AccountUnblockPOSTHandler) +} diff --git a/internal/api/client/accounts/accountupdate.go b/internal/api/client/accounts/accountupdate.go new file mode 100644 index 000000000..5dbf0ce46 --- /dev/null +++ b/internal/api/client/accounts/accountupdate.go @@ -0,0 +1,216 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts + +import ( + "errors" + "fmt" + "net/http" + "strconv" + + "github.com/gin-gonic/gin" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// AccountUpdateCredentialsPATCHHandler swagger:operation PATCH /api/v1/accounts/update_credentials accountUpdate +// +// Update your account. +// +// --- +// tags: +// - accounts +// +// consumes: +// - multipart/form-data +// +// produces: +// - application/json +// +// parameters: +// - +// name: discoverable +// in: formData +// description: Account should be made discoverable and shown in the profile directory (if enabled). +// type: boolean +// - +// name: bot +// in: formData +// description: Account is flagged as a bot. +// type: boolean +// - +// name: display_name +// in: formData +// description: The display name to use for the account. +// type: string +// allowEmptyValue: true +// - +// name: note +// in: formData +// description: Bio/description of this account. +// type: string +// allowEmptyValue: true +// - +// name: avatar +// in: formData +// description: Avatar of the user. +// type: file +// - +// name: header +// in: formData +// description: Header of the user. +// type: file +// - +// name: locked +// in: formData +// description: Require manual approval of follow requests. +// type: boolean +// - +// name: source[privacy] +// in: formData +// description: Default post privacy for authored statuses. +// type: string +// - +// name: source[sensitive] +// in: formData +// description: Mark authored statuses as sensitive by default. +// type: boolean +// - +// name: source[language] +// in: formData +// description: Default language to use for authored statuses (ISO 6391). +// type: string +// - +// name: source[status_format] +// in: formData +// description: Default format to use for authored statuses (plain or markdown). +// type: string +// - +// name: custom_css +// in: formData +// description: >- +// Custom CSS to use when rendering this account's profile or statuses. +// String must be no more than 5,000 characters (~5kb). +// type: string +// - +// name: enable_rss +// in: formData +// description: Enable RSS feed for this account's Public posts at `/[username]/feed.rss` +// type: boolean +// +// security: +// - OAuth2 Bearer: +// - write:accounts +// +// responses: +// '200': +// description: "The newly updated account." +// schema: +// "$ref": "#/definitions/account" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) AccountUpdateCredentialsPATCHHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + form, err := parseUpdateAccountForm(c) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + acctSensitive, errWithCode := m.processor.AccountUpdate(c.Request.Context(), authed, form) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, acctSensitive) +} + +func parseUpdateAccountForm(c *gin.Context) (*apimodel.UpdateCredentialsRequest, error) { + form := &apimodel.UpdateCredentialsRequest{ + Source: &apimodel.UpdateSource{}, + } + + if err := c.ShouldBind(&form); err != nil { + return nil, fmt.Errorf("could not parse form from request: %s", err) + } + + // parse source field-by-field + sourceMap := c.PostFormMap("source") + + if privacy, ok := sourceMap["privacy"]; ok { + form.Source.Privacy = &privacy + } + + if sensitive, ok := sourceMap["sensitive"]; ok { + sensitiveBool, err := strconv.ParseBool(sensitive) + if err != nil { + return nil, fmt.Errorf("error parsing form source[sensitive]: %s", err) + } + form.Source.Sensitive = &sensitiveBool + } + + if language, ok := sourceMap["language"]; ok { + form.Source.Language = &language + } + + if statusFormat, ok := sourceMap["status_format"]; ok { + form.Source.StatusFormat = &statusFormat + } + + if form == nil || + (form.Discoverable == nil && + form.Bot == nil && + form.DisplayName == nil && + form.Note == nil && + form.Avatar == nil && + form.Header == nil && + form.Locked == nil && + form.Source.Privacy == nil && + form.Source.Sensitive == nil && + form.Source.Language == nil && + form.Source.StatusFormat == nil && + form.FieldsAttributes == nil && + form.CustomCSS == nil && + form.EnableRSS == nil) { + return nil, errors.New("empty form submitted") + } + + return form, nil +} diff --git a/internal/api/client/accounts/accountupdate_test.go b/internal/api/client/accounts/accountupdate_test.go new file mode 100644 index 000000000..45a287ec8 --- /dev/null +++ b/internal/api/client/accounts/accountupdate_test.go @@ -0,0 +1,452 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts_test + +import ( + "context" + "encoding/json" + "io/ioutil" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/accounts" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +type AccountUpdateTestSuite struct { + AccountStandardTestSuite +} + +func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandler() { + // set up the request + // we're updating the note of zork + newBio := "this is my new bio read it and weep" + requestBody, w, err := testrig.CreateMultipartFormData( + "", "", + map[string]string{ + "note": newBio, + }) + if err != nil { + panic(err) + } + bodyBytes := requestBody.Bytes() + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodPatch, bodyBytes, accounts.UpdateCredentialsPath, w.FormDataContentType()) + + // call the handler + suite.accountsModule.AccountUpdateCredentialsPATCHHandler(ctx) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusOK, recorder.Code) + + // 2. we should have no error message in the result body + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + // unmarshal the returned account + apimodelAccount := &apimodel.Account{} + err = json.Unmarshal(b, apimodelAccount) + suite.NoError(err) + + // check the returned api model account + // fields should be updated + suite.Equal("

this is my new bio read it and weep

", apimodelAccount.Note) + suite.Equal(newBio, apimodelAccount.Source.Note) +} + +func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandlerUnlockLock() { + // set up the first request + requestBody1, w1, err := testrig.CreateMultipartFormData( + "", "", + map[string]string{ + "locked": "false", + }) + if err != nil { + panic(err) + } + bodyBytes1 := requestBody1.Bytes() + recorder1 := httptest.NewRecorder() + ctx1 := suite.newContext(recorder1, http.MethodPatch, bodyBytes1, accounts.UpdateCredentialsPath, w1.FormDataContentType()) + + // call the handler + suite.accountsModule.AccountUpdateCredentialsPATCHHandler(ctx1) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusOK, recorder1.Code) + + // 2. we should have no error message in the result body + result1 := recorder1.Result() + defer result1.Body.Close() + + // check the response + b1, err := ioutil.ReadAll(result1.Body) + suite.NoError(err) + + // unmarshal the returned account + apimodelAccount1 := &apimodel.Account{} + err = json.Unmarshal(b1, apimodelAccount1) + suite.NoError(err) + + // check the returned api model account + // fields should be updated + suite.False(apimodelAccount1.Locked) + + // set up the first request + requestBody2, w2, err := testrig.CreateMultipartFormData( + "", "", + map[string]string{ + "locked": "true", + }) + if err != nil { + panic(err) + } + bodyBytes2 := requestBody2.Bytes() + recorder2 := httptest.NewRecorder() + ctx2 := suite.newContext(recorder2, http.MethodPatch, bodyBytes2, accounts.UpdateCredentialsPath, w2.FormDataContentType()) + + // call the handler + suite.accountsModule.AccountUpdateCredentialsPATCHHandler(ctx2) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusOK, recorder1.Code) + + // 2. we should have no error message in the result body + result2 := recorder2.Result() + defer result2.Body.Close() + + // check the response + b2, err := ioutil.ReadAll(result2.Body) + suite.NoError(err) + + // unmarshal the returned account + apimodelAccount2 := &apimodel.Account{} + err = json.Unmarshal(b2, apimodelAccount2) + suite.NoError(err) + + // check the returned api model account + // fields should be updated + suite.True(apimodelAccount2.Locked) +} + +func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandlerGetAccountFirst() { + // get the account first to make sure it's in the database cache -- when the account is updated via + // the PATCH handler, it should invalidate the cache and not return the old version + _, err := suite.db.GetAccountByID(context.Background(), suite.testAccounts["local_account_1"].ID) + suite.NoError(err) + + // set up the request + // we're updating the note of zork + newBio := "this is my new bio read it and weep" + requestBody, w, err := testrig.CreateMultipartFormData( + "", "", + map[string]string{ + "note": newBio, + }) + if err != nil { + panic(err) + } + bodyBytes := requestBody.Bytes() + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodPatch, bodyBytes, accounts.UpdateCredentialsPath, w.FormDataContentType()) + + // call the handler + suite.accountsModule.AccountUpdateCredentialsPATCHHandler(ctx) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusOK, recorder.Code) + + // 2. we should have no error message in the result body + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + // unmarshal the returned account + apimodelAccount := &apimodel.Account{} + err = json.Unmarshal(b, apimodelAccount) + suite.NoError(err) + + // check the returned api model account + // fields should be updated + suite.Equal("

this is my new bio read it and weep

", apimodelAccount.Note) + suite.Equal(newBio, apimodelAccount.Source.Note) +} + +func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandlerTwoFields() { + // set up the request + // we're updating the note of zork, and setting locked to true + newBio := "this is my new bio read it and weep :rainbow:" + requestBody, w, err := testrig.CreateMultipartFormData( + "", "", + map[string]string{ + "note": newBio, + "locked": "true", + }) + if err != nil { + panic(err) + } + bodyBytes := requestBody.Bytes() + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodPatch, bodyBytes, accounts.UpdateCredentialsPath, w.FormDataContentType()) + + // call the handler + suite.accountsModule.AccountUpdateCredentialsPATCHHandler(ctx) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusOK, recorder.Code) + + // 2. we should have no error message in the result body + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + // unmarshal the returned account + apimodelAccount := &apimodel.Account{} + err = json.Unmarshal(b, apimodelAccount) + suite.NoError(err) + + // check the returned api model account + // fields should be updated + suite.Equal("

this is my new bio read it and weep :rainbow:

", apimodelAccount.Note) + suite.Equal(newBio, apimodelAccount.Source.Note) + suite.True(apimodelAccount.Locked) + suite.NotEmpty(apimodelAccount.Emojis) + suite.Equal(apimodelAccount.Emojis[0].Shortcode, "rainbow") + + // check the account in the database + dbZork, err := suite.db.GetAccountByID(context.Background(), apimodelAccount.ID) + suite.NoError(err) + suite.Equal(newBio, dbZork.NoteRaw) + suite.Equal("

this is my new bio read it and weep :rainbow:

", dbZork.Note) + suite.True(*dbZork.Locked) + suite.NotEmpty(dbZork.EmojiIDs) +} + +func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandlerWithMedia() { + // set up the request + // we're updating the header image, the display name, and the locked status of zork + // we're removing the note/bio + requestBody, w, err := testrig.CreateMultipartFormData( + "header", "../../../../testrig/media/test-jpeg.jpg", + map[string]string{ + "display_name": "updated zork display name!!!", + "note": "", + "locked": "true", + }) + if err != nil { + panic(err) + } + bodyBytes := requestBody.Bytes() + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodPatch, bodyBytes, accounts.UpdateCredentialsPath, w.FormDataContentType()) + + // call the handler + suite.accountsModule.AccountUpdateCredentialsPATCHHandler(ctx) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusOK, recorder.Code) + + // 2. we should have no error message in the result body + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + // unmarshal the returned account + apimodelAccount := &apimodel.Account{} + err = json.Unmarshal(b, apimodelAccount) + suite.NoError(err) + + // check the returned api model account + // fields should be updated + suite.Equal("updated zork display name!!!", apimodelAccount.DisplayName) + suite.True(apimodelAccount.Locked) + suite.Empty(apimodelAccount.Note) + suite.Empty(apimodelAccount.Source.Note) + + // header values... + // should be set + suite.NotEmpty(apimodelAccount.Header) + suite.NotEmpty(apimodelAccount.HeaderStatic) + + // should be different from the values set before + suite.NotEqual("http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/header/original/01PFPMWK2FF0D9WMHEJHR07C3Q.jpeg", apimodelAccount.Header) + suite.NotEqual("http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/header/small/01PFPMWK2FF0D9WMHEJHR07C3Q.jpeg", apimodelAccount.HeaderStatic) +} + +func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandlerEmptyForm() { + // set up the request + bodyBytes := []byte{} + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodPatch, bodyBytes, accounts.UpdateCredentialsPath, "") + + // call the handler + suite.accountsModule.AccountUpdateCredentialsPATCHHandler(ctx) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusBadRequest, recorder.Code) + + // 2. we should have no error message in the result body + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + suite.Equal(`{"error":"Bad Request: empty form submitted"}`, string(b)) +} + +func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandlerUpdateSource() { + // set up the request + // we're updating the language of zork + newLanguage := "de" + requestBody, w, err := testrig.CreateMultipartFormData( + "", "", + map[string]string{ + "source[privacy]": string(apimodel.VisibilityPrivate), + "source[language]": "de", + "source[sensitive]": "true", + "locked": "true", + }) + if err != nil { + panic(err) + } + bodyBytes := requestBody.Bytes() + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodPatch, bodyBytes, accounts.UpdateCredentialsPath, w.FormDataContentType()) + + // call the handler + suite.accountsModule.AccountUpdateCredentialsPATCHHandler(ctx) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusOK, recorder.Code) + + // 2. we should have no error message in the result body + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + // unmarshal the returned account + apimodelAccount := &apimodel.Account{} + err = json.Unmarshal(b, apimodelAccount) + suite.NoError(err) + + // check the returned api model account + // fields should be updated + suite.Equal(newLanguage, apimodelAccount.Source.Language) + suite.EqualValues(apimodel.VisibilityPrivate, apimodelAccount.Source.Privacy) + suite.True(apimodelAccount.Source.Sensitive) + suite.True(apimodelAccount.Locked) +} + +func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandlerUpdateStatusFormatOK() { + // set up the request + // we're updating the language of zork + requestBody, w, err := testrig.CreateMultipartFormData( + "", "", + map[string]string{ + "source[status_format]": "markdown", + }) + if err != nil { + panic(err) + } + bodyBytes := requestBody.Bytes() + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodPatch, bodyBytes, accounts.UpdateCredentialsPath, w.FormDataContentType()) + + // call the handler + suite.accountsModule.AccountUpdateCredentialsPATCHHandler(ctx) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusOK, recorder.Code) + + // 2. we should have no error message in the result body + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + // unmarshal the returned account + apimodelAccount := &apimodel.Account{} + err = json.Unmarshal(b, apimodelAccount) + suite.NoError(err) + + // check the returned api model account + // fields should be updated + suite.Equal("markdown", apimodelAccount.Source.StatusFormat) + + dbAccount, err := suite.db.GetAccountByID(context.Background(), suite.testAccounts["local_account_1"].ID) + if err != nil { + suite.FailNow(err.Error()) + } + suite.Equal(dbAccount.StatusFormat, "markdown") +} + +func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandlerUpdateStatusFormatBad() { + // set up the request + // we're updating the language of zork + requestBody, w, err := testrig.CreateMultipartFormData( + "", "", + map[string]string{ + "source[status_format]": "peepeepoopoo", + }) + if err != nil { + panic(err) + } + bodyBytes := requestBody.Bytes() + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodPatch, bodyBytes, accounts.UpdateCredentialsPath, w.FormDataContentType()) + + // call the handler + suite.accountsModule.AccountUpdateCredentialsPATCHHandler(ctx) + + suite.Equal(http.StatusBadRequest, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + suite.Equal(`{"error":"Bad Request: status format 'peepeepoopoo' was not recognized, valid options are 'plain', 'markdown'"}`, string(b)) +} + +func TestAccountUpdateTestSuite(t *testing.T) { + suite.Run(t, new(AccountUpdateTestSuite)) +} diff --git a/internal/api/client/accounts/accountverify.go b/internal/api/client/accounts/accountverify.go new file mode 100644 index 000000000..2b39d5ab2 --- /dev/null +++ b/internal/api/client/accounts/accountverify.go @@ -0,0 +1,78 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts + +import ( + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// AccountVerifyGETHandler swagger:operation GET /api/v1/accounts/verify_credentials accountVerify +// +// Verify a token by returning account details pertaining to it. +// +// --- +// tags: +// - accounts +// +// produces: +// - application/json +// +// security: +// - OAuth2 Bearer: +// - read:accounts +// +// responses: +// '200': +// schema: +// "$ref": "#/definitions/account" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) AccountVerifyGETHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + acctSensitive, errWithCode := m.processor.AccountGet(c.Request.Context(), authed, authed.Account.ID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, acctSensitive) +} diff --git a/internal/api/client/accounts/accountverify_test.go b/internal/api/client/accounts/accountverify_test.go new file mode 100644 index 000000000..e74c30aba --- /dev/null +++ b/internal/api/client/accounts/accountverify_test.go @@ -0,0 +1,91 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts_test + +import ( + "encoding/json" + "io/ioutil" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/accounts" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" +) + +type AccountVerifyTestSuite struct { + AccountStandardTestSuite +} + +func (suite *AccountVerifyTestSuite) TestAccountVerifyGet() { + testAccount := suite.testAccounts["local_account_1"] + + // set up the request + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodGet, nil, accounts.VerifyPath, "") + + // call the handler + suite.accountsModule.AccountVerifyGETHandler(ctx) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusOK, recorder.Code) + + // 2. we should have no error message in the result body + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + + // unmarshal the returned account + apimodelAccount := &apimodel.Account{} + err = json.Unmarshal(b, apimodelAccount) + suite.NoError(err) + + createdAt, err := time.Parse(time.RFC3339, apimodelAccount.CreatedAt) + suite.NoError(err) + + suite.Equal(testAccount.ID, apimodelAccount.ID) + suite.Equal(testAccount.Username, apimodelAccount.Username) + suite.Equal(testAccount.Username, apimodelAccount.Acct) + suite.Equal(testAccount.DisplayName, apimodelAccount.DisplayName) + suite.Equal(*testAccount.Locked, apimodelAccount.Locked) + suite.Equal(*testAccount.Bot, apimodelAccount.Bot) + suite.WithinDuration(testAccount.CreatedAt, createdAt, 30*time.Second) // we lose a bit of accuracy serializing so fuzz this a bit + suite.Equal(testAccount.URL, apimodelAccount.URL) + suite.Equal("http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/avatar/original/01F8MH58A357CV5K7R7TJMSH6S.jpeg", apimodelAccount.Avatar) + suite.Equal("http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/avatar/small/01F8MH58A357CV5K7R7TJMSH6S.jpeg", apimodelAccount.AvatarStatic) + suite.Equal("http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/header/original/01PFPMWK2FF0D9WMHEJHR07C3Q.jpeg", apimodelAccount.Header) + suite.Equal("http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/header/small/01PFPMWK2FF0D9WMHEJHR07C3Q.jpeg", apimodelAccount.HeaderStatic) + suite.Equal(2, apimodelAccount.FollowersCount) + suite.Equal(2, apimodelAccount.FollowingCount) + suite.Equal(5, apimodelAccount.StatusesCount) + suite.EqualValues(gtsmodel.VisibilityPublic, apimodelAccount.Source.Privacy) + suite.Equal(testAccount.Language, apimodelAccount.Source.Language) + suite.Equal(testAccount.NoteRaw, apimodelAccount.Source.Note) +} + +func TestAccountVerifyTestSuite(t *testing.T) { + suite.Run(t, new(AccountVerifyTestSuite)) +} diff --git a/internal/api/client/accounts/block.go b/internal/api/client/accounts/block.go new file mode 100644 index 000000000..9e14ecb6e --- /dev/null +++ b/internal/api/client/accounts/block.go @@ -0,0 +1,95 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// AccountBlockPOSTHandler swagger:operation POST /api/v1/accounts/{id}/block accountBlock +// +// Block account with id. +// +// --- +// tags: +// - accounts +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: The id of the account to block. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - write:blocks +// +// responses: +// '200': +// description: Your relationship to the account. +// schema: +// "$ref": "#/definitions/accountRelationship" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) AccountBlockPOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetAcctID := c.Param(IDKey) + if targetAcctID == "" { + err := errors.New("no account id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + relationship, errWithCode := m.processor.AccountBlockCreate(c.Request.Context(), authed, targetAcctID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, relationship) +} diff --git a/internal/api/client/accounts/block_test.go b/internal/api/client/accounts/block_test.go new file mode 100644 index 000000000..474a53eb8 --- /dev/null +++ b/internal/api/client/accounts/block_test.go @@ -0,0 +1,74 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts_test + +import ( + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "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/oauth" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +type BlockTestSuite struct { + AccountStandardTestSuite +} + +func (suite *BlockTestSuite) TestBlockSelf() { + testAcct := suite.testAccounts["local_account_1"] + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedAccount, testAcct) + ctx.Set(oauth.SessionAuthorizedToken, oauth.DBTokenToToken(suite.testTokens["local_account_1"])) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(accounts.BlockPath, ":id", testAcct.ID, 1)), nil) + + ctx.Params = gin.Params{ + gin.Param{ + Key: accounts.IDKey, + Value: testAcct.ID, + }, + } + + suite.accountsModule.AccountBlockPOSTHandler(ctx) + + // 1. status should be Not Acceptable due to attempted self-block + suite.Equal(http.StatusNotAcceptable, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + _ = b + assert.NoError(suite.T(), err) +} + +func TestBlockTestSuite(t *testing.T) { + suite.Run(t, new(BlockTestSuite)) +} diff --git a/internal/api/client/accounts/follow.go b/internal/api/client/accounts/follow.go new file mode 100644 index 000000000..d2a8af886 --- /dev/null +++ b/internal/api/client/accounts/follow.go @@ -0,0 +1,124 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// AccountFollowPOSTHandler swagger:operation POST /api/v1/accounts/{id}/follow accountFollow +// +// Follow account with id. +// +// The parameters can also be given in the body of the request, as JSON, if the content-type is set to 'application/json'. +// The parameters can also be given in the body of the request, as XML, if the content-type is set to 'application/xml'. +// +// --- +// tags: +// - accounts +// +// consumes: +// - application/json +// - application/xml +// - application/x-www-form-urlencoded +// +// parameters: +// - +// name: id +// required: true +// in: path +// description: ID of the account to follow. +// type: string +// - +// name: reblogs +// type: boolean +// default: true +// description: Show reblogs from this account. +// in: formData +// - +// default: false +// description: Notify when this account posts. +// in: formData +// name: notify +// type: boolean +// +// produces: +// - application/json +// +// security: +// - OAuth2 Bearer: +// - write:follows +// +// responses: +// '200': +// name: account relationship +// description: Your relationship to this account. +// schema: +// "$ref": "#/definitions/accountRelationship" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) AccountFollowPOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetAcctID := c.Param(IDKey) + if targetAcctID == "" { + err := errors.New("no account id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + form := &apimodel.AccountFollowRequest{} + if err := c.ShouldBind(form); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + form.ID = targetAcctID + + relationship, errWithCode := m.processor.AccountFollowCreate(c.Request.Context(), authed, form) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, relationship) +} diff --git a/internal/api/client/accounts/follow_test.go b/internal/api/client/accounts/follow_test.go new file mode 100644 index 000000000..fd15c3734 --- /dev/null +++ b/internal/api/client/accounts/follow_test.go @@ -0,0 +1,75 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts_test + +import ( + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "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/oauth" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +type FollowTestSuite struct { + AccountStandardTestSuite +} + +func (suite *FollowTestSuite) TestFollowSelf() { + testAcct := suite.testAccounts["local_account_1"] + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedAccount, testAcct) + ctx.Set(oauth.SessionAuthorizedToken, oauth.DBTokenToToken(suite.testTokens["local_account_1"])) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(accounts.FollowPath, ":id", testAcct.ID, 1)), nil) + + ctx.Params = gin.Params{ + gin.Param{ + Key: accounts.IDKey, + Value: testAcct.ID, + }, + } + + // call the handler + suite.accountsModule.AccountFollowPOSTHandler(ctx) + + // 1. status should be Not Acceptable due to self-follow attempt + suite.Equal(http.StatusNotAcceptable, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + _ = b + assert.NoError(suite.T(), err) +} + +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 new file mode 100644 index 000000000..b464a5ad6 --- /dev/null +++ b/internal/api/client/accounts/followers.go @@ -0,0 +1,98 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// AccountFollowersGETHandler swagger:operation GET /api/v1/accounts/{id}/followers accountFollowers +// +// See followers of account with given id. +// +// --- +// tags: +// - accounts +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: Account ID. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - read:accounts +// +// responses: +// '200': +// name: accounts +// description: Array of accounts that follow this account. +// schema: +// type: array +// items: +// "$ref": "#/definitions/account" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) AccountFollowersGETHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetAcctID := c.Param(IDKey) + if targetAcctID == "" { + err := errors.New("no account id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + followers, errWithCode := m.processor.AccountFollowersGet(c.Request.Context(), authed, targetAcctID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, followers) +} diff --git a/internal/api/client/accounts/following.go b/internal/api/client/accounts/following.go new file mode 100644 index 000000000..4589ad07a --- /dev/null +++ b/internal/api/client/accounts/following.go @@ -0,0 +1,98 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// AccountFollowingGETHandler swagger:operation GET /api/v1/accounts/{id}/following accountFollowing +// +// See accounts followed by given account id. +// +// --- +// tags: +// - accounts +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: Account ID. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - read:accounts +// +// responses: +// '200': +// name: accounts +// description: Array of accounts that are followed by this account. +// schema: +// type: array +// items: +// "$ref": "#/definitions/account" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) AccountFollowingGETHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetAcctID := c.Param(IDKey) + if targetAcctID == "" { + err := errors.New("no account id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + following, errWithCode := m.processor.AccountFollowingGet(c.Request.Context(), authed, targetAcctID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, following) +} diff --git a/internal/api/client/accounts/relationships.go b/internal/api/client/accounts/relationships.go new file mode 100644 index 000000000..60e7b517c --- /dev/null +++ b/internal/api/client/accounts/relationships.go @@ -0,0 +1,93 @@ +package accounts + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// AccountRelationshipsGETHandler swagger:operation GET /api/v1/accounts/relationships accountRelationships +// +// See your account's relationships with the given account IDs. +// +// --- +// tags: +// - accounts +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: array +// items: +// type: string +// description: Account IDs. +// in: query +// required: true +// +// security: +// - OAuth2 Bearer: +// - read:accounts +// +// responses: +// '200': +// name: account relationships +// description: Array of account relationships. +// schema: +// type: array +// items: +// "$ref": "#/definitions/accountRelationship" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) AccountRelationshipsGETHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetAccountIDs := c.QueryArray("id[]") + if len(targetAccountIDs) == 0 { + // check fallback -- let's be generous and see if maybe it's just set as 'id'? + id := c.Query("id") + if id == "" { + err = errors.New("no account id(s) specified in query") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + targetAccountIDs = append(targetAccountIDs, id) + } + + relationships := []apimodel.Relationship{} + + for _, targetAccountID := range targetAccountIDs { + r, errWithCode := m.processor.AccountRelationshipGet(c.Request.Context(), authed, targetAccountID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + relationships = append(relationships, *r) + } + + c.JSON(http.StatusOK, relationships) +} diff --git a/internal/api/client/accounts/statuses.go b/internal/api/client/accounts/statuses.go new file mode 100644 index 000000000..a04517feb --- /dev/null +++ b/internal/api/client/accounts/statuses.go @@ -0,0 +1,246 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts + +import ( + "errors" + "fmt" + "net/http" + "strconv" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// AccountStatusesGETHandler swagger:operation GET /api/v1/accounts/{id}/statuses accountStatuses +// +// See statuses posted by the requested account. +// +// The statuses will be returned in descending chronological order (newest first), with sequential IDs (bigger = newer). +// +// --- +// tags: +// - accounts +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: Account ID. +// in: path +// required: true +// - +// name: limit +// type: integer +// description: Number of statuses to return. +// default: 30 +// in: query +// required: false +// - +// name: exclude_replies +// type: boolean +// description: Exclude statuses that are a reply to another status. +// default: false +// in: query +// required: false +// - +// name: exclude_reblogs +// type: boolean +// description: Exclude statuses that are a reblog/boost of another status. +// default: false +// in: query +// required: false +// - +// name: max_id +// type: string +// description: >- +// Return only statuses *OLDER* than the given max status ID. +// The status with the specified ID will not be included in the response. +// in: query +// - +// name: min_id +// type: string +// description: >- +// Return only statuses *NEWER* than the given min status ID. +// The status with the specified ID will not be included in the response. +// in: query +// required: false +// - +// name: pinned_only +// type: boolean +// description: Show only pinned statuses. In other words, exclude statuses that are not pinned to the given account ID. +// default: false +// in: query +// required: false +// - +// name: only_media +// type: boolean +// description: Show only statuses with media attachments. +// default: false +// in: query +// required: false +// - +// name: only_public +// type: boolean +// description: Show only statuses with a privacy setting of 'public'. +// default: false +// in: query +// required: false +// +// security: +// - OAuth2 Bearer: +// - read:accounts +// +// responses: +// '200': +// name: statuses +// description: Array of statuses. +// schema: +// type: array +// items: +// "$ref": "#/definitions/status" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) AccountStatusesGETHandler(c *gin.Context) { + authed, err := oauth.Authed(c, false, false, false, false) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetAcctID := c.Param(IDKey) + if targetAcctID == "" { + err := errors.New("no account id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + limit := 30 + limitString := c.Query(LimitKey) + if limitString != "" { + i, err := strconv.ParseInt(limitString, 10, 32) + if err != nil { + err := fmt.Errorf("error parsing %s: %s", LimitKey, err) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + limit = int(i) + } + + excludeReplies := false + excludeRepliesString := c.Query(ExcludeRepliesKey) + if excludeRepliesString != "" { + i, err := strconv.ParseBool(excludeRepliesString) + if err != nil { + err := fmt.Errorf("error parsing %s: %s", ExcludeRepliesKey, err) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + excludeReplies = i + } + + excludeReblogs := false + excludeReblogsString := c.Query(ExcludeReblogsKey) + if excludeReblogsString != "" { + i, err := strconv.ParseBool(excludeReblogsString) + if err != nil { + err := fmt.Errorf("error parsing %s: %s", ExcludeReblogsKey, err) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + excludeReblogs = i + } + + maxID := "" + maxIDString := c.Query(MaxIDKey) + if maxIDString != "" { + maxID = maxIDString + } + + minID := "" + minIDString := c.Query(MinIDKey) + if minIDString != "" { + minID = minIDString + } + + pinnedOnly := false + pinnedString := c.Query(PinnedKey) + if pinnedString != "" { + i, err := strconv.ParseBool(pinnedString) + if err != nil { + err := fmt.Errorf("error parsing %s: %s", PinnedKey, err) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + pinnedOnly = i + } + + mediaOnly := false + mediaOnlyString := c.Query(OnlyMediaKey) + if mediaOnlyString != "" { + i, err := strconv.ParseBool(mediaOnlyString) + if err != nil { + err := fmt.Errorf("error parsing %s: %s", OnlyMediaKey, err) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + mediaOnly = i + } + + publicOnly := false + publicOnlyString := c.Query(OnlyPublicKey) + if publicOnlyString != "" { + i, err := strconv.ParseBool(publicOnlyString) + if err != nil { + err := fmt.Errorf("error parsing %s: %s", OnlyPublicKey, err) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + publicOnly = i + } + + resp, errWithCode := m.processor.AccountStatusesGet(c.Request.Context(), authed, targetAcctID, limit, excludeReplies, excludeReblogs, maxID, minID, pinnedOnly, mediaOnly, publicOnly) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + if resp.LinkHeader != "" { + c.Header("Link", resp.LinkHeader) + } + c.JSON(http.StatusOK, resp.Items) +} diff --git a/internal/api/client/accounts/statuses_test.go b/internal/api/client/accounts/statuses_test.go new file mode 100644 index 000000000..92ca9d925 --- /dev/null +++ b/internal/api/client/accounts/statuses_test.go @@ -0,0 +1,123 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts_test + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/accounts" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" +) + +type AccountStatusesTestSuite struct { + AccountStandardTestSuite +} + +func (suite *AccountStatusesTestSuite) TestGetStatusesPublicOnly() { + // set up the request + // we're getting statuses of admin + targetAccount := suite.testAccounts["admin_account"] + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodGet, nil, fmt.Sprintf("/api/v1/accounts/%s/statuses?limit=20&only_media=false&only_public=true", targetAccount.ID), "") + ctx.Params = gin.Params{ + gin.Param{ + Key: accounts.IDKey, + Value: targetAccount.ID, + }, + } + + // call the handler + suite.accountsModule.AccountStatusesGETHandler(ctx) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusOK, recorder.Code) + + // 2. we should have no error message in the result body + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + + // unmarshal the returned statuses + apimodelStatuses := []*apimodel.Status{} + err = json.Unmarshal(b, &apimodelStatuses) + suite.NoError(err) + suite.NotEmpty(apimodelStatuses) + + for _, s := range apimodelStatuses { + suite.Equal(apimodel.VisibilityPublic, s.Visibility) + } + + suite.Equal(`; rel="next", ; rel="prev"`, result.Header.Get("link")) +} + +func (suite *AccountStatusesTestSuite) TestGetStatusesPublicOnlyMediaOnly() { + // set up the request + // we're getting statuses of admin + targetAccount := suite.testAccounts["admin_account"] + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodGet, nil, fmt.Sprintf("/api/v1/accounts/%s/statuses?limit=20&only_media=true&only_public=true", targetAccount.ID), "") + ctx.Params = gin.Params{ + gin.Param{ + Key: accounts.IDKey, + Value: targetAccount.ID, + }, + } + + // call the handler + suite.accountsModule.AccountStatusesGETHandler(ctx) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusOK, recorder.Code) + + // 2. we should have no error message in the result body + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + + // unmarshal the returned statuses + apimodelStatuses := []*apimodel.Status{} + err = json.Unmarshal(b, &apimodelStatuses) + suite.NoError(err) + suite.NotEmpty(apimodelStatuses) + + for _, s := range apimodelStatuses { + suite.NotEmpty(s.MediaAttachments) + suite.Equal(apimodel.VisibilityPublic, s.Visibility) + } + + suite.Equal(`; rel="next", ; rel="prev"`, result.Header.Get("link")) +} + +func TestAccountStatusesTestSuite(t *testing.T) { + suite.Run(t, new(AccountStatusesTestSuite)) +} diff --git a/internal/api/client/accounts/unblock.go b/internal/api/client/accounts/unblock.go new file mode 100644 index 000000000..e0a0a978e --- /dev/null +++ b/internal/api/client/accounts/unblock.go @@ -0,0 +1,96 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// AccountUnblockPOSTHandler swagger:operation POST /api/v1/accounts/{id}/unblock accountUnblock +// +// Unblock account with ID. +// +// --- +// tags: +// - accounts +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: The id of the account to unblock. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - write:blocks +// +// responses: +// '200': +// name: account relationship +// description: Your relationship to this account. +// schema: +// "$ref": "#/definitions/accountRelationship" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) AccountUnblockPOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetAcctID := c.Param(IDKey) + if targetAcctID == "" { + err := errors.New("no account id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + relationship, errWithCode := m.processor.AccountBlockRemove(c.Request.Context(), authed, targetAcctID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, relationship) +} diff --git a/internal/api/client/accounts/unfollow.go b/internal/api/client/accounts/unfollow.go new file mode 100644 index 000000000..95c819903 --- /dev/null +++ b/internal/api/client/accounts/unfollow.go @@ -0,0 +1,96 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package accounts + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// AccountUnfollowPOSTHandler swagger:operation POST /api/v1/accounts/{id}/unfollow accountUnfollow +// +// Unfollow account with id. +// +// --- +// tags: +// - accounts +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: The id of the account to unfollow. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - write:follows +// +// responses: +// '200': +// name: account relationship +// description: Your relationship to this account. +// schema: +// "$ref": "#/definitions/accountRelationship" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) AccountUnfollowPOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetAcctID := c.Param(IDKey) + if targetAcctID == "" { + err := errors.New("no account id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + relationship, errWithCode := m.processor.AccountFollowRemove(c.Request.Context(), authed, targetAcctID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, relationship) +} diff --git a/internal/api/client/admin/accountaction.go b/internal/api/client/admin/accountaction.go index 2dc84a2d0..d40404b15 100644 --- a/internal/api/client/admin/accountaction.go +++ b/internal/api/client/admin/accountaction.go @@ -24,8 +24,8 @@ import ( "net/http" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" ) @@ -85,38 +85,38 @@ import ( func (m *Module) AccountActionPOSTHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } if !*authed.User.Admin { err := fmt.Errorf("user %s not an admin", authed.User.ID) - api.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) return } - form := &model.AdminAccountActionRequest{} + form := &apimodel.AdminAccountActionRequest{} if err := c.ShouldBind(form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } if form.Type == "" { err := errors.New("no type specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } targetAcctID := c.Param(IDKey) if targetAcctID == "" { err := errors.New("no account id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } form.TargetAccountID = targetAcctID if errWithCode := m.processor.AdminAccountAction(c.Request.Context(), authed, form); errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } diff --git a/internal/api/client/admin/admin.go b/internal/api/client/admin/admin.go index 569354c96..b4fb4d6d1 100644 --- a/internal/api/client/admin/admin.go +++ b/internal/api/client/admin/admin.go @@ -21,14 +21,13 @@ package admin import ( "net/http" - "github.com/superseriousbusiness/gotosocial/internal/api" + "github.com/gin-gonic/gin" "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" ) const ( - // BasePath is the base API path for this module. - BasePath = "/api/v1/admin" + // BasePath is the base API path for this module, excluding the api prefix + BasePath = "/v1/admin" // EmojiPath is used for posting/deleting custom emojis. EmojiPath = BasePath + "/custom_emojis" // EmojiPathWithID is used for interacting with a single emoji. @@ -68,32 +67,28 @@ const ( DomainQueryKey = "domain" ) -// Module implements the ClientAPIModule interface for admin-related actions (reports, emojis, etc) type Module struct { processor processing.Processor } -// New returns a new admin module -func New(processor processing.Processor) api.ClientModule { +func New(processor processing.Processor) *Module { return &Module{ processor: processor, } } -// Route attaches all routes from this module to the given router -func (m *Module) Route(r router.Router) error { - r.AttachHandler(http.MethodPost, EmojiPath, m.EmojiCreatePOSTHandler) - r.AttachHandler(http.MethodGet, EmojiPath, m.EmojisGETHandler) - r.AttachHandler(http.MethodDelete, EmojiPathWithID, m.EmojiDELETEHandler) - r.AttachHandler(http.MethodGet, EmojiPathWithID, m.EmojiGETHandler) - r.AttachHandler(http.MethodPatch, EmojiPathWithID, m.EmojiPATCHHandler) - r.AttachHandler(http.MethodPost, DomainBlocksPath, m.DomainBlocksPOSTHandler) - r.AttachHandler(http.MethodGet, DomainBlocksPath, m.DomainBlocksGETHandler) - r.AttachHandler(http.MethodGet, DomainBlocksPathWithID, m.DomainBlockGETHandler) - r.AttachHandler(http.MethodDelete, DomainBlocksPathWithID, m.DomainBlockDELETEHandler) - r.AttachHandler(http.MethodPost, AccountsActionPath, m.AccountActionPOSTHandler) - r.AttachHandler(http.MethodPost, MediaCleanupPath, m.MediaCleanupPOSTHandler) - r.AttachHandler(http.MethodPost, MediaRefetchPath, m.MediaRefetchPOSTHandler) - r.AttachHandler(http.MethodGet, EmojiCategoriesPath, m.EmojiCategoriesGETHandler) - return nil +func (m *Module) Route(attachHandler func(method string, path string, f ...gin.HandlerFunc) gin.IRoutes) { + attachHandler(http.MethodPost, EmojiPath, m.EmojiCreatePOSTHandler) + attachHandler(http.MethodGet, EmojiPath, m.EmojisGETHandler) + attachHandler(http.MethodDelete, EmojiPathWithID, m.EmojiDELETEHandler) + attachHandler(http.MethodGet, EmojiPathWithID, m.EmojiGETHandler) + attachHandler(http.MethodPatch, EmojiPathWithID, m.EmojiPATCHHandler) + attachHandler(http.MethodPost, DomainBlocksPath, m.DomainBlocksPOSTHandler) + attachHandler(http.MethodGet, DomainBlocksPath, m.DomainBlocksGETHandler) + attachHandler(http.MethodGet, DomainBlocksPathWithID, m.DomainBlockGETHandler) + attachHandler(http.MethodDelete, DomainBlocksPathWithID, m.DomainBlockDELETEHandler) + attachHandler(http.MethodPost, AccountsActionPath, m.AccountActionPOSTHandler) + attachHandler(http.MethodPost, MediaCleanupPath, m.MediaCleanupPOSTHandler) + attachHandler(http.MethodPost, MediaRefetchPath, m.MediaRefetchPOSTHandler) + attachHandler(http.MethodGet, EmojiCategoriesPath, m.EmojiCategoriesGETHandler) } diff --git a/internal/api/client/admin/admin_test.go b/internal/api/client/admin/admin_test.go index 52c2630d9..ac3bbcb98 100644 --- a/internal/api/client/admin/admin_test.go +++ b/internal/api/client/admin/admin_test.go @@ -93,7 +93,7 @@ func (suite *AdminStandardTestSuite) SetupTest() { suite.sentEmails = make(map[string]string) suite.emailSender = testrig.NewEmailSender("../../../../web/template/", suite.sentEmails) suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator, suite.emailSender, suite.mediaManager, clientWorker, fedWorker) - suite.adminModule = admin.New(suite.processor).(*admin.Module) + suite.adminModule = admin.New(suite.processor) testrig.StandardDBSetup(suite.db, nil) testrig.StandardStorageSetup(suite.storage, "../../../../testrig/media") } diff --git a/internal/api/client/admin/domainblockcreate.go b/internal/api/client/admin/domainblockcreate.go index 034ea8682..44410abe3 100644 --- a/internal/api/client/admin/domainblockcreate.go +++ b/internal/api/client/admin/domainblockcreate.go @@ -25,8 +25,8 @@ import ( "strconv" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" ) @@ -126,18 +126,18 @@ import ( func (m *Module) DomainBlocksPOSTHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } if !*authed.User.Admin { err := fmt.Errorf("user %s not an admin", authed.User.ID) - api.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } @@ -147,21 +147,21 @@ func (m *Module) DomainBlocksPOSTHandler(c *gin.Context) { i, err := strconv.ParseBool(importString) if err != nil { err := fmt.Errorf("error parsing %s: %s", ImportQueryKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } imp = i } - form := &model.DomainBlockCreateRequest{} + form := &apimodel.DomainBlockCreateRequest{} if err := c.ShouldBind(form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } if err := validateCreateDomainBlock(form, imp); err != nil { err := fmt.Errorf("error validating form: %s", err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } @@ -169,7 +169,7 @@ func (m *Module) DomainBlocksPOSTHandler(c *gin.Context) { // we're importing multiple blocks domainBlocks, errWithCode := m.processor.AdminDomainBlocksImport(c.Request.Context(), authed, form) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } c.JSON(http.StatusOK, domainBlocks) @@ -179,13 +179,13 @@ func (m *Module) DomainBlocksPOSTHandler(c *gin.Context) { // we're just creating one block domainBlock, errWithCode := m.processor.AdminDomainBlockCreate(c.Request.Context(), authed, form) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } c.JSON(http.StatusOK, domainBlock) } -func validateCreateDomainBlock(form *model.DomainBlockCreateRequest, imp bool) error { +func validateCreateDomainBlock(form *apimodel.DomainBlockCreateRequest, imp bool) error { if imp { if form.Domains.Size == 0 { return errors.New("import was specified but list of domains is empty") diff --git a/internal/api/client/admin/domainblockdelete.go b/internal/api/client/admin/domainblockdelete.go index 6f3684418..ddb07e6f6 100644 --- a/internal/api/client/admin/domainblockdelete.go +++ b/internal/api/client/admin/domainblockdelete.go @@ -24,7 +24,7 @@ import ( "net/http" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" ) @@ -72,31 +72,31 @@ import ( func (m *Module) DomainBlockDELETEHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } if !*authed.User.Admin { err := fmt.Errorf("user %s not an admin", authed.User.ID) - api.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } domainBlockID := c.Param(IDKey) if domainBlockID == "" { err := errors.New("no domain block id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } domainBlock, errWithCode := m.processor.AdminDomainBlockDelete(c.Request.Context(), authed, domainBlockID) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } diff --git a/internal/api/client/admin/domainblockget.go b/internal/api/client/admin/domainblockget.go index 3d27b585e..b9d365caa 100644 --- a/internal/api/client/admin/domainblockget.go +++ b/internal/api/client/admin/domainblockget.go @@ -25,7 +25,7 @@ import ( "strconv" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" ) @@ -73,25 +73,25 @@ import ( func (m *Module) DomainBlockGETHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } if !*authed.User.Admin { err := fmt.Errorf("user %s not an admin", authed.User.ID) - api.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } domainBlockID := c.Param(IDKey) if domainBlockID == "" { err := errors.New("no domain block id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } @@ -101,7 +101,7 @@ func (m *Module) DomainBlockGETHandler(c *gin.Context) { i, err := strconv.ParseBool(exportString) if err != nil { err := fmt.Errorf("error parsing %s: %s", ExportQueryKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } export = i @@ -109,7 +109,7 @@ func (m *Module) DomainBlockGETHandler(c *gin.Context) { domainBlock, errWithCode := m.processor.AdminDomainBlockGet(c.Request.Context(), authed, domainBlockID, export) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } diff --git a/internal/api/client/admin/domainblocksget.go b/internal/api/client/admin/domainblocksget.go index a4ab4ac1c..fea0ca35e 100644 --- a/internal/api/client/admin/domainblocksget.go +++ b/internal/api/client/admin/domainblocksget.go @@ -24,7 +24,7 @@ import ( "strconv" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" ) @@ -78,18 +78,18 @@ import ( func (m *Module) DomainBlocksGETHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } if !*authed.User.Admin { err := fmt.Errorf("user %s not an admin", authed.User.ID) - api.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } @@ -99,7 +99,7 @@ func (m *Module) DomainBlocksGETHandler(c *gin.Context) { i, err := strconv.ParseBool(exportString) if err != nil { err := fmt.Errorf("error parsing %s: %s", ExportQueryKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } export = i @@ -107,7 +107,7 @@ func (m *Module) DomainBlocksGETHandler(c *gin.Context) { domainBlocks, errWithCode := m.processor.AdminDomainBlocksGet(c.Request.Context(), authed, export) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } diff --git a/internal/api/client/admin/emojicategoriesget.go b/internal/api/client/admin/emojicategoriesget.go index d8b379674..e69506413 100644 --- a/internal/api/client/admin/emojicategoriesget.go +++ b/internal/api/client/admin/emojicategoriesget.go @@ -23,7 +23,7 @@ import ( "net/http" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" ) @@ -69,24 +69,24 @@ import ( func (m *Module) EmojiCategoriesGETHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } if !*authed.User.Admin { err := fmt.Errorf("user %s not an admin", authed.User.ID) - api.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } categories, errWithCode := m.processor.AdminEmojiCategoriesGet(c.Request.Context()) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } diff --git a/internal/api/client/admin/emojicreate.go b/internal/api/client/admin/emojicreate.go index 2a075708f..8368a12b0 100644 --- a/internal/api/client/admin/emojicreate.go +++ b/internal/api/client/admin/emojicreate.go @@ -24,8 +24,8 @@ import ( "net/http" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/config" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" @@ -100,42 +100,42 @@ import ( func (m *Module) EmojiCreatePOSTHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } if !*authed.User.Admin { err := fmt.Errorf("user %s not an admin", authed.User.ID) - api.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } - form := &model.EmojiCreateRequest{} + form := &apimodel.EmojiCreateRequest{} if err := c.ShouldBind(form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } if err := validateCreateEmoji(form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } apiEmoji, errWithCode := m.processor.AdminEmojiCreate(c.Request.Context(), authed, form) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } c.JSON(http.StatusOK, apiEmoji) } -func validateCreateEmoji(form *model.EmojiCreateRequest) error { +func validateCreateEmoji(form *apimodel.EmojiCreateRequest) error { if form.Image == nil || form.Image.Size == 0 { return errors.New("no emoji given") } diff --git a/internal/api/client/admin/emojidelete.go b/internal/api/client/admin/emojidelete.go index 14f3c70ff..b66116b6d 100644 --- a/internal/api/client/admin/emojidelete.go +++ b/internal/api/client/admin/emojidelete.go @@ -24,7 +24,7 @@ import ( "net/http" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" ) @@ -78,31 +78,31 @@ import ( func (m *Module) EmojiDELETEHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } if !*authed.User.Admin { err := fmt.Errorf("user %s not an admin", authed.User.ID) - api.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } emojiID := c.Param(IDKey) if emojiID == "" { err := errors.New("no emoji id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } emoji, errWithCode := m.processor.AdminEmojiDelete(c.Request.Context(), authed, emojiID) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } diff --git a/internal/api/client/admin/emojiget.go b/internal/api/client/admin/emojiget.go index 60f7d5948..49d586756 100644 --- a/internal/api/client/admin/emojiget.go +++ b/internal/api/client/admin/emojiget.go @@ -24,7 +24,7 @@ import ( "net/http" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" ) @@ -68,31 +68,31 @@ import ( func (m *Module) EmojiGETHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } if !*authed.User.Admin { err := fmt.Errorf("user %s not an admin", authed.User.ID) - api.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } emojiID := c.Param(IDKey) if emojiID == "" { err := errors.New("no emoji id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } emoji, errWithCode := m.processor.AdminEmojiGet(c.Request.Context(), authed, emojiID) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } diff --git a/internal/api/client/admin/emojisget.go b/internal/api/client/admin/emojisget.go index 0b7cfe059..e8b3c0e49 100644 --- a/internal/api/client/admin/emojisget.go +++ b/internal/api/client/admin/emojisget.go @@ -25,7 +25,7 @@ import ( "strings" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/config" "github.com/superseriousbusiness/gotosocial/internal/db" "github.com/superseriousbusiness/gotosocial/internal/gtserror" @@ -125,18 +125,18 @@ import ( func (m *Module) EmojisGETHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } if !*authed.User.Admin { err := fmt.Errorf("user %s not an admin", authed.User.ID) - api.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } @@ -149,7 +149,7 @@ func (m *Module) EmojisGETHandler(c *gin.Context) { i, err := strconv.ParseInt(limitString, 10, 32) if err != nil { err := fmt.Errorf("error parsing %s: %s", LimitKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } limit = int(i) @@ -177,7 +177,7 @@ func (m *Module) EmojisGETHandler(c *gin.Context) { shortcode = strings.Trim(filter[10:], ":") // remove any errant ":" default: err := fmt.Errorf("filter %s not recognized; accepted values are 'domain:[domain]', 'disabled', 'enabled', 'shortcode:[shortcode]'", filter) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } } @@ -200,7 +200,7 @@ func (m *Module) EmojisGETHandler(c *gin.Context) { resp, errWithCode := m.processor.AdminEmojisGet(c.Request.Context(), authed, domain, includeDisabled, includeEnabled, shortcode, maxShortcodeDomain, minShortcodeDomain, limit) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } diff --git a/internal/api/client/admin/emojiupdate.go b/internal/api/client/admin/emojiupdate.go index 695c6bcde..8402b30e9 100644 --- a/internal/api/client/admin/emojiupdate.go +++ b/internal/api/client/admin/emojiupdate.go @@ -25,8 +25,8 @@ import ( "strings" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/config" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" @@ -123,42 +123,42 @@ import ( func (m *Module) EmojiPATCHHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } if !*authed.User.Admin { err := fmt.Errorf("user %s not an admin", authed.User.ID) - api.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } emojiID := c.Param(IDKey) if emojiID == "" { err := errors.New("no emoji id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } - form := &model.EmojiUpdateRequest{} + form := &apimodel.EmojiUpdateRequest{} if err := c.ShouldBind(form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } if err := validateUpdateEmoji(form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } emoji, errWithCode := m.processor.AdminEmojiUpdate(c.Request.Context(), emojiID, form) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } @@ -166,14 +166,14 @@ func (m *Module) EmojiPATCHHandler(c *gin.Context) { } // do a first pass on the form here -func validateUpdateEmoji(form *model.EmojiUpdateRequest) error { +func validateUpdateEmoji(form *apimodel.EmojiUpdateRequest) error { // check + normalize update type so we don't need // to do this trimming + lowercasing again later switch strings.TrimSpace(strings.ToLower(string(form.Type))) { - case string(model.EmojiUpdateDisable): + case string(apimodel.EmojiUpdateDisable): // no params required for this one, so don't bother checking - form.Type = model.EmojiUpdateDisable - case string(model.EmojiUpdateCopy): + form.Type = apimodel.EmojiUpdateDisable + case string(apimodel.EmojiUpdateCopy): // need at least a valid shortcode when doing a copy if form.Shortcode == nil { return errors.New("emoji action type was 'copy' but no shortcode was provided") @@ -190,8 +190,8 @@ func validateUpdateEmoji(form *model.EmojiUpdateRequest) error { } } - form.Type = model.EmojiUpdateCopy - case string(model.EmojiUpdateModify): + form.Type = apimodel.EmojiUpdateCopy + case string(apimodel.EmojiUpdateModify): // need either image or category name for modify hasImage := form.Image != nil && form.Image.Size != 0 hasCategoryName := form.CategoryName != nil @@ -212,7 +212,7 @@ func validateUpdateEmoji(form *model.EmojiUpdateRequest) error { } } - form.Type = model.EmojiUpdateModify + form.Type = apimodel.EmojiUpdateModify default: return errors.New("emoji action type must be one of 'disable', 'copy', 'modify'") } diff --git a/internal/api/client/admin/mediacleanup.go b/internal/api/client/admin/mediacleanup.go index 157f35ab0..7f3fc11d5 100644 --- a/internal/api/client/admin/mediacleanup.go +++ b/internal/api/client/admin/mediacleanup.go @@ -23,8 +23,8 @@ import ( "net/http" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/config" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" @@ -71,19 +71,19 @@ import ( func (m *Module) MediaCleanupPOSTHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } if !*authed.User.Admin { err := fmt.Errorf("user %s not an admin", authed.User.ID) - api.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) return } - form := &model.MediaCleanupRequest{} + form := &apimodel.MediaCleanupRequest{} if err := c.ShouldBind(form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } @@ -98,7 +98,7 @@ func (m *Module) MediaCleanupPOSTHandler(c *gin.Context) { } if errWithCode := m.processor.AdminMediaPrune(c.Request.Context(), remoteCacheDays); errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } diff --git a/internal/api/client/admin/mediarefetch.go b/internal/api/client/admin/mediarefetch.go index 9c8a30c1b..5618843e5 100644 --- a/internal/api/client/admin/mediarefetch.go +++ b/internal/api/client/admin/mediarefetch.go @@ -23,7 +23,7 @@ import ( "net/http" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" ) @@ -74,18 +74,18 @@ import ( func (m *Module) MediaRefetchPOSTHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } if !*authed.User.Admin { err := fmt.Errorf("user %s not an admin", authed.User.ID) - api.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) return } if errWithCode := m.processor.AdminMediaRefetch(c.Request.Context(), authed, c.Query(DomainQueryKey)); errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } diff --git a/internal/api/client/app/app.go b/internal/api/client/app/app.go deleted file mode 100644 index 0bbeb6cc9..000000000 --- a/internal/api/client/app/app.go +++ /dev/null @@ -1,48 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package app - -import ( - "net/http" - - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" -) - -// BasePath is the base path for this api module -const BasePath = "/api/v1/apps" - -// Module implements the ClientAPIModule interface for requests relating to registering/removing applications -type Module struct { - processor processing.Processor -} - -// New returns a new auth module -func New(processor processing.Processor) api.ClientModule { - return &Module{ - processor: processor, - } -} - -// Route satisfies the RESTAPIModule interface -func (m *Module) Route(s router.Router) error { - s.AttachHandler(http.MethodPost, BasePath, m.AppsPOSTHandler) - return nil -} diff --git a/internal/api/client/app/app_test.go b/internal/api/client/app/app_test.go deleted file mode 100644 index 5c1981ba1..000000000 --- a/internal/api/client/app/app_test.go +++ /dev/null @@ -1,21 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package app_test - -// TODO: write tests diff --git a/internal/api/client/app/appcreate.go b/internal/api/client/app/appcreate.go deleted file mode 100644 index 6060c9480..000000000 --- a/internal/api/client/app/appcreate.go +++ /dev/null @@ -1,126 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package app - -import ( - "fmt" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// these consts are used to ensure users can't spam huge entries into our database -const ( - formFieldLen = 1024 - formRedirectLen = 2056 -) - -// AppsPOSTHandler swagger:operation POST /api/v1/apps appCreate -// -// Register a new application on this instance. -// -// The registered application can be used to obtain an application token. -// This can then be used to register a new account, or (through user auth) obtain an access token. -// -// The parameters can also be given in the body of the request, as JSON, if the content-type is set to 'application/json'. -// The parameters can also be given in the body of the request, as XML, if the content-type is set to 'application/xml'. -// -// --- -// tags: -// - apps -// -// consumes: -// - application/json -// - application/xml -// - application/x-www-form-urlencoded -// -// produces: -// - application/json -// -// responses: -// '200': -// description: "The newly-created application." -// schema: -// "$ref": "#/definitions/application" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '403': -// description: forbidden -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) AppsPOSTHandler(c *gin.Context) { - authed, err := oauth.Authed(c, false, false, false, false) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - form := &model.ApplicationCreateRequest{} - if err := c.ShouldBind(form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - if len([]rune(form.ClientName)) > formFieldLen { - err := fmt.Errorf("client_name must be less than %d characters", formFieldLen) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - if len([]rune(form.RedirectURIs)) > formRedirectLen { - err := fmt.Errorf("redirect_uris must be less than %d characters", formRedirectLen) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - if len([]rune(form.Scopes)) > formFieldLen { - err := fmt.Errorf("scopes must be less than %d characters", formFieldLen) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - if len([]rune(form.Website)) > formFieldLen { - err := fmt.Errorf("website must be less than %d characters", formFieldLen) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - apiApp, errWithCode := m.processor.AppCreate(c.Request.Context(), authed, form) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, apiApp) -} diff --git a/internal/api/client/apps/appcreate.go b/internal/api/client/apps/appcreate.go new file mode 100644 index 000000000..f381e9954 --- /dev/null +++ b/internal/api/client/apps/appcreate.go @@ -0,0 +1,126 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package apps + +import ( + "fmt" + "net/http" + + "github.com/gin-gonic/gin" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// these consts are used to ensure users can't spam huge entries into our database +const ( + formFieldLen = 1024 + formRedirectLen = 2056 +) + +// AppsPOSTHandler swagger:operation POST /api/v1/apps appCreate +// +// Register a new application on this instance. +// +// The registered application can be used to obtain an application token. +// This can then be used to register a new account, or (through user auth) obtain an access token. +// +// The parameters can also be given in the body of the request, as JSON, if the content-type is set to 'application/json'. +// The parameters can also be given in the body of the request, as XML, if the content-type is set to 'application/xml'. +// +// --- +// tags: +// - apps +// +// consumes: +// - application/json +// - application/xml +// - application/x-www-form-urlencoded +// +// produces: +// - application/json +// +// responses: +// '200': +// description: "The newly-created application." +// schema: +// "$ref": "#/definitions/application" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '403': +// description: forbidden +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) AppsPOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, false, false, false, false) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + form := &apimodel.ApplicationCreateRequest{} + if err := c.ShouldBind(form); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + if len([]rune(form.ClientName)) > formFieldLen { + err := fmt.Errorf("client_name must be less than %d characters", formFieldLen) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + if len([]rune(form.RedirectURIs)) > formRedirectLen { + err := fmt.Errorf("redirect_uris must be less than %d characters", formRedirectLen) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + if len([]rune(form.Scopes)) > formFieldLen { + err := fmt.Errorf("scopes must be less than %d characters", formFieldLen) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + if len([]rune(form.Website)) > formFieldLen { + err := fmt.Errorf("website must be less than %d characters", formFieldLen) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + apiApp, errWithCode := m.processor.AppCreate(c.Request.Context(), authed, form) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, apiApp) +} diff --git a/internal/api/client/apps/apps.go b/internal/api/client/apps/apps.go new file mode 100644 index 000000000..264a76f6f --- /dev/null +++ b/internal/api/client/apps/apps.go @@ -0,0 +1,43 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package apps + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "github.com/superseriousbusiness/gotosocial/internal/processing" +) + +// BasePath is the base path for this api module, excluding the api prefix +const BasePath = "/v1/apps" + +type Module struct { + processor processing.Processor +} + +func New(processor processing.Processor) *Module { + return &Module{ + processor: processor, + } +} + +func (m *Module) Route(attachHandler func(method string, path string, f ...gin.HandlerFunc) gin.IRoutes) { + attachHandler(http.MethodPost, BasePath, m.AppsPOSTHandler) +} diff --git a/internal/api/client/auth/auth.go b/internal/api/client/auth/auth.go deleted file mode 100644 index 8a1d9d483..000000000 --- a/internal/api/client/auth/auth.go +++ /dev/null @@ -1,105 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package auth - -import ( - "net/http" - - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/db" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/internal/oidc" - "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" -) - -/* #nosec G101 */ -const ( - // AuthSignInPath is the API path for users to sign in through - AuthSignInPath = "/auth/sign_in" - - // CheckYourEmailPath users land here after registering a new account, instructs them to confirm thier email - CheckYourEmailPath = "/check_your_email" - - // WaitForApprovalPath users land here after confirming thier email but before an admin approves thier account - // (if such is required) - WaitForApprovalPath = "/wait_for_approval" - - // AccountDisabledPath users land here when thier account is suspended by an admin - AccountDisabledPath = "/account_disabled" - - // OauthTokenPath is the API path to use for granting token requests to users with valid credentials - OauthTokenPath = "/oauth/token" - - // OauthAuthorizePath is the API path for authorization requests (eg., authorize this app to act on my behalf as a user) - OauthAuthorizePath = "/oauth/authorize" - - // OauthFinalizePath is the API path for completing user registration with additional user details - OauthFinalizePath = "/oauth/finalize" - - // CallbackPath is the API path for receiving callback tokens from external OIDC providers - CallbackPath = oidc.CallbackPath - - callbackStateParam = "state" - callbackCodeParam = "code" - - sessionUserID = "userid" - sessionClientID = "client_id" - sessionRedirectURI = "redirect_uri" - sessionForceLogin = "force_login" - sessionResponseType = "response_type" - sessionScope = "scope" - sessionInternalState = "internal_state" - sessionClientState = "client_state" - sessionClaims = "claims" - sessionAppID = "app_id" -) - -// Module implements the ClientAPIModule interface for -type Module struct { - db db.DB - idp oidc.IDP - processor processing.Processor -} - -// New returns a new auth module -func New(db db.DB, idp oidc.IDP, processor processing.Processor) api.ClientModule { - return &Module{ - db: db, - idp: idp, - processor: processor, - } -} - -// Route satisfies the RESTAPIModule interface -func (m *Module) Route(s router.Router) error { - s.AttachHandler(http.MethodGet, AuthSignInPath, m.SignInGETHandler) - s.AttachHandler(http.MethodPost, AuthSignInPath, m.SignInPOSTHandler) - - s.AttachHandler(http.MethodPost, OauthTokenPath, m.TokenPOSTHandler) - - s.AttachHandler(http.MethodGet, OauthAuthorizePath, m.AuthorizeGETHandler) - s.AttachHandler(http.MethodPost, OauthAuthorizePath, m.AuthorizePOSTHandler) - - s.AttachHandler(http.MethodGet, CallbackPath, m.CallbackGETHandler) - s.AttachHandler(http.MethodPost, OauthFinalizePath, m.FinalizePOSTHandler) - - s.AttachHandler(http.MethodGet, oauth.OOBTokenPath, m.OobHandler) - return nil -} diff --git a/internal/api/client/auth/auth_test.go b/internal/api/client/auth/auth_test.go deleted file mode 100644 index 75e958418..000000000 --- a/internal/api/client/auth/auth_test.go +++ /dev/null @@ -1,139 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package auth_test - -import ( - "bytes" - "context" - "fmt" - "net/http/httptest" - - "github.com/gin-contrib/sessions" - "github.com/gin-contrib/sessions/memstore" - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/auth" - "github.com/superseriousbusiness/gotosocial/internal/concurrency" - "github.com/superseriousbusiness/gotosocial/internal/config" - "github.com/superseriousbusiness/gotosocial/internal/db" - "github.com/superseriousbusiness/gotosocial/internal/email" - "github.com/superseriousbusiness/gotosocial/internal/federation" - "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" - "github.com/superseriousbusiness/gotosocial/internal/media" - "github.com/superseriousbusiness/gotosocial/internal/messages" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/internal/oidc" - "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" - "github.com/superseriousbusiness/gotosocial/internal/storage" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type AuthStandardTestSuite struct { - suite.Suite - db db.DB - storage *storage.Driver - mediaManager media.Manager - federator federation.Federator - processor processing.Processor - emailSender email.Sender - idp oidc.IDP - oauthServer oauth.Server - - // standard suite models - testTokens map[string]*gtsmodel.Token - testClients map[string]*gtsmodel.Client - testApplications map[string]*gtsmodel.Application - testUsers map[string]*gtsmodel.User - testAccounts map[string]*gtsmodel.Account - - // module being tested - authModule *auth.Module -} - -const ( - sessionUserID = "userid" - sessionClientID = "client_id" -) - -func (suite *AuthStandardTestSuite) SetupSuite() { - suite.testTokens = testrig.NewTestTokens() - suite.testClients = testrig.NewTestClients() - suite.testApplications = testrig.NewTestApplications() - suite.testUsers = testrig.NewTestUsers() - suite.testAccounts = testrig.NewTestAccounts() -} - -func (suite *AuthStandardTestSuite) SetupTest() { - testrig.InitTestConfig() - testrig.InitTestLog() - - fedWorker := concurrency.NewWorkerPool[messages.FromFederator](-1, -1) - clientWorker := concurrency.NewWorkerPool[messages.FromClientAPI](-1, -1) - - suite.db = testrig.NewTestDB() - suite.storage = testrig.NewInMemoryStorage() - suite.mediaManager = testrig.NewTestMediaManager(suite.db, suite.storage) - suite.federator = testrig.NewTestFederator(suite.db, testrig.NewTestTransportController(testrig.NewMockHTTPClient(nil, "../../../../testrig/media"), suite.db, fedWorker), suite.storage, suite.mediaManager, fedWorker) - suite.emailSender = testrig.NewEmailSender("../../../../web/template/", nil) - suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator, suite.emailSender, suite.mediaManager, clientWorker, fedWorker) - - suite.oauthServer = testrig.NewTestOauthServer(suite.db) - var err error - suite.idp, err = oidc.NewIDP(context.Background()) - if err != nil { - panic(err) - } - suite.authModule = auth.New(suite.db, suite.idp, suite.processor).(*auth.Module) - testrig.StandardDBSetup(suite.db, suite.testAccounts) -} - -func (suite *AuthStandardTestSuite) TearDownTest() { - testrig.StandardDBTeardown(suite.db) -} - -func (suite *AuthStandardTestSuite) newContext(requestMethod string, requestPath string, requestBody []byte, bodyContentType string) (*gin.Context, *httptest.ResponseRecorder) { - // create the recorder and gin test context - recorder := httptest.NewRecorder() - ctx, engine := testrig.CreateGinTestContext(recorder, nil) - - // load templates into the engine - testrig.ConfigureTemplatesWithGin(engine, "../../../../web/template") - - // create the request - protocol := config.GetProtocol() - host := config.GetHost() - baseURI := fmt.Sprintf("%s://%s", protocol, host) - requestURI := fmt.Sprintf("%s/%s", baseURI, requestPath) - - ctx.Request = httptest.NewRequest(requestMethod, requestURI, bytes.NewReader(requestBody)) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "text/html") - - if bodyContentType != "" { - ctx.Request.Header.Set("Content-Type", bodyContentType) - } - - // trigger the session middleware on the context - store := memstore.NewStore(make([]byte, 32), make([]byte, 32)) - store.Options(router.SessionOptions()) - sessionMiddleware := sessions.Sessions("gotosocial-localhost", store) - sessionMiddleware(ctx) - - return ctx, recorder -} diff --git a/internal/api/client/auth/authorize.go b/internal/api/client/auth/authorize.go deleted file mode 100644 index f28d1dfc9..000000000 --- a/internal/api/client/auth/authorize.go +++ /dev/null @@ -1,335 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package auth - -import ( - "errors" - "fmt" - "net/http" - "net/url" - - "github.com/gin-contrib/sessions" - "github.com/gin-gonic/gin" - "github.com/google/uuid" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/config" - "github.com/superseriousbusiness/gotosocial/internal/db" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// AuthorizeGETHandler should be served as GET at https://example.org/oauth/authorize -// The idea here is to present an oauth authorize page to the user, with a button -// that they have to click to accept. -func (m *Module) AuthorizeGETHandler(c *gin.Context) { - s := sessions.Default(c) - - if _, err := api.NegotiateAccept(c, api.HTMLAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - // UserID will be set in the session by AuthorizePOSTHandler if the caller has already gone through the authentication flow - // If it's not set, then we don't know yet who the user is, so we need to redirect them to the sign in page. - userID, ok := s.Get(sessionUserID).(string) - if !ok || userID == "" { - form := &model.OAuthAuthorize{} - if err := c.ShouldBind(form); err != nil { - m.clearSession(s) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, oauth.HelpfulAdvice), m.processor.InstanceGet) - return - } - - if errWithCode := saveAuthFormToSession(s, form); errWithCode != nil { - m.clearSession(s) - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.Redirect(http.StatusSeeOther, AuthSignInPath) - return - } - - // use session information to validate app, user, and account for this request - clientID, ok := s.Get(sessionClientID).(string) - if !ok || clientID == "" { - m.clearSession(s) - err := fmt.Errorf("key %s was not found in session", sessionClientID) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, oauth.HelpfulAdvice), m.processor.InstanceGet) - return - } - - app := >smodel.Application{} - if err := m.db.GetWhere(c.Request.Context(), []db.Where{{Key: sessionClientID, Value: clientID}}, app); err != nil { - m.clearSession(s) - safe := fmt.Sprintf("application for %s %s could not be retrieved", sessionClientID, clientID) - var errWithCode gtserror.WithCode - if err == db.ErrNoEntries { - errWithCode = gtserror.NewErrorBadRequest(err, safe, oauth.HelpfulAdvice) - } else { - errWithCode = gtserror.NewErrorInternalError(err, safe, oauth.HelpfulAdvice) - } - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - user, err := m.db.GetUserByID(c.Request.Context(), userID) - if err != nil { - m.clearSession(s) - safe := fmt.Sprintf("user with id %s could not be retrieved", userID) - var errWithCode gtserror.WithCode - if err == db.ErrNoEntries { - errWithCode = gtserror.NewErrorBadRequest(err, safe, oauth.HelpfulAdvice) - } else { - errWithCode = gtserror.NewErrorInternalError(err, safe, oauth.HelpfulAdvice) - } - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - acct, err := m.db.GetAccountByID(c.Request.Context(), user.AccountID) - if err != nil { - m.clearSession(s) - safe := fmt.Sprintf("account with id %s could not be retrieved", user.AccountID) - var errWithCode gtserror.WithCode - if err == db.ErrNoEntries { - errWithCode = gtserror.NewErrorBadRequest(err, safe, oauth.HelpfulAdvice) - } else { - errWithCode = gtserror.NewErrorInternalError(err, safe, oauth.HelpfulAdvice) - } - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - if ensureUserIsAuthorizedOrRedirect(c, user, acct) { - return - } - - // Finally we should also get the redirect and scope of this particular request, as stored in the session. - redirect, ok := s.Get(sessionRedirectURI).(string) - if !ok || redirect == "" { - m.clearSession(s) - err := fmt.Errorf("key %s was not found in session", sessionRedirectURI) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, oauth.HelpfulAdvice), m.processor.InstanceGet) - return - } - - scope, ok := s.Get(sessionScope).(string) - if !ok || scope == "" { - m.clearSession(s) - err := fmt.Errorf("key %s was not found in session", sessionScope) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, oauth.HelpfulAdvice), m.processor.InstanceGet) - return - } - - instance, errWithCode := m.processor.InstanceGet(c.Request.Context(), config.GetHost()) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - // the authorize template will display a form to the user where they can get some information - // about the app that's trying to authorize, and the scope of the request. - // They can then approve it if it looks OK to them, which will POST to the AuthorizePOSTHandler - c.HTML(http.StatusOK, "authorize.tmpl", gin.H{ - "appname": app.Name, - "appwebsite": app.Website, - "redirect": redirect, - "scope": scope, - "user": acct.Username, - "instance": instance, - }) -} - -// AuthorizePOSTHandler should be served as POST at https://example.org/oauth/authorize -// At this point we assume that the user has A) logged in and B) accepted that the app should act for them, -// so we should proceed with the authentication flow and generate an oauth token for them if we can. -func (m *Module) AuthorizePOSTHandler(c *gin.Context) { - s := sessions.Default(c) - - // We need to retrieve the original form submitted to the authorizeGEThandler, and - // recreate it on the request so that it can be used further by the oauth2 library. - errs := []string{} - - forceLogin, ok := s.Get(sessionForceLogin).(string) - if !ok { - forceLogin = "false" - } - - responseType, ok := s.Get(sessionResponseType).(string) - if !ok || responseType == "" { - errs = append(errs, fmt.Sprintf("key %s was not found in session", sessionResponseType)) - } - - clientID, ok := s.Get(sessionClientID).(string) - if !ok || clientID == "" { - errs = append(errs, fmt.Sprintf("key %s was not found in session", sessionClientID)) - } - - redirectURI, ok := s.Get(sessionRedirectURI).(string) - if !ok || redirectURI == "" { - errs = append(errs, fmt.Sprintf("key %s was not found in session", sessionRedirectURI)) - } - - scope, ok := s.Get(sessionScope).(string) - if !ok { - errs = append(errs, fmt.Sprintf("key %s was not found in session", sessionScope)) - } - - var clientState string - if s, ok := s.Get(sessionClientState).(string); ok { - clientState = s - } - - userID, ok := s.Get(sessionUserID).(string) - if !ok { - errs = append(errs, fmt.Sprintf("key %s was not found in session", sessionUserID)) - } - - if len(errs) != 0 { - errs = append(errs, oauth.HelpfulAdvice) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(errors.New("one or more missing keys on session during AuthorizePOSTHandler"), errs...), m.processor.InstanceGet) - return - } - - user, err := m.db.GetUserByID(c.Request.Context(), userID) - if err != nil { - m.clearSession(s) - safe := fmt.Sprintf("user with id %s could not be retrieved", userID) - var errWithCode gtserror.WithCode - if err == db.ErrNoEntries { - errWithCode = gtserror.NewErrorBadRequest(err, safe, oauth.HelpfulAdvice) - } else { - errWithCode = gtserror.NewErrorInternalError(err, safe, oauth.HelpfulAdvice) - } - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - acct, err := m.db.GetAccountByID(c.Request.Context(), user.AccountID) - if err != nil { - m.clearSession(s) - safe := fmt.Sprintf("account with id %s could not be retrieved", user.AccountID) - var errWithCode gtserror.WithCode - if err == db.ErrNoEntries { - errWithCode = gtserror.NewErrorBadRequest(err, safe, oauth.HelpfulAdvice) - } else { - errWithCode = gtserror.NewErrorInternalError(err, safe, oauth.HelpfulAdvice) - } - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - if ensureUserIsAuthorizedOrRedirect(c, user, acct) { - return - } - - if redirectURI != oauth.OOBURI { - // we're done with the session now, so just clear it out - m.clearSession(s) - } - - // we have to set the values on the request form - // so that they're picked up by the oauth server - c.Request.Form = url.Values{ - sessionForceLogin: {forceLogin}, - sessionResponseType: {responseType}, - sessionClientID: {clientID}, - sessionRedirectURI: {redirectURI}, - sessionScope: {scope}, - sessionUserID: {userID}, - } - - if clientState != "" { - c.Request.Form.Set("state", clientState) - } - - if errWithCode := m.processor.OAuthHandleAuthorizeRequest(c.Writer, c.Request); errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - } -} - -// saveAuthFormToSession checks the given OAuthAuthorize form, -// and stores the values in the form into the session. -func saveAuthFormToSession(s sessions.Session, form *model.OAuthAuthorize) gtserror.WithCode { - if form == nil { - err := errors.New("OAuthAuthorize form was nil") - return gtserror.NewErrorBadRequest(err, err.Error(), oauth.HelpfulAdvice) - } - - if form.ResponseType == "" { - err := errors.New("field response_type was not set on OAuthAuthorize form") - return gtserror.NewErrorBadRequest(err, err.Error(), oauth.HelpfulAdvice) - } - - if form.ClientID == "" { - err := errors.New("field client_id was not set on OAuthAuthorize form") - return gtserror.NewErrorBadRequest(err, err.Error(), oauth.HelpfulAdvice) - } - - if form.RedirectURI == "" { - err := errors.New("field redirect_uri was not set on OAuthAuthorize form") - return gtserror.NewErrorBadRequest(err, err.Error(), oauth.HelpfulAdvice) - } - - // set default scope to read - if form.Scope == "" { - form.Scope = "read" - } - - // save these values from the form so we can use them elsewhere in the session - s.Set(sessionForceLogin, form.ForceLogin) - s.Set(sessionResponseType, form.ResponseType) - s.Set(sessionClientID, form.ClientID) - s.Set(sessionRedirectURI, form.RedirectURI) - s.Set(sessionScope, form.Scope) - s.Set(sessionInternalState, uuid.NewString()) - s.Set(sessionClientState, form.State) - - if err := s.Save(); err != nil { - err := fmt.Errorf("error saving form values onto session: %s", err) - return gtserror.NewErrorInternalError(err, oauth.HelpfulAdvice) - } - - return nil -} - -func ensureUserIsAuthorizedOrRedirect(ctx *gin.Context, user *gtsmodel.User, account *gtsmodel.Account) (redirected bool) { - if user.ConfirmedAt.IsZero() { - ctx.Redirect(http.StatusSeeOther, CheckYourEmailPath) - redirected = true - return - } - - if !*user.Approved { - ctx.Redirect(http.StatusSeeOther, WaitForApprovalPath) - redirected = true - return - } - - if *user.Disabled || !account.SuspendedAt.IsZero() { - ctx.Redirect(http.StatusSeeOther, AccountDisabledPath) - redirected = true - return - } - - return -} diff --git a/internal/api/client/auth/authorize_test.go b/internal/api/client/auth/authorize_test.go deleted file mode 100644 index 738b3b910..000000000 --- a/internal/api/client/auth/authorize_test.go +++ /dev/null @@ -1,118 +0,0 @@ -package auth_test - -import ( - "context" - "fmt" - "net/http" - "testing" - "time" - - "github.com/gin-contrib/sessions" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/auth" - "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type AuthAuthorizeTestSuite struct { - AuthStandardTestSuite -} - -type authorizeHandlerTestCase struct { - description string - mutateUserAccount func(*gtsmodel.User, *gtsmodel.Account) []string - expectedStatusCode int - expectedLocationHeader string -} - -func (suite *AuthAuthorizeTestSuite) TestAccountAuthorizeHandler() { - tests := []authorizeHandlerTestCase{ - { - description: "user has their email unconfirmed", - mutateUserAccount: func(user *gtsmodel.User, account *gtsmodel.Account) []string { - user.ConfirmedAt = time.Time{} - return []string{"confirmed_at"} - }, - expectedStatusCode: http.StatusSeeOther, - expectedLocationHeader: auth.CheckYourEmailPath, - }, - { - description: "user has their email confirmed but is not approved", - mutateUserAccount: func(user *gtsmodel.User, account *gtsmodel.Account) []string { - user.ConfirmedAt = time.Now() - user.Email = user.UnconfirmedEmail - return []string{"confirmed_at", "email"} - }, - expectedStatusCode: http.StatusSeeOther, - expectedLocationHeader: auth.WaitForApprovalPath, - }, - { - description: "user has their email confirmed and is approved, but User entity has been disabled", - mutateUserAccount: func(user *gtsmodel.User, account *gtsmodel.Account) []string { - user.ConfirmedAt = time.Now() - user.Email = user.UnconfirmedEmail - user.Approved = testrig.TrueBool() - user.Disabled = testrig.TrueBool() - return []string{"confirmed_at", "email", "approved", "disabled"} - }, - expectedStatusCode: http.StatusSeeOther, - expectedLocationHeader: auth.AccountDisabledPath, - }, - { - description: "user has their email confirmed and is approved, but Account entity has been suspended", - mutateUserAccount: func(user *gtsmodel.User, account *gtsmodel.Account) []string { - user.ConfirmedAt = time.Now() - user.Email = user.UnconfirmedEmail - user.Approved = testrig.TrueBool() - user.Disabled = testrig.FalseBool() - account.SuspendedAt = time.Now() - return []string{"confirmed_at", "email", "approved", "disabled"} - }, - expectedStatusCode: http.StatusSeeOther, - expectedLocationHeader: auth.AccountDisabledPath, - }, - } - - doTest := func(testCase authorizeHandlerTestCase) { - ctx, recorder := suite.newContext(http.MethodGet, auth.OauthAuthorizePath, nil, "") - - user := >smodel.User{} - account := >smodel.Account{} - - *user = *suite.testUsers["unconfirmed_account"] - *account = *suite.testAccounts["unconfirmed_account"] - - testSession := sessions.Default(ctx) - testSession.Set(sessionUserID, user.ID) - testSession.Set(sessionClientID, suite.testApplications["application_1"].ClientID) - if err := testSession.Save(); err != nil { - panic(fmt.Errorf("failed on case %s: %w", testCase.description, err)) - } - - columns := testCase.mutateUserAccount(user, account) - - testCase.description = fmt.Sprintf("%s, %t, %s", user.Email, *user.Disabled, account.SuspendedAt) - - err := suite.db.UpdateUser(context.Background(), user, columns...) - suite.NoError(err) - err = suite.db.UpdateAccount(context.Background(), account) - suite.NoError(err) - - // call the handler - suite.authModule.AuthorizeGETHandler(ctx) - - // 1. we should have a redirect - suite.Equal(testCase.expectedStatusCode, recorder.Code, fmt.Sprintf("failed on case: %s", testCase.description)) - - // 2. we should have a redirect to the check your email path, as this user has not confirmed their email yet. - suite.Equal(testCase.expectedLocationHeader, recorder.Header().Get("Location"), fmt.Sprintf("failed on case: %s", testCase.description)) - } - - for _, testCase := range tests { - doTest(testCase) - } -} - -func TestAccountUpdateTestSuite(t *testing.T) { - suite.Run(t, new(AuthAuthorizeTestSuite)) -} diff --git a/internal/api/client/auth/callback.go b/internal/api/client/auth/callback.go deleted file mode 100644 index c97abf7aa..000000000 --- a/internal/api/client/auth/callback.go +++ /dev/null @@ -1,311 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package auth - -import ( - "context" - "errors" - "fmt" - "net" - "net/http" - "strings" - - "github.com/gin-contrib/sessions" - "github.com/gin-gonic/gin" - "github.com/google/uuid" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/config" - "github.com/superseriousbusiness/gotosocial/internal/db" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/internal/oidc" - "github.com/superseriousbusiness/gotosocial/internal/validate" -) - -// extraInfo wraps a form-submitted username and transmitted name -type extraInfo struct { - Username string `form:"username"` - Name string `form:"name"` // note that this is only used for re-rendering the page in case of an error -} - -// CallbackGETHandler parses a token from an external auth provider. -func (m *Module) CallbackGETHandler(c *gin.Context) { - s := sessions.Default(c) - - // check the query vs session state parameter to mitigate csrf - // https://auth0.com/docs/secure/attack-protection/state-parameters - - returnedInternalState := c.Query(callbackStateParam) - if returnedInternalState == "" { - m.clearSession(s) - err := fmt.Errorf("%s parameter not found on callback query", callbackStateParam) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - savedInternalStateI := s.Get(sessionInternalState) - savedInternalState, ok := savedInternalStateI.(string) - if !ok { - m.clearSession(s) - err := fmt.Errorf("key %s was not found in session", sessionInternalState) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - if returnedInternalState != savedInternalState { - m.clearSession(s) - err := errors.New("mismatch between callback state and saved state") - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - // retrieve stored claims using code - code := c.Query(callbackCodeParam) - if code == "" { - m.clearSession(s) - err := fmt.Errorf("%s parameter not found on callback query", callbackCodeParam) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - claims, errWithCode := m.idp.HandleCallback(c.Request.Context(), code) - if errWithCode != nil { - m.clearSession(s) - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - // We can use the client_id on the session to retrieve - // info about the app associated with the client_id - clientID, ok := s.Get(sessionClientID).(string) - if !ok || clientID == "" { - m.clearSession(s) - err := fmt.Errorf("key %s was not found in session", sessionClientID) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, oauth.HelpfulAdvice), m.processor.InstanceGet) - return - } - - app := >smodel.Application{} - if err := m.db.GetWhere(c.Request.Context(), []db.Where{{Key: sessionClientID, Value: clientID}}, app); err != nil { - m.clearSession(s) - safe := fmt.Sprintf("application for %s %s could not be retrieved", sessionClientID, clientID) - var errWithCode gtserror.WithCode - if err == db.ErrNoEntries { - errWithCode = gtserror.NewErrorBadRequest(err, safe, oauth.HelpfulAdvice) - } else { - errWithCode = gtserror.NewErrorInternalError(err, safe, oauth.HelpfulAdvice) - } - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - user, errWithCode := m.fetchUserForClaims(c.Request.Context(), claims, net.IP(c.ClientIP()), app.ID) - if errWithCode != nil { - m.clearSession(s) - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - if user == nil { - // no user exists yet - let's ask them for their preferred username - instance, errWithCode := m.processor.InstanceGet(c.Request.Context(), config.GetHost()) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - // store the claims in the session - that way we know the user is authenticated when processing the form later - s.Set(sessionClaims, claims) - s.Set(sessionAppID, app.ID) - if err := s.Save(); err != nil { - m.clearSession(s) - api.ErrorHandler(c, gtserror.NewErrorInternalError(err), m.processor.InstanceGet) - return - } - c.HTML(http.StatusOK, "finalize.tmpl", gin.H{ - "instance": instance, - "name": claims.Name, - "preferredUsername": claims.PreferredUsername, - }) - return - } - s.Set(sessionUserID, user.ID) - if err := s.Save(); err != nil { - m.clearSession(s) - api.ErrorHandler(c, gtserror.NewErrorInternalError(err), m.processor.InstanceGet) - return - } - c.Redirect(http.StatusFound, OauthAuthorizePath) -} - -// FinalizePOSTHandler registers the user after additional data has been provided -func (m *Module) FinalizePOSTHandler(c *gin.Context) { - s := sessions.Default(c) - - form := &extraInfo{} - if err := c.ShouldBind(form); err != nil { - m.clearSession(s) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, oauth.HelpfulAdvice), m.processor.InstanceGet) - return - } - - // since we have multiple possible validation error, `validationError` is a shorthand for rendering them - validationError := func(err error) { - instance, errWithCode := m.processor.InstanceGet(c.Request.Context(), config.GetHost()) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - c.HTML(http.StatusOK, "finalize.tmpl", gin.H{ - "instance": instance, - "name": form.Name, - "preferredUsername": form.Username, - "error": err, - }) - } - - // check if the username conforms to the spec - if err := validate.Username(form.Username); err != nil { - validationError(err) - return - } - - // see if the username is still available - usernameAvailable, err := m.db.IsUsernameAvailable(c.Request.Context(), form.Username) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, oauth.HelpfulAdvice), m.processor.InstanceGet) - return - } - if !usernameAvailable { - validationError(fmt.Errorf("Username %s is already taken", form.Username)) - return - } - - // retrieve the information previously set by the oidc logic - appID, ok := s.Get(sessionAppID).(string) - if !ok { - err := fmt.Errorf("key %s was not found in session", sessionAppID) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, oauth.HelpfulAdvice), m.processor.InstanceGet) - return - } - - // retrieve the claims returned by the IDP. Having this present means that we previously already verified these claims - claims, ok := s.Get(sessionClaims).(*oidc.Claims) - if !ok { - err := fmt.Errorf("key %s was not found in session", sessionClaims) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, oauth.HelpfulAdvice), m.processor.InstanceGet) - return - } - - // we're now ready to actually create the user - user, errWithCode := m.createUserFromOIDC(c.Request.Context(), claims, form, net.IP(c.ClientIP()), appID) - if errWithCode != nil { - m.clearSession(s) - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - s.Delete(sessionClaims) - s.Delete(sessionAppID) - s.Set(sessionUserID, user.ID) - if err := s.Save(); err != nil { - m.clearSession(s) - api.ErrorHandler(c, gtserror.NewErrorInternalError(err), m.processor.InstanceGet) - return - } - c.Redirect(http.StatusFound, OauthAuthorizePath) -} - -func (m *Module) fetchUserForClaims(ctx context.Context, claims *oidc.Claims, ip net.IP, appID string) (*gtsmodel.User, gtserror.WithCode) { - if claims.Sub == "" { - err := errors.New("no sub claim found - is your provider OIDC compliant?") - return nil, gtserror.NewErrorBadRequest(err, err.Error()) - } - user, err := m.db.GetUserByExternalID(ctx, claims.Sub) - if err == nil { - return user, nil - } - if err != db.ErrNoEntries { - err := fmt.Errorf("error checking database for externalID %s: %s", claims.Sub, err) - return nil, gtserror.NewErrorInternalError(err) - } - if !config.GetOIDCLinkExisting() { - return nil, nil - } - // fallback to email if we want to link existing users - user, err = m.db.GetUserByEmailAddress(ctx, claims.Email) - if err == db.ErrNoEntries { - return nil, nil - } else if err != nil { - err := fmt.Errorf("error checking database for email %s: %s", claims.Email, err) - return nil, gtserror.NewErrorInternalError(err) - } - // at this point we have found a matching user but still need to link the newly received external ID - - user.ExternalID = claims.Sub - err = m.db.UpdateUser(ctx, user, "external_id") - if err != nil { - err := fmt.Errorf("error linking existing user %s: %s", claims.Email, err) - return nil, gtserror.NewErrorInternalError(err) - } - return user, nil -} - -func (m *Module) createUserFromOIDC(ctx context.Context, claims *oidc.Claims, extraInfo *extraInfo, ip net.IP, appID string) (*gtsmodel.User, gtserror.WithCode) { - // check if the email address is available for use; if it's not there's nothing we can so - emailAvailable, err := m.db.IsEmailAvailable(ctx, claims.Email) - if err != nil { - return nil, gtserror.NewErrorBadRequest(err) - } - if !emailAvailable { - help := "The email address given to us by your authentication provider already exists in our records and the server administrator has not enabled account migration" - return nil, gtserror.NewErrorConflict(fmt.Errorf("email address %s is not available", claims.Email), help) - } - - // check if the user is in any recognised admin groups - var admin bool - for _, g := range claims.Groups { - if strings.EqualFold(g, "admin") || strings.EqualFold(g, "admins") { - admin = true - } - } - - // We still need to set *a* password even if it's not a password the user will end up using, so set something random. - // We'll just set two uuids on top of each other, which should be long + random enough to baffle any attempts to crack. - // - // If the user ever wants to log in using gts password rather than oidc flow, they'll have to request a password reset, which is fine - password := uuid.NewString() + uuid.NewString() - - // Since this user is created via oidc, which has been set up by the admin, we can assume that the account is already - // implicitly approved, and that the email address has already been verified: otherwise, we end up in situations where - // the admin first approves the user in OIDC, and then has to approve them again in GoToSocial, which doesn't make sense. - // - // In other words, if a user logs in via OIDC, they should be able to use their account straight away. - // - // See: https://github.com/superseriousbusiness/gotosocial/issues/357 - requireApproval := false - emailVerified := true - - // create the user! this will also create an account and store it in the database so we don't need to do that here - user, err := m.db.NewSignup(ctx, extraInfo.Username, "", requireApproval, claims.Email, password, ip, "", appID, emailVerified, claims.Sub, admin) - if err != nil { - return nil, gtserror.NewErrorInternalError(err) - } - - return user, nil -} diff --git a/internal/api/client/auth/oob.go b/internal/api/client/auth/oob.go deleted file mode 100644 index 92e49d328..000000000 --- a/internal/api/client/auth/oob.go +++ /dev/null @@ -1,111 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package auth - -import ( - "context" - "errors" - "fmt" - "net/http" - - "github.com/gin-contrib/sessions" - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/config" - "github.com/superseriousbusiness/gotosocial/internal/db" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -func (m *Module) OobHandler(c *gin.Context) { - host := config.GetHost() - instance, errWithCode := m.processor.InstanceGet(c.Request.Context(), host) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - instanceGet := func(ctx context.Context, domain string) (*model.Instance, gtserror.WithCode) { return instance, nil } - - oobToken := c.Query("code") - if oobToken == "" { - err := errors.New("no 'code' query value provided in callback redirect") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error(), oauth.HelpfulAdvice), instanceGet) - return - } - - s := sessions.Default(c) - - errs := []string{} - - scope, ok := s.Get(sessionScope).(string) - if !ok { - errs = append(errs, fmt.Sprintf("key %s was not found in session", sessionScope)) - } - - userID, ok := s.Get(sessionUserID).(string) - if !ok { - errs = append(errs, fmt.Sprintf("key %s was not found in session", sessionUserID)) - } - - if len(errs) != 0 { - errs = append(errs, oauth.HelpfulAdvice) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(errors.New("one or more missing keys on session during OobHandler"), errs...), m.processor.InstanceGet) - return - } - - user, err := m.db.GetUserByID(c.Request.Context(), userID) - if err != nil { - m.clearSession(s) - safe := fmt.Sprintf("user with id %s could not be retrieved", userID) - var errWithCode gtserror.WithCode - if err == db.ErrNoEntries { - errWithCode = gtserror.NewErrorBadRequest(err, safe, oauth.HelpfulAdvice) - } else { - errWithCode = gtserror.NewErrorInternalError(err, safe, oauth.HelpfulAdvice) - } - api.ErrorHandler(c, errWithCode, instanceGet) - return - } - - acct, err := m.db.GetAccountByID(c.Request.Context(), user.AccountID) - if err != nil { - m.clearSession(s) - safe := fmt.Sprintf("account with id %s could not be retrieved", user.AccountID) - var errWithCode gtserror.WithCode - if err == db.ErrNoEntries { - errWithCode = gtserror.NewErrorBadRequest(err, safe, oauth.HelpfulAdvice) - } else { - errWithCode = gtserror.NewErrorInternalError(err, safe, oauth.HelpfulAdvice) - } - api.ErrorHandler(c, errWithCode, instanceGet) - return - } - - // we're done with the session now, so just clear it out - m.clearSession(s) - - c.HTML(http.StatusOK, "oob.tmpl", gin.H{ - "instance": instance, - "user": acct.Username, - "oobToken": oobToken, - "scope": scope, - }) -} diff --git a/internal/api/client/auth/signin.go b/internal/api/client/auth/signin.go deleted file mode 100644 index 73a5de398..000000000 --- a/internal/api/client/auth/signin.go +++ /dev/null @@ -1,145 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package auth - -import ( - "context" - "errors" - "fmt" - "net/http" - - "github.com/gin-contrib/sessions" - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/config" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "golang.org/x/crypto/bcrypt" -) - -// login just wraps a form-submitted username (we want an email) and password -type login struct { - Email string `form:"username"` - Password string `form:"password"` -} - -// SignInGETHandler should be served at https://example.org/auth/sign_in. -// The idea is to present a sign in page to the user, where they can enter their username and password. -// The form will then POST to the sign in page, which will be handled by SignInPOSTHandler. -// If an idp provider is set, then the user will be redirected to that to do their sign in. -func (m *Module) SignInGETHandler(c *gin.Context) { - if _, err := api.NegotiateAccept(c, api.HTMLAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - if m.idp == nil { - instance, errWithCode := m.processor.InstanceGet(c.Request.Context(), config.GetHost()) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - // no idp provider, use our own funky little sign in page - c.HTML(http.StatusOK, "sign-in.tmpl", gin.H{ - "instance": instance, - }) - return - } - - // idp provider is in use, so redirect to it - s := sessions.Default(c) - - internalStateI := s.Get(sessionInternalState) - internalState, ok := internalStateI.(string) - if !ok { - m.clearSession(s) - err := fmt.Errorf("key %s was not found in session", sessionInternalState) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - c.Redirect(http.StatusSeeOther, m.idp.AuthCodeURL(internalState)) -} - -// SignInPOSTHandler should be served at https://example.org/auth/sign_in. -// The idea is to present a sign in page to the user, where they can enter their username and password. -// The handler will then redirect to the auth handler served at /auth -func (m *Module) SignInPOSTHandler(c *gin.Context) { - s := sessions.Default(c) - - form := &login{} - if err := c.ShouldBind(form); err != nil { - m.clearSession(s) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, oauth.HelpfulAdvice), m.processor.InstanceGet) - return - } - - userid, errWithCode := m.ValidatePassword(c.Request.Context(), form.Email, form.Password) - if errWithCode != nil { - // don't clear session here, so the user can just press back and try again - // if they accidentally gave the wrong password or something - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - s.Set(sessionUserID, userid) - if err := s.Save(); err != nil { - err := fmt.Errorf("error saving user id onto session: %s", err) - api.ErrorHandler(c, gtserror.NewErrorInternalError(err, oauth.HelpfulAdvice), m.processor.InstanceGet) - } - - c.Redirect(http.StatusFound, OauthAuthorizePath) -} - -// ValidatePassword takes an email address and a password. -// The goal is to authenticate the password against the one for that email -// address stored in the database. If OK, we return the userid (a ulid) for that user, -// so that it can be used in further Oauth flows to generate a token/retreieve an oauth client from the db. -func (m *Module) ValidatePassword(ctx context.Context, email string, password string) (string, gtserror.WithCode) { - if email == "" || password == "" { - err := errors.New("email or password was not provided") - return incorrectPassword(err) - } - - user, err := m.db.GetUserByEmailAddress(ctx, email) - if err != nil { - err := fmt.Errorf("user %s was not retrievable from db during oauth authorization attempt: %s", email, err) - return incorrectPassword(err) - } - - if user.EncryptedPassword == "" { - err := fmt.Errorf("encrypted password for user %s was empty for some reason", user.Email) - return incorrectPassword(err) - } - - if err := bcrypt.CompareHashAndPassword([]byte(user.EncryptedPassword), []byte(password)); err != nil { - err := fmt.Errorf("password hash didn't match for user %s during login attempt: %s", user.Email, err) - return incorrectPassword(err) - } - - return user.ID, nil -} - -// incorrectPassword wraps the given error in a gtserror.WithCode, and returns -// only a generic 'safe' error message to the user, to not give any info away. -func incorrectPassword(err error) (string, gtserror.WithCode) { - safeErr := fmt.Errorf("password/email combination was incorrect") - return "", gtserror.NewErrorUnauthorized(err, safeErr.Error(), oauth.HelpfulAdvice) -} diff --git a/internal/api/client/auth/token.go b/internal/api/client/auth/token.go deleted file mode 100644 index fbbd08404..000000000 --- a/internal/api/client/auth/token.go +++ /dev/null @@ -1,115 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package auth - -import ( - "net/http" - "net/url" - - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - - "github.com/gin-gonic/gin" -) - -type tokenRequestForm struct { - GrantType *string `form:"grant_type" json:"grant_type" xml:"grant_type"` - Code *string `form:"code" json:"code" xml:"code"` - RedirectURI *string `form:"redirect_uri" json:"redirect_uri" xml:"redirect_uri"` - ClientID *string `form:"client_id" json:"client_id" xml:"client_id"` - ClientSecret *string `form:"client_secret" json:"client_secret" xml:"client_secret"` - Scope *string `form:"scope" json:"scope" xml:"scope"` -} - -// TokenPOSTHandler should be served as a POST at https://example.org/oauth/token -// The idea here is to serve an oauth access token to a user, which can be used for authorizing against non-public APIs. -func (m *Module) TokenPOSTHandler(c *gin.Context) { - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - help := []string{} - - form := &tokenRequestForm{} - if err := c.ShouldBind(form); err != nil { - api.OAuthErrorHandler(c, gtserror.NewErrorBadRequest(oauth.InvalidRequest(), err.Error())) - return - } - - c.Request.Form = url.Values{} - - var grantType string - if form.GrantType != nil { - grantType = *form.GrantType - c.Request.Form.Set("grant_type", grantType) - } else { - help = append(help, "grant_type was not set in the token request form, but must be set to authorization_code or client_credentials") - } - - if form.ClientID != nil { - c.Request.Form.Set("client_id", *form.ClientID) - } else { - help = append(help, "client_id was not set in the token request form") - } - - if form.ClientSecret != nil { - c.Request.Form.Set("client_secret", *form.ClientSecret) - } else { - help = append(help, "client_secret was not set in the token request form") - } - - if form.RedirectURI != nil { - c.Request.Form.Set("redirect_uri", *form.RedirectURI) - } else { - help = append(help, "redirect_uri was not set in the token request form") - } - - var code string - if form.Code != nil { - if grantType != "authorization_code" { - help = append(help, "a code was provided in the token request form, but grant_type was not set to authorization_code") - } else { - code = *form.Code - c.Request.Form.Set("code", code) - } - } else if grantType == "authorization_code" { - help = append(help, "code was not set in the token request form, but must be set since grant_type is authorization_code") - } - - if form.Scope != nil { - c.Request.Form.Set("scope", *form.Scope) - } - - if len(help) != 0 { - api.OAuthErrorHandler(c, gtserror.NewErrorBadRequest(oauth.InvalidRequest(), help...)) - return - } - - token, errWithCode := m.processor.OAuthHandleTokenRequest(c.Request) - if errWithCode != nil { - api.OAuthErrorHandler(c, errWithCode) - return - } - - c.Header("Cache-Control", "no-store") - c.Header("Pragma", "no-cache") - c.JSON(http.StatusOK, token) -} diff --git a/internal/api/client/auth/token_test.go b/internal/api/client/auth/token_test.go deleted file mode 100644 index 50bbd6918..000000000 --- a/internal/api/client/auth/token_test.go +++ /dev/null @@ -1,215 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package auth_test - -import ( - "context" - "encoding/json" - "io/ioutil" - "net/http" - "testing" - "time" - - "github.com/stretchr/testify/suite" - apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/db" - "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type TokenTestSuite struct { - AuthStandardTestSuite -} - -func (suite *TokenTestSuite) TestPOSTTokenEmptyForm() { - ctx, recorder := suite.newContext(http.MethodPost, "oauth/token", []byte{}, "") - ctx.Request.Header.Set("accept", "application/json") - - suite.authModule.TokenPOSTHandler(ctx) - - suite.Equal(http.StatusBadRequest, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - suite.Equal(`{"error":"invalid_request","error_description":"Bad Request: grant_type was not set in the token request form, but must be set to authorization_code or client_credentials: client_id was not set in the token request form: client_secret was not set in the token request form: redirect_uri was not set in the token request form"}`, string(b)) -} - -func (suite *TokenTestSuite) TestRetrieveClientCredentialsOK() { - testClient := suite.testClients["local_account_1"] - - requestBody, w, err := testrig.CreateMultipartFormData( - "", "", - map[string]string{ - "grant_type": "client_credentials", - "client_id": testClient.ID, - "client_secret": testClient.Secret, - "redirect_uri": "http://localhost:8080", - }) - if err != nil { - panic(err) - } - bodyBytes := requestBody.Bytes() - - ctx, recorder := suite.newContext(http.MethodPost, "oauth/token", bodyBytes, w.FormDataContentType()) - ctx.Request.Header.Set("accept", "application/json") - - suite.authModule.TokenPOSTHandler(ctx) - - suite.Equal(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - t := &apimodel.Token{} - err = json.Unmarshal(b, t) - suite.NoError(err) - - suite.Equal("Bearer", t.TokenType) - suite.NotEmpty(t.AccessToken) - suite.NotEmpty(t.CreatedAt) - suite.WithinDuration(time.Now(), time.Unix(t.CreatedAt, 0), 1*time.Minute) - - // there should be a token in the database now too - dbToken := >smodel.Token{} - err = suite.db.GetWhere(context.Background(), []db.Where{{Key: "access", Value: t.AccessToken}}, dbToken) - suite.NoError(err) - suite.NotNil(dbToken) -} - -func (suite *TokenTestSuite) TestRetrieveAuthorizationCodeOK() { - testClient := suite.testClients["local_account_1"] - testUserAuthorizationToken := suite.testTokens["local_account_1_user_authorization_token"] - - requestBody, w, err := testrig.CreateMultipartFormData( - "", "", - map[string]string{ - "grant_type": "authorization_code", - "client_id": testClient.ID, - "client_secret": testClient.Secret, - "redirect_uri": "http://localhost:8080", - "code": testUserAuthorizationToken.Code, - }) - if err != nil { - panic(err) - } - bodyBytes := requestBody.Bytes() - - ctx, recorder := suite.newContext(http.MethodPost, "oauth/token", bodyBytes, w.FormDataContentType()) - ctx.Request.Header.Set("accept", "application/json") - - suite.authModule.TokenPOSTHandler(ctx) - - suite.Equal(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - t := &apimodel.Token{} - err = json.Unmarshal(b, t) - suite.NoError(err) - - suite.Equal("Bearer", t.TokenType) - suite.NotEmpty(t.AccessToken) - suite.NotEmpty(t.CreatedAt) - suite.WithinDuration(time.Now(), time.Unix(t.CreatedAt, 0), 1*time.Minute) - - dbToken := >smodel.Token{} - err = suite.db.GetWhere(context.Background(), []db.Where{{Key: "access", Value: t.AccessToken}}, dbToken) - suite.NoError(err) - suite.NotNil(dbToken) -} - -func (suite *TokenTestSuite) TestRetrieveAuthorizationCodeNoCode() { - testClient := suite.testClients["local_account_1"] - - requestBody, w, err := testrig.CreateMultipartFormData( - "", "", - map[string]string{ - "grant_type": "authorization_code", - "client_id": testClient.ID, - "client_secret": testClient.Secret, - "redirect_uri": "http://localhost:8080", - }) - if err != nil { - panic(err) - } - bodyBytes := requestBody.Bytes() - - ctx, recorder := suite.newContext(http.MethodPost, "oauth/token", bodyBytes, w.FormDataContentType()) - ctx.Request.Header.Set("accept", "application/json") - - suite.authModule.TokenPOSTHandler(ctx) - - suite.Equal(http.StatusBadRequest, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - suite.Equal(`{"error":"invalid_request","error_description":"Bad Request: code was not set in the token request form, but must be set since grant_type is authorization_code"}`, string(b)) -} - -func (suite *TokenTestSuite) TestRetrieveAuthorizationCodeWrongGrantType() { - testClient := suite.testClients["local_account_1"] - - requestBody, w, err := testrig.CreateMultipartFormData( - "", "", - map[string]string{ - "grant_type": "client_credentials", - "client_id": testClient.ID, - "client_secret": testClient.Secret, - "redirect_uri": "http://localhost:8080", - "code": "peepeepoopoo", - }) - if err != nil { - panic(err) - } - bodyBytes := requestBody.Bytes() - - ctx, recorder := suite.newContext(http.MethodPost, "oauth/token", bodyBytes, w.FormDataContentType()) - ctx.Request.Header.Set("accept", "application/json") - - suite.authModule.TokenPOSTHandler(ctx) - - suite.Equal(http.StatusBadRequest, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - suite.Equal(`{"error":"invalid_request","error_description":"Bad Request: a code was provided in the token request form, but grant_type was not set to authorization_code"}`, string(b)) -} - -func TestTokenTestSuite(t *testing.T) { - suite.Run(t, &TokenTestSuite{}) -} diff --git a/internal/api/client/auth/util.go b/internal/api/client/auth/util.go deleted file mode 100644 index d59983c55..000000000 --- a/internal/api/client/auth/util.go +++ /dev/null @@ -1,31 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package auth - -import ( - "github.com/gin-contrib/sessions" -) - -func (m *Module) clearSession(s sessions.Session) { - s.Clear() - - if err := s.Save(); err != nil { - panic(err) - } -} diff --git a/internal/api/client/blocks/blocks.go b/internal/api/client/blocks/blocks.go index 2211a8076..df2ee65bb 100644 --- a/internal/api/client/blocks/blocks.go +++ b/internal/api/client/blocks/blocks.go @@ -21,14 +21,13 @@ package blocks import ( "net/http" - "github.com/superseriousbusiness/gotosocial/internal/api" + "github.com/gin-gonic/gin" "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" ) const ( - // BasePath is the base URI path for serving favourites - BasePath = "/api/v1/blocks" + // BasePath is the base URI path for serving blocks, minus the api prefix. + BasePath = "/v1/blocks" // MaxIDKey is the url query for setting a max ID to return MaxIDKey = "max_id" @@ -38,20 +37,16 @@ const ( LimitKey = "limit" ) -// Module implements the ClientAPIModule interface for everything relating to viewing blocks type Module struct { processor processing.Processor } -// New returns a new blocks module -func New(processor processing.Processor) api.ClientModule { +func New(processor processing.Processor) *Module { return &Module{ processor: processor, } } -// Route attaches all routes from this module to the given router -func (m *Module) Route(r router.Router) error { - r.AttachHandler(http.MethodGet, BasePath, m.BlocksGETHandler) - return nil +func (m *Module) Route(attachHandler func(method string, path string, f ...gin.HandlerFunc) gin.IRoutes) { + attachHandler(http.MethodGet, BasePath, m.BlocksGETHandler) } diff --git a/internal/api/client/blocks/blocksget.go b/internal/api/client/blocks/blocksget.go index 98f5ce6ea..290ea6617 100644 --- a/internal/api/client/blocks/blocksget.go +++ b/internal/api/client/blocks/blocksget.go @@ -24,7 +24,7 @@ import ( "strconv" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" ) @@ -96,12 +96,12 @@ import ( func (m *Module) BlocksGETHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } @@ -123,7 +123,7 @@ func (m *Module) BlocksGETHandler(c *gin.Context) { i, err := strconv.ParseInt(limitString, 10, 32) if err != nil { err := fmt.Errorf("error parsing %s: %s", LimitKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } limit = int(i) @@ -131,7 +131,7 @@ func (m *Module) BlocksGETHandler(c *gin.Context) { resp, errWithCode := m.processor.BlocksGet(c.Request.Context(), authed, maxID, sinceID, limit) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } diff --git a/internal/api/client/bookmarks/bookmarks.go b/internal/api/client/bookmarks/bookmarks.go index 492b7364c..d0273321c 100644 --- a/internal/api/client/bookmarks/bookmarks.go +++ b/internal/api/client/bookmarks/bookmarks.go @@ -21,9 +21,8 @@ package bookmarks import ( "net/http" - "github.com/superseriousbusiness/gotosocial/internal/api" + "github.com/gin-gonic/gin" "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" ) const ( @@ -31,20 +30,16 @@ const ( BasePath = "/api/v1/bookmarks" ) -// Module implements the ClientAPIModule interface for everything related to bookmarks type Module struct { processor processing.Processor } -// New returns a new emoji module -func New(processor processing.Processor) api.ClientModule { +func New(processor processing.Processor) *Module { return &Module{ processor: processor, } } -// Route attaches all routes from this module to the given router -func (m *Module) Route(r router.Router) error { - r.AttachHandler(http.MethodGet, BasePath, m.BookmarksGETHandler) - return nil +func (m *Module) Route(attachHandler func(method string, path string, f ...gin.HandlerFunc) gin.IRoutes) { + attachHandler(http.MethodGet, BasePath, m.BookmarksGETHandler) } diff --git a/internal/api/client/bookmarks/bookmarks_test.go b/internal/api/client/bookmarks/bookmarks_test.go index b4a4bdfb1..3bd12aee1 100644 --- a/internal/api/client/bookmarks/bookmarks_test.go +++ b/internal/api/client/bookmarks/bookmarks_test.go @@ -29,7 +29,7 @@ import ( "github.com/stretchr/testify/suite" "github.com/superseriousbusiness/gotosocial/internal/api/client/bookmarks" - "github.com/superseriousbusiness/gotosocial/internal/api/client/status" + "github.com/superseriousbusiness/gotosocial/internal/api/client/statuses" "github.com/superseriousbusiness/gotosocial/internal/api/model" "github.com/superseriousbusiness/gotosocial/internal/concurrency" "github.com/superseriousbusiness/gotosocial/internal/db" @@ -67,7 +67,7 @@ type BookmarkTestSuite struct { testFollows map[string]*gtsmodel.Follow // module being tested - statusModule *status.Module + statusModule *statuses.Module bookmarkModule *bookmarks.Module } @@ -99,8 +99,8 @@ func (suite *BookmarkTestSuite) SetupTest() { suite.federator = testrig.NewTestFederator(suite.db, testrig.NewTestTransportController(testrig.NewMockHTTPClient(nil, "../../../../testrig/media"), suite.db, fedWorker), suite.storage, suite.mediaManager, fedWorker) suite.emailSender = testrig.NewEmailSender("../../../../web/template/", nil) suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator, suite.emailSender, suite.mediaManager, clientWorker, fedWorker) - suite.statusModule = status.New(suite.processor).(*status.Module) - suite.bookmarkModule = bookmarks.New(suite.processor).(*bookmarks.Module) + suite.statusModule = statuses.New(suite.processor) + suite.bookmarkModule = bookmarks.New(suite.processor) suite.NoError(suite.processor.Start()) } @@ -123,7 +123,7 @@ func (suite *BookmarkTestSuite) TestGetBookmark() { ctx.Set(oauth.SessionAuthorizedToken, oauthToken) ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(status.BookmarkPath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(statuses.BookmarkPath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting ctx.Request.Header.Set("accept", "application/json") suite.bookmarkModule.BookmarksGETHandler(ctx) diff --git a/internal/api/client/bookmarks/bookmarksget.go b/internal/api/client/bookmarks/bookmarksget.go index dafc896ef..8f587f13d 100644 --- a/internal/api/client/bookmarks/bookmarksget.go +++ b/internal/api/client/bookmarks/bookmarksget.go @@ -6,7 +6,7 @@ import ( "strconv" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" ) @@ -56,12 +56,12 @@ const ( func (m *Module) BookmarksGETHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } @@ -71,7 +71,7 @@ func (m *Module) BookmarksGETHandler(c *gin.Context) { i, err := strconv.ParseInt(limitString, 10, 64) if err != nil { err := fmt.Errorf("error parsing %s: %s", LimitKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } limit = int(i) @@ -91,12 +91,12 @@ func (m *Module) BookmarksGETHandler(c *gin.Context) { resp, errWithCode := m.processor.BookmarksGet(c.Request.Context(), authed, maxID, minID, limit) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } diff --git a/internal/api/client/customemojis/customemojis.go b/internal/api/client/customemojis/customemojis.go new file mode 100644 index 000000000..ab89415d0 --- /dev/null +++ b/internal/api/client/customemojis/customemojis.go @@ -0,0 +1,45 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package customemojis + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "github.com/superseriousbusiness/gotosocial/internal/processing" +) + +const ( + // BasePath is the base path for serving custom emojis, minus the 'api' prefix + BasePath = "/v1/custom_emojis" +) + +type Module struct { + processor processing.Processor +} + +func New(processor processing.Processor) *Module { + return &Module{ + processor: processor, + } +} + +func (m *Module) Route(attachHandler func(method string, path string, f ...gin.HandlerFunc) gin.IRoutes) { + attachHandler(http.MethodGet, BasePath, m.CustomEmojisGETHandler) +} diff --git a/internal/api/client/customemojis/customemojisget.go b/internal/api/client/customemojis/customemojisget.go new file mode 100644 index 000000000..3428071d0 --- /dev/null +++ b/internal/api/client/customemojis/customemojisget.go @@ -0,0 +1,76 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package customemojis + +import ( + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// CustomEmojisGETHandler swagger:operation GET /api/v1/custom_emojis customEmojisGet +// +// Get an array of custom emojis available on the instance. +// +// --- +// tags: +// - custom_emojis +// +// produces: +// - application/json +// +// security: +// - OAuth2 Bearer: +// - read:custom_emojis +// +// responses: +// '200': +// description: Array of custom emojis. +// schema: +// type: array +// items: +// "$ref": "#/definitions/emoji" +// '401': +// description: unauthorized +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) CustomEmojisGETHandler(c *gin.Context) { + if _, err := oauth.Authed(c, true, true, true, true); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + emojis, errWithCode := m.processor.CustomEmojisGet(c) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, emojis) +} diff --git a/internal/api/client/emoji/emoji.go b/internal/api/client/emoji/emoji.go deleted file mode 100644 index 871a12854..000000000 --- a/internal/api/client/emoji/emoji.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package emoji - -import ( - "net/http" - - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" -) - -const ( - // BasePath is the base path for serving the emoji API - BasePath = "/api/v1/custom_emojis" -) - -// Module implements the ClientAPIModule interface for everything related to emoji -type Module struct { - processor processing.Processor -} - -// New returns a new emoji module -func New(processor processing.Processor) api.ClientModule { - return &Module{ - processor: processor, - } -} - -// Route attaches all routes from this module to the given router -func (m *Module) Route(r router.Router) error { - r.AttachHandler(http.MethodGet, BasePath, m.EmojisGETHandler) - return nil -} diff --git a/internal/api/client/emoji/emojisget.go b/internal/api/client/emoji/emojisget.go deleted file mode 100644 index d41e5e7df..000000000 --- a/internal/api/client/emoji/emojisget.go +++ /dev/null @@ -1,58 +0,0 @@ -package emoji - -import ( - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// EmojisGETHandler swagger:operation GET /api/v1/custom_emojis customEmojisGet -// -// Get an array of custom emojis available on the instance. -// -// --- -// tags: -// - custom_emojis -// -// produces: -// - application/json -// -// security: -// - OAuth2 Bearer: -// - read:custom_emojis -// -// responses: -// '200': -// description: Array of custom emojis. -// schema: -// type: array -// items: -// "$ref": "#/definitions/emoji" -// '401': -// description: unauthorized -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) EmojisGETHandler(c *gin.Context) { - if _, err := oauth.Authed(c, true, true, true, true); err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - emojis, errWithCode := m.processor.CustomEmojisGet(c) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, emojis) -} diff --git a/internal/api/client/favourites/favourites.go b/internal/api/client/favourites/favourites.go index f310d6873..5abc85a27 100644 --- a/internal/api/client/favourites/favourites.go +++ b/internal/api/client/favourites/favourites.go @@ -21,14 +21,13 @@ package favourites import ( "net/http" - "github.com/superseriousbusiness/gotosocial/internal/api" + "github.com/gin-gonic/gin" "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" ) const ( - // BasePath is the base URI path for serving favourites - BasePath = "/api/v1/favourites" + // BasePath is the base URI path for serving favourites, minus the 'api' prefix + BasePath = "/v1/favourites" // MaxIDKey is the url query for setting a max status ID to return MaxIDKey = "max_id" @@ -42,20 +41,16 @@ const ( LocalKey = "local" ) -// Module implements the ClientAPIModule interface for everything relating to viewing favourites type Module struct { processor processing.Processor } -// New returns a new favourites module -func New(processor processing.Processor) api.ClientModule { +func New(processor processing.Processor) *Module { return &Module{ processor: processor, } } -// Route attaches all routes from this module to the given router -func (m *Module) Route(r router.Router) error { - r.AttachHandler(http.MethodGet, BasePath, m.FavouritesGETHandler) - return nil +func (m *Module) Route(attachHandler func(method string, path string, f ...gin.HandlerFunc) gin.IRoutes) { + attachHandler(http.MethodGet, BasePath, m.FavouritesGETHandler) } diff --git a/internal/api/client/favourites/favourites_test.go b/internal/api/client/favourites/favourites_test.go index c84da6b32..050b72536 100644 --- a/internal/api/client/favourites/favourites_test.go +++ b/internal/api/client/favourites/favourites_test.go @@ -87,7 +87,7 @@ func (suite *FavouritesStandardTestSuite) SetupTest() { suite.federator = testrig.NewTestFederator(suite.db, testrig.NewTestTransportController(testrig.NewMockHTTPClient(nil, "../../../../testrig/media"), suite.db, fedWorker), suite.storage, suite.mediaManager, fedWorker) suite.emailSender = testrig.NewEmailSender("../../../../web/template/", nil) suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator, suite.emailSender, suite.mediaManager, clientWorker, fedWorker) - suite.favModule = favourites.New(suite.processor).(*favourites.Module) + suite.favModule = favourites.New(suite.processor) suite.NoError(suite.processor.Start()) } diff --git a/internal/api/client/favourites/favouritesget.go b/internal/api/client/favourites/favouritesget.go index 5ff032b9a..9b6bb715e 100644 --- a/internal/api/client/favourites/favouritesget.go +++ b/internal/api/client/favourites/favouritesget.go @@ -6,7 +6,7 @@ import ( "strconv" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" ) @@ -78,12 +78,12 @@ import ( func (m *Module) FavouritesGETHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } @@ -105,7 +105,7 @@ func (m *Module) FavouritesGETHandler(c *gin.Context) { i, err := strconv.ParseInt(limitString, 10, 32) if err != nil { err := fmt.Errorf("error parsing %s: %s", LimitKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } limit = int(i) @@ -113,7 +113,7 @@ func (m *Module) FavouritesGETHandler(c *gin.Context) { resp, errWithCode := m.processor.FavedTimelineGet(c.Request.Context(), authed, maxID, minID, limit) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } diff --git a/internal/api/client/fileserver/fileserver.go b/internal/api/client/fileserver/fileserver.go deleted file mode 100644 index dcb54f986..000000000 --- a/internal/api/client/fileserver/fileserver.go +++ /dev/null @@ -1,64 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package fileserver - -import ( - "fmt" - "net/http" - - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" - "github.com/superseriousbusiness/gotosocial/internal/uris" -) - -const ( - // FileServeBasePath forms the first part of the fileserver path. - FileServeBasePath = "/" + uris.FileserverPath - // AccountIDKey is the url key for account id (an account ulid) - AccountIDKey = "account_id" - // MediaTypeKey is the url key for media type (usually something like attachment or header etc) - MediaTypeKey = "media_type" - // MediaSizeKey is the url key for the desired media size--original/small/static - MediaSizeKey = "media_size" - // FileNameKey is the actual filename being sought. Will usually be a UUID then something like .jpeg - FileNameKey = "file_name" -) - -// FileServer implements the RESTAPIModule interface. -// The goal here is to serve requested media files if the gotosocial server is configured to use local storage. -type FileServer struct { - processor processing.Processor -} - -// New returns a new fileServer module -func New(processor processing.Processor) api.ClientModule { - return &FileServer{ - processor: processor, - } -} - -// Route satisfies the RESTAPIModule interface -func (m *FileServer) Route(s router.Router) error { - // something like "/fileserver/:account_id/:media_type/:media_size/:file_name" - fileServePath := fmt.Sprintf("%s/:%s/:%s/:%s/:%s", FileServeBasePath, AccountIDKey, MediaTypeKey, MediaSizeKey, FileNameKey) - s.AttachHandler(http.MethodGet, fileServePath, m.ServeFile) - s.AttachHandler(http.MethodHead, fileServePath, m.ServeFile) - return nil -} diff --git a/internal/api/client/fileserver/fileserver_test.go b/internal/api/client/fileserver/fileserver_test.go deleted file mode 100644 index f1fab5672..000000000 --- a/internal/api/client/fileserver/fileserver_test.go +++ /dev/null @@ -1,109 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package fileserver_test - -import ( - "context" - - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/fileserver" - "github.com/superseriousbusiness/gotosocial/internal/concurrency" - "github.com/superseriousbusiness/gotosocial/internal/db" - "github.com/superseriousbusiness/gotosocial/internal/email" - "github.com/superseriousbusiness/gotosocial/internal/federation" - "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" - "github.com/superseriousbusiness/gotosocial/internal/log" - "github.com/superseriousbusiness/gotosocial/internal/media" - "github.com/superseriousbusiness/gotosocial/internal/messages" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/storage" - "github.com/superseriousbusiness/gotosocial/internal/typeutils" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type FileserverTestSuite struct { - // standard suite interfaces - suite.Suite - db db.DB - storage *storage.Driver - federator federation.Federator - tc typeutils.TypeConverter - processor processing.Processor - mediaManager media.Manager - oauthServer oauth.Server - emailSender email.Sender - - // standard suite models - testTokens map[string]*gtsmodel.Token - testClients map[string]*gtsmodel.Client - testApplications map[string]*gtsmodel.Application - testUsers map[string]*gtsmodel.User - testAccounts map[string]*gtsmodel.Account - testAttachments map[string]*gtsmodel.MediaAttachment - - // item being tested - fileServer *fileserver.FileServer -} - -/* - TEST INFRASTRUCTURE -*/ - -func (suite *FileserverTestSuite) SetupSuite() { - testrig.InitTestConfig() - testrig.InitTestLog() - - fedWorker := concurrency.NewWorkerPool[messages.FromFederator](-1, -1) - clientWorker := concurrency.NewWorkerPool[messages.FromClientAPI](-1, -1) - - suite.db = testrig.NewTestDB() - suite.storage = testrig.NewInMemoryStorage() - suite.federator = testrig.NewTestFederator(suite.db, testrig.NewTestTransportController(testrig.NewMockHTTPClient(nil, "../../../../testrig/media"), suite.db, fedWorker), suite.storage, suite.mediaManager, fedWorker) - suite.emailSender = testrig.NewEmailSender("../../../../web/template/", nil) - - suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator, suite.emailSender, testrig.NewTestMediaManager(suite.db, suite.storage), clientWorker, fedWorker) - suite.tc = testrig.NewTestTypeConverter(suite.db) - suite.mediaManager = testrig.NewTestMediaManager(suite.db, suite.storage) - suite.oauthServer = testrig.NewTestOauthServer(suite.db) - - suite.fileServer = fileserver.New(suite.processor).(*fileserver.FileServer) -} - -func (suite *FileserverTestSuite) SetupTest() { - testrig.StandardDBSetup(suite.db, nil) - testrig.StandardStorageSetup(suite.storage, "../../../../testrig/media") - suite.testTokens = testrig.NewTestTokens() - suite.testClients = testrig.NewTestClients() - suite.testApplications = testrig.NewTestApplications() - suite.testUsers = testrig.NewTestUsers() - suite.testAccounts = testrig.NewTestAccounts() - suite.testAttachments = testrig.NewTestAttachments() -} - -func (suite *FileserverTestSuite) TearDownSuite() { - if err := suite.db.Stop(context.Background()); err != nil { - log.Panicf("error closing db connection: %s", err) - } -} - -func (suite *FileserverTestSuite) TearDownTest() { - testrig.StandardDBTeardown(suite.db) - testrig.StandardStorageTeardown(suite.storage) -} diff --git a/internal/api/client/fileserver/servefile.go b/internal/api/client/fileserver/servefile.go deleted file mode 100644 index d2328a5fc..000000000 --- a/internal/api/client/fileserver/servefile.go +++ /dev/null @@ -1,135 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package fileserver - -import ( - "bytes" - "fmt" - "io" - "net/http" - "strconv" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/log" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// ServeFile is for serving attachments, headers, and avatars to the requester from instance storage. -// -// Note: to mitigate scraping attempts, no information should be given out on a bad request except "404 page not found". -// Don't give away account ids or media ids or anything like that; callers shouldn't be able to infer anything. -func (m *FileServer) ServeFile(c *gin.Context) { - authed, err := oauth.Authed(c, false, false, false, false) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotFound(err), m.processor.InstanceGet) - return - } - - // We use request params to check what to pull out of the database/storage so check everything. A request URL should be formatted as follows: - // "https://example.org/fileserver/[ACCOUNT_ID]/[MEDIA_TYPE]/[MEDIA_SIZE]/[FILE_NAME]" - // "FILE_NAME" consists of two parts, the attachment's database id, a period, and the file extension. - accountID := c.Param(AccountIDKey) - if accountID == "" { - err := fmt.Errorf("missing %s from request", AccountIDKey) - api.ErrorHandler(c, gtserror.NewErrorNotFound(err), m.processor.InstanceGet) - return - } - - mediaType := c.Param(MediaTypeKey) - if mediaType == "" { - err := fmt.Errorf("missing %s from request", MediaTypeKey) - api.ErrorHandler(c, gtserror.NewErrorNotFound(err), m.processor.InstanceGet) - return - } - - mediaSize := c.Param(MediaSizeKey) - if mediaSize == "" { - err := fmt.Errorf("missing %s from request", MediaSizeKey) - api.ErrorHandler(c, gtserror.NewErrorNotFound(err), m.processor.InstanceGet) - return - } - - fileName := c.Param(FileNameKey) - if fileName == "" { - err := fmt.Errorf("missing %s from request", FileNameKey) - api.ErrorHandler(c, gtserror.NewErrorNotFound(err), m.processor.InstanceGet) - return - } - - content, errWithCode := m.processor.FileGet(c.Request.Context(), authed, &model.GetContentRequestForm{ - AccountID: accountID, - MediaType: mediaType, - MediaSize: mediaSize, - FileName: fileName, - }) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - defer func() { - // close content when we're done - if content.Content != nil { - if err := content.Content.Close(); err != nil { - log.Errorf("ServeFile: error closing readcloser: %s", err) - } - } - }() - - if content.URL != nil { - c.Redirect(http.StatusFound, content.URL.String()) - return - } - - // TODO: if the requester only accepts text/html we should try to serve them *something*. - // This is mostly needed because when sharing a link to a gts-hosted file on something like mastodon, the masto servers will - // attempt to look up the content to provide a preview of the link, and they ask for text/html. - format, err := api.NegotiateAccept(c, api.MIME(content.ContentType)) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - // since we'll never host different files at the same - // URL (bc the ULIDs are generated per piece of media), - // it's sensible and safe to use a long cache here, so - // that clients don't keep fetching files over + over again - c.Header("Cache-Control", "max-age=604800") - - if c.Request.Method == http.MethodHead { - c.Header("Content-Type", format) - c.Header("Content-Length", strconv.FormatInt(content.ContentLength, 10)) - c.Status(http.StatusOK) - return - } - - // try to slurp the first few bytes to make sure we have something - b := bytes.NewBuffer(make([]byte, 0, 64)) - if _, err := io.CopyN(b, content.Content, 64); err != nil { - err = fmt.Errorf("ServeFile: error reading from content: %w", err) - api.ErrorHandler(c, gtserror.NewErrorNotFound(err, err.Error()), m.processor.InstanceGet) - return - } - - // we're good, return the slurped bytes + the rest of the content - c.DataFromReader(http.StatusOK, content.ContentLength, format, io.MultiReader(b, content.Content), nil) -} diff --git a/internal/api/client/fileserver/servefile_test.go b/internal/api/client/fileserver/servefile_test.go deleted file mode 100644 index 1ca0c60d6..000000000 --- a/internal/api/client/fileserver/servefile_test.go +++ /dev/null @@ -1,272 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package fileserver_test - -import ( - "context" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/fileserver" - "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" - "github.com/superseriousbusiness/gotosocial/internal/media" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type ServeFileTestSuite struct { - FileserverTestSuite -} - -// GetFile is just a convenience function to save repetition in this test suite. -// It takes the required params to serve a file, calls the handler, and returns -// the http status code, the response headers, and the parsed body bytes. -func (suite *ServeFileTestSuite) GetFile( - accountID string, - mediaType media.Type, - mediaSize media.Size, - filename string, -) (code int, headers http.Header, body []byte) { - recorder := httptest.NewRecorder() - - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Request = httptest.NewRequest(http.MethodGet, "http://localhost:8080/whatever", nil) - ctx.Request.Header.Set("accept", "*/*") - ctx.AddParam(fileserver.AccountIDKey, accountID) - ctx.AddParam(fileserver.MediaTypeKey, string(mediaType)) - ctx.AddParam(fileserver.MediaSizeKey, string(mediaSize)) - ctx.AddParam(fileserver.FileNameKey, filename) - - suite.fileServer.ServeFile(ctx) - code = recorder.Code - headers = recorder.Result().Header - - var err error - body, err = ioutil.ReadAll(recorder.Body) - if err != nil { - suite.FailNow(err.Error()) - } - - return -} - -// UncacheAttachment is a convenience function that uncaches the targetAttachment by -// removing its associated files from storage, and updating the database. -func (suite *ServeFileTestSuite) UncacheAttachment(targetAttachment *gtsmodel.MediaAttachment) { - ctx := context.Background() - - cached := false - targetAttachment.Cached = &cached - - if err := suite.db.UpdateByID(ctx, targetAttachment, targetAttachment.ID, "cached"); err != nil { - suite.FailNow(err.Error()) - } - if err := suite.storage.Delete(ctx, targetAttachment.File.Path); err != nil { - suite.FailNow(err.Error()) - } - if err := suite.storage.Delete(ctx, targetAttachment.Thumbnail.Path); err != nil { - suite.FailNow(err.Error()) - } -} - -func (suite *ServeFileTestSuite) TestServeOriginalLocalFileOK() { - targetAttachment := >smodel.MediaAttachment{} - *targetAttachment = *suite.testAttachments["admin_account_status_1_attachment_1"] - fileInStorage, err := suite.storage.Get(context.Background(), targetAttachment.File.Path) - if err != nil { - suite.FailNow(err.Error()) - } - - code, headers, body := suite.GetFile( - targetAttachment.AccountID, - media.TypeAttachment, - media.SizeOriginal, - targetAttachment.ID+".jpeg", - ) - - suite.Equal(http.StatusOK, code) - suite.Equal("image/jpeg", headers.Get("content-type")) - suite.Equal(fileInStorage, body) -} - -func (suite *ServeFileTestSuite) TestServeSmallLocalFileOK() { - targetAttachment := >smodel.MediaAttachment{} - *targetAttachment = *suite.testAttachments["admin_account_status_1_attachment_1"] - fileInStorage, err := suite.storage.Get(context.Background(), targetAttachment.Thumbnail.Path) - if err != nil { - suite.FailNow(err.Error()) - } - - code, headers, body := suite.GetFile( - targetAttachment.AccountID, - media.TypeAttachment, - media.SizeSmall, - targetAttachment.ID+".jpeg", - ) - - suite.Equal(http.StatusOK, code) - suite.Equal("image/jpeg", headers.Get("content-type")) - suite.Equal(fileInStorage, body) -} - -func (suite *ServeFileTestSuite) TestServeOriginalRemoteFileOK() { - targetAttachment := >smodel.MediaAttachment{} - *targetAttachment = *suite.testAttachments["remote_account_1_status_1_attachment_1"] - fileInStorage, err := suite.storage.Get(context.Background(), targetAttachment.File.Path) - if err != nil { - suite.FailNow(err.Error()) - } - - code, headers, body := suite.GetFile( - targetAttachment.AccountID, - media.TypeAttachment, - media.SizeOriginal, - targetAttachment.ID+".jpeg", - ) - - suite.Equal(http.StatusOK, code) - suite.Equal("image/jpeg", headers.Get("content-type")) - suite.Equal(fileInStorage, body) -} - -func (suite *ServeFileTestSuite) TestServeSmallRemoteFileOK() { - targetAttachment := >smodel.MediaAttachment{} - *targetAttachment = *suite.testAttachments["remote_account_1_status_1_attachment_1"] - fileInStorage, err := suite.storage.Get(context.Background(), targetAttachment.Thumbnail.Path) - if err != nil { - suite.FailNow(err.Error()) - } - - code, headers, body := suite.GetFile( - targetAttachment.AccountID, - media.TypeAttachment, - media.SizeSmall, - targetAttachment.ID+".jpeg", - ) - - suite.Equal(http.StatusOK, code) - suite.Equal("image/jpeg", headers.Get("content-type")) - suite.Equal(fileInStorage, body) -} - -func (suite *ServeFileTestSuite) TestServeOriginalRemoteFileRecache() { - targetAttachment := >smodel.MediaAttachment{} - *targetAttachment = *suite.testAttachments["remote_account_1_status_1_attachment_1"] - fileInStorage, err := suite.storage.Get(context.Background(), targetAttachment.File.Path) - if err != nil { - suite.FailNow(err.Error()) - } - - // uncache the attachment so we'll have to refetch it from the 'remote' instance - suite.UncacheAttachment(targetAttachment) - - code, headers, body := suite.GetFile( - targetAttachment.AccountID, - media.TypeAttachment, - media.SizeOriginal, - targetAttachment.ID+".jpeg", - ) - - suite.Equal(http.StatusOK, code) - suite.Equal("image/jpeg", headers.Get("content-type")) - suite.Equal(fileInStorage, body) -} - -func (suite *ServeFileTestSuite) TestServeSmallRemoteFileRecache() { - targetAttachment := >smodel.MediaAttachment{} - *targetAttachment = *suite.testAttachments["remote_account_1_status_1_attachment_1"] - fileInStorage, err := suite.storage.Get(context.Background(), targetAttachment.Thumbnail.Path) - if err != nil { - suite.FailNow(err.Error()) - } - - // uncache the attachment so we'll have to refetch it from the 'remote' instance - suite.UncacheAttachment(targetAttachment) - - code, headers, body := suite.GetFile( - targetAttachment.AccountID, - media.TypeAttachment, - media.SizeSmall, - targetAttachment.ID+".jpeg", - ) - - suite.Equal(http.StatusOK, code) - suite.Equal("image/jpeg", headers.Get("content-type")) - suite.Equal(fileInStorage, body) -} - -func (suite *ServeFileTestSuite) TestServeOriginalRemoteFileRecacheNotFound() { - targetAttachment := >smodel.MediaAttachment{} - *targetAttachment = *suite.testAttachments["remote_account_1_status_1_attachment_1"] - - // uncache the attachment *and* set the remote URL to something that will return a 404 - suite.UncacheAttachment(targetAttachment) - targetAttachment.RemoteURL = "http://nothing.at.this.url/weeeeeeeee" - if err := suite.db.UpdateByID(context.Background(), targetAttachment, targetAttachment.ID, "remote_url"); err != nil { - suite.FailNow(err.Error()) - } - - code, _, _ := suite.GetFile( - targetAttachment.AccountID, - media.TypeAttachment, - media.SizeOriginal, - targetAttachment.ID+".jpeg", - ) - - suite.Equal(http.StatusNotFound, code) -} - -func (suite *ServeFileTestSuite) TestServeSmallRemoteFileRecacheNotFound() { - targetAttachment := >smodel.MediaAttachment{} - *targetAttachment = *suite.testAttachments["remote_account_1_status_1_attachment_1"] - - // uncache the attachment *and* set the remote URL to something that will return a 404 - suite.UncacheAttachment(targetAttachment) - targetAttachment.RemoteURL = "http://nothing.at.this.url/weeeeeeeee" - if err := suite.db.UpdateByID(context.Background(), targetAttachment, targetAttachment.ID, "remote_url"); err != nil { - suite.FailNow(err.Error()) - } - - code, _, _ := suite.GetFile( - targetAttachment.AccountID, - media.TypeAttachment, - media.SizeSmall, - targetAttachment.ID+".jpeg", - ) - - suite.Equal(http.StatusNotFound, code) -} - -// Callers trying to get some random-ass file that doesn't exist should just get a 404 -func (suite *ServeFileTestSuite) TestServeFileNotFound() { - code, _, _ := suite.GetFile( - "01GMMY4G9B0QEG0PQK5Q5JGJWZ", - media.TypeAttachment, - media.SizeOriginal, - "01GMMY68Y7E5DJ3CA3Y9SS8524.jpeg", - ) - - suite.Equal(http.StatusNotFound, code) -} - -func TestServeFileTestSuite(t *testing.T) { - suite.Run(t, new(ServeFileTestSuite)) -} diff --git a/internal/api/client/filter/filter.go b/internal/api/client/filter/filter.go deleted file mode 100644 index cf801e0a5..000000000 --- a/internal/api/client/filter/filter.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package filter - -import ( - "net/http" - - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" -) - -const ( - // BasePath is the base path for serving the filter API - BasePath = "/api/v1/filters" -) - -// Module implements the ClientAPIModule interface for every related to filters -type Module struct { - processor processing.Processor -} - -// New returns a new filter module -func New(processor processing.Processor) api.ClientModule { - return &Module{ - processor: processor, - } -} - -// Route attaches all routes from this module to the given router -func (m *Module) Route(r router.Router) error { - r.AttachHandler(http.MethodGet, BasePath, m.FiltersGETHandler) - return nil -} diff --git a/internal/api/client/filter/filtersget.go b/internal/api/client/filter/filtersget.go deleted file mode 100644 index 8e0a0bb34..000000000 --- a/internal/api/client/filter/filtersget.go +++ /dev/null @@ -1,25 +0,0 @@ -package filter - -import ( - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// FiltersGETHandler returns a list of filters set by/for the authed account -func (m *Module) FiltersGETHandler(c *gin.Context) { - if _, err := oauth.Authed(c, true, true, true, true); err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, []string{}) -} diff --git a/internal/api/client/filters/filter.go b/internal/api/client/filters/filter.go new file mode 100644 index 000000000..bdfd89ffe --- /dev/null +++ b/internal/api/client/filters/filter.go @@ -0,0 +1,45 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package filter + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "github.com/superseriousbusiness/gotosocial/internal/processing" +) + +const ( + // BasePath is the base path for serving the filters API, minus the 'api' prefix + BasePath = "/v1/filters" +) + +type Module struct { + processor processing.Processor +} + +func New(processor processing.Processor) *Module { + return &Module{ + processor: processor, + } +} + +func (m *Module) Route(attachHandler func(method string, path string, f ...gin.HandlerFunc) gin.IRoutes) { + attachHandler(http.MethodGet, BasePath, m.FiltersGETHandler) +} diff --git a/internal/api/client/filters/filtersget.go b/internal/api/client/filters/filtersget.go new file mode 100644 index 000000000..71d6cac3e --- /dev/null +++ b/internal/api/client/filters/filtersget.go @@ -0,0 +1,25 @@ +package filter + +import ( + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// FiltersGETHandler returns a list of filters set by/for the authed account +func (m *Module) FiltersGETHandler(c *gin.Context) { + if _, err := oauth.Authed(c, true, true, true, true); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, []string{}) +} diff --git a/internal/api/client/followrequest/authorize.go b/internal/api/client/followrequest/authorize.go deleted file mode 100644 index a5a392f76..000000000 --- a/internal/api/client/followrequest/authorize.go +++ /dev/null @@ -1,98 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package followrequest - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// FollowRequestAuthorizePOSTHandler swagger:operation POST /api/v1/follow_requests/{account_id}/authorize authorizeFollowRequest -// -// Accept/authorize follow request from the given account ID. -// -// Accept a follow request and put the requesting account in your 'followers' list. -// -// --- -// tags: -// - follow_requests -// -// produces: -// - application/json -// -// parameters: -// - -// name: account_id -// type: string -// description: ID of the account requesting to follow you. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - write:follows -// -// responses: -// '200': -// name: account relationship -// description: Your relationship to this account. -// schema: -// "$ref": "#/definitions/accountRelationship" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) FollowRequestAuthorizePOSTHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - originAccountID := c.Param(IDKey) - if originAccountID == "" { - err := errors.New("no account id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - relationship, errWithCode := m.processor.FollowRequestAccept(c.Request.Context(), authed, originAccountID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, relationship) -} diff --git a/internal/api/client/followrequest/authorize_test.go b/internal/api/client/followrequest/authorize_test.go deleted file mode 100644 index 693380d91..000000000 --- a/internal/api/client/followrequest/authorize_test.go +++ /dev/null @@ -1,115 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package followrequest_test - -import ( - "context" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/followrequest" - "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" -) - -type AuthorizeTestSuite struct { - FollowRequestStandardTestSuite -} - -func (suite *AuthorizeTestSuite) TestAuthorize() { - requestingAccount := suite.testAccounts["remote_account_2"] - targetAccount := suite.testAccounts["local_account_1"] - - // put a follow request in the database - fr := >smodel.FollowRequest{ - ID: "01FJ1S8DX3STJJ6CEYPMZ1M0R3", - CreatedAt: time.Now(), - UpdatedAt: time.Now(), - URI: fmt.Sprintf("%s/follow/01FJ1S8DX3STJJ6CEYPMZ1M0R3", requestingAccount.URI), - AccountID: requestingAccount.ID, - TargetAccountID: targetAccount.ID, - } - - err := suite.db.Put(context.Background(), fr) - suite.NoError(err) - - recorder := httptest.NewRecorder() - ctx := suite.newContext(recorder, http.MethodPost, []byte{}, fmt.Sprintf("/api/v1/follow_requests/%s/authorize", requestingAccount.ID), "") - - ctx.Params = gin.Params{ - gin.Param{ - Key: followrequest.IDKey, - Value: requestingAccount.ID, - }, - } - - // call the handler - suite.followRequestModule.FollowRequestAuthorizePOSTHandler(ctx) - - // 1. we should have OK because our request was valid - suite.Equal(http.StatusOK, recorder.Code) - - // 2. we should have no error message in the result body - result := recorder.Result() - defer result.Body.Close() - - // check the response - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - - suite.Equal(`{"id":"01FHMQX3GAABWSM0S2VZEC2SWC","following":false,"showing_reblogs":false,"notifying":false,"followed_by":true,"blocking":false,"blocked_by":false,"muting":false,"muting_notifications":false,"requested":false,"domain_blocking":false,"endorsed":false,"note":""}`, string(b)) -} - -func (suite *AuthorizeTestSuite) TestAuthorizeNoFR() { - requestingAccount := suite.testAccounts["remote_account_2"] - - recorder := httptest.NewRecorder() - ctx := suite.newContext(recorder, http.MethodPost, []byte{}, fmt.Sprintf("/api/v1/follow_requests/%s/authorize", requestingAccount.ID), "") - - ctx.Params = gin.Params{ - gin.Param{ - Key: followrequest.IDKey, - Value: requestingAccount.ID, - }, - } - - // call the handler - suite.followRequestModule.FollowRequestAuthorizePOSTHandler(ctx) - - suite.Equal(http.StatusNotFound, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - - // check the response - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - - suite.Equal(`{"error":"Not Found"}`, string(b)) -} - -func TestAuthorizeTestSuite(t *testing.T) { - suite.Run(t, &AuthorizeTestSuite{}) -} diff --git a/internal/api/client/followrequest/followrequest.go b/internal/api/client/followrequest/followrequest.go deleted file mode 100644 index a511d7226..000000000 --- a/internal/api/client/followrequest/followrequest.go +++ /dev/null @@ -1,61 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package followrequest - -import ( - "net/http" - - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" -) - -const ( - // IDKey is for account IDs - IDKey = "id" - // BasePath is the base path for serving the follow request API - BasePath = "/api/v1/follow_requests" - // BasePathWithID is just the base path with the ID key in it. - // Use this anywhere you need to know the ID of the account that owns the follow request being queried. - BasePathWithID = BasePath + "/:" + IDKey - // AuthorizePath is used for authorizing follow requests - AuthorizePath = BasePathWithID + "/authorize" - // RejectPath is used for rejecting follow requests - RejectPath = BasePathWithID + "/reject" -) - -// Module implements the ClientAPIModule interface -type Module struct { - processor processing.Processor -} - -// New returns a new follow request module -func New(processor processing.Processor) api.ClientModule { - return &Module{ - processor: processor, - } -} - -// Route attaches all routes from this module to the given router -func (m *Module) Route(r router.Router) error { - r.AttachHandler(http.MethodGet, BasePath, m.FollowRequestGETHandler) - r.AttachHandler(http.MethodPost, AuthorizePath, m.FollowRequestAuthorizePOSTHandler) - r.AttachHandler(http.MethodPost, RejectPath, m.FollowRequestRejectPOSTHandler) - return nil -} diff --git a/internal/api/client/followrequest/followrequest_test.go b/internal/api/client/followrequest/followrequest_test.go deleted file mode 100644 index ca00ea054..000000000 --- a/internal/api/client/followrequest/followrequest_test.go +++ /dev/null @@ -1,122 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package followrequest_test - -import ( - "bytes" - "fmt" - "net/http/httptest" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/followrequest" - "github.com/superseriousbusiness/gotosocial/internal/concurrency" - "github.com/superseriousbusiness/gotosocial/internal/config" - "github.com/superseriousbusiness/gotosocial/internal/db" - "github.com/superseriousbusiness/gotosocial/internal/email" - "github.com/superseriousbusiness/gotosocial/internal/federation" - "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" - "github.com/superseriousbusiness/gotosocial/internal/media" - "github.com/superseriousbusiness/gotosocial/internal/messages" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/storage" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type FollowRequestStandardTestSuite struct { - suite.Suite - db db.DB - storage *storage.Driver - mediaManager media.Manager - federator federation.Federator - processor processing.Processor - emailSender email.Sender - - // standard suite models - testTokens map[string]*gtsmodel.Token - testClients map[string]*gtsmodel.Client - testApplications map[string]*gtsmodel.Application - testUsers map[string]*gtsmodel.User - testAccounts map[string]*gtsmodel.Account - testAttachments map[string]*gtsmodel.MediaAttachment - testStatuses map[string]*gtsmodel.Status - - // module being tested - followRequestModule *followrequest.Module -} - -func (suite *FollowRequestStandardTestSuite) SetupSuite() { - suite.testTokens = testrig.NewTestTokens() - suite.testClients = testrig.NewTestClients() - suite.testApplications = testrig.NewTestApplications() - suite.testUsers = testrig.NewTestUsers() - suite.testAccounts = testrig.NewTestAccounts() - suite.testAttachments = testrig.NewTestAttachments() - suite.testStatuses = testrig.NewTestStatuses() -} - -func (suite *FollowRequestStandardTestSuite) SetupTest() { - testrig.InitTestConfig() - testrig.InitTestLog() - - fedWorker := concurrency.NewWorkerPool[messages.FromFederator](-1, -1) - clientWorker := concurrency.NewWorkerPool[messages.FromClientAPI](-1, -1) - - suite.db = testrig.NewTestDB() - suite.storage = testrig.NewInMemoryStorage() - suite.mediaManager = testrig.NewTestMediaManager(suite.db, suite.storage) - suite.federator = testrig.NewTestFederator(suite.db, testrig.NewTestTransportController(testrig.NewMockHTTPClient(nil, "../../../../testrig/media"), suite.db, fedWorker), suite.storage, suite.mediaManager, fedWorker) - suite.emailSender = testrig.NewEmailSender("../../../../web/template/", nil) - suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator, suite.emailSender, suite.mediaManager, clientWorker, fedWorker) - suite.followRequestModule = followrequest.New(suite.processor).(*followrequest.Module) - testrig.StandardDBSetup(suite.db, nil) - testrig.StandardStorageSetup(suite.storage, "../../../../testrig/media") - - suite.NoError(suite.processor.Start()) -} - -func (suite *FollowRequestStandardTestSuite) TearDownTest() { - testrig.StandardDBTeardown(suite.db) - testrig.StandardStorageTeardown(suite.storage) -} - -func (suite *FollowRequestStandardTestSuite) newContext(recorder *httptest.ResponseRecorder, requestMethod string, requestBody []byte, requestPath string, bodyContentType string) *gin.Context { - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauth.DBTokenToToken(suite.testTokens["local_account_1"])) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - - protocol := config.GetProtocol() - host := config.GetHost() - - baseURI := fmt.Sprintf("%s://%s", protocol, host) - requestURI := fmt.Sprintf("%s/%s", baseURI, requestPath) - - ctx.Request = httptest.NewRequest(requestMethod, requestURI, bytes.NewReader(requestBody)) // the endpoint we're hitting - - if bodyContentType != "" { - ctx.Request.Header.Set("Content-Type", bodyContentType) - } - ctx.Request.Header.Set("accept", "application/json") - - return ctx -} diff --git a/internal/api/client/followrequest/get.go b/internal/api/client/followrequest/get.go deleted file mode 100644 index 8a2be3686..000000000 --- a/internal/api/client/followrequest/get.go +++ /dev/null @@ -1,93 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package followrequest - -import ( - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// 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). -// -// --- -// tags: -// - follow_requests -// -// produces: -// - application/json -// -// parameters: -// - -// name: limit -// type: integer -// description: Number of accounts to return. -// default: 40 -// in: query -// -// security: -// - OAuth2 Bearer: -// - read:follows -// -// responses: -// '200': -// headers: -// Link: -// type: string -// description: Links to the next and previous queries. -// schema: -// type: array -// items: -// "$ref": "#/definitions/account" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) FollowRequestGETHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - accts, errWithCode := m.processor.FollowRequestsGet(c.Request.Context(), authed) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, accts) -} diff --git a/internal/api/client/followrequest/get_test.go b/internal/api/client/followrequest/get_test.go deleted file mode 100644 index c9b72a35b..000000000 --- a/internal/api/client/followrequest/get_test.go +++ /dev/null @@ -1,78 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package followrequest_test - -import ( - "context" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" -) - -type GetTestSuite struct { - FollowRequestStandardTestSuite -} - -func (suite *GetTestSuite) TestGet() { - requestingAccount := suite.testAccounts["remote_account_2"] - targetAccount := suite.testAccounts["local_account_1"] - - // put a follow request in the database - fr := >smodel.FollowRequest{ - ID: "01FJ1S8DX3STJJ6CEYPMZ1M0R3", - CreatedAt: time.Now(), - UpdatedAt: time.Now(), - URI: fmt.Sprintf("%s/follow/01FJ1S8DX3STJJ6CEYPMZ1M0R3", requestingAccount.URI), - AccountID: requestingAccount.ID, - TargetAccountID: targetAccount.ID, - } - - err := suite.db.Put(context.Background(), fr) - suite.NoError(err) - - recorder := httptest.NewRecorder() - ctx := suite.newContext(recorder, http.MethodGet, []byte{}, "/api/v1/follow_requests", "") - - // call the handler - suite.followRequestModule.FollowRequestGETHandler(ctx) - - // 1. we should have OK because our request was valid - suite.Equal(http.StatusOK, recorder.Code) - - // 2. we should have no error message in the result body - result := recorder.Result() - defer result.Body.Close() - - // check the response - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - - suite.Equal(`[{"id":"01FHMQX3GAABWSM0S2VZEC2SWC","username":"Some_User","acct":"Some_User@example.org","display_name":"some user","locked":true,"bot":false,"created_at":"2020-08-10T12:13:28.000Z","note":"i'm a real son of a gun","url":"http://example.org/@Some_User","avatar":"","avatar_static":"","header":"http://localhost:8080/assets/default_header.png","header_static":"http://localhost:8080/assets/default_header.png","followers_count":0,"following_count":0,"statuses_count":0,"last_status_at":null,"emojis":[],"fields":[]}]`, string(b)) -} - -func TestGetTestSuite(t *testing.T) { - suite.Run(t, &GetTestSuite{}) -} diff --git a/internal/api/client/followrequest/reject.go b/internal/api/client/followrequest/reject.go deleted file mode 100644 index 717dbf4dd..000000000 --- a/internal/api/client/followrequest/reject.go +++ /dev/null @@ -1,96 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package followrequest - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// FollowRequestRejectPOSTHandler swagger:operation POST /api/v1/follow_requests/{account_id}/reject rejectFollowRequest -// -// Reject/deny follow request from the given account ID. -// -// --- -// tags: -// - follow_requests -// -// produces: -// - application/json -// -// parameters: -// - -// name: account_id -// type: string -// description: ID of the account requesting to follow you. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - write:follows -// -// responses: -// '200': -// name: account relationship -// description: Your relationship to this account. -// schema: -// "$ref": "#/definitions/accountRelationship" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) FollowRequestRejectPOSTHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - originAccountID := c.Param(IDKey) - if originAccountID == "" { - err := errors.New("no account id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - relationship, errWithCode := m.processor.FollowRequestReject(c.Request.Context(), authed, originAccountID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, relationship) -} diff --git a/internal/api/client/followrequest/reject_test.go b/internal/api/client/followrequest/reject_test.go deleted file mode 100644 index 94c646ddc..000000000 --- a/internal/api/client/followrequest/reject_test.go +++ /dev/null @@ -1,87 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package followrequest_test - -import ( - "context" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/followrequest" - "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" -) - -type RejectTestSuite struct { - FollowRequestStandardTestSuite -} - -func (suite *RejectTestSuite) TestReject() { - requestingAccount := suite.testAccounts["remote_account_2"] - targetAccount := suite.testAccounts["local_account_1"] - - // put a follow request in the database - fr := >smodel.FollowRequest{ - ID: "01FJ1S8DX3STJJ6CEYPMZ1M0R3", - CreatedAt: time.Now(), - UpdatedAt: time.Now(), - URI: fmt.Sprintf("%s/follow/01FJ1S8DX3STJJ6CEYPMZ1M0R3", requestingAccount.URI), - AccountID: requestingAccount.ID, - TargetAccountID: targetAccount.ID, - } - - err := suite.db.Put(context.Background(), fr) - suite.NoError(err) - - recorder := httptest.NewRecorder() - ctx := suite.newContext(recorder, http.MethodPost, []byte{}, fmt.Sprintf("/api/v1/follow_requests/%s/reject", requestingAccount.ID), "") - - ctx.Params = gin.Params{ - gin.Param{ - Key: followrequest.IDKey, - Value: requestingAccount.ID, - }, - } - - // call the handler - suite.followRequestModule.FollowRequestRejectPOSTHandler(ctx) - - // 1. we should have OK because our request was valid - suite.Equal(http.StatusOK, recorder.Code) - - // 2. we should have no error message in the result body - result := recorder.Result() - defer result.Body.Close() - - // check the response - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - - suite.Equal(`{"id":"01FHMQX3GAABWSM0S2VZEC2SWC","following":false,"showing_reblogs":false,"notifying":false,"followed_by":false,"blocking":false,"blocked_by":false,"muting":false,"muting_notifications":false,"requested":false,"domain_blocking":false,"endorsed":false,"note":""}`, string(b)) -} - -func TestRejectTestSuite(t *testing.T) { - suite.Run(t, &RejectTestSuite{}) -} diff --git a/internal/api/client/followrequests/authorize.go b/internal/api/client/followrequests/authorize.go new file mode 100644 index 000000000..d30bb979f --- /dev/null +++ b/internal/api/client/followrequests/authorize.go @@ -0,0 +1,98 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package followrequests + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// FollowRequestAuthorizePOSTHandler swagger:operation POST /api/v1/follow_requests/{account_id}/authorize authorizeFollowRequest +// +// Accept/authorize follow request from the given account ID. +// +// Accept a follow request and put the requesting account in your 'followers' list. +// +// --- +// tags: +// - follow_requests +// +// produces: +// - application/json +// +// parameters: +// - +// name: account_id +// type: string +// description: ID of the account requesting to follow you. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - write:follows +// +// responses: +// '200': +// name: account relationship +// description: Your relationship to this account. +// schema: +// "$ref": "#/definitions/accountRelationship" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) FollowRequestAuthorizePOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + originAccountID := c.Param(IDKey) + if originAccountID == "" { + err := errors.New("no account id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + relationship, errWithCode := m.processor.FollowRequestAccept(c.Request.Context(), authed, originAccountID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, relationship) +} diff --git a/internal/api/client/followrequests/authorize_test.go b/internal/api/client/followrequests/authorize_test.go new file mode 100644 index 000000000..048c462c7 --- /dev/null +++ b/internal/api/client/followrequests/authorize_test.go @@ -0,0 +1,115 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package followrequests_test + +import ( + "context" + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/followrequests" + "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" +) + +type AuthorizeTestSuite struct { + FollowRequestStandardTestSuite +} + +func (suite *AuthorizeTestSuite) TestAuthorize() { + requestingAccount := suite.testAccounts["remote_account_2"] + targetAccount := suite.testAccounts["local_account_1"] + + // put a follow request in the database + fr := >smodel.FollowRequest{ + ID: "01FJ1S8DX3STJJ6CEYPMZ1M0R3", + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + URI: fmt.Sprintf("%s/follow/01FJ1S8DX3STJJ6CEYPMZ1M0R3", requestingAccount.URI), + AccountID: requestingAccount.ID, + TargetAccountID: targetAccount.ID, + } + + err := suite.db.Put(context.Background(), fr) + suite.NoError(err) + + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodPost, []byte{}, fmt.Sprintf("/api/v1/follow_requests/%s/authorize", requestingAccount.ID), "") + + ctx.Params = gin.Params{ + gin.Param{ + Key: followrequests.IDKey, + Value: requestingAccount.ID, + }, + } + + // call the handler + suite.followRequestModule.FollowRequestAuthorizePOSTHandler(ctx) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusOK, recorder.Code) + + // 2. we should have no error message in the result body + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + + suite.Equal(`{"id":"01FHMQX3GAABWSM0S2VZEC2SWC","following":false,"showing_reblogs":false,"notifying":false,"followed_by":true,"blocking":false,"blocked_by":false,"muting":false,"muting_notifications":false,"requested":false,"domain_blocking":false,"endorsed":false,"note":""}`, string(b)) +} + +func (suite *AuthorizeTestSuite) TestAuthorizeNoFR() { + requestingAccount := suite.testAccounts["remote_account_2"] + + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodPost, []byte{}, fmt.Sprintf("/api/v1/follow_requests/%s/authorize", requestingAccount.ID), "") + + ctx.Params = gin.Params{ + gin.Param{ + Key: followrequests.IDKey, + Value: requestingAccount.ID, + }, + } + + // call the handler + suite.followRequestModule.FollowRequestAuthorizePOSTHandler(ctx) + + suite.Equal(http.StatusNotFound, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + + suite.Equal(`{"error":"Not Found"}`, string(b)) +} + +func TestAuthorizeTestSuite(t *testing.T) { + suite.Run(t, &AuthorizeTestSuite{}) +} diff --git a/internal/api/client/followrequests/followrequest.go b/internal/api/client/followrequests/followrequest.go new file mode 100644 index 000000000..d9d241e63 --- /dev/null +++ b/internal/api/client/followrequests/followrequest.go @@ -0,0 +1,56 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package followrequests + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "github.com/superseriousbusiness/gotosocial/internal/processing" +) + +const ( + // IDKey is for account IDs + IDKey = "id" + // BasePath is the base path for serving the follow request API, minus the 'api' prefix + BasePath = "/v1/follow_requests" + // BasePathWithID is just the base path with the ID key in it. + // Use this anywhere you need to know the ID of the account that owns the follow request being queried. + BasePathWithID = BasePath + "/:" + IDKey + // AuthorizePath is used for authorizing follow requests + AuthorizePath = BasePathWithID + "/authorize" + // RejectPath is used for rejecting follow requests + RejectPath = BasePathWithID + "/reject" +) + +type Module struct { + processor processing.Processor +} + +func New(processor processing.Processor) *Module { + return &Module{ + processor: processor, + } +} + +func (m *Module) Route(attachHandler func(method string, path string, f ...gin.HandlerFunc) gin.IRoutes) { + attachHandler(http.MethodGet, BasePath, m.FollowRequestGETHandler) + attachHandler(http.MethodPost, AuthorizePath, m.FollowRequestAuthorizePOSTHandler) + attachHandler(http.MethodPost, RejectPath, m.FollowRequestRejectPOSTHandler) +} diff --git a/internal/api/client/followrequests/followrequest_test.go b/internal/api/client/followrequests/followrequest_test.go new file mode 100644 index 000000000..c8036cd24 --- /dev/null +++ b/internal/api/client/followrequests/followrequest_test.go @@ -0,0 +1,122 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package followrequests_test + +import ( + "bytes" + "fmt" + "net/http/httptest" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/followrequests" + "github.com/superseriousbusiness/gotosocial/internal/concurrency" + "github.com/superseriousbusiness/gotosocial/internal/config" + "github.com/superseriousbusiness/gotosocial/internal/db" + "github.com/superseriousbusiness/gotosocial/internal/email" + "github.com/superseriousbusiness/gotosocial/internal/federation" + "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" + "github.com/superseriousbusiness/gotosocial/internal/media" + "github.com/superseriousbusiness/gotosocial/internal/messages" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/internal/processing" + "github.com/superseriousbusiness/gotosocial/internal/storage" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +type FollowRequestStandardTestSuite struct { + suite.Suite + db db.DB + storage *storage.Driver + mediaManager media.Manager + federator federation.Federator + processor processing.Processor + emailSender email.Sender + + // standard suite models + testTokens map[string]*gtsmodel.Token + testClients map[string]*gtsmodel.Client + testApplications map[string]*gtsmodel.Application + testUsers map[string]*gtsmodel.User + testAccounts map[string]*gtsmodel.Account + testAttachments map[string]*gtsmodel.MediaAttachment + testStatuses map[string]*gtsmodel.Status + + // module being tested + followRequestModule *followrequests.Module +} + +func (suite *FollowRequestStandardTestSuite) SetupSuite() { + suite.testTokens = testrig.NewTestTokens() + suite.testClients = testrig.NewTestClients() + suite.testApplications = testrig.NewTestApplications() + suite.testUsers = testrig.NewTestUsers() + suite.testAccounts = testrig.NewTestAccounts() + suite.testAttachments = testrig.NewTestAttachments() + suite.testStatuses = testrig.NewTestStatuses() +} + +func (suite *FollowRequestStandardTestSuite) SetupTest() { + testrig.InitTestConfig() + testrig.InitTestLog() + + fedWorker := concurrency.NewWorkerPool[messages.FromFederator](-1, -1) + clientWorker := concurrency.NewWorkerPool[messages.FromClientAPI](-1, -1) + + suite.db = testrig.NewTestDB() + suite.storage = testrig.NewInMemoryStorage() + suite.mediaManager = testrig.NewTestMediaManager(suite.db, suite.storage) + suite.federator = testrig.NewTestFederator(suite.db, testrig.NewTestTransportController(testrig.NewMockHTTPClient(nil, "../../../../testrig/media"), suite.db, fedWorker), suite.storage, suite.mediaManager, fedWorker) + suite.emailSender = testrig.NewEmailSender("../../../../web/template/", nil) + suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator, suite.emailSender, suite.mediaManager, clientWorker, fedWorker) + suite.followRequestModule = followrequests.New(suite.processor) + testrig.StandardDBSetup(suite.db, nil) + testrig.StandardStorageSetup(suite.storage, "../../../../testrig/media") + + suite.NoError(suite.processor.Start()) +} + +func (suite *FollowRequestStandardTestSuite) TearDownTest() { + testrig.StandardDBTeardown(suite.db) + testrig.StandardStorageTeardown(suite.storage) +} + +func (suite *FollowRequestStandardTestSuite) newContext(recorder *httptest.ResponseRecorder, requestMethod string, requestBody []byte, requestPath string, bodyContentType string) *gin.Context { + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauth.DBTokenToToken(suite.testTokens["local_account_1"])) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + + protocol := config.GetProtocol() + host := config.GetHost() + + baseURI := fmt.Sprintf("%s://%s", protocol, host) + requestURI := fmt.Sprintf("%s/%s", baseURI, requestPath) + + ctx.Request = httptest.NewRequest(requestMethod, requestURI, bytes.NewReader(requestBody)) // the endpoint we're hitting + + if bodyContentType != "" { + ctx.Request.Header.Set("Content-Type", bodyContentType) + } + ctx.Request.Header.Set("accept", "application/json") + + return ctx +} diff --git a/internal/api/client/followrequests/get.go b/internal/api/client/followrequests/get.go new file mode 100644 index 000000000..1153f0f4b --- /dev/null +++ b/internal/api/client/followrequests/get.go @@ -0,0 +1,93 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package followrequests + +import ( + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// 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). +// +// --- +// tags: +// - follow_requests +// +// produces: +// - application/json +// +// parameters: +// - +// name: limit +// type: integer +// description: Number of accounts to return. +// default: 40 +// in: query +// +// security: +// - OAuth2 Bearer: +// - read:follows +// +// responses: +// '200': +// headers: +// Link: +// type: string +// description: Links to the next and previous queries. +// schema: +// type: array +// items: +// "$ref": "#/definitions/account" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) FollowRequestGETHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + accts, errWithCode := m.processor.FollowRequestsGet(c.Request.Context(), authed) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, accts) +} diff --git a/internal/api/client/followrequests/get_test.go b/internal/api/client/followrequests/get_test.go new file mode 100644 index 000000000..d4c9da0a1 --- /dev/null +++ b/internal/api/client/followrequests/get_test.go @@ -0,0 +1,78 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package followrequests_test + +import ( + "context" + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" +) + +type GetTestSuite struct { + FollowRequestStandardTestSuite +} + +func (suite *GetTestSuite) TestGet() { + requestingAccount := suite.testAccounts["remote_account_2"] + targetAccount := suite.testAccounts["local_account_1"] + + // put a follow request in the database + fr := >smodel.FollowRequest{ + ID: "01FJ1S8DX3STJJ6CEYPMZ1M0R3", + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + URI: fmt.Sprintf("%s/follow/01FJ1S8DX3STJJ6CEYPMZ1M0R3", requestingAccount.URI), + AccountID: requestingAccount.ID, + TargetAccountID: targetAccount.ID, + } + + err := suite.db.Put(context.Background(), fr) + suite.NoError(err) + + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodGet, []byte{}, "/api/v1/follow_requests", "") + + // call the handler + suite.followRequestModule.FollowRequestGETHandler(ctx) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusOK, recorder.Code) + + // 2. we should have no error message in the result body + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + + suite.Equal(`[{"id":"01FHMQX3GAABWSM0S2VZEC2SWC","username":"Some_User","acct":"Some_User@example.org","display_name":"some user","locked":true,"bot":false,"created_at":"2020-08-10T12:13:28.000Z","note":"i'm a real son of a gun","url":"http://example.org/@Some_User","avatar":"","avatar_static":"","header":"http://localhost:8080/assets/default_header.png","header_static":"http://localhost:8080/assets/default_header.png","followers_count":0,"following_count":0,"statuses_count":0,"last_status_at":null,"emojis":[],"fields":[]}]`, string(b)) +} + +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 new file mode 100644 index 000000000..782f932cd --- /dev/null +++ b/internal/api/client/followrequests/reject.go @@ -0,0 +1,96 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package followrequests + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// FollowRequestRejectPOSTHandler swagger:operation POST /api/v1/follow_requests/{account_id}/reject rejectFollowRequest +// +// Reject/deny follow request from the given account ID. +// +// --- +// tags: +// - follow_requests +// +// produces: +// - application/json +// +// parameters: +// - +// name: account_id +// type: string +// description: ID of the account requesting to follow you. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - write:follows +// +// responses: +// '200': +// name: account relationship +// description: Your relationship to this account. +// schema: +// "$ref": "#/definitions/accountRelationship" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) FollowRequestRejectPOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + originAccountID := c.Param(IDKey) + if originAccountID == "" { + err := errors.New("no account id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + relationship, errWithCode := m.processor.FollowRequestReject(c.Request.Context(), authed, originAccountID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, relationship) +} diff --git a/internal/api/client/followrequests/reject_test.go b/internal/api/client/followrequests/reject_test.go new file mode 100644 index 000000000..cea42829d --- /dev/null +++ b/internal/api/client/followrequests/reject_test.go @@ -0,0 +1,87 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package followrequests_test + +import ( + "context" + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/followrequests" + "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" +) + +type RejectTestSuite struct { + FollowRequestStandardTestSuite +} + +func (suite *RejectTestSuite) TestReject() { + requestingAccount := suite.testAccounts["remote_account_2"] + targetAccount := suite.testAccounts["local_account_1"] + + // put a follow request in the database + fr := >smodel.FollowRequest{ + ID: "01FJ1S8DX3STJJ6CEYPMZ1M0R3", + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + URI: fmt.Sprintf("%s/follow/01FJ1S8DX3STJJ6CEYPMZ1M0R3", requestingAccount.URI), + AccountID: requestingAccount.ID, + TargetAccountID: targetAccount.ID, + } + + err := suite.db.Put(context.Background(), fr) + suite.NoError(err) + + recorder := httptest.NewRecorder() + ctx := suite.newContext(recorder, http.MethodPost, []byte{}, fmt.Sprintf("/api/v1/follow_requests/%s/reject", requestingAccount.ID), "") + + ctx.Params = gin.Params{ + gin.Param{ + Key: followrequests.IDKey, + Value: requestingAccount.ID, + }, + } + + // call the handler + suite.followRequestModule.FollowRequestRejectPOSTHandler(ctx) + + // 1. we should have OK because our request was valid + suite.Equal(http.StatusOK, recorder.Code) + + // 2. we should have no error message in the result body + result := recorder.Result() + defer result.Body.Close() + + // check the response + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + + suite.Equal(`{"id":"01FHMQX3GAABWSM0S2VZEC2SWC","following":false,"showing_reblogs":false,"notifying":false,"followed_by":false,"blocking":false,"blocked_by":false,"muting":false,"muting_notifications":false,"requested":false,"domain_blocking":false,"endorsed":false,"note":""}`, string(b)) +} + +func TestRejectTestSuite(t *testing.T) { + suite.Run(t, &RejectTestSuite{}) +} diff --git a/internal/api/client/instance/instance.go b/internal/api/client/instance/instance.go index 16ff7c9f9..101e8cea4 100644 --- a/internal/api/client/instance/instance.go +++ b/internal/api/client/instance/instance.go @@ -21,36 +21,31 @@ package instance import ( "net/http" - "github.com/superseriousbusiness/gotosocial/internal/api" + "github.com/gin-gonic/gin" "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" ) const ( - // InstanceInformationPath is for serving instance info requests - InstanceInformationPath = "api/v1/instance" + // InstanceInformationPath is for serving instance info requests, minus the 'api' prefix. + InstanceInformationPath = "/v1/instance" // InstancePeersPath is for serving instance peers requests. InstancePeersPath = InstanceInformationPath + "/peers" // PeersFilterKey is used to provide filters to /api/v1/instance/peers PeersFilterKey = "filter" ) -// Module implements the ClientModule interface type Module struct { processor processing.Processor } -// New returns a new instance information module -func New(processor processing.Processor) api.ClientModule { +func New(processor processing.Processor) *Module { return &Module{ processor: processor, } } -// Route satisfies the ClientModule interface -func (m *Module) Route(s router.Router) error { - s.AttachHandler(http.MethodGet, InstanceInformationPath, m.InstanceInformationGETHandler) - s.AttachHandler(http.MethodPatch, InstanceInformationPath, m.InstanceUpdatePATCHHandler) - s.AttachHandler(http.MethodGet, InstancePeersPath, m.InstancePeersGETHandler) - return nil +func (m *Module) Route(attachHandler func(method string, path string, f ...gin.HandlerFunc) gin.IRoutes) { + attachHandler(http.MethodGet, InstanceInformationPath, m.InstanceInformationGETHandler) + attachHandler(http.MethodPatch, InstanceInformationPath, m.InstanceUpdatePATCHHandler) + attachHandler(http.MethodGet, InstancePeersPath, m.InstancePeersGETHandler) } diff --git a/internal/api/client/instance/instance_test.go b/internal/api/client/instance/instance_test.go index 26f29027d..33efbc847 100644 --- a/internal/api/client/instance/instance_test.go +++ b/internal/api/client/instance/instance_test.go @@ -88,7 +88,7 @@ func (suite *InstanceStandardTestSuite) SetupTest() { suite.sentEmails = make(map[string]string) suite.emailSender = testrig.NewEmailSender("../../../../web/template/", suite.sentEmails) suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator, suite.emailSender, suite.mediaManager, clientWorker, fedWorker) - suite.instanceModule = instance.New(suite.processor).(*instance.Module) + suite.instanceModule = instance.New(suite.processor) testrig.StandardDBSetup(suite.db, nil) testrig.StandardStorageSetup(suite.storage, "../../../../testrig/media") } diff --git a/internal/api/client/instance/instanceget.go b/internal/api/client/instance/instanceget.go index bcedf398b..dfb8330ff 100644 --- a/internal/api/client/instance/instanceget.go +++ b/internal/api/client/instance/instanceget.go @@ -21,7 +21,7 @@ package instance import ( "net/http" - "github.com/superseriousbusiness/gotosocial/internal/api" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/config" "github.com/superseriousbusiness/gotosocial/internal/gtserror" @@ -49,14 +49,14 @@ import ( // '500': // description: internal error func (m *Module) InstanceInformationGETHandler(c *gin.Context) { - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } instance, errWithCode := m.processor.InstanceGet(c.Request.Context(), config.GetHost()) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } diff --git a/internal/api/client/instance/instancepatch.go b/internal/api/client/instance/instancepatch.go index d4fa8ca5d..891ce8e38 100644 --- a/internal/api/client/instance/instancepatch.go +++ b/internal/api/client/instance/instancepatch.go @@ -24,8 +24,8 @@ import ( "net/http" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/config" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" @@ -130,42 +130,42 @@ import ( func (m *Module) InstanceUpdatePATCHHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } if !*authed.User.Admin { err := errors.New("user is not an admin so cannot update instance settings") - api.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorForbidden(err, err.Error()), m.processor.InstanceGet) return } - form := &model.InstanceSettingsUpdateRequest{} + form := &apimodel.InstanceSettingsUpdateRequest{} if err := c.ShouldBind(&form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } if err := validateInstanceUpdate(form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } i, errWithCode := m.processor.InstancePatch(c.Request.Context(), form) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } c.JSON(http.StatusOK, i) } -func validateInstanceUpdate(form *model.InstanceSettingsUpdateRequest) error { +func validateInstanceUpdate(form *apimodel.InstanceSettingsUpdateRequest) error { if form.Title == nil && form.ContactUsername == nil && form.ContactEmail == nil && diff --git a/internal/api/client/instance/instancepeersget.go b/internal/api/client/instance/instancepeersget.go index f7d05acdc..de6e40e7c 100644 --- a/internal/api/client/instance/instancepeersget.go +++ b/internal/api/client/instance/instancepeersget.go @@ -23,7 +23,7 @@ import ( "net/http" "strings" - "github.com/superseriousbusiness/gotosocial/internal/api" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" @@ -101,12 +101,12 @@ import ( func (m *Module) InstancePeersGETHandler(c *gin.Context) { authed, err := oauth.Authed(c, false, false, false, false) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } @@ -124,7 +124,7 @@ func (m *Module) InstancePeersGETHandler(c *gin.Context) { includeOpen = true default: err := fmt.Errorf("filter %s not recognized; accepted values are 'open', 'suspended'", trimmed) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } } @@ -138,7 +138,7 @@ func (m *Module) InstancePeersGETHandler(c *gin.Context) { data, errWithCode := m.processor.InstancePeersGet(c.Request.Context(), authed, includeSuspended, includeOpen, flat) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } diff --git a/internal/api/client/list/list.go b/internal/api/client/list/list.go deleted file mode 100644 index c64ada43e..000000000 --- a/internal/api/client/list/list.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package list - -import ( - "net/http" - - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" -) - -const ( - // BasePath is the base path for serving the lists API - BasePath = "/api/v1/lists" -) - -// Module implements the ClientAPIModule interface for everything related to lists -type Module struct { - processor processing.Processor -} - -// New returns a new list module -func New(processor processing.Processor) api.ClientModule { - return &Module{ - processor: processor, - } -} - -// Route attaches all routes from this module to the given router -func (m *Module) Route(r router.Router) error { - r.AttachHandler(http.MethodGet, BasePath, m.ListsGETHandler) - return nil -} diff --git a/internal/api/client/list/listsgets.go b/internal/api/client/list/listsgets.go deleted file mode 100644 index 246a1216a..000000000 --- a/internal/api/client/list/listsgets.go +++ /dev/null @@ -1,25 +0,0 @@ -package list - -import ( - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// ListsGETHandler returns a list of lists created by/for the authed account -func (m *Module) ListsGETHandler(c *gin.Context) { - if _, err := oauth.Authed(c, true, true, true, true); err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, []string{}) -} diff --git a/internal/api/client/lists/list.go b/internal/api/client/lists/list.go new file mode 100644 index 000000000..c14917b98 --- /dev/null +++ b/internal/api/client/lists/list.go @@ -0,0 +1,45 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package lists + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "github.com/superseriousbusiness/gotosocial/internal/processing" +) + +const ( + // BasePath is the base path for serving the lists API, minus the 'api' prefix + BasePath = "/v1/lists" +) + +type Module struct { + processor processing.Processor +} + +func New(processor processing.Processor) *Module { + return &Module{ + processor: processor, + } +} + +func (m *Module) Route(attachHandler func(method string, path string, f ...gin.HandlerFunc) gin.IRoutes) { + attachHandler(http.MethodGet, BasePath, m.ListsGETHandler) +} diff --git a/internal/api/client/lists/listsgets.go b/internal/api/client/lists/listsgets.go new file mode 100644 index 000000000..a4e5cbefa --- /dev/null +++ b/internal/api/client/lists/listsgets.go @@ -0,0 +1,44 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package lists + +import ( + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// ListsGETHandler returns a list of lists created by/for the authed account +func (m *Module) ListsGETHandler(c *gin.Context) { + if _, err := oauth.Authed(c, true, true, true, true); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + // todo: implement this; currently it's a no-op + c.JSON(http.StatusOK, []string{}) +} diff --git a/internal/api/client/media/media.go b/internal/api/client/media/media.go index 87cc2f091..889a4f3df 100644 --- a/internal/api/client/media/media.go +++ b/internal/api/client/media/media.go @@ -21,34 +21,31 @@ package media import ( "net/http" - "github.com/superseriousbusiness/gotosocial/internal/api" + "github.com/gin-gonic/gin" "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" ) const ( - IDKey = "id" // IDKey is the key for media attachment IDs - APIVersionKey = "api_version" // APIVersionKey is the key for which version of the API to use (v1 or v2) - BasePathWithAPIVersion = "/api/:" + APIVersionKey + "/media" // BasePathWithAPIVersion is the base API path for making media requests through v1 or v2 of the api (for mastodon API compatibility) - BasePathWithIDV1 = "/api/v1/media/:" + IDKey // BasePathWithID corresponds to a media attachment with the given ID + IDKey = "id" // IDKey is the key for media attachment IDs + APIVersionKey = "api_version" // APIVersionKey is the key for which version of the API to use (v1 or v2) + APIv1 = "v1" // APIV1 corresponds to version 1 of the api + APIv2 = "v2" // APIV2 corresponds to version 2 of the api + BasePath = "/:" + APIVersionKey + "/media" // BasePath is the base API path for making media requests through v1 or v2 of the api (for mastodon API compatibility) + AttachmentWithID = BasePath + "/:" + IDKey // BasePathWithID corresponds to a media attachment with the given ID ) -// Module implements the ClientAPIModule interface for media type Module struct { processor processing.Processor } -// New returns a new auth module -func New(processor processing.Processor) api.ClientModule { +func New(processor processing.Processor) *Module { return &Module{ processor: processor, } } -// Route satisfies the RESTAPIModule interface -func (m *Module) Route(s router.Router) error { - s.AttachHandler(http.MethodPost, BasePathWithAPIVersion, m.MediaCreatePOSTHandler) - s.AttachHandler(http.MethodGet, BasePathWithIDV1, m.MediaGETHandler) - s.AttachHandler(http.MethodPut, BasePathWithIDV1, m.MediaPUTHandler) - return nil +func (m *Module) Route(attachHandler func(method string, path string, f ...gin.HandlerFunc) gin.IRoutes) { + attachHandler(http.MethodPost, BasePath, m.MediaCreatePOSTHandler) + attachHandler(http.MethodGet, AttachmentWithID, m.MediaGETHandler) + attachHandler(http.MethodPut, AttachmentWithID, m.MediaPUTHandler) } diff --git a/internal/api/client/media/mediacreate.go b/internal/api/client/media/mediacreate.go index db8b2ea56..7e29b2bb3 100644 --- a/internal/api/client/media/mediacreate.go +++ b/internal/api/client/media/mediacreate.go @@ -24,8 +24,8 @@ import ( "net/http" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/config" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" @@ -94,42 +94,42 @@ import ( // '500': // description: internal server error func (m *Module) MediaCreatePOSTHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiVersion := c.Param(APIVersionKey) + if apiVersion != APIv1 && apiVersion != APIv2 { + err := errors.New("api version must be one of v1 or v2 for this path") + apiutil.ErrorHandler(c, gtserror.NewErrorNotFound(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } - apiVersion := c.Param(APIVersionKey) - if apiVersion != "v1" && apiVersion != "v2" { - err := errors.New("api version must be one of v1 or v2") - api.ErrorHandler(c, gtserror.NewErrorNotFound(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } - form := &model.AttachmentRequest{} + form := &apimodel.AttachmentRequest{} if err := c.ShouldBind(&form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } if err := validateCreateMedia(form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } apiAttachment, errWithCode := m.processor.MediaCreate(c.Request.Context(), authed, form) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } - if apiVersion == "v2" { + if apiVersion == APIv2 { // the mastodon v2 media API specifies that the URL should be null // and that the client should call /api/v1/media/:id to get the URL // @@ -141,7 +141,7 @@ func (m *Module) MediaCreatePOSTHandler(c *gin.Context) { c.JSON(http.StatusOK, apiAttachment) } -func validateCreateMedia(form *model.AttachmentRequest) error { +func validateCreateMedia(form *apimodel.AttachmentRequest) error { // check there actually is a file attached and it's not size 0 if form.File == nil { return errors.New("no attachment given") diff --git a/internal/api/client/media/mediacreate_test.go b/internal/api/client/media/mediacreate_test.go index 2f6fb12a4..9e787b4b9 100644 --- a/internal/api/client/media/mediacreate_test.go +++ b/internal/api/client/media/mediacreate_test.go @@ -30,10 +30,9 @@ import ( "net/http/httptest" "testing" - "github.com/gin-gonic/gin" "github.com/stretchr/testify/suite" mediamodule "github.com/superseriousbusiness/gotosocial/internal/api/client/media" - "github.com/superseriousbusiness/gotosocial/internal/api/model" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" "github.com/superseriousbusiness/gotosocial/internal/concurrency" "github.com/superseriousbusiness/gotosocial/internal/config" "github.com/superseriousbusiness/gotosocial/internal/db" @@ -96,7 +95,7 @@ func (suite *MediaCreateTestSuite) SetupSuite() { suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator, suite.emailSender, suite.mediaManager, clientWorker, fedWorker) // setup module being tested - suite.mediaModule = mediamodule.New(suite.processor).(*mediamodule.Module) + suite.mediaModule = mediamodule.New(suite.processor) } func (suite *MediaCreateTestSuite) TearDownSuite() { @@ -158,12 +157,7 @@ func (suite *MediaCreateTestSuite) TestMediaCreateSuccessful() { ctx.Request = httptest.NewRequest(http.MethodPost, "http://localhost:8080/api/v1/media", bytes.NewReader(buf.Bytes())) // the endpoint we're hitting ctx.Request.Header.Set("Content-Type", w.FormDataContentType()) ctx.Request.Header.Set("accept", "application/json") - ctx.Params = gin.Params{ - gin.Param{ - Key: mediamodule.APIVersionKey, - Value: "v1", - }, - } + ctx.AddParam(mediamodule.APIVersionKey, mediamodule.APIv1) // do the actual request suite.mediaModule.MediaCreatePOSTHandler(ctx) @@ -188,26 +182,26 @@ func (suite *MediaCreateTestSuite) TestMediaCreateSuccessful() { suite.NoError(err) fmt.Println(string(b)) - attachmentReply := &model.Attachment{} + attachmentReply := &apimodel.Attachment{} err = json.Unmarshal(b, attachmentReply) suite.NoError(err) suite.Equal("this is a test image -- a cool background from somewhere", *attachmentReply.Description) suite.Equal("image", attachmentReply.Type) - suite.EqualValues(model.MediaMeta{ - Original: model.MediaDimensions{ + suite.EqualValues(apimodel.MediaMeta{ + Original: apimodel.MediaDimensions{ Width: 1920, Height: 1080, Size: "1920x1080", Aspect: 1.7777778, }, - Small: model.MediaDimensions{ + Small: apimodel.MediaDimensions{ Width: 512, Height: 288, Size: "512x288", Aspect: 1.7777778, }, - Focus: model.MediaFocus{ + Focus: apimodel.MediaFocus{ X: -0.5, Y: 0.5, }, @@ -252,12 +246,7 @@ func (suite *MediaCreateTestSuite) TestMediaCreateSuccessfulV2() { ctx.Request = httptest.NewRequest(http.MethodPost, "http://localhost:8080/api/v2/media", bytes.NewReader(buf.Bytes())) // the endpoint we're hitting ctx.Request.Header.Set("Content-Type", w.FormDataContentType()) ctx.Request.Header.Set("accept", "application/json") - ctx.Params = gin.Params{ - gin.Param{ - Key: mediamodule.APIVersionKey, - Value: "v2", - }, - } + ctx.AddParam(mediamodule.APIVersionKey, mediamodule.APIv2) // do the actual request suite.mediaModule.MediaCreatePOSTHandler(ctx) @@ -282,26 +271,26 @@ func (suite *MediaCreateTestSuite) TestMediaCreateSuccessfulV2() { suite.NoError(err) fmt.Println(string(b)) - attachmentReply := &model.Attachment{} + attachmentReply := &apimodel.Attachment{} err = json.Unmarshal(b, attachmentReply) suite.NoError(err) suite.Equal("this is a test image -- a cool background from somewhere", *attachmentReply.Description) suite.Equal("image", attachmentReply.Type) - suite.EqualValues(model.MediaMeta{ - Original: model.MediaDimensions{ + suite.EqualValues(apimodel.MediaMeta{ + Original: apimodel.MediaDimensions{ Width: 1920, Height: 1080, Size: "1920x1080", Aspect: 1.7777778, }, - Small: model.MediaDimensions{ + Small: apimodel.MediaDimensions{ Width: 512, Height: 288, Size: "512x288", Aspect: 1.7777778, }, - Focus: model.MediaFocus{ + Focus: apimodel.MediaFocus{ X: -0.5, Y: 0.5, }, @@ -342,12 +331,7 @@ func (suite *MediaCreateTestSuite) TestMediaCreateLongDescription() { ctx.Request = httptest.NewRequest(http.MethodPost, "http://localhost:8080/api/v1/media", bytes.NewReader(buf.Bytes())) // the endpoint we're hitting ctx.Request.Header.Set("Content-Type", w.FormDataContentType()) ctx.Request.Header.Set("accept", "application/json") - ctx.Params = gin.Params{ - gin.Param{ - Key: mediamodule.APIVersionKey, - Value: "v1", - }, - } + ctx.AddParam(mediamodule.APIVersionKey, mediamodule.APIv1) // do the actual request suite.mediaModule.MediaCreatePOSTHandler(ctx) @@ -388,12 +372,7 @@ func (suite *MediaCreateTestSuite) TestMediaCreateTooShortDescription() { ctx.Request = httptest.NewRequest(http.MethodPost, "http://localhost:8080/api/v1/media", bytes.NewReader(buf.Bytes())) // the endpoint we're hitting ctx.Request.Header.Set("Content-Type", w.FormDataContentType()) ctx.Request.Header.Set("accept", "application/json") - ctx.Params = gin.Params{ - gin.Param{ - Key: mediamodule.APIVersionKey, - Value: "v1", - }, - } + ctx.AddParam(mediamodule.APIVersionKey, mediamodule.APIv1) // do the actual request suite.mediaModule.MediaCreatePOSTHandler(ctx) diff --git a/internal/api/client/media/mediaget.go b/internal/api/client/media/mediaget.go index fd232c4c7..b22c8e79c 100644 --- a/internal/api/client/media/mediaget.go +++ b/internal/api/client/media/mediaget.go @@ -23,7 +23,7 @@ import ( "net/http" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" ) @@ -67,27 +67,33 @@ import ( // '500': // description: internal server error func (m *Module) MediaGETHandler(c *gin.Context) { + if apiVersion := c.Param(APIVersionKey); apiVersion != APIv1 { + err := errors.New("api version must be one v1 for this path") + apiutil.ErrorHandler(c, gtserror.NewErrorNotFound(err, err.Error()), m.processor.InstanceGet) + return + } + authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } attachmentID := c.Param(IDKey) if attachmentID == "" { err := errors.New("no attachment id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } attachment, errWithCode := m.processor.MediaGet(c.Request.Context(), authed, attachmentID) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } diff --git a/internal/api/client/media/mediaupdate.go b/internal/api/client/media/mediaupdate.go index 438eaca23..9cfd8a5f1 100644 --- a/internal/api/client/media/mediaupdate.go +++ b/internal/api/client/media/mediaupdate.go @@ -24,8 +24,8 @@ import ( "net/http" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/config" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" @@ -99,45 +99,51 @@ import ( // '500': // description: internal server error func (m *Module) MediaPUTHandler(c *gin.Context) { + if apiVersion := c.Param(APIVersionKey); apiVersion != APIv1 { + err := errors.New("api version must be one v1 for this path") + apiutil.ErrorHandler(c, gtserror.NewErrorNotFound(err, err.Error()), m.processor.InstanceGet) + return + } + authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } attachmentID := c.Param(IDKey) if attachmentID == "" { err := errors.New("no attachment id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } - form := &model.AttachmentUpdateRequest{} + form := &apimodel.AttachmentUpdateRequest{} if err := c.ShouldBind(form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } if err := validateUpdateMedia(form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } attachment, errWithCode := m.processor.MediaUpdate(c.Request.Context(), authed, attachmentID, form) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } c.JSON(http.StatusOK, attachment) } -func validateUpdateMedia(form *model.AttachmentUpdateRequest) error { +func validateUpdateMedia(form *apimodel.AttachmentUpdateRequest) error { minDescriptionChars := config.GetMediaDescriptionMinChars() maxDescriptionChars := config.GetMediaDescriptionMaxChars() diff --git a/internal/api/client/media/mediaupdate_test.go b/internal/api/client/media/mediaupdate_test.go index e5abb0a91..bcf9a4dfe 100644 --- a/internal/api/client/media/mediaupdate_test.go +++ b/internal/api/client/media/mediaupdate_test.go @@ -28,10 +28,9 @@ import ( "net/http/httptest" "testing" - "github.com/gin-gonic/gin" "github.com/stretchr/testify/suite" mediamodule "github.com/superseriousbusiness/gotosocial/internal/api/client/media" - "github.com/superseriousbusiness/gotosocial/internal/api/model" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" "github.com/superseriousbusiness/gotosocial/internal/concurrency" "github.com/superseriousbusiness/gotosocial/internal/config" "github.com/superseriousbusiness/gotosocial/internal/db" @@ -94,7 +93,7 @@ func (suite *MediaUpdateTestSuite) SetupSuite() { suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator, suite.emailSender, suite.mediaManager, clientWorker, fedWorker) // setup module being tested - suite.mediaModule = mediamodule.New(suite.processor).(*mediamodule.Module) + suite.mediaModule = mediamodule.New(suite.processor) } func (suite *MediaUpdateTestSuite) TearDownSuite() { @@ -148,12 +147,8 @@ func (suite *MediaUpdateTestSuite) TestUpdateImage() { ctx.Request = httptest.NewRequest(http.MethodPut, fmt.Sprintf("http://localhost:8080/api/v1/media/%s", toUpdate.ID), bytes.NewReader(buf.Bytes())) // the endpoint we're hitting ctx.Request.Header.Set("Content-Type", w.FormDataContentType()) ctx.Request.Header.Set("accept", "application/json") - ctx.Params = gin.Params{ - gin.Param{ - Key: mediamodule.IDKey, - Value: toUpdate.ID, - }, - } + ctx.AddParam(mediamodule.APIVersionKey, mediamodule.APIv1) + ctx.AddParam(mediamodule.IDKey, toUpdate.ID) // do the actual request suite.mediaModule.MediaPUTHandler(ctx) @@ -167,17 +162,17 @@ func (suite *MediaUpdateTestSuite) TestUpdateImage() { suite.NoError(err) // reply should be an attachment - attachmentReply := &model.Attachment{} + attachmentReply := &apimodel.Attachment{} err = json.Unmarshal(b, attachmentReply) suite.NoError(err) // the reply should contain the updated fields suite.Equal("new description!", *attachmentReply.Description) suite.EqualValues("image", attachmentReply.Type) - suite.EqualValues(model.MediaMeta{ - Original: model.MediaDimensions{Width: 800, Height: 450, FrameRate: "", Duration: 0, Bitrate: 0, Size: "800x450", Aspect: 1.7777778}, - Small: model.MediaDimensions{Width: 256, Height: 144, FrameRate: "", Duration: 0, Bitrate: 0, Size: "256x144", Aspect: 1.7777778}, - Focus: model.MediaFocus{X: -0.1, Y: 0.3}, + suite.EqualValues(apimodel.MediaMeta{ + Original: apimodel.MediaDimensions{Width: 800, Height: 450, FrameRate: "", Duration: 0, Bitrate: 0, Size: "800x450", Aspect: 1.7777778}, + Small: apimodel.MediaDimensions{Width: 256, Height: 144, FrameRate: "", Duration: 0, Bitrate: 0, Size: "256x144", Aspect: 1.7777778}, + Focus: apimodel.MediaFocus{X: -0.1, Y: 0.3}, }, attachmentReply.Meta) suite.Equal(toUpdate.Blurhash, attachmentReply.Blurhash) suite.Equal(toUpdate.ID, attachmentReply.ID) @@ -213,12 +208,8 @@ func (suite *MediaUpdateTestSuite) TestUpdateImageShortDescription() { ctx.Request = httptest.NewRequest(http.MethodPut, fmt.Sprintf("http://localhost:8080/api/v1/media/%s", toUpdate.ID), bytes.NewReader(buf.Bytes())) // the endpoint we're hitting ctx.Request.Header.Set("Content-Type", w.FormDataContentType()) ctx.Request.Header.Set("accept", "application/json") - ctx.Params = gin.Params{ - gin.Param{ - Key: mediamodule.IDKey, - Value: toUpdate.ID, - }, - } + ctx.AddParam(mediamodule.APIVersionKey, mediamodule.APIv1) + ctx.AddParam(mediamodule.IDKey, toUpdate.ID) // do the actual request suite.mediaModule.MediaPUTHandler(ctx) diff --git a/internal/api/client/notification/notification.go b/internal/api/client/notification/notification.go deleted file mode 100644 index 6ade0b02f..000000000 --- a/internal/api/client/notification/notification.go +++ /dev/null @@ -1,66 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package notification - -import ( - "net/http" - - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" -) - -const ( - // IDKey is for notification UUIDs - IDKey = "id" - // BasePath is the base path for serving the notification API - BasePath = "/api/v1/notifications" - // BasePathWithID is just the base path with the ID key in it. - // Use this anywhere you need to know the ID of the notification being queried. - BasePathWithID = BasePath + "/:" + IDKey - BasePathWithClear = BasePath + "/clear" - - // ExcludeTypes is an array specifying notification types to exclude - ExcludeTypesKey = "exclude_types[]" - // MaxIDKey is the url query for setting a max notification ID to return - MaxIDKey = "max_id" - // LimitKey is for specifying maximum number of notifications to return. - LimitKey = "limit" - // SinceIDKey is for specifying the minimum notification ID to return. - SinceIDKey = "since_id" -) - -// Module implements the ClientAPIModule interface for every related to posting/deleting/interacting with notifications -type Module struct { - processor processing.Processor -} - -// New returns a new notification module -func New(processor processing.Processor) api.ClientModule { - return &Module{ - processor: processor, - } -} - -// Route attaches all routes from this module to the given router -func (m *Module) Route(r router.Router) error { - r.AttachHandler(http.MethodGet, BasePath, m.NotificationsGETHandler) - r.AttachHandler(http.MethodPost, BasePathWithClear, m.NotificationsClearPOSTHandler) - return nil -} diff --git a/internal/api/client/notification/notificationsclear.go b/internal/api/client/notification/notificationsclear.go deleted file mode 100644 index b97371638..000000000 --- a/internal/api/client/notification/notificationsclear.go +++ /dev/null @@ -1,80 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package notification - -import ( - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// NotificationsClearPOSTHandler swagger:operation POST /api/v1/notifications clearNotifications -// -// Clear/delete all notifications for currently authorized user. -// -// Will return an empty object `{}` to indicate success. -// -// --- -// tags: -// - notifications -// -// produces: -// - application/json -// -// security: -// - OAuth2 Bearer: -// - read:notifications -// -// responses: -// '200': -// schema: -// type: object -// '400': -// description: bad request -// '401': -// description: unauthorized -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) NotificationsClearPOSTHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - errWithCode := m.processor.NotificationsClear(c.Request.Context(), authed) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, struct{}{}) -} diff --git a/internal/api/client/notification/notificationsget.go b/internal/api/client/notification/notificationsget.go deleted file mode 100644 index d6b3f5162..000000000 --- a/internal/api/client/notification/notificationsget.go +++ /dev/null @@ -1,159 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package notification - -import ( - "fmt" - "net/http" - "strconv" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// NotificationsGETHandler swagger:operation GET /api/v1/notifications notifications -// -// Get notifications for currently authorized user. -// -// The notifications will be returned in descending chronological order (newest first), with sequential IDs (bigger = newer). -// -// The next and previous queries can be parsed from the returned Link header. -// Example: -// -// ``` -// ; rel="next", ; rel="prev" -// ```` -// -// --- -// tags: -// - notifications -// -// produces: -// - application/json -// -// parameters: -// - -// name: limit -// type: integer -// description: Number of notifications to return. -// default: 20 -// in: query -// required: false -// - -// name: exclude_types -// type: array -// items: -// type: string -// description: Array of types of notifications to exclude (follow, favourite, reblog, mention, poll, follow_request) -// in: query -// required: false -// - -// name: max_id -// type: string -// description: >- -// Return only notifications *OLDER* than the given max status ID. -// The status with the specified ID will not be included in the response. -// in: query -// required: false -// - -// name: since_id -// type: string -// description: |- -// Return only notifications *NEWER* than the given since status ID. -// The status with the specified ID will not be included in the response. -// in: query -// required: false -// -// security: -// - OAuth2 Bearer: -// - read:notifications -// -// responses: -// '200': -// headers: -// Link: -// type: string -// description: Links to the next and previous queries. -// name: notifications -// description: Array of notifications. -// schema: -// type: array -// items: -// "$ref": "#/definitions/notification" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) NotificationsGETHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - limit := 20 - limitString := c.Query(LimitKey) - if limitString != "" { - i, err := strconv.ParseInt(limitString, 10, 32) - if err != nil { - err := fmt.Errorf("error parsing %s: %s", LimitKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - limit = int(i) - } - - maxID := "" - maxIDString := c.Query(MaxIDKey) - if maxIDString != "" { - maxID = maxIDString - } - - sinceID := "" - sinceIDString := c.Query(SinceIDKey) - if sinceIDString != "" { - sinceID = sinceIDString - } - - excludeTypes := c.QueryArray(ExcludeTypesKey) - - resp, errWithCode := m.processor.NotificationsGet(c.Request.Context(), authed, excludeTypes, limit, maxID, sinceID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - if resp.LinkHeader != "" { - c.Header("Link", resp.LinkHeader) - } - c.JSON(http.StatusOK, resp.Items) -} diff --git a/internal/api/client/notifications/notifications.go b/internal/api/client/notifications/notifications.go new file mode 100644 index 000000000..235f0a678 --- /dev/null +++ b/internal/api/client/notifications/notifications.go @@ -0,0 +1,61 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package notifications + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "github.com/superseriousbusiness/gotosocial/internal/processing" +) + +const ( + // IDKey is for notification UUIDs + IDKey = "id" + // BasePath is the base path for serving the notification API, minus the 'api' prefix. + BasePath = "/v1/notifications" + // BasePathWithID is just the base path with the ID key in it. + // Use this anywhere you need to know the ID of the notification being queried. + BasePathWithID = BasePath + "/:" + IDKey + BasePathWithClear = BasePath + "/clear" + + // ExcludeTypes is an array specifying notification types to exclude + ExcludeTypesKey = "exclude_types[]" + // MaxIDKey is the url query for setting a max notification ID to return + MaxIDKey = "max_id" + // LimitKey is for specifying maximum number of notifications to return. + LimitKey = "limit" + // SinceIDKey is for specifying the minimum notification ID to return. + SinceIDKey = "since_id" +) + +type Module struct { + processor processing.Processor +} + +func New(processor processing.Processor) *Module { + return &Module{ + processor: processor, + } +} + +func (m *Module) Route(attachHandler func(method string, path string, f ...gin.HandlerFunc) gin.IRoutes) { + attachHandler(http.MethodGet, BasePath, m.NotificationsGETHandler) + attachHandler(http.MethodPost, BasePathWithClear, m.NotificationsClearPOSTHandler) +} diff --git a/internal/api/client/notifications/notificationsclear.go b/internal/api/client/notifications/notificationsclear.go new file mode 100644 index 000000000..48c074504 --- /dev/null +++ b/internal/api/client/notifications/notificationsclear.go @@ -0,0 +1,80 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package notifications + +import ( + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// NotificationsClearPOSTHandler swagger:operation POST /api/v1/notifications clearNotifications +// +// Clear/delete all notifications for currently authorized user. +// +// Will return an empty object `{}` to indicate success. +// +// --- +// tags: +// - notifications +// +// produces: +// - application/json +// +// security: +// - OAuth2 Bearer: +// - read:notifications +// +// responses: +// '200': +// schema: +// type: object +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) NotificationsClearPOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + errWithCode := m.processor.NotificationsClear(c.Request.Context(), authed) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, struct{}{}) +} diff --git a/internal/api/client/notifications/notificationsget.go b/internal/api/client/notifications/notificationsget.go new file mode 100644 index 000000000..09000d02a --- /dev/null +++ b/internal/api/client/notifications/notificationsget.go @@ -0,0 +1,159 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package notifications + +import ( + "fmt" + "net/http" + "strconv" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// NotificationsGETHandler swagger:operation GET /api/v1/notifications notifications +// +// Get notifications for currently authorized user. +// +// The notifications will be returned in descending chronological order (newest first), with sequential IDs (bigger = newer). +// +// The next and previous queries can be parsed from the returned Link header. +// Example: +// +// ``` +// ; rel="next", ; rel="prev" +// ```` +// +// --- +// tags: +// - notifications +// +// produces: +// - application/json +// +// parameters: +// - +// name: limit +// type: integer +// description: Number of notifications to return. +// default: 20 +// in: query +// required: false +// - +// name: exclude_types +// type: array +// items: +// type: string +// description: Array of types of notifications to exclude (follow, favourite, reblog, mention, poll, follow_request) +// in: query +// required: false +// - +// name: max_id +// type: string +// description: >- +// Return only notifications *OLDER* than the given max status ID. +// The status with the specified ID will not be included in the response. +// in: query +// required: false +// - +// name: since_id +// type: string +// description: |- +// Return only notifications *NEWER* than the given since status ID. +// The status with the specified ID will not be included in the response. +// in: query +// required: false +// +// security: +// - OAuth2 Bearer: +// - read:notifications +// +// responses: +// '200': +// headers: +// Link: +// type: string +// description: Links to the next and previous queries. +// name: notifications +// description: Array of notifications. +// schema: +// type: array +// items: +// "$ref": "#/definitions/notification" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) NotificationsGETHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + limit := 20 + limitString := c.Query(LimitKey) + if limitString != "" { + i, err := strconv.ParseInt(limitString, 10, 32) + if err != nil { + err := fmt.Errorf("error parsing %s: %s", LimitKey, err) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + limit = int(i) + } + + maxID := "" + maxIDString := c.Query(MaxIDKey) + if maxIDString != "" { + maxID = maxIDString + } + + sinceID := "" + sinceIDString := c.Query(SinceIDKey) + if sinceIDString != "" { + sinceID = sinceIDString + } + + excludeTypes := c.QueryArray(ExcludeTypesKey) + + resp, errWithCode := m.processor.NotificationsGet(c.Request.Context(), authed, excludeTypes, limit, maxID, sinceID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + if resp.LinkHeader != "" { + c.Header("Link", resp.LinkHeader) + } + c.JSON(http.StatusOK, resp.Items) +} diff --git a/internal/api/client/search/search.go b/internal/api/client/search/search.go index 71370a6d5..bebe0bd61 100644 --- a/internal/api/client/search/search.go +++ b/internal/api/client/search/search.go @@ -21,17 +21,16 @@ package search import ( "net/http" - "github.com/superseriousbusiness/gotosocial/internal/api" + "github.com/gin-gonic/gin" "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" ) const ( - // BasePathV1 is the base path for serving v1 of the search API - BasePathV1 = "/api/v1/search" + // BasePathV1 is the base path for serving v1 of the search API, minus the 'api' prefix + BasePathV1 = "/v1/search" - // BasePathV2 is the base path for serving v2 of the search API - BasePathV2 = "/api/v2/search" + // BasePathV2 is the base path for serving v2 of the search API, minus the 'api' prefix + BasePathV2 = "/v2/search" // AccountIDKey -- If provided, statuses returned will be authored only by this account AccountIDKey = "account_id" @@ -62,21 +61,17 @@ const ( TypeStatuses = "statuses" ) -// Module implements the ClientAPIModule interface for everything related to searching type Module struct { processor processing.Processor } -// New returns a new search module -func New(processor processing.Processor) api.ClientModule { +func New(processor processing.Processor) *Module { return &Module{ processor: processor, } } -// Route attaches all routes from this module to the given router -func (m *Module) Route(r router.Router) error { - r.AttachHandler(http.MethodGet, BasePathV1, m.SearchGETHandler) - r.AttachHandler(http.MethodGet, BasePathV2, m.SearchGETHandler) - return nil +func (m *Module) Route(attachHandler func(method string, path string, f ...gin.HandlerFunc) gin.IRoutes) { + attachHandler(http.MethodGet, BasePathV1, m.SearchGETHandler) + attachHandler(http.MethodGet, BasePathV2, m.SearchGETHandler) } diff --git a/internal/api/client/search/search_test.go b/internal/api/client/search/search_test.go index 11b5b80b2..3cb5e8377 100644 --- a/internal/api/client/search/search_test.go +++ b/internal/api/client/search/search_test.go @@ -84,7 +84,7 @@ func (suite *SearchStandardTestSuite) SetupTest() { suite.sentEmails = make(map[string]string) suite.emailSender = testrig.NewEmailSender("../../../../web/template/", suite.sentEmails) suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator, suite.emailSender, suite.mediaManager, clientWorker, fedWorker) - suite.searchModule = search.New(suite.processor).(*search.Module) + suite.searchModule = search.New(suite.processor) testrig.StandardDBSetup(suite.db, nil) testrig.StandardStorageSetup(suite.storage, "../../../../testrig/media") diff --git a/internal/api/client/search/searchget.go b/internal/api/client/search/searchget.go index 7026213ac..15786e6e3 100644 --- a/internal/api/client/search/searchget.go +++ b/internal/api/client/search/searchget.go @@ -25,8 +25,8 @@ import ( "strconv" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" ) @@ -66,12 +66,12 @@ import ( func (m *Module) SearchGETHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } @@ -82,7 +82,7 @@ func (m *Module) SearchGETHandler(c *gin.Context) { excludeUnreviewed, err = strconv.ParseBool(excludeUnreviewedString) if err != nil { err := fmt.Errorf("error parsing %s: %s", ExcludeUnreviewedKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } } @@ -90,7 +90,7 @@ func (m *Module) SearchGETHandler(c *gin.Context) { query := c.Query(QueryKey) if query == "" { err := errors.New("query parameter q was empty") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } @@ -101,7 +101,7 @@ func (m *Module) SearchGETHandler(c *gin.Context) { resolve, err = strconv.ParseBool(resolveString) if err != nil { err := fmt.Errorf("error parsing %s: %s", ResolveKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } } @@ -112,7 +112,7 @@ func (m *Module) SearchGETHandler(c *gin.Context) { i, err := strconv.ParseInt(limitString, 10, 32) if err != nil { err := fmt.Errorf("error parsing %s: %s", LimitKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } limit = int(i) @@ -130,7 +130,7 @@ func (m *Module) SearchGETHandler(c *gin.Context) { i, err := strconv.ParseInt(offsetString, 10, 32) if err != nil { err := fmt.Errorf("error parsing %s: %s", OffsetKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } offset = int(i) @@ -143,12 +143,12 @@ func (m *Module) SearchGETHandler(c *gin.Context) { following, err = strconv.ParseBool(followingString) if err != nil { err := fmt.Errorf("error parsing %s: %s", FollowingKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } } - searchQuery := &model.SearchQuery{ + searchQuery := &apimodel.SearchQuery{ AccountID: c.Query(AccountIDKey), MaxID: c.Query(MaxIDKey), MinID: c.Query(MinIDKey), @@ -163,7 +163,7 @@ func (m *Module) SearchGETHandler(c *gin.Context) { results, errWithCode := m.processor.SearchGet(c.Request.Context(), authed, searchQuery) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } diff --git a/internal/api/client/status/status.go b/internal/api/client/status/status.go deleted file mode 100644 index dc32ae9b5..000000000 --- a/internal/api/client/status/status.go +++ /dev/null @@ -1,123 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status - -import ( - "net/http" - "strings" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/log" - "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" -) - -const ( - // IDKey is for status UUIDs - IDKey = "id" - // BasePath is the base path for serving the status API - BasePath = "/api/v1/statuses" - // BasePathWithID is just the base path with the ID key in it. - // Use this anywhere you need to know the ID of the status being queried. - BasePathWithID = BasePath + "/:" + IDKey - - // ContextPath is used for fetching context of posts - ContextPath = BasePathWithID + "/context" - - // FavouritedPath is for seeing who's faved a given status - FavouritedPath = BasePathWithID + "/favourited_by" - // FavouritePath is for posting a fave on a status - FavouritePath = BasePathWithID + "/favourite" - // UnfavouritePath is for removing a fave from a status - UnfavouritePath = BasePathWithID + "/unfavourite" - - // RebloggedPath is for seeing who's boosted a given status - RebloggedPath = BasePathWithID + "/reblogged_by" - // ReblogPath is for boosting/reblogging a given status - ReblogPath = BasePathWithID + "/reblog" - // UnreblogPath is for undoing a boost/reblog of a given status - UnreblogPath = BasePathWithID + "/unreblog" - - // BookmarkPath is for creating a bookmark on a given status - BookmarkPath = BasePathWithID + "/bookmark" - // UnbookmarkPath is for removing a bookmark from a given status - UnbookmarkPath = BasePathWithID + "/unbookmark" - - // MutePath is for muting a given status so that notifications will no longer be received about it. - MutePath = BasePathWithID + "/mute" - // UnmutePath is for undoing an existing mute - UnmutePath = BasePathWithID + "/unmute" - - // PinPath is for pinning a status to an account profile so that it's the first thing people see - PinPath = BasePathWithID + "/pin" - // UnpinPath is for undoing a pin and returning a status to the ever-swirling drain of time and entropy - UnpinPath = BasePathWithID + "/unpin" -) - -// Module implements the ClientAPIModule interface for every related to posting/deleting/interacting with statuses -type Module struct { - processor processing.Processor -} - -// New returns a new account module -func New(processor processing.Processor) api.ClientModule { - return &Module{ - processor: processor, - } -} - -// Route attaches all routes from this module to the given router -func (m *Module) Route(r router.Router) error { - r.AttachHandler(http.MethodPost, BasePath, m.StatusCreatePOSTHandler) - r.AttachHandler(http.MethodDelete, BasePathWithID, m.StatusDELETEHandler) - - r.AttachHandler(http.MethodPost, FavouritePath, m.StatusFavePOSTHandler) - r.AttachHandler(http.MethodPost, UnfavouritePath, m.StatusUnfavePOSTHandler) - r.AttachHandler(http.MethodGet, FavouritedPath, m.StatusFavedByGETHandler) - - r.AttachHandler(http.MethodPost, ReblogPath, m.StatusBoostPOSTHandler) - r.AttachHandler(http.MethodPost, UnreblogPath, m.StatusUnboostPOSTHandler) - r.AttachHandler(http.MethodGet, RebloggedPath, m.StatusBoostedByGETHandler) - - r.AttachHandler(http.MethodPost, BookmarkPath, m.StatusBookmarkPOSTHandler) - r.AttachHandler(http.MethodPost, UnbookmarkPath, m.StatusUnbookmarkPOSTHandler) - - r.AttachHandler(http.MethodGet, ContextPath, m.StatusContextGETHandler) - - r.AttachHandler(http.MethodGet, BasePathWithID, m.muxHandler) - return nil -} - -// muxHandler is a little workaround to overcome the limitations of Gin -func (m *Module) muxHandler(c *gin.Context) { - log.Debug("entering mux handler") - ru := c.Request.RequestURI - - if c.Request.Method == http.MethodGet { - switch { - case strings.HasPrefix(ru, ContextPath): - // TODO - case strings.HasPrefix(ru, FavouritedPath): - m.StatusFavedByGETHandler(c) - default: - m.StatusGETHandler(c) - } - } -} diff --git a/internal/api/client/status/status_test.go b/internal/api/client/status/status_test.go deleted file mode 100644 index 7c3f094f2..000000000 --- a/internal/api/client/status/status_test.go +++ /dev/null @@ -1,98 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status_test - -import ( - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/status" - "github.com/superseriousbusiness/gotosocial/internal/concurrency" - "github.com/superseriousbusiness/gotosocial/internal/db" - "github.com/superseriousbusiness/gotosocial/internal/email" - "github.com/superseriousbusiness/gotosocial/internal/federation" - "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" - "github.com/superseriousbusiness/gotosocial/internal/media" - "github.com/superseriousbusiness/gotosocial/internal/messages" - "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/storage" - "github.com/superseriousbusiness/gotosocial/internal/typeutils" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type StatusStandardTestSuite struct { - // standard suite interfaces - suite.Suite - db db.DB - tc typeutils.TypeConverter - mediaManager media.Manager - federator federation.Federator - emailSender email.Sender - processor processing.Processor - storage *storage.Driver - - // standard suite models - testTokens map[string]*gtsmodel.Token - testClients map[string]*gtsmodel.Client - testApplications map[string]*gtsmodel.Application - testUsers map[string]*gtsmodel.User - testAccounts map[string]*gtsmodel.Account - testAttachments map[string]*gtsmodel.MediaAttachment - testStatuses map[string]*gtsmodel.Status - testFollows map[string]*gtsmodel.Follow - - // module being tested - statusModule *status.Module -} - -func (suite *StatusStandardTestSuite) SetupSuite() { - suite.testTokens = testrig.NewTestTokens() - suite.testClients = testrig.NewTestClients() - suite.testApplications = testrig.NewTestApplications() - suite.testUsers = testrig.NewTestUsers() - suite.testAccounts = testrig.NewTestAccounts() - suite.testAttachments = testrig.NewTestAttachments() - suite.testStatuses = testrig.NewTestStatuses() - suite.testFollows = testrig.NewTestFollows() -} - -func (suite *StatusStandardTestSuite) SetupTest() { - testrig.InitTestConfig() - testrig.InitTestLog() - - suite.db = testrig.NewTestDB() - suite.tc = testrig.NewTestTypeConverter(suite.db) - suite.storage = testrig.NewInMemoryStorage() - testrig.StandardDBSetup(suite.db, nil) - testrig.StandardStorageSetup(suite.storage, "../../../../testrig/media") - - fedWorker := concurrency.NewWorkerPool[messages.FromFederator](-1, -1) - clientWorker := concurrency.NewWorkerPool[messages.FromClientAPI](-1, -1) - - suite.mediaManager = testrig.NewTestMediaManager(suite.db, suite.storage) - suite.federator = testrig.NewTestFederator(suite.db, testrig.NewTestTransportController(testrig.NewMockHTTPClient(nil, "../../../../testrig/media"), suite.db, fedWorker), suite.storage, suite.mediaManager, fedWorker) - suite.emailSender = testrig.NewEmailSender("../../../../web/template/", nil) - suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator, suite.emailSender, suite.mediaManager, clientWorker, fedWorker) - suite.statusModule = status.New(suite.processor).(*status.Module) - - suite.NoError(suite.processor.Start()) -} - -func (suite *StatusStandardTestSuite) TearDownTest() { - testrig.StandardDBTeardown(suite.db) - testrig.StandardStorageTeardown(suite.storage) -} diff --git a/internal/api/client/status/statusbookmark.go b/internal/api/client/status/statusbookmark.go deleted file mode 100644 index 983becd72..000000000 --- a/internal/api/client/status/statusbookmark.go +++ /dev/null @@ -1,98 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// StatusBookmarkPOSTHandler swagger:operation POST /api/v1/statuses/{id}/bookmark statusBookmark -// -// Bookmark status with the given ID. -// -// --- -// tags: -// - statuses -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: string -// description: Target status ID. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - write:statuses -// -// responses: -// '200': -// name: status -// description: The status. -// schema: -// "$ref": "#/definitions/status" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '403': -// description: forbidden -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) StatusBookmarkPOSTHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetStatusID := c.Param(IDKey) - if targetStatusID == "" { - err := errors.New("no status id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - apiStatus, errWithCode := m.processor.StatusBookmark(c.Request.Context(), authed, targetStatusID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, apiStatus) -} diff --git a/internal/api/client/status/statusbookmark_test.go b/internal/api/client/status/statusbookmark_test.go deleted file mode 100644 index d3da4f297..000000000 --- a/internal/api/client/status/statusbookmark_test.go +++ /dev/null @@ -1,83 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status_test - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/status" - "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type StatusBookmarkTestSuite struct { - StatusStandardTestSuite -} - -func (suite *StatusBookmarkTestSuite) TestPostBookmark() { - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - - targetStatus := suite.testStatuses["admin_account_status_1"] - - // setup - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(status.BookmarkPath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - - // normally the router would populate these params from the path values, - // but because we're calling the function directly, we need to set them manually. - ctx.Params = gin.Params{ - gin.Param{ - Key: status.IDKey, - Value: targetStatus.ID, - }, - } - - suite.statusModule.StatusBookmarkPOSTHandler(ctx) - - // check response - suite.EqualValues(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - statusReply := &model.Status{} - err = json.Unmarshal(b, statusReply) - suite.NoError(err) - - suite.True(statusReply.Bookmarked) -} - -func TestStatusBookmarkTestSuite(t *testing.T) { - suite.Run(t, new(StatusBookmarkTestSuite)) -} diff --git a/internal/api/client/status/statusboost.go b/internal/api/client/status/statusboost.go deleted file mode 100644 index d43bedd6c..000000000 --- a/internal/api/client/status/statusboost.go +++ /dev/null @@ -1,101 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// StatusBoostPOSTHandler swagger:operation POST /api/v1/statuses/{id}/reblog statusReblog -// -// Reblog/boost status with the given ID. -// -// If the target status is rebloggable/boostable, it will be shared with your followers. -// This is equivalent to an ActivityPub 'Announce' activity. -// -// --- -// tags: -// - statuses -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: string -// description: Target status ID. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - write:statuses -// -// responses: -// '200': -// name: status -// description: The boost of the status. -// schema: -// "$ref": "#/definitions/status" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '403': -// description: forbidden -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) StatusBoostPOSTHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetStatusID := c.Param(IDKey) - if targetStatusID == "" { - err := errors.New("no status id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - apiStatus, errWithCode := m.processor.StatusBoost(c.Request.Context(), authed, targetStatusID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, apiStatus) -} diff --git a/internal/api/client/status/statusboost_test.go b/internal/api/client/status/statusboost_test.go deleted file mode 100644 index 5b4b1b3cd..000000000 --- a/internal/api/client/status/statusboost_test.go +++ /dev/null @@ -1,247 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status_test - -import ( - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/status" - "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type StatusBoostTestSuite struct { - StatusStandardTestSuite -} - -func (suite *StatusBoostTestSuite) TestPostBoost() { - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - - targetStatus := suite.testStatuses["admin_account_status_1"] - - // setup - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(status.ReblogPath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - - // normally the router would populate these params from the path values, - // but because we're calling the function directly, we need to set them manually. - ctx.Params = gin.Params{ - gin.Param{ - Key: status.IDKey, - Value: targetStatus.ID, - }, - } - - suite.statusModule.StatusBoostPOSTHandler(ctx) - - // check response - suite.EqualValues(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - statusReply := &model.Status{} - err = json.Unmarshal(b, statusReply) - suite.NoError(err) - - suite.False(statusReply.Sensitive) - suite.Equal(model.VisibilityPublic, statusReply.Visibility) - - suite.Equal(targetStatus.ContentWarning, statusReply.SpoilerText) - suite.Equal(targetStatus.Content, statusReply.Content) - suite.Equal("the_mighty_zork", statusReply.Account.Username) - suite.Len(statusReply.MediaAttachments, 0) - suite.Len(statusReply.Mentions, 0) - suite.Len(statusReply.Emojis, 0) - suite.Len(statusReply.Tags, 0) - - suite.NotNil(statusReply.Application) - suite.Equal("really cool gts application", statusReply.Application.Name) - - suite.NotNil(statusReply.Reblog) - suite.Equal(1, statusReply.Reblog.ReblogsCount) - suite.Equal(1, statusReply.Reblog.FavouritesCount) - suite.Equal(targetStatus.Content, statusReply.Reblog.Content) - suite.Equal(targetStatus.ContentWarning, statusReply.Reblog.SpoilerText) - suite.Equal(targetStatus.AccountID, statusReply.Reblog.Account.ID) - suite.Len(statusReply.Reblog.MediaAttachments, 1) - suite.Len(statusReply.Reblog.Tags, 1) - suite.Len(statusReply.Reblog.Emojis, 1) - suite.Equal("superseriousbusiness", statusReply.Reblog.Application.Name) -} - -func (suite *StatusBoostTestSuite) TestPostBoostOwnFollowersOnly() { - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - - testStatus := suite.testStatuses["local_account_1_status_5"] - testAccount := suite.testAccounts["local_account_1"] - testUser := suite.testUsers["local_account_1"] - - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, testUser) - ctx.Set(oauth.SessionAuthorizedAccount, testAccount) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(status.ReblogPath, ":id", testStatus.ID, 1)), nil) - ctx.Request.Header.Set("accept", "application/json") - - ctx.Params = gin.Params{ - gin.Param{ - Key: status.IDKey, - Value: testStatus.ID, - }, - } - - suite.statusModule.StatusBoostPOSTHandler(ctx) - - // check response - suite.EqualValues(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - responseStatus := &model.Status{} - err = json.Unmarshal(b, responseStatus) - suite.NoError(err) - - suite.False(responseStatus.Sensitive) - suite.Equal(suite.tc.VisToAPIVis(context.Background(), testStatus.Visibility), responseStatus.Visibility) - - suite.Equal(testStatus.ContentWarning, responseStatus.SpoilerText) - suite.Equal(testStatus.Content, responseStatus.Content) - suite.Equal("the_mighty_zork", responseStatus.Account.Username) - suite.Len(responseStatus.MediaAttachments, 0) - suite.Len(responseStatus.Mentions, 0) - suite.Len(responseStatus.Emojis, 0) - suite.Len(responseStatus.Tags, 0) - - suite.NotNil(responseStatus.Application) - suite.Equal("really cool gts application", responseStatus.Application.Name) - - suite.NotNil(responseStatus.Reblog) - suite.Equal(1, responseStatus.Reblog.ReblogsCount) - suite.Equal(0, responseStatus.Reblog.FavouritesCount) - suite.Equal(testStatus.Content, responseStatus.Reblog.Content) - suite.Equal(testStatus.ContentWarning, responseStatus.Reblog.SpoilerText) - suite.Equal(testStatus.AccountID, responseStatus.Reblog.Account.ID) - suite.Equal(suite.tc.VisToAPIVis(context.Background(), testStatus.Visibility), responseStatus.Reblog.Visibility) - suite.Empty(responseStatus.Reblog.MediaAttachments) - suite.Empty(responseStatus.Reblog.Tags) - suite.Empty(responseStatus.Reblog.Emojis) - suite.Equal("really cool gts application", responseStatus.Reblog.Application.Name) -} - -// try to boost a status that's not boostable -func (suite *StatusBoostTestSuite) TestPostUnboostable() { - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - - targetStatus := suite.testStatuses["local_account_2_status_4"] - - // setup - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(status.ReblogPath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - - // normally the router would populate these params from the path values, - // but because we're calling the function directly, we need to set them manually. - ctx.Params = gin.Params{ - gin.Param{ - Key: status.IDKey, - Value: targetStatus.ID, - }, - } - - suite.statusModule.StatusBoostPOSTHandler(ctx) - - // check response - suite.Equal(http.StatusForbidden, recorder.Code) // we 403 unboostable statuses - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - suite.Equal(`{"error":"Forbidden"}`, string(b)) -} - -// try to boost a status that's not visible to the user -func (suite *StatusBoostTestSuite) TestPostNotVisible() { - // stop local_account_2 following zork - err := suite.db.DeleteByID(context.Background(), suite.testFollows["local_account_2_local_account_1"].ID, >smodel.Follow{}) - suite.NoError(err) - - t := suite.testTokens["local_account_2"] - oauthToken := oauth.DBTokenToToken(t) - - targetStatus := suite.testStatuses["local_account_1_status_3"] // this is a mutual only status and these accounts aren't mutuals - - // setup - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_2"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_2"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(status.ReblogPath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - - // normally the router would populate these params from the path values, - // but because we're calling the function directly, we need to set them manually. - ctx.Params = gin.Params{ - gin.Param{ - Key: status.IDKey, - Value: targetStatus.ID, - }, - } - - suite.statusModule.StatusBoostPOSTHandler(ctx) - - // check response - suite.Equal(http.StatusNotFound, recorder.Code) // we 404 statuses that aren't visible -} - -func TestStatusBoostTestSuite(t *testing.T) { - suite.Run(t, new(StatusBoostTestSuite)) -} diff --git a/internal/api/client/status/statusboostedby.go b/internal/api/client/status/statusboostedby.go deleted file mode 100644 index 4a175f6e9..000000000 --- a/internal/api/client/status/statusboostedby.go +++ /dev/null @@ -1,89 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// StatusBoostedByGETHandler swagger:operation GET /api/v1/statuses/{id}/reblogged_by statusBoostedBy -// -// View accounts that have reblogged/boosted the target status. -// -// --- -// tags: -// - statuses -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: string -// description: Target status ID. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - read:accounts -// -// responses: -// '200': -// schema: -// type: array -// items: -// "$ref": "#/definitions/account" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '403': -// description: forbidden -// '404': -// description: not found -func (m *Module) StatusBoostedByGETHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - targetStatusID := c.Param(IDKey) - if targetStatusID == "" { - err := errors.New("no status id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - apiAccounts, errWithCode := m.processor.StatusBoostedBy(c.Request.Context(), authed, targetStatusID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, apiAccounts) -} diff --git a/internal/api/client/status/statusboostedby_test.go b/internal/api/client/status/statusboostedby_test.go deleted file mode 100644 index 0d7c9f7ab..000000000 --- a/internal/api/client/status/statusboostedby_test.go +++ /dev/null @@ -1,112 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status_test - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/status" - "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type StatusBoostedByTestSuite struct { - StatusStandardTestSuite -} - -func (suite *StatusBoostedByTestSuite) TestRebloggedByOK() { - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - targetStatus := suite.testStatuses["local_account_1_status_1"] - - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodGet, fmt.Sprintf("http://localhost:8080%s", strings.Replace(status.RebloggedPath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - ctx.AddParam("id", targetStatus.ID) - - suite.statusModule.StatusBoostedByGETHandler(ctx) - - suite.EqualValues(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - accounts := []*gtsmodel.Account{} - err = json.Unmarshal(b, &accounts) - suite.NoError(err) - - if !suite.Len(accounts, 1) { - suite.FailNow("should have had 1 account") - } - - suite.Equal(accounts[0].ID, suite.testAccounts["admin_account"].ID) -} - -func (suite *StatusBoostedByTestSuite) TestRebloggedByUseBoostWrapperID() { - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - targetStatus := suite.testStatuses["admin_account_status_4"] // admin_account_status_4 is a boost of local_account_1_status_1 - - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodGet, fmt.Sprintf("http://localhost:8080%s", strings.Replace(status.RebloggedPath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - ctx.AddParam("id", targetStatus.ID) - - suite.statusModule.StatusBoostedByGETHandler(ctx) - - suite.EqualValues(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - accounts := []*gtsmodel.Account{} - err = json.Unmarshal(b, &accounts) - suite.NoError(err) - - if !suite.Len(accounts, 1) { - suite.FailNow("should have had 1 account") - } - - suite.Equal(accounts[0].ID, suite.testAccounts["admin_account"].ID) -} - -func TestStatusBoostedByTestSuite(t *testing.T) { - suite.Run(t, new(StatusBoostedByTestSuite)) -} diff --git a/internal/api/client/status/statuscontext.go b/internal/api/client/status/statuscontext.go deleted file mode 100644 index 632a151d5..000000000 --- a/internal/api/client/status/statuscontext.go +++ /dev/null @@ -1,100 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// StatusContextGETHandler swagger:operation GET /api/v1/statuses/{id}/context statusContext -// -// Return ancestors and descendants of the given status. -// -// The returned statuses will be ordered in a thread structure, so they are suitable to be displayed in the order in which they were returned. -// -// --- -// tags: -// - statuses -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: string -// description: Target status ID. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - read:statuses -// -// responses: -// '200': -// name: statuses -// description: Status context object. -// schema: -// "$ref": "#/definitions/statusContext" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '403': -// description: forbidden -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) StatusContextGETHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetStatusID := c.Param(IDKey) - if targetStatusID == "" { - err := errors.New("no status id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - statusContext, errWithCode := m.processor.StatusGetContext(c.Request.Context(), authed, targetStatusID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, statusContext) -} diff --git a/internal/api/client/status/statuscreate.go b/internal/api/client/status/statuscreate.go deleted file mode 100644 index c1427411d..000000000 --- a/internal/api/client/status/statuscreate.go +++ /dev/null @@ -1,172 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status - -import ( - "errors" - "fmt" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/config" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/internal/validate" -) - -// StatusCreatePOSTHandler swagger:operation POST /api/v1/statuses statusCreate -// -// Create a new status. -// -// The parameters can also be given in the body of the request, as JSON, if the content-type is set to 'application/json'. -// The parameters can also be given in the body of the request, as XML, if the content-type is set to 'application/xml'. -// -// --- -// tags: -// - statuses -// -// consumes: -// - application/json -// - application/xml -// - application/x-www-form-urlencoded -// -// produces: -// - application/json -// -// security: -// - OAuth2 Bearer: -// - write:statuses -// -// responses: -// '200': -// description: "The newly created status." -// schema: -// "$ref": "#/definitions/status" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '403': -// description: forbidden -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) StatusCreatePOSTHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - form := &model.AdvancedStatusCreateForm{} - if err := c.ShouldBind(form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - // DO NOT COMMIT THIS UNCOMMENTED, IT WILL CAUSE MASS CHAOS. - // this is being left in as an ode to kim's shitposting. - // - // user := authed.Account.DisplayName - // if user == "" { - // user = authed.Account.Username - // } - // form.Status += "\n\nsent from " + user + "'s iphone\n" - - if err := validateCreateStatus(form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - apiStatus, errWithCode := m.processor.StatusCreate(c.Request.Context(), authed, form) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, apiStatus) -} - -func validateCreateStatus(form *model.AdvancedStatusCreateForm) error { - hasStatus := form.Status != "" - hasMedia := len(form.MediaIDs) != 0 - hasPoll := form.Poll != nil - - if !hasStatus && !hasMedia && !hasPoll { - return errors.New("no status, media, or poll provided") - } - - if hasMedia && hasPoll { - return errors.New("can't post media + poll in same status") - } - - maxChars := config.GetStatusesMaxChars() - maxMediaFiles := config.GetStatusesMediaMaxFiles() - maxPollOptions := config.GetStatusesPollMaxOptions() - maxPollChars := config.GetStatusesPollOptionMaxChars() - maxCwChars := config.GetStatusesCWMaxChars() - - if form.Status != "" { - if length := len([]rune(form.Status)); length > maxChars { - return fmt.Errorf("status too long, %d characters provided but limit is %d", length, maxChars) - } - } - - if len(form.MediaIDs) > maxMediaFiles { - return fmt.Errorf("too many media files attached to status, %d attached but limit is %d", len(form.MediaIDs), maxMediaFiles) - } - - if form.Poll != nil { - if form.Poll.Options == nil { - return errors.New("poll with no options") - } - if len(form.Poll.Options) > maxPollOptions { - return fmt.Errorf("too many poll options provided, %d provided but limit is %d", len(form.Poll.Options), maxPollOptions) - } - for _, p := range form.Poll.Options { - if length := len([]rune(p)); length > maxPollChars { - return fmt.Errorf("poll option too long, %d characters provided but limit is %d", length, maxPollChars) - } - } - } - - if form.SpoilerText != "" { - if length := len([]rune(form.SpoilerText)); length > maxCwChars { - return fmt.Errorf("content-warning/spoilertext too long, %d characters provided but limit is %d", length, maxCwChars) - } - } - - if form.Language != "" { - if err := validate.Language(form.Language); err != nil { - return err - } - } - - return nil -} diff --git a/internal/api/client/status/statuscreate_test.go b/internal/api/client/status/statuscreate_test.go deleted file mode 100644 index c143489f3..000000000 --- a/internal/api/client/status/statuscreate_test.go +++ /dev/null @@ -1,398 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status_test - -import ( - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "net/url" - "testing" - - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/status" - "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/db" - "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type StatusCreateTestSuite struct { - StatusStandardTestSuite -} - -const ( - statusWithLinksAndTags = "#test alright, should be able to post #links with fragments in them now, let's see........\n\nhttps://docs.gotosocial.org/en/latest/user_guide/posts/#links\n\n#gotosocial\n\n(tobi remember to pull the docker image challenge)" - statusMarkdown = "# Title\n\n## Smaller title\n\nThis is a post written in [markdown](https://www.markdownguide.org/)\n\n" - statusMarkdownExpected = "

Title

Smaller title

This is a post written in markdown

" -) - -// Post a new status with some custom visibility settings -func (suite *StatusCreateTestSuite) TestPostNewStatus() { - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - - // setup - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", status.BasePath), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - ctx.Request.Form = url.Values{ - "status": {"this is a brand new status! #helloworld"}, - "spoiler_text": {"hello hello"}, - "sensitive": {"true"}, - "visibility": {string(model.VisibilityMutualsOnly)}, - "likeable": {"false"}, - "replyable": {"false"}, - "federated": {"false"}, - } - suite.statusModule.StatusCreatePOSTHandler(ctx) - - // check response - - // 1. we should have OK from our call to the function - suite.EqualValues(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - statusReply := &model.Status{} - err = json.Unmarshal(b, statusReply) - suite.NoError(err) - - suite.Equal("hello hello", statusReply.SpoilerText) - suite.Equal("

this is a brand new status! #helloworld

", statusReply.Content) - suite.True(statusReply.Sensitive) - suite.Equal(model.VisibilityPrivate, statusReply.Visibility) // even though we set this status to mutuals only, it should serialize to private, because the mastodon api has no idea about mutuals_only - suite.Len(statusReply.Tags, 1) - suite.Equal(model.Tag{ - Name: "helloworld", - URL: "http://localhost:8080/tags/helloworld", - }, statusReply.Tags[0]) - - gtsTag := >smodel.Tag{} - err = suite.db.GetWhere(context.Background(), []db.Where{{Key: "name", Value: "helloworld"}}, gtsTag) - suite.NoError(err) - suite.Equal(statusReply.Account.ID, gtsTag.FirstSeenFromAccountID) -} - -func (suite *StatusCreateTestSuite) TestPostNewStatusMarkdown() { - // set default post language of account 1 to markdown - testAccount := suite.testAccounts["local_account_1"] - testAccount.StatusFormat = "markdown" - a := testAccount - - err := suite.db.UpdateAccount(context.Background(), a) - if err != nil { - suite.FailNow(err.Error()) - } - suite.Equal(a.StatusFormat, "markdown") - - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, a) - - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", status.BasePath), nil) - ctx.Request.Header.Set("accept", "application/json") - ctx.Request.Form = url.Values{ - "status": {statusMarkdown}, - "visibility": {string(model.VisibilityPublic)}, - } - suite.statusModule.StatusCreatePOSTHandler(ctx) - - suite.EqualValues(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - statusReply := &model.Status{} - err = json.Unmarshal(b, statusReply) - suite.NoError(err) - - suite.Equal(statusMarkdownExpected, statusReply.Content) -} - -// mention an account that is not yet known to the instance -- it should be looked up and put in the db -func (suite *StatusCreateTestSuite) TestMentionUnknownAccount() { - // first remove remote account 1 from the database so it gets looked up again - remoteAccount := suite.testAccounts["remote_account_1"] - err := suite.db.DeleteAccount(context.Background(), remoteAccount.ID) - suite.NoError(err) - - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - - // setup - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", status.BasePath), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - ctx.Request.Form = url.Values{ - "status": {"hello @brand_new_person@unknown-instance.com"}, - "visibility": {string(model.VisibilityPublic)}, - } - suite.statusModule.StatusCreatePOSTHandler(ctx) - - suite.EqualValues(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - statusReply := &model.Status{} - err = json.Unmarshal(b, statusReply) - suite.NoError(err) - - // if the status is properly formatted, that means the account has been put in the db - suite.Equal(`

hello @brand_new_person

`, statusReply.Content) - suite.Equal(model.VisibilityPublic, statusReply.Visibility) -} - -func (suite *StatusCreateTestSuite) TestPostAnotherNewStatus() { - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - - // setup - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", status.BasePath), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - ctx.Request.Form = url.Values{ - "status": {statusWithLinksAndTags}, - } - suite.statusModule.StatusCreatePOSTHandler(ctx) - - // check response - - // 1. we should have OK from our call to the function - suite.EqualValues(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - statusReply := &model.Status{} - err = json.Unmarshal(b, statusReply) - suite.NoError(err) - - suite.Equal("

#test alright, should be able to post #links with fragments in them now, let's see........

docs.gotosocial.org/en/latest/user_guide/posts/#links

#gotosocial

(tobi remember to pull the docker image challenge)

", statusReply.Content) -} - -func (suite *StatusCreateTestSuite) TestPostNewStatusWithEmoji() { - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - - // setup - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", status.BasePath), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - ctx.Request.Form = url.Values{ - "status": {"here is a rainbow emoji a few times! :rainbow: :rainbow: :rainbow: \n here's an emoji that isn't in the db: :test_emoji: "}, - } - suite.statusModule.StatusCreatePOSTHandler(ctx) - - suite.EqualValues(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - statusReply := &model.Status{} - err = json.Unmarshal(b, statusReply) - suite.NoError(err) - - suite.Equal("", statusReply.SpoilerText) - suite.Equal("

here is a rainbow emoji a few times! :rainbow: :rainbow: :rainbow:
here's an emoji that isn't in the db: :test_emoji:

", statusReply.Content) - - suite.Len(statusReply.Emojis, 1) - apiEmoji := statusReply.Emojis[0] - gtsEmoji := testrig.NewTestEmojis()["rainbow"] - - suite.Equal(gtsEmoji.Shortcode, apiEmoji.Shortcode) - suite.Equal(gtsEmoji.ImageURL, apiEmoji.URL) - suite.Equal(gtsEmoji.ImageStaticURL, apiEmoji.StaticURL) -} - -// Try to reply to a status that doesn't exist -func (suite *StatusCreateTestSuite) TestReplyToNonexistentStatus() { - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - - // setup - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", status.BasePath), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - ctx.Request.Form = url.Values{ - "status": {"this is a reply to a status that doesn't exist"}, - "spoiler_text": {"don't open cuz it won't work"}, - "in_reply_to_id": {"3759e7ef-8ee1-4c0c-86f6-8b70b9ad3d50"}, - } - suite.statusModule.StatusCreatePOSTHandler(ctx) - - // check response - - suite.EqualValues(http.StatusBadRequest, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - suite.Equal(`{"error":"Bad Request: status with id 3759e7ef-8ee1-4c0c-86f6-8b70b9ad3d50 not replyable because it doesn't exist"}`, string(b)) -} - -// Post a reply to the status of a local user that allows replies. -func (suite *StatusCreateTestSuite) TestReplyToLocalStatus() { - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - - // setup - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", status.BasePath), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - ctx.Request.Form = url.Values{ - "status": {fmt.Sprintf("hello @%s this reply should work!", testrig.NewTestAccounts()["local_account_2"].Username)}, - "in_reply_to_id": {testrig.NewTestStatuses()["local_account_2_status_1"].ID}, - } - suite.statusModule.StatusCreatePOSTHandler(ctx) - - // check response - suite.EqualValues(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - statusReply := &model.Status{} - err = json.Unmarshal(b, statusReply) - suite.NoError(err) - - suite.Equal("", statusReply.SpoilerText) - suite.Equal(fmt.Sprintf("

hello @%s this reply should work!

", testrig.NewTestAccounts()["local_account_2"].Username, testrig.NewTestAccounts()["local_account_2"].Username), statusReply.Content) - suite.False(statusReply.Sensitive) - suite.Equal(model.VisibilityPublic, statusReply.Visibility) - suite.Equal(testrig.NewTestStatuses()["local_account_2_status_1"].ID, *statusReply.InReplyToID) - suite.Equal(testrig.NewTestAccounts()["local_account_2"].ID, *statusReply.InReplyToAccountID) - suite.Len(statusReply.Mentions, 1) -} - -// Take a media file which is currently not associated with a status, and attach it to a new status. -func (suite *StatusCreateTestSuite) TestAttachNewMediaSuccess() { - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - - attachment := suite.testAttachments["local_account_1_unattached_1"] - - // setup - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", status.BasePath), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - ctx.Request.Form = url.Values{ - "status": {"here's an image attachment"}, - "media_ids[]": {attachment.ID}, - } - suite.statusModule.StatusCreatePOSTHandler(ctx) - - // check response - suite.EqualValues(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - statusResponse := &model.Status{} - err = json.Unmarshal(b, statusResponse) - suite.NoError(err) - - suite.Equal("", statusResponse.SpoilerText) - suite.Equal("

here's an image attachment

", statusResponse.Content) - suite.False(statusResponse.Sensitive) - suite.Equal(model.VisibilityPublic, statusResponse.Visibility) - - // there should be one media attachment - suite.Len(statusResponse.MediaAttachments, 1) - - // get the updated media attachment from the database - gtsAttachment, err := suite.db.GetAttachmentByID(context.Background(), statusResponse.MediaAttachments[0].ID) - suite.NoError(err) - - // convert it to a api attachment - gtsAttachmentAsapi, err := suite.tc.AttachmentToAPIAttachment(context.Background(), gtsAttachment) - suite.NoError(err) - - // compare it with what we have now - suite.EqualValues(statusResponse.MediaAttachments[0], gtsAttachmentAsapi) - - // the status id of the attachment should now be set to the id of the status we just created - suite.Equal(statusResponse.ID, gtsAttachment.StatusID) -} - -func TestStatusCreateTestSuite(t *testing.T) { - suite.Run(t, new(StatusCreateTestSuite)) -} diff --git a/internal/api/client/status/statusdelete.go b/internal/api/client/status/statusdelete.go deleted file mode 100644 index b37dd5f14..000000000 --- a/internal/api/client/status/statusdelete.go +++ /dev/null @@ -1,100 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// StatusDELETEHandler swagger:operation DELETE /api/v1/statuses/{id} statusDelete -// -// Delete status with the given ID. The status must belong to you. -// -// The deleted status will be returned in the response. The `text` field will contain the original text of the status as it was submitted. -// This is useful when doing a 'delete and redraft' type operation. -// -// --- -// tags: -// - statuses -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: string -// description: Target status ID. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - write:statuses -// -// responses: -// '200': -// description: "The status that was just deleted." -// schema: -// "$ref": "#/definitions/status" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '403': -// description: forbidden -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) StatusDELETEHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetStatusID := c.Param(IDKey) - if targetStatusID == "" { - err := errors.New("no status id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - apiStatus, errWithCode := m.processor.StatusDelete(c.Request.Context(), authed, targetStatusID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, apiStatus) -} diff --git a/internal/api/client/status/statusdelete_test.go b/internal/api/client/status/statusdelete_test.go deleted file mode 100644 index f97a13eec..000000000 --- a/internal/api/client/status/statusdelete_test.go +++ /dev/null @@ -1,91 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status_test - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/status" - "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/db" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type StatusDeleteTestSuite struct { - StatusStandardTestSuite -} - -func (suite *StatusDeleteTestSuite) TestPostDelete() { - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - targetStatus := suite.testStatuses["local_account_1_status_1"] - - // setup - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodDelete, fmt.Sprintf("http://localhost:8080%s", strings.Replace(status.BasePathWithID, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - - // normally the router would populate these params from the path values, - // but because we're calling the function directly, we need to set them manually. - ctx.Params = gin.Params{ - gin.Param{ - Key: status.IDKey, - Value: targetStatus.ID, - }, - } - - suite.statusModule.StatusDELETEHandler(ctx) - - // check response - suite.EqualValues(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - statusReply := &model.Status{} - err = json.Unmarshal(b, statusReply) - suite.NoError(err) - suite.NotNil(statusReply) - - if !testrig.WaitFor(func() bool { - _, err := suite.db.GetStatusByID(ctx, targetStatus.ID) - return errors.Is(err, db.ErrNoEntries) - }) { - suite.FailNow("time out waiting for status to be deleted") - } - -} - -func TestStatusDeleteTestSuite(t *testing.T) { - suite.Run(t, new(StatusDeleteTestSuite)) -} diff --git a/internal/api/client/status/statusfave.go b/internal/api/client/status/statusfave.go deleted file mode 100644 index 3117e7ef2..000000000 --- a/internal/api/client/status/statusfave.go +++ /dev/null @@ -1,97 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// StatusFavePOSTHandler swagger:operation POST /api/v1/statuses/{id}/favourite statusFave -// -// Star/like/favourite the given status, if permitted. -// -// --- -// tags: -// - statuses -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: string -// description: Target status ID. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - write:statuses -// -// responses: -// '200': -// description: "The newly faved status." -// schema: -// "$ref": "#/definitions/status" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '403': -// description: forbidden -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) StatusFavePOSTHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetStatusID := c.Param(IDKey) - if targetStatusID == "" { - err := errors.New("no status id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - apiStatus, errWithCode := m.processor.StatusFave(c.Request.Context(), authed, targetStatusID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, apiStatus) -} diff --git a/internal/api/client/status/statusfave_test.go b/internal/api/client/status/statusfave_test.go deleted file mode 100644 index da5d2a48a..000000000 --- a/internal/api/client/status/statusfave_test.go +++ /dev/null @@ -1,131 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status_test - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/status" - "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type StatusFaveTestSuite struct { - StatusStandardTestSuite -} - -// fave a status -func (suite *StatusFaveTestSuite) TestPostFave() { - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - - targetStatus := suite.testStatuses["admin_account_status_2"] - - // setup - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(status.FavouritePath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - - // normally the router would populate these params from the path values, - // but because we're calling the function directly, we need to set them manually. - ctx.Params = gin.Params{ - gin.Param{ - Key: status.IDKey, - Value: targetStatus.ID, - }, - } - - suite.statusModule.StatusFavePOSTHandler(ctx) - - // check response - suite.EqualValues(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - - statusReply := &model.Status{} - err = json.Unmarshal(b, statusReply) - assert.NoError(suite.T(), err) - - assert.Equal(suite.T(), targetStatus.ContentWarning, statusReply.SpoilerText) - assert.Equal(suite.T(), targetStatus.Content, statusReply.Content) - assert.True(suite.T(), statusReply.Sensitive) - assert.Equal(suite.T(), model.VisibilityPublic, statusReply.Visibility) - assert.True(suite.T(), statusReply.Favourited) - assert.Equal(suite.T(), 1, statusReply.FavouritesCount) -} - -// try to fave a status that's not faveable -func (suite *StatusFaveTestSuite) TestPostUnfaveable() { - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - - targetStatus := suite.testStatuses["local_account_2_status_3"] // this one is unlikeable and unreplyable - - // setup - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(status.FavouritePath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - - // normally the router would populate these params from the path values, - // but because we're calling the function directly, we need to set them manually. - ctx.Params = gin.Params{ - gin.Param{ - Key: status.IDKey, - Value: targetStatus.ID, - }, - } - - suite.statusModule.StatusFavePOSTHandler(ctx) - - // check response - suite.EqualValues(http.StatusForbidden, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - assert.Equal(suite.T(), `{"error":"Forbidden"}`, string(b)) -} - -func TestStatusFaveTestSuite(t *testing.T) { - suite.Run(t, new(StatusFaveTestSuite)) -} diff --git a/internal/api/client/status/statusfavedby.go b/internal/api/client/status/statusfavedby.go deleted file mode 100644 index 20ef86ded..000000000 --- a/internal/api/client/status/statusfavedby.go +++ /dev/null @@ -1,98 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// StatusFavedByGETHandler swagger:operation GET /api/v1/statuses/{id}/favourited_by statusFavedBy -// -// View accounts that have faved/starred/liked the target status. -// -// --- -// tags: -// - statuses -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: string -// description: Target status ID. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - read:accounts -// -// responses: -// '200': -// schema: -// type: array -// items: -// "$ref": "#/definitions/account" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '403': -// description: forbidden -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) StatusFavedByGETHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetStatusID := c.Param(IDKey) - if targetStatusID == "" { - err := errors.New("no status id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - apiAccounts, errWithCode := m.processor.StatusFavedBy(c.Request.Context(), authed, targetStatusID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, apiAccounts) -} diff --git a/internal/api/client/status/statusfavedby_test.go b/internal/api/client/status/statusfavedby_test.go deleted file mode 100644 index e704fa724..000000000 --- a/internal/api/client/status/statusfavedby_test.go +++ /dev/null @@ -1,88 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status_test - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/status" - "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type StatusFavedByTestSuite struct { - StatusStandardTestSuite -} - -func (suite *StatusFavedByTestSuite) TestGetFavedBy() { - t := suite.testTokens["local_account_2"] - oauthToken := oauth.DBTokenToToken(t) - - targetStatus := suite.testStatuses["admin_account_status_1"] // this status is faved by local_account_1 - - // setup - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_2"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_2"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_2"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(status.FavouritedPath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - - // normally the router would populate these params from the path values, - // but because we're calling the function directly, we need to set them manually. - ctx.Params = gin.Params{ - gin.Param{ - Key: status.IDKey, - Value: targetStatus.ID, - }, - } - - suite.statusModule.StatusFavedByGETHandler(ctx) - - // check response - suite.EqualValues(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - - accts := []model.Account{} - err = json.Unmarshal(b, &accts) - assert.NoError(suite.T(), err) - - assert.Len(suite.T(), accts, 1) - assert.Equal(suite.T(), "the_mighty_zork", accts[0].Username) -} - -func TestStatusFavedByTestSuite(t *testing.T) { - suite.Run(t, new(StatusFavedByTestSuite)) -} diff --git a/internal/api/client/status/statusget.go b/internal/api/client/status/statusget.go deleted file mode 100644 index a0d0e913c..000000000 --- a/internal/api/client/status/statusget.go +++ /dev/null @@ -1,97 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// StatusGETHandler swagger:operation GET /api/v1/statuses/{id} statusGet -// -// View status with the given ID. -// -// --- -// tags: -// - statuses -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: string -// description: Target status ID. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - read:statuses -// -// responses: -// '200': -// description: "The requested status." -// schema: -// "$ref": "#/definitions/status" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '403': -// description: forbidden -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) StatusGETHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetStatusID := c.Param(IDKey) - if targetStatusID == "" { - err := errors.New("no status id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - apiStatus, errWithCode := m.processor.StatusGet(c.Request.Context(), authed, targetStatusID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, apiStatus) -} diff --git a/internal/api/client/status/statusget_test.go b/internal/api/client/status/statusget_test.go deleted file mode 100644 index d11c9b587..000000000 --- a/internal/api/client/status/statusget_test.go +++ /dev/null @@ -1,33 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" -) - -type StatusGetTestSuite struct { - StatusStandardTestSuite -} - -func TestStatusGetTestSuite(t *testing.T) { - suite.Run(t, new(StatusGetTestSuite)) -} diff --git a/internal/api/client/status/statusunbookmark.go b/internal/api/client/status/statusunbookmark.go deleted file mode 100644 index aa090f8c9..000000000 --- a/internal/api/client/status/statusunbookmark.go +++ /dev/null @@ -1,98 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// StatusUnbookmarkPOSTHandler swagger:operation POST /api/v1/statuses/{id}/unbookmark statusUnbookmark -// -// Unbookmark status with the given ID. -// -// --- -// tags: -// - statuses -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: string -// description: Target status ID. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - write:statuses -// -// responses: -// '200': -// name: status -// description: The status. -// schema: -// "$ref": "#/definitions/status" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '403': -// description: forbidden -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) StatusUnbookmarkPOSTHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetStatusID := c.Param(IDKey) - if targetStatusID == "" { - err := errors.New("no status id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - apiStatus, errWithCode := m.processor.StatusUnbookmark(c.Request.Context(), authed, targetStatusID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, apiStatus) -} diff --git a/internal/api/client/status/statusunbookmark_test.go b/internal/api/client/status/statusunbookmark_test.go deleted file mode 100644 index 09a18ab9b..000000000 --- a/internal/api/client/status/statusunbookmark_test.go +++ /dev/null @@ -1,78 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status_test - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/status" - "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type StatusUnbookmarkTestSuite struct { - StatusStandardTestSuite -} - -func (suite *StatusUnbookmarkTestSuite) TestPostUnbookmark() { - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - - targetStatus := suite.testStatuses["admin_account_status_1"] - - // setup - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(status.UnbookmarkPath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - - ctx.Params = gin.Params{ - gin.Param{ - Key: status.IDKey, - Value: targetStatus.ID, - }, - } - - suite.statusModule.StatusUnbookmarkPOSTHandler(ctx) - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - suite.NoError(err) - - statusReply := &model.Status{} - err = json.Unmarshal(b, statusReply) - suite.NoError(err) - - suite.False(statusReply.Bookmarked) -} - -func TestStatusUnbookmarkTestSuite(t *testing.T) { - suite.Run(t, new(StatusUnbookmarkTestSuite)) -} diff --git a/internal/api/client/status/statusunboost.go b/internal/api/client/status/statusunboost.go deleted file mode 100644 index 45a8e0ece..000000000 --- a/internal/api/client/status/statusunboost.go +++ /dev/null @@ -1,98 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// StatusUnboostPOSTHandler swagger:operation POST /api/v1/statuses/{id}/unreblog statusUnreblog -// -// Unreblog/unboost status with the given ID. -// -// --- -// tags: -// - statuses -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: string -// description: Target status ID. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - write:statuses -// -// responses: -// '200': -// name: status -// description: The unboosted status. -// schema: -// "$ref": "#/definitions/status" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '403': -// description: forbidden -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) StatusUnboostPOSTHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetStatusID := c.Param(IDKey) - if targetStatusID == "" { - err := errors.New("no status id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - apiStatus, errWithCode := m.processor.StatusUnboost(c.Request.Context(), authed, targetStatusID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, apiStatus) -} diff --git a/internal/api/client/status/statusunfave.go b/internal/api/client/status/statusunfave.go deleted file mode 100644 index 19d3da3bd..000000000 --- a/internal/api/client/status/statusunfave.go +++ /dev/null @@ -1,97 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// StatusUnfavePOSTHandler swagger:operation POST /api/v1/statuses/{id}/unfavourite statusUnfave -// -// Unstar/unlike/unfavourite the given status. -// -// --- -// tags: -// - statuses -// -// produces: -// - application/json -// -// parameters: -// - -// name: id -// type: string -// description: Target status ID. -// in: path -// required: true -// -// security: -// - OAuth2 Bearer: -// - write:statuses -// -// responses: -// '200': -// description: "The unfaved status." -// schema: -// "$ref": "#/definitions/status" -// '400': -// description: bad request -// '401': -// description: unauthorized -// '403': -// description: forbidden -// '404': -// description: not found -// '406': -// description: not acceptable -// '500': -// description: internal server error -func (m *Module) StatusUnfavePOSTHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - targetStatusID := c.Param(IDKey) - if targetStatusID == "" { - err := errors.New("no status id specified") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - - apiStatus, errWithCode := m.processor.StatusUnfave(c.Request.Context(), authed, targetStatusID) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - c.JSON(http.StatusOK, apiStatus) -} diff --git a/internal/api/client/status/statusunfave_test.go b/internal/api/client/status/statusunfave_test.go deleted file mode 100644 index b8448d657..000000000 --- a/internal/api/client/status/statusunfave_test.go +++ /dev/null @@ -1,143 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package status_test - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/api/client/status" - "github.com/superseriousbusiness/gotosocial/internal/api/model" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/testrig" -) - -type StatusUnfaveTestSuite struct { - StatusStandardTestSuite -} - -// unfave a status -func (suite *StatusUnfaveTestSuite) TestPostUnfave() { - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - - // this is the status we wanna unfave: in the testrig it's already faved by this account - targetStatus := suite.testStatuses["admin_account_status_1"] - - // setup - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(status.UnfavouritePath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - - // normally the router would populate these params from the path values, - // but because we're calling the function directly, we need to set them manually. - ctx.Params = gin.Params{ - gin.Param{ - Key: status.IDKey, - Value: targetStatus.ID, - }, - } - - suite.statusModule.StatusUnfavePOSTHandler(ctx) - - // check response - suite.EqualValues(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - - statusReply := &model.Status{} - err = json.Unmarshal(b, statusReply) - assert.NoError(suite.T(), err) - - assert.Equal(suite.T(), targetStatus.ContentWarning, statusReply.SpoilerText) - assert.Equal(suite.T(), targetStatus.Content, statusReply.Content) - assert.False(suite.T(), statusReply.Sensitive) - assert.Equal(suite.T(), model.VisibilityPublic, statusReply.Visibility) - assert.False(suite.T(), statusReply.Favourited) - assert.Equal(suite.T(), 0, statusReply.FavouritesCount) -} - -// try to unfave a status that's already not faved -func (suite *StatusUnfaveTestSuite) TestPostAlreadyNotFaved() { - t := suite.testTokens["local_account_1"] - oauthToken := oauth.DBTokenToToken(t) - - // this is the status we wanna unfave: in the testrig it's not faved by this account - targetStatus := suite.testStatuses["admin_account_status_2"] - - // setup - recorder := httptest.NewRecorder() - ctx, _ := testrig.CreateGinTestContext(recorder, nil) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) - ctx.Set(oauth.SessionAuthorizedToken, oauthToken) - ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(status.UnfavouritePath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting - ctx.Request.Header.Set("accept", "application/json") - - // normally the router would populate these params from the path values, - // but because we're calling the function directly, we need to set them manually. - ctx.Params = gin.Params{ - gin.Param{ - Key: status.IDKey, - Value: targetStatus.ID, - }, - } - - suite.statusModule.StatusUnfavePOSTHandler(ctx) - - // check response - suite.EqualValues(http.StatusOK, recorder.Code) - - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - - statusReply := &model.Status{} - err = json.Unmarshal(b, statusReply) - assert.NoError(suite.T(), err) - - assert.Equal(suite.T(), targetStatus.ContentWarning, statusReply.SpoilerText) - assert.Equal(suite.T(), targetStatus.Content, statusReply.Content) - assert.True(suite.T(), statusReply.Sensitive) - assert.Equal(suite.T(), model.VisibilityPublic, statusReply.Visibility) - assert.False(suite.T(), statusReply.Favourited) - assert.Equal(suite.T(), 0, statusReply.FavouritesCount) -} - -func TestStatusUnfaveTestSuite(t *testing.T) { - suite.Run(t, new(StatusUnfaveTestSuite)) -} diff --git a/internal/api/client/statuses/status.go b/internal/api/client/statuses/status.go new file mode 100644 index 000000000..7f58e8c9d --- /dev/null +++ b/internal/api/client/statuses/status.go @@ -0,0 +1,100 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "github.com/superseriousbusiness/gotosocial/internal/processing" +) + +const ( + // IDKey is for status UUIDs + IDKey = "id" + // BasePath is the base path for serving the statuses API, minus the 'api' prefix + BasePath = "/v1/statuses" + // BasePathWithID is just the base path with the ID key in it. + // Use this anywhere you need to know the ID of the status being queried. + BasePathWithID = BasePath + "/:" + IDKey + + // FavouritedPath is for seeing who's faved a given status + FavouritedPath = BasePathWithID + "/favourited_by" + // FavouritePath is for posting a fave on a status + FavouritePath = BasePathWithID + "/favourite" + // UnfavouritePath is for removing a fave from a status + UnfavouritePath = BasePathWithID + "/unfavourite" + + // RebloggedPath is for seeing who's boosted a given status + RebloggedPath = BasePathWithID + "/reblogged_by" + // ReblogPath is for boosting/reblogging a given status + ReblogPath = BasePathWithID + "/reblog" + // UnreblogPath is for undoing a boost/reblog of a given status + UnreblogPath = BasePathWithID + "/unreblog" + + // BookmarkPath is for creating a bookmark on a given status + BookmarkPath = BasePathWithID + "/bookmark" + // UnbookmarkPath is for removing a bookmark from a given status + UnbookmarkPath = BasePathWithID + "/unbookmark" + + // MutePath is for muting a given status so that notifications will no longer be received about it. + MutePath = BasePathWithID + "/mute" + // UnmutePath is for undoing an existing mute + UnmutePath = BasePathWithID + "/unmute" + + // PinPath is for pinning a status to an account profile so that it's the first thing people see + PinPath = BasePathWithID + "/pin" + // UnpinPath is for undoing a pin and returning a status to the ever-swirling drain of time and entropy + UnpinPath = BasePathWithID + "/unpin" + + // ContextPath is used for fetching context of posts + ContextPath = BasePathWithID + "/context" +) + +type Module struct { + processor processing.Processor +} + +func New(processor processing.Processor) *Module { + return &Module{ + processor: processor, + } +} + +func (m *Module) Route(attachHandler func(method string, path string, f ...gin.HandlerFunc) gin.IRoutes) { + // create / get / delete status + attachHandler(http.MethodPost, BasePath, m.StatusCreatePOSTHandler) + attachHandler(http.MethodGet, BasePathWithID, m.StatusGETHandler) + attachHandler(http.MethodDelete, BasePathWithID, m.StatusDELETEHandler) + + // fave stuff + attachHandler(http.MethodPost, FavouritePath, m.StatusFavePOSTHandler) + attachHandler(http.MethodPost, UnfavouritePath, m.StatusUnfavePOSTHandler) + attachHandler(http.MethodGet, FavouritedPath, m.StatusFavedByGETHandler) + + // reblog stuff + attachHandler(http.MethodPost, ReblogPath, m.StatusBoostPOSTHandler) + attachHandler(http.MethodPost, UnreblogPath, m.StatusUnboostPOSTHandler) + attachHandler(http.MethodGet, RebloggedPath, m.StatusBoostedByGETHandler) + attachHandler(http.MethodPost, BookmarkPath, m.StatusBookmarkPOSTHandler) + attachHandler(http.MethodPost, UnbookmarkPath, m.StatusUnbookmarkPOSTHandler) + + // context / status thread + attachHandler(http.MethodGet, ContextPath, m.StatusContextGETHandler) +} diff --git a/internal/api/client/statuses/status_test.go b/internal/api/client/statuses/status_test.go new file mode 100644 index 000000000..0bf824fdb --- /dev/null +++ b/internal/api/client/statuses/status_test.go @@ -0,0 +1,98 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses_test + +import ( + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/statuses" + "github.com/superseriousbusiness/gotosocial/internal/concurrency" + "github.com/superseriousbusiness/gotosocial/internal/db" + "github.com/superseriousbusiness/gotosocial/internal/email" + "github.com/superseriousbusiness/gotosocial/internal/federation" + "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" + "github.com/superseriousbusiness/gotosocial/internal/media" + "github.com/superseriousbusiness/gotosocial/internal/messages" + "github.com/superseriousbusiness/gotosocial/internal/processing" + "github.com/superseriousbusiness/gotosocial/internal/storage" + "github.com/superseriousbusiness/gotosocial/internal/typeutils" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +type StatusStandardTestSuite struct { + // standard suite interfaces + suite.Suite + db db.DB + tc typeutils.TypeConverter + mediaManager media.Manager + federator federation.Federator + emailSender email.Sender + processor processing.Processor + storage *storage.Driver + + // standard suite models + testTokens map[string]*gtsmodel.Token + testClients map[string]*gtsmodel.Client + testApplications map[string]*gtsmodel.Application + testUsers map[string]*gtsmodel.User + testAccounts map[string]*gtsmodel.Account + testAttachments map[string]*gtsmodel.MediaAttachment + testStatuses map[string]*gtsmodel.Status + testFollows map[string]*gtsmodel.Follow + + // module being tested + statusModule *statuses.Module +} + +func (suite *StatusStandardTestSuite) SetupSuite() { + suite.testTokens = testrig.NewTestTokens() + suite.testClients = testrig.NewTestClients() + suite.testApplications = testrig.NewTestApplications() + suite.testUsers = testrig.NewTestUsers() + suite.testAccounts = testrig.NewTestAccounts() + suite.testAttachments = testrig.NewTestAttachments() + suite.testStatuses = testrig.NewTestStatuses() + suite.testFollows = testrig.NewTestFollows() +} + +func (suite *StatusStandardTestSuite) SetupTest() { + testrig.InitTestConfig() + testrig.InitTestLog() + + suite.db = testrig.NewTestDB() + suite.tc = testrig.NewTestTypeConverter(suite.db) + suite.storage = testrig.NewInMemoryStorage() + testrig.StandardDBSetup(suite.db, nil) + testrig.StandardStorageSetup(suite.storage, "../../../../testrig/media") + + fedWorker := concurrency.NewWorkerPool[messages.FromFederator](-1, -1) + clientWorker := concurrency.NewWorkerPool[messages.FromClientAPI](-1, -1) + + suite.mediaManager = testrig.NewTestMediaManager(suite.db, suite.storage) + suite.federator = testrig.NewTestFederator(suite.db, testrig.NewTestTransportController(testrig.NewMockHTTPClient(nil, "../../../../testrig/media"), suite.db, fedWorker), suite.storage, suite.mediaManager, fedWorker) + suite.emailSender = testrig.NewEmailSender("../../../../web/template/", nil) + suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator, suite.emailSender, suite.mediaManager, clientWorker, fedWorker) + suite.statusModule = statuses.New(suite.processor) + + suite.NoError(suite.processor.Start()) +} + +func (suite *StatusStandardTestSuite) TearDownTest() { + testrig.StandardDBTeardown(suite.db) + testrig.StandardStorageTeardown(suite.storage) +} diff --git a/internal/api/client/statuses/statusbookmark.go b/internal/api/client/statuses/statusbookmark.go new file mode 100644 index 000000000..4efa53528 --- /dev/null +++ b/internal/api/client/statuses/statusbookmark.go @@ -0,0 +1,98 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// StatusBookmarkPOSTHandler swagger:operation POST /api/v1/statuses/{id}/bookmark statusBookmark +// +// Bookmark status with the given ID. +// +// --- +// tags: +// - statuses +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: Target status ID. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - write:statuses +// +// responses: +// '200': +// name: status +// description: The status. +// schema: +// "$ref": "#/definitions/status" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '403': +// description: forbidden +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) StatusBookmarkPOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetStatusID := c.Param(IDKey) + if targetStatusID == "" { + err := errors.New("no status id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + apiStatus, errWithCode := m.processor.StatusBookmark(c.Request.Context(), authed, targetStatusID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, apiStatus) +} diff --git a/internal/api/client/statuses/statusbookmark_test.go b/internal/api/client/statuses/statusbookmark_test.go new file mode 100644 index 000000000..ba2de78e1 --- /dev/null +++ b/internal/api/client/statuses/statusbookmark_test.go @@ -0,0 +1,83 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses_test + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/statuses" + "github.com/superseriousbusiness/gotosocial/internal/api/model" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +type StatusBookmarkTestSuite struct { + StatusStandardTestSuite +} + +func (suite *StatusBookmarkTestSuite) TestPostBookmark() { + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + + targetStatus := suite.testStatuses["admin_account_status_1"] + + // setup + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(statuses.BookmarkPath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + + // normally the router would populate these params from the path values, + // but because we're calling the function directly, we need to set them manually. + ctx.Params = gin.Params{ + gin.Param{ + Key: statuses.IDKey, + Value: targetStatus.ID, + }, + } + + suite.statusModule.StatusBookmarkPOSTHandler(ctx) + + // check response + suite.EqualValues(http.StatusOK, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + statusReply := &model.Status{} + err = json.Unmarshal(b, statusReply) + suite.NoError(err) + + suite.True(statusReply.Bookmarked) +} + +func TestStatusBookmarkTestSuite(t *testing.T) { + suite.Run(t, new(StatusBookmarkTestSuite)) +} diff --git a/internal/api/client/statuses/statusboost.go b/internal/api/client/statuses/statusboost.go new file mode 100644 index 000000000..c8921b1b6 --- /dev/null +++ b/internal/api/client/statuses/statusboost.go @@ -0,0 +1,101 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// StatusBoostPOSTHandler swagger:operation POST /api/v1/statuses/{id}/reblog statusReblog +// +// Reblog/boost status with the given ID. +// +// If the target status is rebloggable/boostable, it will be shared with your followers. +// This is equivalent to an ActivityPub 'Announce' activity. +// +// --- +// tags: +// - statuses +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: Target status ID. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - write:statuses +// +// responses: +// '200': +// name: status +// description: The boost of the status. +// schema: +// "$ref": "#/definitions/status" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '403': +// description: forbidden +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) StatusBoostPOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetStatusID := c.Param(IDKey) + if targetStatusID == "" { + err := errors.New("no status id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + apiStatus, errWithCode := m.processor.StatusBoost(c.Request.Context(), authed, targetStatusID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, apiStatus) +} diff --git a/internal/api/client/statuses/statusboost_test.go b/internal/api/client/statuses/statusboost_test.go new file mode 100644 index 000000000..13ca2acf2 --- /dev/null +++ b/internal/api/client/statuses/statusboost_test.go @@ -0,0 +1,247 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses_test + +import ( + "context" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/statuses" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +type StatusBoostTestSuite struct { + StatusStandardTestSuite +} + +func (suite *StatusBoostTestSuite) TestPostBoost() { + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + + targetStatus := suite.testStatuses["admin_account_status_1"] + + // setup + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(statuses.ReblogPath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + + // normally the router would populate these params from the path values, + // but because we're calling the function directly, we need to set them manually. + ctx.Params = gin.Params{ + gin.Param{ + Key: statuses.IDKey, + Value: targetStatus.ID, + }, + } + + suite.statusModule.StatusBoostPOSTHandler(ctx) + + // check response + suite.EqualValues(http.StatusOK, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + statusReply := &apimodel.Status{} + err = json.Unmarshal(b, statusReply) + suite.NoError(err) + + suite.False(statusReply.Sensitive) + suite.Equal(apimodel.VisibilityPublic, statusReply.Visibility) + + suite.Equal(targetStatus.ContentWarning, statusReply.SpoilerText) + suite.Equal(targetStatus.Content, statusReply.Content) + suite.Equal("the_mighty_zork", statusReply.Account.Username) + suite.Len(statusReply.MediaAttachments, 0) + suite.Len(statusReply.Mentions, 0) + suite.Len(statusReply.Emojis, 0) + suite.Len(statusReply.Tags, 0) + + suite.NotNil(statusReply.Application) + suite.Equal("really cool gts application", statusReply.Application.Name) + + suite.NotNil(statusReply.Reblog) + suite.Equal(1, statusReply.Reblog.ReblogsCount) + suite.Equal(1, statusReply.Reblog.FavouritesCount) + suite.Equal(targetStatus.Content, statusReply.Reblog.Content) + suite.Equal(targetStatus.ContentWarning, statusReply.Reblog.SpoilerText) + suite.Equal(targetStatus.AccountID, statusReply.Reblog.Account.ID) + suite.Len(statusReply.Reblog.MediaAttachments, 1) + suite.Len(statusReply.Reblog.Tags, 1) + suite.Len(statusReply.Reblog.Emojis, 1) + suite.Equal("superseriousbusiness", statusReply.Reblog.Application.Name) +} + +func (suite *StatusBoostTestSuite) TestPostBoostOwnFollowersOnly() { + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + + testStatus := suite.testStatuses["local_account_1_status_5"] + testAccount := suite.testAccounts["local_account_1"] + testUser := suite.testUsers["local_account_1"] + + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, testUser) + ctx.Set(oauth.SessionAuthorizedAccount, testAccount) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(statuses.ReblogPath, ":id", testStatus.ID, 1)), nil) + ctx.Request.Header.Set("accept", "application/json") + + ctx.Params = gin.Params{ + gin.Param{ + Key: statuses.IDKey, + Value: testStatus.ID, + }, + } + + suite.statusModule.StatusBoostPOSTHandler(ctx) + + // check response + suite.EqualValues(http.StatusOK, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + responseStatus := &apimodel.Status{} + err = json.Unmarshal(b, responseStatus) + suite.NoError(err) + + suite.False(responseStatus.Sensitive) + suite.Equal(suite.tc.VisToAPIVis(context.Background(), testStatus.Visibility), responseStatus.Visibility) + + suite.Equal(testStatus.ContentWarning, responseStatus.SpoilerText) + suite.Equal(testStatus.Content, responseStatus.Content) + suite.Equal("the_mighty_zork", responseStatus.Account.Username) + suite.Len(responseStatus.MediaAttachments, 0) + suite.Len(responseStatus.Mentions, 0) + suite.Len(responseStatus.Emojis, 0) + suite.Len(responseStatus.Tags, 0) + + suite.NotNil(responseStatus.Application) + suite.Equal("really cool gts application", responseStatus.Application.Name) + + suite.NotNil(responseStatus.Reblog) + suite.Equal(1, responseStatus.Reblog.ReblogsCount) + suite.Equal(0, responseStatus.Reblog.FavouritesCount) + suite.Equal(testStatus.Content, responseStatus.Reblog.Content) + suite.Equal(testStatus.ContentWarning, responseStatus.Reblog.SpoilerText) + suite.Equal(testStatus.AccountID, responseStatus.Reblog.Account.ID) + suite.Equal(suite.tc.VisToAPIVis(context.Background(), testStatus.Visibility), responseStatus.Reblog.Visibility) + suite.Empty(responseStatus.Reblog.MediaAttachments) + suite.Empty(responseStatus.Reblog.Tags) + suite.Empty(responseStatus.Reblog.Emojis) + suite.Equal("really cool gts application", responseStatus.Reblog.Application.Name) +} + +// try to boost a status that's not boostable +func (suite *StatusBoostTestSuite) TestPostUnboostable() { + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + + targetStatus := suite.testStatuses["local_account_2_status_4"] + + // setup + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(statuses.ReblogPath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + + // normally the router would populate these params from the path values, + // but because we're calling the function directly, we need to set them manually. + ctx.Params = gin.Params{ + gin.Param{ + Key: statuses.IDKey, + Value: targetStatus.ID, + }, + } + + suite.statusModule.StatusBoostPOSTHandler(ctx) + + // check response + suite.Equal(http.StatusForbidden, recorder.Code) // we 403 unboostable statuses + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + suite.Equal(`{"error":"Forbidden"}`, string(b)) +} + +// try to boost a status that's not visible to the user +func (suite *StatusBoostTestSuite) TestPostNotVisible() { + // stop local_account_2 following zork + err := suite.db.DeleteByID(context.Background(), suite.testFollows["local_account_2_local_account_1"].ID, >smodel.Follow{}) + suite.NoError(err) + + t := suite.testTokens["local_account_2"] + oauthToken := oauth.DBTokenToToken(t) + + targetStatus := suite.testStatuses["local_account_1_status_3"] // this is a mutual only status and these accounts aren't mutuals + + // setup + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_2"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_2"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(statuses.ReblogPath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + + // normally the router would populate these params from the path values, + // but because we're calling the function directly, we need to set them manually. + ctx.Params = gin.Params{ + gin.Param{ + Key: statuses.IDKey, + Value: targetStatus.ID, + }, + } + + suite.statusModule.StatusBoostPOSTHandler(ctx) + + // check response + suite.Equal(http.StatusNotFound, recorder.Code) // we 404 statuses that aren't visible +} + +func TestStatusBoostTestSuite(t *testing.T) { + suite.Run(t, new(StatusBoostTestSuite)) +} diff --git a/internal/api/client/statuses/statusboostedby.go b/internal/api/client/statuses/statusboostedby.go new file mode 100644 index 000000000..dc1567dba --- /dev/null +++ b/internal/api/client/statuses/statusboostedby.go @@ -0,0 +1,89 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// StatusBoostedByGETHandler swagger:operation GET /api/v1/statuses/{id}/reblogged_by statusBoostedBy +// +// View accounts that have reblogged/boosted the target status. +// +// --- +// tags: +// - statuses +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: Target status ID. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - read:accounts +// +// responses: +// '200': +// schema: +// type: array +// items: +// "$ref": "#/definitions/account" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '403': +// description: forbidden +// '404': +// description: not found +func (m *Module) StatusBoostedByGETHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + targetStatusID := c.Param(IDKey) + if targetStatusID == "" { + err := errors.New("no status id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + apiAccounts, errWithCode := m.processor.StatusBoostedBy(c.Request.Context(), authed, targetStatusID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, apiAccounts) +} diff --git a/internal/api/client/statuses/statusboostedby_test.go b/internal/api/client/statuses/statusboostedby_test.go new file mode 100644 index 000000000..576dee369 --- /dev/null +++ b/internal/api/client/statuses/statusboostedby_test.go @@ -0,0 +1,112 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses_test + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/statuses" + "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +type StatusBoostedByTestSuite struct { + StatusStandardTestSuite +} + +func (suite *StatusBoostedByTestSuite) TestRebloggedByOK() { + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + targetStatus := suite.testStatuses["local_account_1_status_1"] + + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodGet, fmt.Sprintf("http://localhost:8080%s", strings.Replace(statuses.RebloggedPath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + ctx.AddParam("id", targetStatus.ID) + + suite.statusModule.StatusBoostedByGETHandler(ctx) + + suite.EqualValues(http.StatusOK, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + accounts := []*gtsmodel.Account{} + err = json.Unmarshal(b, &accounts) + suite.NoError(err) + + if !suite.Len(accounts, 1) { + suite.FailNow("should have had 1 account") + } + + suite.Equal(accounts[0].ID, suite.testAccounts["admin_account"].ID) +} + +func (suite *StatusBoostedByTestSuite) TestRebloggedByUseBoostWrapperID() { + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + targetStatus := suite.testStatuses["admin_account_status_4"] // admin_account_status_4 is a boost of local_account_1_status_1 + + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodGet, fmt.Sprintf("http://localhost:8080%s", strings.Replace(statuses.RebloggedPath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + ctx.AddParam("id", targetStatus.ID) + + suite.statusModule.StatusBoostedByGETHandler(ctx) + + suite.EqualValues(http.StatusOK, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + accounts := []*gtsmodel.Account{} + err = json.Unmarshal(b, &accounts) + suite.NoError(err) + + if !suite.Len(accounts, 1) { + suite.FailNow("should have had 1 account") + } + + suite.Equal(accounts[0].ID, suite.testAccounts["admin_account"].ID) +} + +func TestStatusBoostedByTestSuite(t *testing.T) { + suite.Run(t, new(StatusBoostedByTestSuite)) +} diff --git a/internal/api/client/statuses/statuscontext.go b/internal/api/client/statuses/statuscontext.go new file mode 100644 index 000000000..9a6ac9f7f --- /dev/null +++ b/internal/api/client/statuses/statuscontext.go @@ -0,0 +1,100 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// StatusContextGETHandler swagger:operation GET /api/v1/statuses/{id}/context statusContext +// +// Return ancestors and descendants of the given status. +// +// The returned statuses will be ordered in a thread structure, so they are suitable to be displayed in the order in which they were returned. +// +// --- +// tags: +// - statuses +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: Target status ID. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - read:statuses +// +// responses: +// '200': +// name: statuses +// description: Status context object. +// schema: +// "$ref": "#/definitions/statusContext" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '403': +// description: forbidden +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) StatusContextGETHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetStatusID := c.Param(IDKey) + if targetStatusID == "" { + err := errors.New("no status id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + statusContext, errWithCode := m.processor.StatusGetContext(c.Request.Context(), authed, targetStatusID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, statusContext) +} diff --git a/internal/api/client/statuses/statuscreate.go b/internal/api/client/statuses/statuscreate.go new file mode 100644 index 000000000..d36c93e77 --- /dev/null +++ b/internal/api/client/statuses/statuscreate.go @@ -0,0 +1,172 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses + +import ( + "errors" + "fmt" + "net/http" + + "github.com/gin-gonic/gin" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/config" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/internal/validate" +) + +// StatusCreatePOSTHandler swagger:operation POST /api/v1/statuses statusCreate +// +// Create a new status. +// +// The parameters can also be given in the body of the request, as JSON, if the content-type is set to 'application/json'. +// The parameters can also be given in the body of the request, as XML, if the content-type is set to 'application/xml'. +// +// --- +// tags: +// - statuses +// +// consumes: +// - application/json +// - application/xml +// - application/x-www-form-urlencoded +// +// produces: +// - application/json +// +// security: +// - OAuth2 Bearer: +// - write:statuses +// +// responses: +// '200': +// description: "The newly created status." +// schema: +// "$ref": "#/definitions/status" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '403': +// description: forbidden +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) StatusCreatePOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + form := &apimodel.AdvancedStatusCreateForm{} + if err := c.ShouldBind(form); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + // DO NOT COMMIT THIS UNCOMMENTED, IT WILL CAUSE MASS CHAOS. + // this is being left in as an ode to kim's shitposting. + // + // user := authed.Account.DisplayName + // if user == "" { + // user = authed.Account.Username + // } + // form.Status += "\n\nsent from " + user + "'s iphone\n" + + if err := validateCreateStatus(form); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + apiStatus, errWithCode := m.processor.StatusCreate(c.Request.Context(), authed, form) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, apiStatus) +} + +func validateCreateStatus(form *apimodel.AdvancedStatusCreateForm) error { + hasStatus := form.Status != "" + hasMedia := len(form.MediaIDs) != 0 + hasPoll := form.Poll != nil + + if !hasStatus && !hasMedia && !hasPoll { + return errors.New("no status, media, or poll provided") + } + + if hasMedia && hasPoll { + return errors.New("can't post media + poll in same status") + } + + maxChars := config.GetStatusesMaxChars() + maxMediaFiles := config.GetStatusesMediaMaxFiles() + maxPollOptions := config.GetStatusesPollMaxOptions() + maxPollChars := config.GetStatusesPollOptionMaxChars() + maxCwChars := config.GetStatusesCWMaxChars() + + if form.Status != "" { + if length := len([]rune(form.Status)); length > maxChars { + return fmt.Errorf("status too long, %d characters provided but limit is %d", length, maxChars) + } + } + + if len(form.MediaIDs) > maxMediaFiles { + return fmt.Errorf("too many media files attached to status, %d attached but limit is %d", len(form.MediaIDs), maxMediaFiles) + } + + if form.Poll != nil { + if form.Poll.Options == nil { + return errors.New("poll with no options") + } + if len(form.Poll.Options) > maxPollOptions { + return fmt.Errorf("too many poll options provided, %d provided but limit is %d", len(form.Poll.Options), maxPollOptions) + } + for _, p := range form.Poll.Options { + if length := len([]rune(p)); length > maxPollChars { + return fmt.Errorf("poll option too long, %d characters provided but limit is %d", length, maxPollChars) + } + } + } + + if form.SpoilerText != "" { + if length := len([]rune(form.SpoilerText)); length > maxCwChars { + return fmt.Errorf("content-warning/spoilertext too long, %d characters provided but limit is %d", length, maxCwChars) + } + } + + if form.Language != "" { + if err := validate.Language(form.Language); err != nil { + return err + } + } + + return nil +} diff --git a/internal/api/client/statuses/statuscreate_test.go b/internal/api/client/statuses/statuscreate_test.go new file mode 100644 index 000000000..3648d7520 --- /dev/null +++ b/internal/api/client/statuses/statuscreate_test.go @@ -0,0 +1,398 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses_test + +import ( + "context" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/statuses" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + "github.com/superseriousbusiness/gotosocial/internal/db" + "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +type StatusCreateTestSuite struct { + StatusStandardTestSuite +} + +const ( + statusWithLinksAndTags = "#test alright, should be able to post #links with fragments in them now, let's see........\n\nhttps://docs.gotosocial.org/en/latest/user_guide/posts/#links\n\n#gotosocial\n\n(tobi remember to pull the docker image challenge)" + statusMarkdown = "# Title\n\n## Smaller title\n\nThis is a post written in [markdown](https://www.markdownguide.org/)\n\n" + statusMarkdownExpected = "

Title

Smaller title

This is a post written in markdown

" +) + +// Post a new status with some custom visibility settings +func (suite *StatusCreateTestSuite) TestPostNewStatus() { + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + + // setup + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", statuses.BasePath), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + ctx.Request.Form = url.Values{ + "status": {"this is a brand new status! #helloworld"}, + "spoiler_text": {"hello hello"}, + "sensitive": {"true"}, + "visibility": {string(apimodel.VisibilityMutualsOnly)}, + "likeable": {"false"}, + "replyable": {"false"}, + "federated": {"false"}, + } + suite.statusModule.StatusCreatePOSTHandler(ctx) + + // check response + + // 1. we should have OK from our call to the function + suite.EqualValues(http.StatusOK, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + statusReply := &apimodel.Status{} + err = json.Unmarshal(b, statusReply) + suite.NoError(err) + + suite.Equal("hello hello", statusReply.SpoilerText) + suite.Equal("

this is a brand new status! #helloworld

", statusReply.Content) + suite.True(statusReply.Sensitive) + suite.Equal(apimodel.VisibilityPrivate, statusReply.Visibility) // even though we set this status to mutuals only, it should serialize to private, because the mastodon api has no idea about mutuals_only + suite.Len(statusReply.Tags, 1) + suite.Equal(apimodel.Tag{ + Name: "helloworld", + URL: "http://localhost:8080/tags/helloworld", + }, statusReply.Tags[0]) + + gtsTag := >smodel.Tag{} + err = suite.db.GetWhere(context.Background(), []db.Where{{Key: "name", Value: "helloworld"}}, gtsTag) + suite.NoError(err) + suite.Equal(statusReply.Account.ID, gtsTag.FirstSeenFromAccountID) +} + +func (suite *StatusCreateTestSuite) TestPostNewStatusMarkdown() { + // set default post language of account 1 to markdown + testAccount := suite.testAccounts["local_account_1"] + testAccount.StatusFormat = "markdown" + a := testAccount + + err := suite.db.UpdateAccount(context.Background(), a) + if err != nil { + suite.FailNow(err.Error()) + } + suite.Equal(a.StatusFormat, "markdown") + + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, a) + + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", statuses.BasePath), nil) + ctx.Request.Header.Set("accept", "application/json") + ctx.Request.Form = url.Values{ + "status": {statusMarkdown}, + "visibility": {string(apimodel.VisibilityPublic)}, + } + suite.statusModule.StatusCreatePOSTHandler(ctx) + + suite.EqualValues(http.StatusOK, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + statusReply := &apimodel.Status{} + err = json.Unmarshal(b, statusReply) + suite.NoError(err) + + suite.Equal(statusMarkdownExpected, statusReply.Content) +} + +// mention an account that is not yet known to the instance -- it should be looked up and put in the db +func (suite *StatusCreateTestSuite) TestMentionUnknownAccount() { + // first remove remote account 1 from the database so it gets looked up again + remoteAccount := suite.testAccounts["remote_account_1"] + err := suite.db.DeleteAccount(context.Background(), remoteAccount.ID) + suite.NoError(err) + + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + + // setup + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", statuses.BasePath), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + ctx.Request.Form = url.Values{ + "status": {"hello @brand_new_person@unknown-instance.com"}, + "visibility": {string(apimodel.VisibilityPublic)}, + } + suite.statusModule.StatusCreatePOSTHandler(ctx) + + suite.EqualValues(http.StatusOK, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + statusReply := &apimodel.Status{} + err = json.Unmarshal(b, statusReply) + suite.NoError(err) + + // if the status is properly formatted, that means the account has been put in the db + suite.Equal(`

hello @brand_new_person

`, statusReply.Content) + suite.Equal(apimodel.VisibilityPublic, statusReply.Visibility) +} + +func (suite *StatusCreateTestSuite) TestPostAnotherNewStatus() { + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + + // setup + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", statuses.BasePath), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + ctx.Request.Form = url.Values{ + "status": {statusWithLinksAndTags}, + } + suite.statusModule.StatusCreatePOSTHandler(ctx) + + // check response + + // 1. we should have OK from our call to the function + suite.EqualValues(http.StatusOK, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + statusReply := &apimodel.Status{} + err = json.Unmarshal(b, statusReply) + suite.NoError(err) + + suite.Equal("

#test alright, should be able to post #links with fragments in them now, let's see........

docs.gotosocial.org/en/latest/user_guide/posts/#links

#gotosocial

(tobi remember to pull the docker image challenge)

", statusReply.Content) +} + +func (suite *StatusCreateTestSuite) TestPostNewStatusWithEmoji() { + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + + // setup + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", statuses.BasePath), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + ctx.Request.Form = url.Values{ + "status": {"here is a rainbow emoji a few times! :rainbow: :rainbow: :rainbow: \n here's an emoji that isn't in the db: :test_emoji: "}, + } + suite.statusModule.StatusCreatePOSTHandler(ctx) + + suite.EqualValues(http.StatusOK, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + statusReply := &apimodel.Status{} + err = json.Unmarshal(b, statusReply) + suite.NoError(err) + + suite.Equal("", statusReply.SpoilerText) + suite.Equal("

here is a rainbow emoji a few times! :rainbow: :rainbow: :rainbow:
here's an emoji that isn't in the db: :test_emoji:

", statusReply.Content) + + suite.Len(statusReply.Emojis, 1) + apiEmoji := statusReply.Emojis[0] + gtsEmoji := testrig.NewTestEmojis()["rainbow"] + + suite.Equal(gtsEmoji.Shortcode, apiEmoji.Shortcode) + suite.Equal(gtsEmoji.ImageURL, apiEmoji.URL) + suite.Equal(gtsEmoji.ImageStaticURL, apiEmoji.StaticURL) +} + +// Try to reply to a status that doesn't exist +func (suite *StatusCreateTestSuite) TestReplyToNonexistentStatus() { + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + + // setup + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", statuses.BasePath), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + ctx.Request.Form = url.Values{ + "status": {"this is a reply to a status that doesn't exist"}, + "spoiler_text": {"don't open cuz it won't work"}, + "in_reply_to_id": {"3759e7ef-8ee1-4c0c-86f6-8b70b9ad3d50"}, + } + suite.statusModule.StatusCreatePOSTHandler(ctx) + + // check response + + suite.EqualValues(http.StatusBadRequest, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + suite.Equal(`{"error":"Bad Request: status with id 3759e7ef-8ee1-4c0c-86f6-8b70b9ad3d50 not replyable because it doesn't exist"}`, string(b)) +} + +// Post a reply to the status of a local user that allows replies. +func (suite *StatusCreateTestSuite) TestReplyToLocalStatus() { + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + + // setup + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", statuses.BasePath), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + ctx.Request.Form = url.Values{ + "status": {fmt.Sprintf("hello @%s this reply should work!", testrig.NewTestAccounts()["local_account_2"].Username)}, + "in_reply_to_id": {testrig.NewTestStatuses()["local_account_2_status_1"].ID}, + } + suite.statusModule.StatusCreatePOSTHandler(ctx) + + // check response + suite.EqualValues(http.StatusOK, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + statusReply := &apimodel.Status{} + err = json.Unmarshal(b, statusReply) + suite.NoError(err) + + suite.Equal("", statusReply.SpoilerText) + suite.Equal(fmt.Sprintf("

hello @%s this reply should work!

", testrig.NewTestAccounts()["local_account_2"].Username, testrig.NewTestAccounts()["local_account_2"].Username), statusReply.Content) + suite.False(statusReply.Sensitive) + suite.Equal(apimodel.VisibilityPublic, statusReply.Visibility) + suite.Equal(testrig.NewTestStatuses()["local_account_2_status_1"].ID, *statusReply.InReplyToID) + suite.Equal(testrig.NewTestAccounts()["local_account_2"].ID, *statusReply.InReplyToAccountID) + suite.Len(statusReply.Mentions, 1) +} + +// Take a media file which is currently not associated with a status, and attach it to a new status. +func (suite *StatusCreateTestSuite) TestAttachNewMediaSuccess() { + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + + attachment := suite.testAttachments["local_account_1_unattached_1"] + + // setup + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", statuses.BasePath), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + ctx.Request.Form = url.Values{ + "status": {"here's an image attachment"}, + "media_ids[]": {attachment.ID}, + } + suite.statusModule.StatusCreatePOSTHandler(ctx) + + // check response + suite.EqualValues(http.StatusOK, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + statusResponse := &apimodel.Status{} + err = json.Unmarshal(b, statusResponse) + suite.NoError(err) + + suite.Equal("", statusResponse.SpoilerText) + suite.Equal("

here's an image attachment

", statusResponse.Content) + suite.False(statusResponse.Sensitive) + suite.Equal(apimodel.VisibilityPublic, statusResponse.Visibility) + + // there should be one media attachment + suite.Len(statusResponse.MediaAttachments, 1) + + // get the updated media attachment from the database + gtsAttachment, err := suite.db.GetAttachmentByID(context.Background(), statusResponse.MediaAttachments[0].ID) + suite.NoError(err) + + // convert it to a api attachment + gtsAttachmentAsapi, err := suite.tc.AttachmentToAPIAttachment(context.Background(), gtsAttachment) + suite.NoError(err) + + // compare it with what we have now + suite.EqualValues(statusResponse.MediaAttachments[0], gtsAttachmentAsapi) + + // the status id of the attachment should now be set to the id of the status we just created + suite.Equal(statusResponse.ID, gtsAttachment.StatusID) +} + +func TestStatusCreateTestSuite(t *testing.T) { + suite.Run(t, new(StatusCreateTestSuite)) +} diff --git a/internal/api/client/statuses/statusdelete.go b/internal/api/client/statuses/statusdelete.go new file mode 100644 index 000000000..3db7397db --- /dev/null +++ b/internal/api/client/statuses/statusdelete.go @@ -0,0 +1,100 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// StatusDELETEHandler swagger:operation DELETE /api/v1/statuses/{id} statusDelete +// +// Delete status with the given ID. The status must belong to you. +// +// The deleted status will be returned in the response. The `text` field will contain the original text of the status as it was submitted. +// This is useful when doing a 'delete and redraft' type operation. +// +// --- +// tags: +// - statuses +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: Target status ID. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - write:statuses +// +// responses: +// '200': +// description: "The status that was just deleted." +// schema: +// "$ref": "#/definitions/status" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '403': +// description: forbidden +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) StatusDELETEHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetStatusID := c.Param(IDKey) + if targetStatusID == "" { + err := errors.New("no status id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + apiStatus, errWithCode := m.processor.StatusDelete(c.Request.Context(), authed, targetStatusID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, apiStatus) +} diff --git a/internal/api/client/statuses/statusdelete_test.go b/internal/api/client/statuses/statusdelete_test.go new file mode 100644 index 000000000..9a9ceef8f --- /dev/null +++ b/internal/api/client/statuses/statusdelete_test.go @@ -0,0 +1,91 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses_test + +import ( + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/statuses" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + "github.com/superseriousbusiness/gotosocial/internal/db" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +type StatusDeleteTestSuite struct { + StatusStandardTestSuite +} + +func (suite *StatusDeleteTestSuite) TestPostDelete() { + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + targetStatus := suite.testStatuses["local_account_1_status_1"] + + // setup + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodDelete, fmt.Sprintf("http://localhost:8080%s", strings.Replace(statuses.BasePathWithID, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + + // normally the router would populate these params from the path values, + // but because we're calling the function directly, we need to set them manually. + ctx.Params = gin.Params{ + gin.Param{ + Key: statuses.IDKey, + Value: targetStatus.ID, + }, + } + + suite.statusModule.StatusDELETEHandler(ctx) + + // check response + suite.EqualValues(http.StatusOK, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + statusReply := &apimodel.Status{} + err = json.Unmarshal(b, statusReply) + suite.NoError(err) + suite.NotNil(statusReply) + + if !testrig.WaitFor(func() bool { + _, err := suite.db.GetStatusByID(ctx, targetStatus.ID) + return errors.Is(err, db.ErrNoEntries) + }) { + suite.FailNow("time out waiting for status to be deleted") + } + +} + +func TestStatusDeleteTestSuite(t *testing.T) { + suite.Run(t, new(StatusDeleteTestSuite)) +} diff --git a/internal/api/client/statuses/statusfave.go b/internal/api/client/statuses/statusfave.go new file mode 100644 index 000000000..bd9ded147 --- /dev/null +++ b/internal/api/client/statuses/statusfave.go @@ -0,0 +1,97 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// StatusFavePOSTHandler swagger:operation POST /api/v1/statuses/{id}/favourite statusFave +// +// Star/like/favourite the given status, if permitted. +// +// --- +// tags: +// - statuses +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: Target status ID. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - write:statuses +// +// responses: +// '200': +// description: "The newly faved status." +// schema: +// "$ref": "#/definitions/status" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '403': +// description: forbidden +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) StatusFavePOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetStatusID := c.Param(IDKey) + if targetStatusID == "" { + err := errors.New("no status id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + apiStatus, errWithCode := m.processor.StatusFave(c.Request.Context(), authed, targetStatusID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, apiStatus) +} diff --git a/internal/api/client/statuses/statusfave_test.go b/internal/api/client/statuses/statusfave_test.go new file mode 100644 index 000000000..20805d87c --- /dev/null +++ b/internal/api/client/statuses/statusfave_test.go @@ -0,0 +1,132 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses_test + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/statuses" + + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +type StatusFaveTestSuite struct { + StatusStandardTestSuite +} + +// fave a status +func (suite *StatusFaveTestSuite) TestPostFave() { + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + + targetStatus := suite.testStatuses["admin_account_status_2"] + + // setup + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(statuses.FavouritePath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + + // normally the router would populate these params from the path values, + // but because we're calling the function directly, we need to set them manually. + ctx.Params = gin.Params{ + gin.Param{ + Key: statuses.IDKey, + Value: targetStatus.ID, + }, + } + + suite.statusModule.StatusFavePOSTHandler(ctx) + + // check response + suite.EqualValues(http.StatusOK, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + + statusReply := &apimodel.Status{} + err = json.Unmarshal(b, statusReply) + assert.NoError(suite.T(), err) + + assert.Equal(suite.T(), targetStatus.ContentWarning, statusReply.SpoilerText) + assert.Equal(suite.T(), targetStatus.Content, statusReply.Content) + assert.True(suite.T(), statusReply.Sensitive) + assert.Equal(suite.T(), apimodel.VisibilityPublic, statusReply.Visibility) + assert.True(suite.T(), statusReply.Favourited) + assert.Equal(suite.T(), 1, statusReply.FavouritesCount) +} + +// try to fave a status that's not faveable +func (suite *StatusFaveTestSuite) TestPostUnfaveable() { + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + + targetStatus := suite.testStatuses["local_account_2_status_3"] // this one is unlikeable and unreplyable + + // setup + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(statuses.FavouritePath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + + // normally the router would populate these params from the path values, + // but because we're calling the function directly, we need to set them manually. + ctx.Params = gin.Params{ + gin.Param{ + Key: statuses.IDKey, + Value: targetStatus.ID, + }, + } + + suite.statusModule.StatusFavePOSTHandler(ctx) + + // check response + suite.EqualValues(http.StatusForbidden, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + assert.Equal(suite.T(), `{"error":"Forbidden"}`, string(b)) +} + +func TestStatusFaveTestSuite(t *testing.T) { + suite.Run(t, new(StatusFaveTestSuite)) +} diff --git a/internal/api/client/statuses/statusfavedby.go b/internal/api/client/statuses/statusfavedby.go new file mode 100644 index 000000000..aa0f1f8d6 --- /dev/null +++ b/internal/api/client/statuses/statusfavedby.go @@ -0,0 +1,98 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// StatusFavedByGETHandler swagger:operation GET /api/v1/statuses/{id}/favourited_by statusFavedBy +// +// View accounts that have faved/starred/liked the target status. +// +// --- +// tags: +// - statuses +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: Target status ID. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - read:accounts +// +// responses: +// '200': +// schema: +// type: array +// items: +// "$ref": "#/definitions/account" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '403': +// description: forbidden +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) StatusFavedByGETHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetStatusID := c.Param(IDKey) + if targetStatusID == "" { + err := errors.New("no status id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + apiAccounts, errWithCode := m.processor.StatusFavedBy(c.Request.Context(), authed, targetStatusID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, apiAccounts) +} diff --git a/internal/api/client/statuses/statusfavedby_test.go b/internal/api/client/statuses/statusfavedby_test.go new file mode 100644 index 000000000..fc04c490e --- /dev/null +++ b/internal/api/client/statuses/statusfavedby_test.go @@ -0,0 +1,88 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses_test + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/statuses" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +type StatusFavedByTestSuite struct { + StatusStandardTestSuite +} + +func (suite *StatusFavedByTestSuite) TestGetFavedBy() { + t := suite.testTokens["local_account_2"] + oauthToken := oauth.DBTokenToToken(t) + + targetStatus := suite.testStatuses["admin_account_status_1"] // this status is faved by local_account_1 + + // setup + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_2"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_2"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_2"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(statuses.FavouritedPath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + + // normally the router would populate these params from the path values, + // but because we're calling the function directly, we need to set them manually. + ctx.Params = gin.Params{ + gin.Param{ + Key: statuses.IDKey, + Value: targetStatus.ID, + }, + } + + suite.statusModule.StatusFavedByGETHandler(ctx) + + // check response + suite.EqualValues(http.StatusOK, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + + accts := []apimodel.Account{} + err = json.Unmarshal(b, &accts) + assert.NoError(suite.T(), err) + + assert.Len(suite.T(), accts, 1) + assert.Equal(suite.T(), "the_mighty_zork", accts[0].Username) +} + +func TestStatusFavedByTestSuite(t *testing.T) { + suite.Run(t, new(StatusFavedByTestSuite)) +} diff --git a/internal/api/client/statuses/statusget.go b/internal/api/client/statuses/statusget.go new file mode 100644 index 000000000..5e7a59027 --- /dev/null +++ b/internal/api/client/statuses/statusget.go @@ -0,0 +1,97 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// StatusGETHandler swagger:operation GET /api/v1/statuses/{id} statusGet +// +// View status with the given ID. +// +// --- +// tags: +// - statuses +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: Target status ID. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - read:statuses +// +// responses: +// '200': +// description: "The requested status." +// schema: +// "$ref": "#/definitions/status" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '403': +// description: forbidden +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) StatusGETHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetStatusID := c.Param(IDKey) + if targetStatusID == "" { + err := errors.New("no status id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + apiStatus, errWithCode := m.processor.StatusGet(c.Request.Context(), authed, targetStatusID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, apiStatus) +} diff --git a/internal/api/client/statuses/statusget_test.go b/internal/api/client/statuses/statusget_test.go new file mode 100644 index 000000000..e8e1fd8f4 --- /dev/null +++ b/internal/api/client/statuses/statusget_test.go @@ -0,0 +1,33 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses_test + +import ( + "testing" + + "github.com/stretchr/testify/suite" +) + +type StatusGetTestSuite struct { + StatusStandardTestSuite +} + +func TestStatusGetTestSuite(t *testing.T) { + suite.Run(t, new(StatusGetTestSuite)) +} diff --git a/internal/api/client/statuses/statusunbookmark.go b/internal/api/client/statuses/statusunbookmark.go new file mode 100644 index 000000000..117ef833b --- /dev/null +++ b/internal/api/client/statuses/statusunbookmark.go @@ -0,0 +1,98 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// StatusUnbookmarkPOSTHandler swagger:operation POST /api/v1/statuses/{id}/unbookmark statusUnbookmark +// +// Unbookmark status with the given ID. +// +// --- +// tags: +// - statuses +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: Target status ID. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - write:statuses +// +// responses: +// '200': +// name: status +// description: The status. +// schema: +// "$ref": "#/definitions/status" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '403': +// description: forbidden +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) StatusUnbookmarkPOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetStatusID := c.Param(IDKey) + if targetStatusID == "" { + err := errors.New("no status id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + apiStatus, errWithCode := m.processor.StatusUnbookmark(c.Request.Context(), authed, targetStatusID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, apiStatus) +} diff --git a/internal/api/client/statuses/statusunbookmark_test.go b/internal/api/client/statuses/statusunbookmark_test.go new file mode 100644 index 000000000..9c4667ad8 --- /dev/null +++ b/internal/api/client/statuses/statusunbookmark_test.go @@ -0,0 +1,78 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses_test + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/statuses" + "github.com/superseriousbusiness/gotosocial/internal/api/model" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +type StatusUnbookmarkTestSuite struct { + StatusStandardTestSuite +} + +func (suite *StatusUnbookmarkTestSuite) TestPostUnbookmark() { + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + + targetStatus := suite.testStatuses["admin_account_status_1"] + + // setup + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(statuses.UnbookmarkPath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + + ctx.Params = gin.Params{ + gin.Param{ + Key: statuses.IDKey, + Value: targetStatus.ID, + }, + } + + suite.statusModule.StatusUnbookmarkPOSTHandler(ctx) + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + suite.NoError(err) + + statusReply := &model.Status{} + err = json.Unmarshal(b, statusReply) + suite.NoError(err) + + suite.False(statusReply.Bookmarked) +} + +func TestStatusUnbookmarkTestSuite(t *testing.T) { + suite.Run(t, new(StatusUnbookmarkTestSuite)) +} diff --git a/internal/api/client/statuses/statusunboost.go b/internal/api/client/statuses/statusunboost.go new file mode 100644 index 000000000..e91081195 --- /dev/null +++ b/internal/api/client/statuses/statusunboost.go @@ -0,0 +1,98 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// StatusUnboostPOSTHandler swagger:operation POST /api/v1/statuses/{id}/unreblog statusUnreblog +// +// Unreblog/unboost status with the given ID. +// +// --- +// tags: +// - statuses +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: Target status ID. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - write:statuses +// +// responses: +// '200': +// name: status +// description: The unboosted status. +// schema: +// "$ref": "#/definitions/status" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '403': +// description: forbidden +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) StatusUnboostPOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetStatusID := c.Param(IDKey) + if targetStatusID == "" { + err := errors.New("no status id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + apiStatus, errWithCode := m.processor.StatusUnboost(c.Request.Context(), authed, targetStatusID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, apiStatus) +} diff --git a/internal/api/client/statuses/statusunfave.go b/internal/api/client/statuses/statusunfave.go new file mode 100644 index 000000000..57ae88e1e --- /dev/null +++ b/internal/api/client/statuses/statusunfave.go @@ -0,0 +1,97 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// StatusUnfavePOSTHandler swagger:operation POST /api/v1/statuses/{id}/unfavourite statusUnfave +// +// Unstar/unlike/unfavourite the given status. +// +// --- +// tags: +// - statuses +// +// produces: +// - application/json +// +// parameters: +// - +// name: id +// type: string +// description: Target status ID. +// in: path +// required: true +// +// security: +// - OAuth2 Bearer: +// - write:statuses +// +// responses: +// '200': +// description: "The unfaved status." +// schema: +// "$ref": "#/definitions/status" +// '400': +// description: bad request +// '401': +// description: unauthorized +// '403': +// description: forbidden +// '404': +// description: not found +// '406': +// description: not acceptable +// '500': +// description: internal server error +func (m *Module) StatusUnfavePOSTHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + targetStatusID := c.Param(IDKey) + if targetStatusID == "" { + err := errors.New("no status id specified") + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + + apiStatus, errWithCode := m.processor.StatusUnfave(c.Request.Context(), authed, targetStatusID) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + c.JSON(http.StatusOK, apiStatus) +} diff --git a/internal/api/client/statuses/statusunfave_test.go b/internal/api/client/statuses/statusunfave_test.go new file mode 100644 index 000000000..2ca3450a4 --- /dev/null +++ b/internal/api/client/statuses/statusunfave_test.go @@ -0,0 +1,143 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package statuses_test + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/api/client/statuses" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/testrig" +) + +type StatusUnfaveTestSuite struct { + StatusStandardTestSuite +} + +// unfave a status +func (suite *StatusUnfaveTestSuite) TestPostUnfave() { + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + + // this is the status we wanna unfave: in the testrig it's already faved by this account + targetStatus := suite.testStatuses["admin_account_status_1"] + + // setup + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(statuses.UnfavouritePath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + + // normally the router would populate these params from the path values, + // but because we're calling the function directly, we need to set them manually. + ctx.Params = gin.Params{ + gin.Param{ + Key: statuses.IDKey, + Value: targetStatus.ID, + }, + } + + suite.statusModule.StatusUnfavePOSTHandler(ctx) + + // check response + suite.EqualValues(http.StatusOK, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + + statusReply := &apimodel.Status{} + err = json.Unmarshal(b, statusReply) + assert.NoError(suite.T(), err) + + assert.Equal(suite.T(), targetStatus.ContentWarning, statusReply.SpoilerText) + assert.Equal(suite.T(), targetStatus.Content, statusReply.Content) + assert.False(suite.T(), statusReply.Sensitive) + assert.Equal(suite.T(), apimodel.VisibilityPublic, statusReply.Visibility) + assert.False(suite.T(), statusReply.Favourited) + assert.Equal(suite.T(), 0, statusReply.FavouritesCount) +} + +// try to unfave a status that's already not faved +func (suite *StatusUnfaveTestSuite) TestPostAlreadyNotFaved() { + t := suite.testTokens["local_account_1"] + oauthToken := oauth.DBTokenToToken(t) + + // this is the status we wanna unfave: in the testrig it's not faved by this account + targetStatus := suite.testStatuses["admin_account_status_2"] + + // setup + recorder := httptest.NewRecorder() + ctx, _ := testrig.CreateGinTestContext(recorder, nil) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) + ctx.Set(oauth.SessionAuthorizedToken, oauthToken) + ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"]) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"]) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080%s", strings.Replace(statuses.UnfavouritePath, ":id", targetStatus.ID, 1)), nil) // the endpoint we're hitting + ctx.Request.Header.Set("accept", "application/json") + + // normally the router would populate these params from the path values, + // but because we're calling the function directly, we need to set them manually. + ctx.Params = gin.Params{ + gin.Param{ + Key: statuses.IDKey, + Value: targetStatus.ID, + }, + } + + suite.statusModule.StatusUnfavePOSTHandler(ctx) + + // check response + suite.EqualValues(http.StatusOK, recorder.Code) + + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + + statusReply := &apimodel.Status{} + err = json.Unmarshal(b, statusReply) + assert.NoError(suite.T(), err) + + assert.Equal(suite.T(), targetStatus.ContentWarning, statusReply.SpoilerText) + assert.Equal(suite.T(), targetStatus.Content, statusReply.Content) + assert.True(suite.T(), statusReply.Sensitive) + assert.Equal(suite.T(), apimodel.VisibilityPublic, statusReply.Visibility) + assert.False(suite.T(), statusReply.Favourited) + assert.Equal(suite.T(), 0, statusReply.FavouritesCount) +} + +func TestStatusUnfaveTestSuite(t *testing.T) { + suite.Run(t, new(StatusUnfaveTestSuite)) +} diff --git a/internal/api/client/streaming/stream.go b/internal/api/client/streaming/stream.go index a9cb62732..de98719c2 100644 --- a/internal/api/client/streaming/stream.go +++ b/internal/api/client/streaming/stream.go @@ -1,3 +1,21 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + package streaming import ( @@ -6,7 +24,7 @@ import ( "time" "codeberg.org/gruf/go-kv" - "github.com/superseriousbusiness/gotosocial/internal/api" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/log" @@ -14,12 +32,15 @@ import ( "github.com/gorilla/websocket" ) -var wsUpgrader = websocket.Upgrader{ - ReadBufferSize: 1024, - WriteBufferSize: 1024, - // we expect cors requests (via eg., pinafore.social) so be lenient - CheckOrigin: func(r *http.Request) bool { return true }, -} +var ( + wsUpgrader = websocket.Upgrader{ + ReadBufferSize: 1024, + WriteBufferSize: 1024, + // we expect cors requests (via eg., pinafore.social) so be lenient + CheckOrigin: func(r *http.Request) bool { return true }, + } + errNoToken = fmt.Errorf("no access token provided under query key %s or under header %s", AccessTokenQueryKey, AccessTokenHeader) +) // StreamGETHandler swagger:operation GET /api/v1/streaming streamGet // @@ -125,29 +146,33 @@ func (m *Module) StreamGETHandler(c *gin.Context) { streamType := c.Query(StreamQueryKey) if streamType == "" { err := fmt.Errorf("no stream type provided under query key %s", StreamQueryKey) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } - accessToken := c.Query(AccessTokenQueryKey) - if accessToken == "" { - accessToken = c.GetHeader(AccessTokenHeader) - } - if accessToken == "" { - err := fmt.Errorf("no access token provided under query key %s or under header %s", AccessTokenQueryKey, AccessTokenHeader) - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + var accessToken string + if t := c.Query(AccessTokenQueryKey); t != "" { + // try query param first + accessToken = t + } else if t := c.GetHeader(AccessTokenHeader); t != "" { + // fall back to Sec-Websocket-Protocol + accessToken = t + } else { + // no token + err := errNoToken + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } account, errWithCode := m.processor.AuthorizeStreamingRequest(c.Request.Context(), accessToken) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } stream, errWithCode := m.processor.OpenStreamForAccount(c.Request.Context(), account, streamType) if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } @@ -175,6 +200,7 @@ func (m *Module) StreamGETHandler(c *gin.Context) { }() streamTicker := time.NewTicker(m.tickDuration) + defer streamTicker.Stop() // We want to stay in the loop as long as possible while the client is connected. // The only thing that should break the loop is if the client leaves or the connection becomes unhealthy. diff --git a/internal/api/client/streaming/streaming.go b/internal/api/client/streaming/streaming.go index b15dfbdbd..f9d9fdf36 100644 --- a/internal/api/client/streaming/streaming.go +++ b/internal/api/client/streaming/streaming.go @@ -22,14 +22,13 @@ import ( "net/http" "time" - "github.com/superseriousbusiness/gotosocial/internal/api" + "github.com/gin-gonic/gin" "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" ) const ( - // BasePath is the path for the streaming api - BasePath = "/api/v1/streaming" + // BasePath is the path for the streaming api, minus the 'api' prefix + BasePath = "/v1/streaming" // StreamQueryKey is the query key for the type of stream being requested StreamQueryKey = "stream" @@ -41,29 +40,25 @@ const ( AccessTokenHeader = "Sec-Websocket-Protocol" ) -// Module implements the api.ClientModule interface for everything related to streaming type Module struct { processor processing.Processor tickDuration time.Duration } -// New returns a new streaming module -func New(processor processing.Processor) api.ClientModule { +func New(processor processing.Processor) *Module { return &Module{ processor: processor, tickDuration: 30 * time.Second, } } -func NewWithTickDuration(processor processing.Processor, tickDuration time.Duration) api.ClientModule { +func NewWithTickDuration(processor processing.Processor, tickDuration time.Duration) *Module { return &Module{ processor: processor, tickDuration: tickDuration, } } -// Route attaches all routes from this module to the given router -func (m *Module) Route(r router.Router) error { - r.AttachHandler(http.MethodGet, BasePath, m.StreamGETHandler) - return nil +func (m *Module) Route(attachHandler func(method string, path string, f ...gin.HandlerFunc) gin.IRoutes) { + attachHandler(http.MethodGet, BasePath, m.StreamGETHandler) } diff --git a/internal/api/client/streaming/streaming_test.go b/internal/api/client/streaming/streaming_test.go index 49c983fff..2f2d850c1 100644 --- a/internal/api/client/streaming/streaming_test.go +++ b/internal/api/client/streaming/streaming_test.go @@ -99,7 +99,7 @@ func (suite *StreamingTestSuite) SetupTest() { suite.federator = testrig.NewTestFederator(suite.db, testrig.NewTestTransportController(testrig.NewMockHTTPClient(nil, "../../../../testrig/media"), suite.db, fedWorker), suite.storage, suite.mediaManager, fedWorker) suite.emailSender = testrig.NewEmailSender("../../../../web/template/", nil) suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator, suite.emailSender, suite.mediaManager, clientWorker, fedWorker) - suite.streamingModule = streaming.NewWithTickDuration(suite.processor, 1).(*streaming.Module) + suite.streamingModule = streaming.NewWithTickDuration(suite.processor, 1) suite.NoError(suite.processor.Start()) } diff --git a/internal/api/client/timeline/home.go b/internal/api/client/timeline/home.go deleted file mode 100644 index e6135dd63..000000000 --- a/internal/api/client/timeline/home.go +++ /dev/null @@ -1,176 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package timeline - -import ( - "fmt" - "net/http" - "strconv" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// HomeTimelineGETHandler swagger:operation GET /api/v1/timelines/home homeTimeline -// -// See statuses/posts by accounts you follow. -// -// The statuses will be returned in descending chronological order (newest first), with sequential IDs (bigger = newer). -// -// The returned Link header can be used to generate the previous and next queries when scrolling up or down a timeline. -// -// Example: -// -// ``` -// ; rel="next", ; rel="prev" -// ```` -// -// --- -// tags: -// - timelines -// -// produces: -// - application/json -// -// parameters: -// - -// name: max_id -// type: string -// description: >- -// Return only statuses *OLDER* than the given max status ID. -// The status with the specified ID will not be included in the response. -// in: query -// required: false -// - -// name: since_id -// type: string -// description: >- -// Return only statuses *NEWER* than the given since status ID. -// The status with the specified ID will not be included in the response. -// in: query -// - -// name: min_id -// type: string -// description: >- -// Return only statuses *NEWER* than the given since status ID. -// The status with the specified ID will not be included in the response. -// in: query -// required: false -// - -// name: limit -// type: integer -// description: Number of statuses to return. -// default: 20 -// in: query -// required: false -// - -// name: local -// type: boolean -// description: Show only statuses posted by local accounts. -// default: false -// in: query -// required: false -// -// security: -// - OAuth2 Bearer: -// - read:statuses -// -// responses: -// '200': -// name: statuses -// description: Array of statuses. -// schema: -// type: array -// items: -// "$ref": "#/definitions/status" -// headers: -// Link: -// type: string -// description: Links to the next and previous queries. -// '401': -// description: unauthorized -// '400': -// description: bad request -func (m *Module) HomeTimelineGETHandler(c *gin.Context) { - authed, err := oauth.Authed(c, true, true, true, true) - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - maxID := "" - maxIDString := c.Query(MaxIDKey) - if maxIDString != "" { - maxID = maxIDString - } - - sinceID := "" - sinceIDString := c.Query(SinceIDKey) - if sinceIDString != "" { - sinceID = sinceIDString - } - - minID := "" - minIDString := c.Query(MinIDKey) - if minIDString != "" { - minID = minIDString - } - - limit := 20 - limitString := c.Query(LimitKey) - if limitString != "" { - i, err := strconv.ParseInt(limitString, 10, 32) - if err != nil { - err := fmt.Errorf("error parsing %s: %s", LimitKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - limit = int(i) - } - - local := false - localString := c.Query(LocalKey) - if localString != "" { - i, err := strconv.ParseBool(localString) - if err != nil { - err := fmt.Errorf("error parsing %s: %s", LocalKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - local = i - } - - resp, errWithCode := m.processor.HomeTimelineGet(c.Request.Context(), authed, maxID, sinceID, minID, limit, local) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - if resp.LinkHeader != "" { - c.Header("Link", resp.LinkHeader) - } - c.JSON(http.StatusOK, resp.Items) -} diff --git a/internal/api/client/timeline/public.go b/internal/api/client/timeline/public.go deleted file mode 100644 index fda23438b..000000000 --- a/internal/api/client/timeline/public.go +++ /dev/null @@ -1,187 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package timeline - -import ( - "fmt" - "net/http" - "strconv" - - "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/config" - "github.com/superseriousbusiness/gotosocial/internal/gtserror" - "github.com/superseriousbusiness/gotosocial/internal/oauth" -) - -// PublicTimelineGETHandler swagger:operation GET /api/v1/timelines/public publicTimeline -// -// See public statuses/posts that your instance is aware of. -// -// The statuses will be returned in descending chronological order (newest first), with sequential IDs (bigger = newer). -// -// The returned Link header can be used to generate the previous and next queries when scrolling up or down a timeline. -// -// Example: -// -// ``` -// ; rel="next", ; rel="prev" -// ```` -// -// --- -// tags: -// - timelines -// -// produces: -// - application/json -// -// parameters: -// - -// name: max_id -// type: string -// description: >- -// Return only statuses *OLDER* than the given max status ID. -// The status with the specified ID will not be included in the response. -// in: query -// required: false -// - -// name: since_id -// type: string -// description: >- -// Return only statuses *NEWER* than the given since status ID. -// The status with the specified ID will not be included in the response. -// in: query -// - -// name: min_id -// type: string -// description: >- -// Return only statuses *NEWER* than the given since status ID. -// The status with the specified ID will not be included in the response. -// in: query -// required: false -// - -// name: limit -// type: integer -// description: Number of statuses to return. -// default: 20 -// in: query -// required: false -// - -// name: local -// type: boolean -// description: Show only statuses posted by local accounts. -// default: false -// in: query -// required: false -// -// security: -// - OAuth2 Bearer: -// - read:statuses -// -// responses: -// '200': -// name: statuses -// description: Array of statuses. -// schema: -// type: array -// items: -// "$ref": "#/definitions/status" -// headers: -// Link: -// type: string -// description: Links to the next and previous queries. -// '401': -// description: unauthorized -// '400': -// description: bad request -func (m *Module) PublicTimelineGETHandler(c *gin.Context) { - var authed *oauth.Auth - var err error - - if config.GetInstanceExposePublicTimeline() { - // If the public timeline is allowed to be exposed, still check if we - // can extract various authentication properties, but don't require them. - authed, err = oauth.Authed(c, false, false, false, false) - } else { - authed, err = oauth.Authed(c, true, true, true, true) - } - - if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) - return - } - - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) - return - } - - maxID := "" - maxIDString := c.Query(MaxIDKey) - if maxIDString != "" { - maxID = maxIDString - } - - sinceID := "" - sinceIDString := c.Query(SinceIDKey) - if sinceIDString != "" { - sinceID = sinceIDString - } - - minID := "" - minIDString := c.Query(MinIDKey) - if minIDString != "" { - minID = minIDString - } - - limit := 20 - limitString := c.Query(LimitKey) - if limitString != "" { - i, err := strconv.ParseInt(limitString, 10, 32) - if err != nil { - err := fmt.Errorf("error parsing %s: %s", LimitKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - limit = int(i) - } - - local := false - localString := c.Query(LocalKey) - if localString != "" { - i, err := strconv.ParseBool(localString) - if err != nil { - err := fmt.Errorf("error parsing %s: %s", LocalKey, err) - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) - return - } - local = i - } - - resp, errWithCode := m.processor.PublicTimelineGet(c.Request.Context(), authed, maxID, sinceID, minID, limit, local) - if errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) - return - } - - if resp.LinkHeader != "" { - c.Header("Link", resp.LinkHeader) - } - c.JSON(http.StatusOK, resp.Items) -} diff --git a/internal/api/client/timeline/timeline.go b/internal/api/client/timeline/timeline.go deleted file mode 100644 index 3604a1fc2..000000000 --- a/internal/api/client/timeline/timeline.go +++ /dev/null @@ -1,65 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package timeline - -import ( - "net/http" - - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" -) - -const ( - // BasePath is the base URI path for serving timelines - BasePath = "/api/v1/timelines" - // HomeTimeline is the path for the home timeline - HomeTimeline = BasePath + "/home" - // PublicTimeline is the path for the public (and public local) timeline - PublicTimeline = BasePath + "/public" - // MaxIDKey is the url query for setting a max status ID to return - MaxIDKey = "max_id" - // SinceIDKey is the url query for returning results newer than the given ID - SinceIDKey = "since_id" - // MinIDKey is the url query for returning results immediately newer than the given ID - MinIDKey = "min_id" - // LimitKey is for specifying maximum number of results to return. - LimitKey = "limit" - // LocalKey is for specifying whether only local statuses should be returned - LocalKey = "local" -) - -// Module implements the ClientAPIModule interface for everything relating to viewing timelines -type Module struct { - processor processing.Processor -} - -// New returns a new timeline module -func New(processor processing.Processor) api.ClientModule { - return &Module{ - processor: processor, - } -} - -// Route attaches all routes from this module to the given router -func (m *Module) Route(r router.Router) error { - r.AttachHandler(http.MethodGet, HomeTimeline, m.HomeTimelineGETHandler) - r.AttachHandler(http.MethodGet, PublicTimeline, m.PublicTimelineGETHandler) - return nil -} diff --git a/internal/api/client/timelines/home.go b/internal/api/client/timelines/home.go new file mode 100644 index 000000000..33af8fe5e --- /dev/null +++ b/internal/api/client/timelines/home.go @@ -0,0 +1,176 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package timelines + +import ( + "fmt" + "net/http" + "strconv" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// HomeTimelineGETHandler swagger:operation GET /api/v1/timelines/home homeTimeline +// +// See statuses/posts by accounts you follow. +// +// The statuses will be returned in descending chronological order (newest first), with sequential IDs (bigger = newer). +// +// The returned Link header can be used to generate the previous and next queries when scrolling up or down a timeline. +// +// Example: +// +// ``` +// ; rel="next", ; rel="prev" +// ```` +// +// --- +// tags: +// - timelines +// +// produces: +// - application/json +// +// parameters: +// - +// name: max_id +// type: string +// description: >- +// Return only statuses *OLDER* than the given max status ID. +// The status with the specified ID will not be included in the response. +// in: query +// required: false +// - +// name: since_id +// type: string +// description: >- +// Return only statuses *NEWER* than the given since status ID. +// The status with the specified ID will not be included in the response. +// in: query +// - +// name: min_id +// type: string +// description: >- +// Return only statuses *NEWER* than the given since status ID. +// The status with the specified ID will not be included in the response. +// in: query +// required: false +// - +// name: limit +// type: integer +// description: Number of statuses to return. +// default: 20 +// in: query +// required: false +// - +// name: local +// type: boolean +// description: Show only statuses posted by local accounts. +// default: false +// in: query +// required: false +// +// security: +// - OAuth2 Bearer: +// - read:statuses +// +// responses: +// '200': +// name: statuses +// description: Array of statuses. +// schema: +// type: array +// items: +// "$ref": "#/definitions/status" +// headers: +// Link: +// type: string +// description: Links to the next and previous queries. +// '401': +// description: unauthorized +// '400': +// description: bad request +func (m *Module) HomeTimelineGETHandler(c *gin.Context) { + authed, err := oauth.Authed(c, true, true, true, true) + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + maxID := "" + maxIDString := c.Query(MaxIDKey) + if maxIDString != "" { + maxID = maxIDString + } + + sinceID := "" + sinceIDString := c.Query(SinceIDKey) + if sinceIDString != "" { + sinceID = sinceIDString + } + + minID := "" + minIDString := c.Query(MinIDKey) + if minIDString != "" { + minID = minIDString + } + + limit := 20 + limitString := c.Query(LimitKey) + if limitString != "" { + i, err := strconv.ParseInt(limitString, 10, 32) + if err != nil { + err := fmt.Errorf("error parsing %s: %s", LimitKey, err) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + limit = int(i) + } + + local := false + localString := c.Query(LocalKey) + if localString != "" { + i, err := strconv.ParseBool(localString) + if err != nil { + err := fmt.Errorf("error parsing %s: %s", LocalKey, err) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + local = i + } + + resp, errWithCode := m.processor.HomeTimelineGet(c.Request.Context(), authed, maxID, sinceID, minID, limit, local) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + if resp.LinkHeader != "" { + c.Header("Link", resp.LinkHeader) + } + c.JSON(http.StatusOK, resp.Items) +} diff --git a/internal/api/client/timelines/public.go b/internal/api/client/timelines/public.go new file mode 100644 index 000000000..efe351a37 --- /dev/null +++ b/internal/api/client/timelines/public.go @@ -0,0 +1,187 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package timelines + +import ( + "fmt" + "net/http" + "strconv" + + "github.com/gin-gonic/gin" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" + "github.com/superseriousbusiness/gotosocial/internal/config" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" + "github.com/superseriousbusiness/gotosocial/internal/oauth" +) + +// PublicTimelineGETHandler swagger:operation GET /api/v1/timelines/public publicTimeline +// +// See public statuses/posts that your instance is aware of. +// +// The statuses will be returned in descending chronological order (newest first), with sequential IDs (bigger = newer). +// +// The returned Link header can be used to generate the previous and next queries when scrolling up or down a timeline. +// +// Example: +// +// ``` +// ; rel="next", ; rel="prev" +// ```` +// +// --- +// tags: +// - timelines +// +// produces: +// - application/json +// +// parameters: +// - +// name: max_id +// type: string +// description: >- +// Return only statuses *OLDER* than the given max status ID. +// The status with the specified ID will not be included in the response. +// in: query +// required: false +// - +// name: since_id +// type: string +// description: >- +// Return only statuses *NEWER* than the given since status ID. +// The status with the specified ID will not be included in the response. +// in: query +// - +// name: min_id +// type: string +// description: >- +// Return only statuses *NEWER* than the given since status ID. +// The status with the specified ID will not be included in the response. +// in: query +// required: false +// - +// name: limit +// type: integer +// description: Number of statuses to return. +// default: 20 +// in: query +// required: false +// - +// name: local +// type: boolean +// description: Show only statuses posted by local accounts. +// default: false +// in: query +// required: false +// +// security: +// - OAuth2 Bearer: +// - read:statuses +// +// responses: +// '200': +// name: statuses +// description: Array of statuses. +// schema: +// type: array +// items: +// "$ref": "#/definitions/status" +// headers: +// Link: +// type: string +// description: Links to the next and previous queries. +// '401': +// description: unauthorized +// '400': +// description: bad request +func (m *Module) PublicTimelineGETHandler(c *gin.Context) { + var authed *oauth.Auth + var err error + + if config.GetInstanceExposePublicTimeline() { + // If the public timeline is allowed to be exposed, still check if we + // can extract various authentication properties, but don't require them. + authed, err = oauth.Authed(c, false, false, false, false) + } else { + authed, err = oauth.Authed(c, true, true, true, true) + } + + if err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + return + } + + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + return + } + + maxID := "" + maxIDString := c.Query(MaxIDKey) + if maxIDString != "" { + maxID = maxIDString + } + + sinceID := "" + sinceIDString := c.Query(SinceIDKey) + if sinceIDString != "" { + sinceID = sinceIDString + } + + minID := "" + minIDString := c.Query(MinIDKey) + if minIDString != "" { + minID = minIDString + } + + limit := 20 + limitString := c.Query(LimitKey) + if limitString != "" { + i, err := strconv.ParseInt(limitString, 10, 32) + if err != nil { + err := fmt.Errorf("error parsing %s: %s", LimitKey, err) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + limit = int(i) + } + + local := false + localString := c.Query(LocalKey) + if localString != "" { + i, err := strconv.ParseBool(localString) + if err != nil { + err := fmt.Errorf("error parsing %s: %s", LocalKey, err) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } + local = i + } + + resp, errWithCode := m.processor.PublicTimelineGet(c.Request.Context(), authed, maxID, sinceID, minID, limit, local) + if errWithCode != nil { + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + return + } + + if resp.LinkHeader != "" { + c.Header("Link", resp.LinkHeader) + } + c.JSON(http.StatusOK, resp.Items) +} diff --git a/internal/api/client/timelines/timeline.go b/internal/api/client/timelines/timeline.go new file mode 100644 index 000000000..609e1855e --- /dev/null +++ b/internal/api/client/timelines/timeline.go @@ -0,0 +1,60 @@ +/* + GoToSocial + Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package timelines + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "github.com/superseriousbusiness/gotosocial/internal/processing" +) + +const ( + // BasePath is the base URI path for serving timelines, minus the 'api' prefix. + BasePath = "/v1/timelines" + // HomeTimeline is the path for the home timeline + HomeTimeline = BasePath + "/home" + // PublicTimeline is the path for the public (and public local) timeline + PublicTimeline = BasePath + "/public" + // MaxIDKey is the url query for setting a max status ID to return + MaxIDKey = "max_id" + // SinceIDKey is the url query for returning results newer than the given ID + SinceIDKey = "since_id" + // MinIDKey is the url query for returning results immediately newer than the given ID + MinIDKey = "min_id" + // LimitKey is for specifying maximum number of results to return. + LimitKey = "limit" + // LocalKey is for specifying whether only local statuses should be returned + LocalKey = "local" +) + +type Module struct { + processor processing.Processor +} + +func New(processor processing.Processor) *Module { + return &Module{ + processor: processor, + } +} + +func (m *Module) Route(attachHandler func(method string, path string, f ...gin.HandlerFunc) gin.IRoutes) { + attachHandler(http.MethodGet, HomeTimeline, m.HomeTimelineGETHandler) + attachHandler(http.MethodGet, PublicTimeline, m.PublicTimelineGETHandler) +} diff --git a/internal/api/client/user/passwordchange.go b/internal/api/client/user/passwordchange.go index a900af897..c766d915c 100644 --- a/internal/api/client/user/passwordchange.go +++ b/internal/api/client/user/passwordchange.go @@ -23,8 +23,8 @@ import ( "net/http" "github.com/gin-gonic/gin" - "github.com/superseriousbusiness/gotosocial/internal/api" - "github.com/superseriousbusiness/gotosocial/internal/api/model" + apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" + apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/oauth" ) @@ -68,35 +68,35 @@ import ( func (m *Module) PasswordChangePOSTHandler(c *gin.Context) { authed, err := oauth.Authed(c, true, true, true, true) if err != nil { - api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) + if _, err := apiutil.NegotiateAccept(c, apiutil.JSONAcceptHeaders...); err != nil { + apiutil.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } - form := &model.PasswordChangeRequest{} + form := &apimodel.PasswordChangeRequest{} if err := c.ShouldBind(form); err != nil { - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } if form.OldPassword == "" { err := errors.New("password change request missing field old_password") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } if form.NewPassword == "" { err := errors.New("password change request missing field new_password") - api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + apiutil.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } if errWithCode := m.processor.UserChangePassword(c.Request.Context(), authed, form); errWithCode != nil { - api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) + apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } diff --git a/internal/api/client/user/user.go b/internal/api/client/user/user.go index 86a0096e0..5e6002b40 100644 --- a/internal/api/client/user/user.go +++ b/internal/api/client/user/user.go @@ -21,32 +21,27 @@ package user import ( "net/http" - "github.com/superseriousbusiness/gotosocial/internal/api" + "github.com/gin-gonic/gin" "github.com/superseriousbusiness/gotosocial/internal/processing" - "github.com/superseriousbusiness/gotosocial/internal/router" ) const ( - // BasePath is the base URI path for this module - BasePath = "/api/v1/user" + // BasePath is the base URI path for this module, minus the 'api' prefix + BasePath = "/v1/user" // PasswordChangePath is the path for POSTing a password change request. PasswordChangePath = BasePath + "/password_change" ) -// Module implements the ClientAPIModule interface type Module struct { processor processing.Processor } -// New returns a new user module -func New(processor processing.Processor) api.ClientModule { +func New(processor processing.Processor) *Module { return &Module{ processor: processor, } } -// Route attaches all routes from this module to the given router -func (m *Module) Route(r router.Router) error { - r.AttachHandler(http.MethodPost, PasswordChangePath, m.PasswordChangePOSTHandler) - return nil +func (m *Module) Route(attachHandler func(method string, path string, f ...gin.HandlerFunc) gin.IRoutes) { + attachHandler(http.MethodPost, PasswordChangePath, m.PasswordChangePOSTHandler) } diff --git a/internal/api/client/user/user_test.go b/internal/api/client/user/user_test.go index cc4fafca9..055b1f7a4 100644 --- a/internal/api/client/user/user_test.go +++ b/internal/api/client/user/user_test.go @@ -73,7 +73,7 @@ func (suite *UserStandardTestSuite) SetupTest() { suite.sentEmails = make(map[string]string) suite.emailSender = testrig.NewEmailSender("../../../../web/template/", suite.sentEmails) suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator, suite.emailSender, suite.mediaManager, clientWorker, fedWorker) - suite.userModule = user.New(suite.processor).(*user.Module) + suite.userModule = user.New(suite.processor) testrig.StandardDBSetup(suite.db, suite.testAccounts) testrig.StandardStorageSetup(suite.storage, "../../../../testrig/media") -- cgit v1.2.3