2023-03-12 16:00:57 +01:00
// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
2021-04-19 19:42:19 +02:00
2021-05-08 14:25:55 +02:00
package typeutils
2021-04-19 19:42:19 +02:00
import (
2021-08-25 15:34:33 +02:00
"context"
2023-05-07 19:53:21 +02:00
"errors"
2021-04-19 19:42:19 +02:00
"fmt"
2022-12-22 11:48:28 +01:00
"math"
"strconv"
2021-05-17 19:06:58 +02:00
"strings"
2024-05-06 13:49:08 +02:00
"time"
2021-04-19 19:42:19 +02:00
2024-06-03 11:20:53 +02:00
"codeberg.org/gruf/go-debug"
2023-01-02 13:10:50 +01:00
apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
2021-12-07 13:31:39 +01:00
"github.com/superseriousbusiness/gotosocial/internal/config"
2023-05-07 19:53:21 +02:00
"github.com/superseriousbusiness/gotosocial/internal/db"
2024-05-06 13:49:08 +02:00
statusfilter "github.com/superseriousbusiness/gotosocial/internal/filter/status"
2022-12-22 11:48:28 +01:00
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
2021-05-08 14:25:55 +02:00
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
2023-11-17 11:35:28 +01:00
"github.com/superseriousbusiness/gotosocial/internal/language"
2022-07-19 10:47:55 +02:00
"github.com/superseriousbusiness/gotosocial/internal/log"
2022-06-26 10:58:45 +02:00
"github.com/superseriousbusiness/gotosocial/internal/media"
2024-05-06 13:49:08 +02:00
"github.com/superseriousbusiness/gotosocial/internal/text"
2023-07-31 15:47:35 +02:00
"github.com/superseriousbusiness/gotosocial/internal/uris"
2022-05-24 18:21:27 +02:00
"github.com/superseriousbusiness/gotosocial/internal/util"
2021-04-19 19:42:19 +02:00
)
2022-09-08 12:36:42 +02:00
const (
instanceStatusesCharactersReservedPerURL = 25
instanceMediaAttachmentsImageMatrixLimit = 16777216 // width * height
instanceMediaAttachmentsVideoMatrixLimit = 16777216 // width * height
instanceMediaAttachmentsVideoFrameRateLimit = 60
instancePollsMinExpiration = 300 // seconds
instancePollsMaxExpiration = 2629746 // seconds
2023-02-02 14:08:13 +01:00
instanceAccountsMaxFeaturedTags = 10
2023-06-13 12:21:26 +02:00
instanceAccountsMaxProfileFields = 6 // FIXME: https://github.com/superseriousbusiness/gotosocial/issues/1876
2023-02-02 14:08:13 +01:00
instanceSourceURL = "https://github.com/superseriousbusiness/gotosocial"
2023-07-21 19:49:13 +02:00
instanceMastodonVersion = "3.5.3"
2022-09-08 12:36:42 +02:00
)
2023-03-02 12:06:40 +01:00
var instanceStatusesSupportedMimeTypes = [ ] string {
string ( apimodel . StatusContentTypePlain ) ,
string ( apimodel . StatusContentTypeMarkdown ) ,
}
2023-07-21 19:49:13 +02:00
func toMastodonVersion ( in string ) string {
return instanceMastodonVersion + "+" + strings . ReplaceAll ( in , " " , "-" )
}
2023-09-23 18:44:11 +02:00
// AppToAPIAppSensitive takes a db model application as a param, and returns a populated apitype application, or an error
// if something goes wrong. The returned application should be ready to serialize on an API level, and may have sensitive fields
// (such as client id and client secret), so serve it only to an authorized user who should have permission to see it.
func ( c * Converter ) AccountToAPIAccountSensitive ( ctx context . Context , a * gtsmodel . Account ) ( * apimodel . Account , error ) {
2024-04-16 13:10:13 +02:00
// We can build this sensitive account model
// by first getting the public account, and
// then adding the Source object to it.
2021-10-04 15:24:19 +02:00
apiAccount , err := c . AccountToAPIAccountPublic ( ctx , a )
2021-04-19 19:42:19 +02:00
if err != nil {
return nil , err
}
2024-04-16 13:10:13 +02:00
// Ensure account stats populated.
if a . Stats == nil {
if err := c . state . DB . PopulateAccountStats ( ctx , a ) ; err != nil {
return nil , gtserror . Newf (
"error getting stats for account %s: %w" ,
a . ID , err ,
)
}
2021-04-19 19:42:19 +02:00
}
2023-03-02 12:06:40 +01:00
statusContentType := string ( apimodel . StatusContentTypeDefault )
2024-03-22 14:03:46 +01:00
if a . Settings . StatusContentType != "" {
statusContentType = a . Settings . StatusContentType
2022-08-06 12:09:21 +02:00
}
2023-01-02 13:10:50 +01:00
apiAccount . Source = & apimodel . Source {
2024-03-22 14:03:46 +01:00
Privacy : c . VisToAPIVis ( ctx , a . Settings . Privacy ) ,
Sensitive : * a . Settings . Sensitive ,
Language : a . Settings . Language ,
2023-03-02 12:06:40 +01:00
StatusContentType : statusContentType ,
2022-05-07 17:55:27 +02:00
Note : a . NoteRaw ,
2023-05-09 12:16:10 +02:00
Fields : c . fieldsToAPIFields ( a . FieldsRaw ) ,
2024-04-16 13:10:13 +02:00
FollowRequestsCount : * a . Stats . FollowRequestsCount ,
2024-01-16 17:22:44 +01:00
AlsoKnownAsURIs : a . AlsoKnownAsURIs ,
2021-04-19 19:42:19 +02:00
}
2021-10-04 15:24:19 +02:00
return apiAccount , nil
2021-04-19 19:42:19 +02:00
}
2023-09-23 18:44:11 +02:00
// AccountToAPIAccountPublic takes a db model account as a param, and returns a populated apitype account, or an error
// if something goes wrong. The returned account should be ready to serialize on an API level, and may NOT have sensitive fields.
// In other words, this is the public record that the server has of an account.
func ( c * Converter ) AccountToAPIAccountPublic ( ctx context . Context , a * gtsmodel . Account ) ( * apimodel . Account , error ) {
2024-04-16 13:10:13 +02:00
// Populate account struct fields.
err := c . state . DB . PopulateAccount ( ctx , a )
switch {
case err == nil :
// No problem.
case err != nil && a . Stats != nil :
// We have stats so that's
// *maybe* OK, try to continue.
2023-05-07 19:53:21 +02:00
log . Errorf ( ctx , "error(s) populating account, will continue: %s" , err )
2024-04-16 13:10:13 +02:00
default :
// There was an error and we don't
// have stats, we can't continue.
return nil , gtserror . Newf ( "account stats not populated, could not continue: %w" , err )
2023-05-07 19:53:21 +02:00
}
// Basic account stats:
// - Followers count
// - Following count
// - Statuses count
// - Last status time
2024-04-16 13:10:13 +02:00
var (
followersCount = * a . Stats . FollowersCount
followingCount = * a . Stats . FollowingCount
statusesCount = * a . Stats . StatusesCount
lastStatusAt = func ( ) * string {
if a . Stats . LastStatusAt . IsZero ( ) {
return nil
}
return util . Ptr ( util . FormatISO8601 ( a . Stats . LastStatusAt ) )
} ( )
)
2021-04-19 19:42:19 +02:00
2023-05-07 19:53:21 +02:00
// Profile media + nice extras:
// - Avatar
// - Header
// - Fields
// - Emojis
var (
aviURL string
aviURLStatic string
headerURL string
headerURLStatic string
)
if a . AvatarMediaAttachment != nil {
aviURL = a . AvatarMediaAttachment . URL
aviURLStatic = a . AvatarMediaAttachment . Thumbnail . URL
2021-04-19 19:42:19 +02:00
}
2023-05-07 19:53:21 +02:00
if a . HeaderMediaAttachment != nil {
headerURL = a . HeaderMediaAttachment . URL
headerURLStatic = a . HeaderMediaAttachment . Thumbnail . URL
}
2022-11-29 18:59:59 +01:00
2023-05-09 12:16:10 +02:00
// convert account gts model fields to front api model fields
fields := c . fieldsToAPIFields ( a . Fields )
2021-04-19 19:42:19 +02:00
2023-05-07 19:53:21 +02:00
// GTS model emojis -> frontend.
2022-11-29 18:59:59 +01:00
apiEmojis , err := c . convertEmojisToAPIEmojis ( ctx , a . Emojis , a . EmojiIDs )
if err != nil {
2023-02-17 12:02:29 +01:00
log . Errorf ( ctx , "error converting account emojis: %v" , err )
2022-09-26 11:56:01 +02:00
}
2021-05-27 16:06:24 +02:00
2023-05-07 19:53:21 +02:00
// Bits that vary between remote + local accounts:
// - Account (acct) string.
// - Role.
2024-04-02 11:42:24 +02:00
// - Settings things (enableRSS, theme, customCSS, hideCollections).
2023-05-07 19:53:21 +02:00
var (
2024-04-02 11:42:24 +02:00
acct string
role * apimodel . AccountRole
enableRSS bool
theme string
customCSS string
hideCollections bool
2023-05-07 19:53:21 +02:00
)
if a . IsRemote ( ) {
// Domain may be in Punycode,
// de-punify it just in case.
d , err := util . DePunify ( a . Domain )
if err != nil {
2024-01-16 17:22:44 +01:00
return nil , gtserror . Newf ( "error de-punifying domain %s for account id %s: %w" , a . Domain , a . ID , err )
2023-05-07 19:53:21 +02:00
}
2022-11-15 10:19:32 +01:00
2023-05-07 19:53:21 +02:00
acct = a . Username + "@" + d
2021-04-19 19:42:19 +02:00
} else {
2023-05-09 17:05:35 +02:00
// This is a local account, try to
// fetch more info. Skip for instance
// accounts since they have no user.
if ! a . IsInstance ( ) {
2023-09-23 18:44:11 +02:00
user , err := c . state . DB . GetUserByAccountID ( ctx , a . ID )
2023-05-09 17:05:35 +02:00
if err != nil {
2024-01-16 17:22:44 +01:00
return nil , gtserror . Newf ( "error getting user from database for account id %s: %w" , a . ID , err )
2023-05-09 17:05:35 +02:00
}
switch {
case * user . Admin :
role = & apimodel . AccountRole { Name : apimodel . AccountRoleAdmin }
case * user . Moderator :
role = & apimodel . AccountRole { Name : apimodel . AccountRoleModerator }
default :
role = & apimodel . AccountRole { Name : apimodel . AccountRoleUser }
}
2024-03-22 14:03:46 +01:00
enableRSS = * a . Settings . EnableRSS
2024-03-25 18:32:24 +01:00
theme = a . Settings . Theme
2024-03-22 14:03:46 +01:00
customCSS = a . Settings . CustomCSS
2024-04-02 11:42:24 +02:00
hideCollections = * a . Settings . HideCollections
2022-11-15 10:19:32 +01:00
}
2023-05-09 17:05:35 +02:00
acct = a . Username // omit domain
2021-04-19 19:42:19 +02:00
}
2024-01-16 17:22:44 +01:00
// Populate moved.
var moved * apimodel . Account
if a . MovedTo != nil {
moved , err = c . AccountToAPIAccountPublic ( ctx , a . MovedTo )
if err != nil {
log . Errorf ( ctx , "error converting account movedTo: %v" , err )
}
}
2024-01-19 14:02:04 +01:00
// Bool ptrs should be set, but warn
// and use a default if they're not.
var boolPtrDef = func (
pName string ,
p * bool ,
d bool ,
) bool {
if p != nil {
return * p
}
log . Warnf ( ctx ,
"%s ptr was nil, using default %t" ,
pName , d ,
)
return d
}
var (
locked = boolPtrDef ( "locked" , a . Locked , true )
discoverable = boolPtrDef ( "discoverable" , a . Discoverable , false )
bot = boolPtrDef ( "bot" , a . Bot , false )
)
2023-05-07 19:53:21 +02:00
// Remaining properties are simple and
// can be populated directly below.
2021-07-11 16:22:21 +02:00
2023-01-02 13:10:50 +01:00
accountFrontend := & apimodel . Account {
2024-04-02 11:42:24 +02:00
ID : a . ID ,
Username : a . Username ,
Acct : acct ,
DisplayName : a . DisplayName ,
Locked : locked ,
Discoverable : discoverable ,
Bot : bot ,
CreatedAt : util . FormatISO8601 ( a . CreatedAt ) ,
Note : a . Note ,
URL : a . URL ,
Avatar : aviURL ,
AvatarStatic : aviURLStatic ,
Header : headerURL ,
HeaderStatic : headerURLStatic ,
FollowersCount : followersCount ,
FollowingCount : followingCount ,
StatusesCount : statusesCount ,
LastStatusAt : lastStatusAt ,
Emojis : apiEmojis ,
Fields : fields ,
Suspended : ! a . SuspendedAt . IsZero ( ) ,
Theme : theme ,
CustomCSS : customCSS ,
EnableRSS : enableRSS ,
HideCollections : hideCollections ,
Role : role ,
Moved : moved ,
2021-08-20 12:26:56 +02:00
}
2023-05-07 19:53:21 +02:00
// Bodge default avatar + header in,
// if we didn't have one already.
2022-09-04 14:41:42 +02:00
c . ensureAvatar ( accountFrontend )
c . ensureHeader ( accountFrontend )
2021-08-20 12:26:56 +02:00
return accountFrontend , nil
2021-07-11 16:22:21 +02:00
}
2023-09-23 18:44:11 +02:00
func ( c * Converter ) fieldsToAPIFields ( f [ ] * gtsmodel . Field ) [ ] apimodel . Field {
2023-05-09 12:16:10 +02:00
fields := make ( [ ] apimodel . Field , len ( f ) )
for i , field := range f {
mField := apimodel . Field {
Name : field . Name ,
Value : field . Value ,
}
if ! field . VerifiedAt . IsZero ( ) {
mField . VerifiedAt = func ( ) * string { s := util . FormatISO8601 ( field . VerifiedAt ) ; return & s } ( )
}
fields [ i ] = mField
}
return fields
}
2023-09-23 18:44:11 +02:00
// AccountToAPIAccountBlocked takes a db model account as a param, and returns a apitype account, or an error if
// something goes wrong. The returned account will be a bare minimum representation of the account. This function should be used
// when someone wants to view an account they've blocked.
func ( c * Converter ) AccountToAPIAccountBlocked ( ctx context . Context , a * gtsmodel . Account ) ( * apimodel . Account , error ) {
2023-05-07 19:53:21 +02:00
var (
acct string
role * apimodel . AccountRole
)
if a . IsRemote ( ) {
// Domain may be in Punycode,
// de-punify it just in case.
d , err := util . DePunify ( a . Domain )
if err != nil {
2023-10-30 19:01:00 +01:00
return nil , gtserror . Newf ( "error de-punifying domain %s for account id %s: %w" , a . Domain , a . ID , err )
2023-05-07 19:53:21 +02:00
}
acct = a . Username + "@" + d
2021-07-11 16:22:21 +02:00
} else {
2023-05-09 17:05:35 +02:00
// This is a local account, try to
// fetch more info. Skip for instance
// accounts since they have no user.
if ! a . IsInstance ( ) {
2023-09-23 18:44:11 +02:00
user , err := c . state . DB . GetUserByAccountID ( ctx , a . ID )
2023-05-09 17:05:35 +02:00
if err != nil {
2023-10-30 19:01:00 +01:00
return nil , gtserror . Newf ( "error getting user from database for account id %s: %w" , a . ID , err )
2023-05-09 17:05:35 +02:00
}
switch {
case * user . Admin :
role = & apimodel . AccountRole { Name : apimodel . AccountRoleAdmin }
case * user . Moderator :
role = & apimodel . AccountRole { Name : apimodel . AccountRoleModerator }
default :
role = & apimodel . AccountRole { Name : apimodel . AccountRoleUser }
}
2023-05-07 19:53:21 +02:00
}
2023-05-09 17:05:35 +02:00
acct = a . Username // omit domain
2021-07-11 16:22:21 +02:00
}
2023-10-30 19:01:00 +01:00
account := & apimodel . Account {
ID : a . ID ,
Username : a . Username ,
Acct : acct ,
Bot : * a . Bot ,
CreatedAt : util . FormatISO8601 ( a . CreatedAt ) ,
URL : a . URL ,
2024-06-06 12:22:16 +02:00
// Empty array (not nillable).
Emojis : make ( [ ] apimodel . Emoji , 0 ) ,
// Empty array (not nillable).
Fields : make ( [ ] apimodel . Field , 0 ) ,
2023-10-30 19:01:00 +01:00
Suspended : ! a . SuspendedAt . IsZero ( ) ,
Role : role ,
}
// Don't show the account's actual
// avatar+header since it may be
// upsetting to the blocker. Just
// show generic avatar+header instead.
c . ensureAvatar ( account )
c . ensureHeader ( account )
return account , nil
2021-04-19 19:42:19 +02:00
}
2023-09-23 18:44:11 +02:00
func ( c * Converter ) AccountToAdminAPIAccount ( ctx context . Context , a * gtsmodel . Account ) ( * apimodel . AdminAccountInfo , error ) {
2023-01-25 11:12:17 +01:00
var (
email string
ip * string
domain * string
locale string
confirmed bool
inviteRequest * string
approved bool
disabled bool
2023-02-20 17:00:44 +01:00
role = apimodel . AccountRole { Name : apimodel . AccountRoleUser } // assume user by default
2023-01-25 11:12:17 +01:00
createdByApplicationID string
)
2024-03-22 14:03:46 +01:00
if err := c . state . DB . PopulateAccount ( ctx , a ) ; err != nil {
log . Errorf ( ctx , "error(s) populating account, will continue: %s" , err )
}
2023-03-31 15:01:29 +02:00
if a . IsRemote ( ) {
2023-05-07 19:53:21 +02:00
// Domain may be in Punycode,
// de-punify it just in case.
d , err := util . DePunify ( a . Domain )
if err != nil {
return nil , fmt . Errorf ( "AccountToAdminAPIAccount: error de-punifying domain %s for account id %s: %w" , a . Domain , a . ID , err )
}
domain = & d
2023-05-09 17:05:35 +02:00
} else if ! a . IsInstance ( ) {
// This is a local, non-instance
// acct; we can fetch more info.
2023-09-23 18:44:11 +02:00
user , err := c . state . DB . GetUserByAccountID ( ctx , a . ID )
2023-01-25 11:12:17 +01:00
if err != nil {
return nil , fmt . Errorf ( "AccountToAdminAPIAccount: error getting user from database for account id %s: %w" , a . ID , err )
}
if user . Email != "" {
email = user . Email
} else {
email = user . UnconfirmedEmail
}
2024-04-11 11:45:53 +02:00
if i := user . SignUpIP . String ( ) ; i != "<nil>" {
2023-01-25 11:12:17 +01:00
ip = & i
}
locale = user . Locale
2024-04-11 11:45:53 +02:00
if user . Reason != "" {
inviteRequest = & user . Reason
2023-03-31 15:01:29 +02:00
}
2023-05-09 17:05:35 +02:00
2023-01-25 11:12:17 +01:00
if * user . Admin {
2023-02-20 17:00:44 +01:00
role . Name = apimodel . AccountRoleAdmin
2023-01-25 11:12:17 +01:00
} else if * user . Moderator {
2023-02-20 17:00:44 +01:00
role . Name = apimodel . AccountRoleModerator
2023-01-25 11:12:17 +01:00
}
2023-05-09 17:05:35 +02:00
2023-01-25 11:12:17 +01:00
confirmed = ! user . ConfirmedAt . IsZero ( )
approved = * user . Approved
disabled = * user . Disabled
createdByApplicationID = user . CreatedByApplicationID
}
apiAccount , err := c . AccountToAPIAccountPublic ( ctx , a )
if err != nil {
return nil , fmt . Errorf ( "AccountToAdminAPIAccount: error converting account to api account for account id %s: %w" , a . ID , err )
}
return & apimodel . AdminAccountInfo {
ID : a . ID ,
Username : a . Username ,
Domain : domain ,
CreatedAt : util . FormatISO8601 ( a . CreatedAt ) ,
Email : email ,
IP : ip ,
IPs : [ ] interface { } { } , // not implemented,
Locale : locale ,
InviteRequest : inviteRequest ,
2023-02-20 17:00:44 +01:00
Role : role ,
2023-01-25 11:12:17 +01:00
Confirmed : confirmed ,
Approved : approved ,
Disabled : disabled ,
2023-05-07 19:53:21 +02:00
Silenced : ! a . SilencedAt . IsZero ( ) ,
Suspended : ! a . SuspendedAt . IsZero ( ) ,
2023-01-25 11:12:17 +01:00
Account : apiAccount ,
CreatedByApplicationID : createdByApplicationID ,
InvitedByAccountID : "" , // not implemented (yet)
} , nil
}
2023-09-23 18:44:11 +02:00
func ( c * Converter ) AppToAPIAppSensitive ( ctx context . Context , a * gtsmodel . Application ) ( * apimodel . Application , error ) {
2023-01-02 13:10:50 +01:00
return & apimodel . Application {
2021-04-19 19:42:19 +02:00
ID : a . ID ,
Name : a . Name ,
Website : a . Website ,
RedirectURI : a . RedirectURI ,
ClientID : a . ClientID ,
ClientSecret : a . ClientSecret ,
} , nil
}
2023-09-23 18:44:11 +02:00
// AppToAPIAppPublic takes a db model application as a param, and returns a populated apitype application, or an error
// if something goes wrong. The returned application should be ready to serialize on an API level, and has sensitive
// fields sanitized so that it can be served to non-authorized accounts without revealing any private information.
func ( c * Converter ) AppToAPIAppPublic ( ctx context . Context , a * gtsmodel . Application ) ( * apimodel . Application , error ) {
2023-01-02 13:10:50 +01:00
return & apimodel . Application {
2021-04-19 19:42:19 +02:00
Name : a . Name ,
Website : a . Website ,
} , nil
}
2023-09-23 18:44:11 +02:00
// AttachmentToAPIAttachment converts a gts model media attacahment into its api representation for serialization on the API.
func ( c * Converter ) AttachmentToAPIAttachment ( ctx context . Context , a * gtsmodel . MediaAttachment ) ( apimodel . Attachment , error ) {
2023-01-02 13:10:50 +01:00
apiAttachment := apimodel . Attachment {
2023-11-10 19:29:26 +01:00
ID : a . ID ,
Type : strings . ToLower ( string ( a . Type ) ) ,
}
// Don't try to serialize meta for
// unknown attachments, there's no point.
if a . Type != gtsmodel . FileTypeUnknown {
apiAttachment . Meta = & apimodel . MediaMeta {
2023-01-02 13:10:50 +01:00
Original : apimodel . MediaDimensions {
2021-04-19 19:42:19 +02:00
Width : a . FileMeta . Original . Width ,
Height : a . FileMeta . Original . Height ,
} ,
2023-01-02 13:10:50 +01:00
Small : apimodel . MediaDimensions {
2021-04-19 19:42:19 +02:00
Width : a . FileMeta . Small . Width ,
Height : a . FileMeta . Small . Height ,
2023-01-16 16:19:17 +01:00
Size : strconv . Itoa ( a . FileMeta . Small . Width ) + "x" + strconv . Itoa ( a . FileMeta . Small . Height ) ,
2021-04-19 19:42:19 +02:00
Aspect : float32 ( a . FileMeta . Small . Aspect ) ,
} ,
2023-11-10 19:29:26 +01:00
}
}
if i := a . Blurhash ; i != "" {
apiAttachment . Blurhash = & i
2022-07-22 12:48:19 +02:00
}
2022-12-22 11:48:28 +01:00
if i := a . URL ; i != "" {
2022-07-22 12:48:19 +02:00
apiAttachment . URL = & i
2023-11-10 19:29:26 +01:00
apiAttachment . TextURL = & i
}
if i := a . Thumbnail . URL ; i != "" {
apiAttachment . PreviewURL = & i
2022-07-22 12:48:19 +02:00
}
2022-12-22 11:48:28 +01:00
if i := a . RemoteURL ; i != "" {
2022-07-22 12:48:19 +02:00
apiAttachment . RemoteURL = & i
}
2022-12-22 11:48:28 +01:00
if i := a . Thumbnail . RemoteURL ; i != "" {
2022-07-22 12:48:19 +02:00
apiAttachment . PreviewRemoteURL = & i
}
2022-12-22 11:48:28 +01:00
if i := a . Description ; i != "" {
2022-07-22 12:48:19 +02:00
apiAttachment . Description = & i
}
2023-11-10 19:29:26 +01:00
// Type-specific fields.
2023-01-16 16:19:17 +01:00
switch a . Type {
2023-11-10 19:29:26 +01:00
2023-01-16 16:19:17 +01:00
case gtsmodel . FileTypeImage :
apiAttachment . Meta . Original . Size = strconv . Itoa ( a . FileMeta . Original . Width ) + "x" + strconv . Itoa ( a . FileMeta . Original . Height )
apiAttachment . Meta . Original . Aspect = float32 ( a . FileMeta . Original . Aspect )
apiAttachment . Meta . Focus = & apimodel . MediaFocus {
X : a . FileMeta . Focus . X ,
Y : a . FileMeta . Focus . Y ,
}
2023-11-10 19:29:26 +01:00
2023-01-16 16:19:17 +01:00
case gtsmodel . FileTypeVideo :
if i := a . FileMeta . Original . Duration ; i != nil {
apiAttachment . Meta . Original . Duration = * i
}
2022-12-22 11:48:28 +01:00
2023-01-16 16:19:17 +01:00
if i := a . FileMeta . Original . Framerate ; i != nil {
2023-11-10 19:29:26 +01:00
// The masto api expects this as a string in
// the format `integer/1`, so 30fps is `30/1`.
2023-01-16 16:19:17 +01:00
round := math . Round ( float64 ( * i ) )
2023-11-10 19:29:26 +01:00
fr := strconv . Itoa ( int ( round ) )
2023-01-16 16:19:17 +01:00
apiAttachment . Meta . Original . FrameRate = fr + "/1"
}
2022-12-22 11:48:28 +01:00
2023-01-16 16:19:17 +01:00
if i := a . FileMeta . Original . Bitrate ; i != nil {
apiAttachment . Meta . Original . Bitrate = int ( * i )
}
2022-12-22 11:48:28 +01:00
}
2022-07-22 12:48:19 +02:00
return apiAttachment , nil
2021-04-19 19:42:19 +02:00
}
2023-09-23 18:44:11 +02:00
// MentionToAPIMention converts a gts model mention into its api (frontend) representation for serialization on the API.
func ( c * Converter ) MentionToAPIMention ( ctx context . Context , m * gtsmodel . Mention ) ( apimodel . Mention , error ) {
2021-08-25 15:34:33 +02:00
if m . TargetAccount == nil {
2023-09-23 18:44:11 +02:00
targetAccount , err := c . state . DB . GetAccountByID ( ctx , m . TargetAccountID )
2021-08-25 15:34:33 +02:00
if err != nil {
2023-01-02 13:10:50 +01:00
return apimodel . Mention { } , err
2021-08-25 15:34:33 +02:00
}
m . TargetAccount = targetAccount
2021-04-19 19:42:19 +02:00
}
var acct string
2023-05-07 19:53:21 +02:00
if m . TargetAccount . IsLocal ( ) {
2021-08-25 15:34:33 +02:00
acct = m . TargetAccount . Username
2021-04-19 19:42:19 +02:00
} else {
2023-05-07 19:53:21 +02:00
// Domain may be in Punycode,
// de-punify it just in case.
d , err := util . DePunify ( m . TargetAccount . Domain )
if err != nil {
err = fmt . Errorf ( "MentionToAPIMention: error de-punifying domain %s for account id %s: %w" , m . TargetAccount . Domain , m . TargetAccountID , err )
return apimodel . Mention { } , err
}
acct = m . TargetAccount . Username + "@" + d
2021-04-19 19:42:19 +02:00
}
2023-01-02 13:10:50 +01:00
return apimodel . Mention {
2021-08-25 15:34:33 +02:00
ID : m . TargetAccount . ID ,
Username : m . TargetAccount . Username ,
URL : m . TargetAccount . URL ,
2021-04-19 19:42:19 +02:00
Acct : acct ,
} , nil
}
2023-09-23 18:44:11 +02:00
// EmojiToAPIEmoji converts a gts model emoji into its api (frontend) representation for serialization on the API.
func ( c * Converter ) EmojiToAPIEmoji ( ctx context . Context , e * gtsmodel . Emoji ) ( apimodel . Emoji , error ) {
2022-11-14 23:47:27 +01:00
var category string
if e . CategoryID != "" {
if e . Category == nil {
var err error
2023-09-23 18:44:11 +02:00
e . Category , err = c . state . DB . GetEmojiCategory ( ctx , e . CategoryID )
2022-11-14 23:47:27 +01:00
if err != nil {
2023-01-02 13:10:50 +01:00
return apimodel . Emoji { } , err
2022-11-14 23:47:27 +01:00
}
}
category = e . Category . Name
}
2023-01-02 13:10:50 +01:00
return apimodel . Emoji {
2021-04-19 19:42:19 +02:00
Shortcode : e . Shortcode ,
URL : e . ImageURL ,
StaticURL : e . ImageStaticURL ,
2022-08-15 12:35:05 +02:00
VisibleInPicker : * e . VisibleInPicker ,
2022-11-14 23:47:27 +01:00
Category : category ,
2021-04-19 19:42:19 +02:00
} , nil
}
2023-09-23 18:44:11 +02:00
// EmojiToAdminAPIEmoji converts a gts model emoji into an API representation with extra admin information.
func ( c * Converter ) EmojiToAdminAPIEmoji ( ctx context . Context , e * gtsmodel . Emoji ) ( * apimodel . AdminEmoji , error ) {
2022-10-12 15:01:42 +02:00
emoji , err := c . EmojiToAPIEmoji ( ctx , e )
if err != nil {
return nil , err
}
2024-01-29 15:57:22 +01:00
if ! e . IsLocal ( ) {
2023-05-07 19:53:21 +02:00
// Domain may be in Punycode,
// de-punify it just in case.
var err error
e . Domain , err = util . DePunify ( e . Domain )
if err != nil {
err = fmt . Errorf ( "EmojiToAdminAPIEmoji: error de-punifying domain %s for emoji id %s: %w" , e . Domain , e . ID , err )
return nil , err
}
}
2023-01-02 13:10:50 +01:00
return & apimodel . AdminEmoji {
2022-10-12 15:01:42 +02:00
Emoji : emoji ,
ID : e . ID ,
Disabled : * e . Disabled ,
Domain : e . Domain ,
UpdatedAt : util . FormatISO8601 ( e . UpdatedAt ) ,
TotalFileSize : e . ImageFileSize + e . ImageStaticFileSize ,
ContentType : e . ImageContentType ,
URI : e . URI ,
} , nil
}
2023-09-23 18:44:11 +02:00
// EmojiCategoryToAPIEmojiCategory converts a gts model emoji category into its api (frontend) representation.
func ( c * Converter ) EmojiCategoryToAPIEmojiCategory ( ctx context . Context , category * gtsmodel . EmojiCategory ) ( * apimodel . EmojiCategory , error ) {
2023-01-02 13:10:50 +01:00
return & apimodel . EmojiCategory {
2022-11-14 23:47:27 +01:00
ID : category . ID ,
Name : category . Name ,
} , nil
}
2023-09-23 18:44:11 +02:00
// TagToAPITag converts a gts model tag into its api (frontend) representation for serialization on the API.
// If stubHistory is set to 'true', then the 'history' field of the tag will be populated with a pointer to an empty slice, for API compatibility reasons.
func ( c * Converter ) TagToAPITag ( ctx context . Context , t * gtsmodel . Tag , stubHistory bool ) ( apimodel . Tag , error ) {
2023-01-02 13:10:50 +01:00
return apimodel . Tag {
2023-07-31 15:47:35 +02:00
Name : strings . ToLower ( t . Name ) ,
2023-11-10 19:29:26 +01:00
URL : uris . URIForTag ( t . Name ) ,
2023-07-31 15:47:35 +02:00
History : func ( ) * [ ] any {
if ! stubHistory {
return nil
}
h := make ( [ ] any , 0 )
return & h
} ( ) ,
2021-04-19 19:42:19 +02:00
} , nil
}
2023-11-10 19:29:26 +01:00
// StatusToAPIStatus converts a gts model status into its api
// (frontend) representation for serialization on the API.
//
// Requesting account can be nil.
2024-05-06 13:49:08 +02:00
//
// Filter context can be the empty string if these statuses are not being filtered.
//
// If there is a matching "hide" filter, the returned status will be nil with a ErrHideStatus error;
// callers need to handle that case by excluding it from results.
2023-11-10 19:29:26 +01:00
func ( c * Converter ) StatusToAPIStatus (
ctx context . Context ,
s * gtsmodel . Status ,
requestingAccount * gtsmodel . Account ,
2024-05-06 13:49:08 +02:00
filterContext statusfilter . FilterContext ,
filters [ ] * gtsmodel . Filter ,
2023-11-10 19:29:26 +01:00
) ( * apimodel . Status , error ) {
2024-05-06 13:49:08 +02:00
apiStatus , err := c . statusToFrontend ( ctx , s , requestingAccount , filterContext , filters )
2023-11-10 19:29:26 +01:00
if err != nil {
return nil , err
}
// Normalize status for the API by pruning
// out unknown attachment types and replacing
// them with a helpful message.
var aside string
aside , apiStatus . MediaAttachments = placeholdUnknownAttachments ( apiStatus . MediaAttachments )
apiStatus . Content += aside
return apiStatus , nil
}
2024-05-06 13:49:08 +02:00
// statusToAPIFilterResults applies filters to a status and returns an API filter result object.
// The result may be nil if no filters matched.
// If the status should not be returned at all, it returns the ErrHideStatus error.
func ( c * Converter ) statusToAPIFilterResults (
ctx context . Context ,
s * gtsmodel . Status ,
requestingAccount * gtsmodel . Account ,
filterContext statusfilter . FilterContext ,
filters [ ] * gtsmodel . Filter ,
) ( [ ] apimodel . FilterResult , error ) {
if filterContext == "" || len ( filters ) == 0 || s . AccountID == requestingAccount . ID {
return nil , nil
}
filterResults := make ( [ ] apimodel . FilterResult , 0 , len ( filters ) )
now := time . Now ( )
for _ , filter := range filters {
if ! filterAppliesInContext ( filter , filterContext ) {
// Filter doesn't apply to this context.
continue
}
if ! filter . ExpiresAt . IsZero ( ) && filter . ExpiresAt . Before ( now ) {
// Filter is expired.
continue
}
// List all matching keywords.
keywordMatches := make ( [ ] string , 0 , len ( filter . Keywords ) )
fields := filterableTextFields ( s )
for _ , filterKeyword := range filter . Keywords {
var isMatch bool
for _ , field := range fields {
2024-05-21 15:20:19 +02:00
if filterKeyword . Regexp . MatchString ( field ) {
2024-05-06 13:49:08 +02:00
isMatch = true
break
}
}
if isMatch {
keywordMatches = append ( keywordMatches , filterKeyword . Keyword )
}
}
// A status has only one ID. Not clear why this is a list in the Mastodon API.
statusMatches := make ( [ ] string , 0 , 1 )
for _ , filterStatus := range filter . Statuses {
if s . ID == filterStatus . StatusID {
statusMatches = append ( statusMatches , filterStatus . StatusID )
break
}
}
if len ( keywordMatches ) > 0 || len ( statusMatches ) > 0 {
switch filter . Action {
case gtsmodel . FilterActionWarn :
// Record what matched.
apiFilter , err := c . FilterToAPIFilterV2 ( ctx , filter )
if err != nil {
return nil , err
}
filterResults = append ( filterResults , apimodel . FilterResult {
Filter : * apiFilter ,
KeywordMatches : keywordMatches ,
StatusMatches : statusMatches ,
} )
case gtsmodel . FilterActionHide :
// Don't show this status. Immediate return.
return nil , statusfilter . ErrHideStatus
}
}
}
return filterResults , nil
}
// filterableTextFields returns all text from a status that we might want to filter on:
// - content
// - content warning
// - media descriptions
// - poll options
func filterableTextFields ( s * gtsmodel . Status ) [ ] string {
fieldCount := 2 + len ( s . Attachments )
if s . Poll != nil {
fieldCount += len ( s . Poll . Options )
}
fields := make ( [ ] string , 0 , fieldCount )
if s . Content != "" {
fields = append ( fields , text . SanitizeToPlaintext ( s . Content ) )
}
if s . ContentWarning != "" {
fields = append ( fields , s . ContentWarning )
}
for _ , attachment := range s . Attachments {
if attachment . Description != "" {
fields = append ( fields , attachment . Description )
}
}
if s . Poll != nil {
for _ , option := range s . Poll . Options {
if option != "" {
fields = append ( fields , option )
}
}
}
return fields
}
// filterAppliesInContext returns whether a given filter applies in a given context.
func filterAppliesInContext ( filter * gtsmodel . Filter , filterContext statusfilter . FilterContext ) bool {
switch filterContext {
case statusfilter . FilterContextHome :
return util . PtrValueOr ( filter . ContextHome , false )
case statusfilter . FilterContextNotifications :
return util . PtrValueOr ( filter . ContextNotifications , false )
case statusfilter . FilterContextPublic :
return util . PtrValueOr ( filter . ContextPublic , false )
case statusfilter . FilterContextThread :
return util . PtrValueOr ( filter . ContextThread , false )
case statusfilter . FilterContextAccount :
return util . PtrValueOr ( filter . ContextAccount , false )
}
return false
}
2023-11-10 19:29:26 +01:00
// StatusToWebStatus converts a gts model status into an
// api representation suitable for serving into a web template.
//
// Requesting account can be nil.
func ( c * Converter ) StatusToWebStatus (
ctx context . Context ,
s * gtsmodel . Status ,
requestingAccount * gtsmodel . Account ,
) ( * apimodel . Status , error ) {
2024-05-06 13:49:08 +02:00
webStatus , err := c . statusToFrontend ( ctx , s , requestingAccount , statusfilter . FilterContextNone , nil )
2023-11-17 11:35:28 +01:00
if err != nil {
return nil , err
}
2023-12-27 11:23:52 +01:00
// Whack a newline before and after each "pre" to make it easier to outdent it.
webStatus . Content = strings . ReplaceAll ( webStatus . Content , "<pre>" , "\n<pre>" )
webStatus . Content = strings . ReplaceAll ( webStatus . Content , "</pre>" , "</pre>\n" )
2023-11-17 11:35:28 +01:00
// Add additional information for template.
// Assume empty langs, hope for not empty language.
webStatus . LanguageTag = new ( language . Language )
if lang := webStatus . Language ; lang != nil {
langTag , err := language . Parse ( * lang )
if err != nil {
log . Warnf (
ctx ,
"error parsing %s as language tag: %v" ,
* lang , err ,
)
} else {
webStatus . LanguageTag = langTag
}
}
2023-11-22 12:17:42 +01:00
if poll := webStatus . Poll ; poll != nil {
// Calculate vote share of each poll option and
// format them for easier template consumption.
totalVotes := poll . VotesCount
webPollOptions := make ( [ ] apimodel . WebPollOption , len ( poll . Options ) )
for i , option := range poll . Options {
var voteShare float32
2023-12-12 14:47:07 +01:00
if totalVotes != 0 && option . VotesCount != nil {
voteShare = float32 ( * option . VotesCount ) / float32 ( totalVotes ) * 100
2023-11-22 12:17:42 +01:00
}
// Format to two decimal points and ditch any
// trailing zeroes.
//
// We want to be precise enough that eg., "1.54%"
// is distinct from "1.68%" in polls with loads
// of votes.
//
// However, if we've got eg., a two-option poll
// in which each option has half the votes, then
// "50%" looks better than "50.00%".
//
// By the same token, it's pointless to show
// "0.00%" or "100.00%".
voteShareStr := fmt . Sprintf ( "%.2f" , voteShare )
voteShareStr = strings . TrimSuffix ( voteShareStr , ".00" )
webPollOption := apimodel . WebPollOption {
PollOption : option ,
2023-11-22 16:27:32 +01:00
PollID : poll . ID ,
2023-11-22 12:17:42 +01:00
Emojis : webStatus . Emojis ,
LanguageTag : webStatus . LanguageTag ,
VoteShare : voteShare ,
VoteShareStr : voteShareStr ,
}
webPollOptions [ i ] = webPollOption
}
webStatus . WebPollOptions = webPollOptions
}
2023-12-05 12:43:07 +01:00
// Set additional templating
// variables on media attachments.
for _ , a := range webStatus . MediaAttachments {
a . Sensitive = webStatus . Sensitive
}
2023-12-27 11:23:52 +01:00
webStatus . Local = * s . Local
2023-11-17 11:35:28 +01:00
return webStatus , nil
2023-11-10 19:29:26 +01:00
}
2024-04-17 14:49:20 +02:00
// StatusToAPIStatusSource returns the *apimodel.StatusSource of the given status.
// Callers should check beforehand whether a requester has permission to view the
// source of the status, and ensure they're passing only a local status into this function.
func ( c * Converter ) StatusToAPIStatusSource ( ctx context . Context , s * gtsmodel . Status ) ( * apimodel . StatusSource , error ) {
2024-04-18 13:22:55 +02:00
// TODO: remove this when edit support is added.
text := "**STATUS EDITS ARE NOT CURRENTLY SUPPORTED IN GOTOSOCIAL (coming in 2024)**\n" +
"You can review the original text of your status below, but you will not be able to submit this edit.\n\n---\n\n" + s . Text
2024-04-17 14:49:20 +02:00
return & apimodel . StatusSource {
ID : s . ID ,
2024-04-18 13:22:55 +02:00
Text : text ,
2024-04-17 14:49:20 +02:00
SpoilerText : s . ContentWarning ,
} , nil
}
2023-11-10 19:29:26 +01:00
// statusToFrontend is a package internal function for
// parsing a status into its initial frontend representation.
2023-09-23 18:44:11 +02:00
//
// Requesting account can be nil.
2023-11-10 19:29:26 +01:00
func ( c * Converter ) statusToFrontend (
ctx context . Context ,
s * gtsmodel . Status ,
requestingAccount * gtsmodel . Account ,
2024-05-06 13:49:08 +02:00
filterContext statusfilter . FilterContext ,
filters [ ] * gtsmodel . Filter ,
2023-11-10 19:29:26 +01:00
) ( * apimodel . Status , error ) {
2023-12-01 15:27:15 +01:00
// Try to populate status struct pointer fields.
// We can continue in many cases of partial failure,
// but there are some fields we actually need.
2023-09-23 18:44:11 +02:00
if err := c . state . DB . PopulateStatus ( ctx , s ) ; err != nil {
2023-05-09 13:25:48 +02:00
if s . Account == nil {
2023-12-01 15:27:15 +01:00
err = gtserror . Newf ( "error(s) populating status, cannot continue (status.Account not set): %w" , err )
return nil , err
}
if s . BoostOfID != "" && s . BoostOf == nil {
err = gtserror . Newf ( "error(s) populating status, cannot continue (status.BoostOfID set, but status.Boost not set): %w" , err )
return nil , err
2023-05-09 13:25:48 +02:00
}
2021-04-19 19:42:19 +02:00
2023-05-09 13:25:48 +02:00
log . Errorf ( ctx , "error(s) populating status, will continue: %v" , err )
2021-04-19 19:42:19 +02:00
}
2023-05-09 13:25:48 +02:00
apiAuthorAccount , err := c . AccountToAPIAccountPublic ( ctx , s . Account )
2021-04-19 19:42:19 +02:00
if err != nil {
2023-11-10 19:29:26 +01:00
return nil , gtserror . Newf ( "error converting status author: %w" , err )
2021-04-19 19:42:19 +02:00
}
2023-09-23 18:44:11 +02:00
repliesCount , err := c . state . DB . CountStatusReplies ( ctx , s . ID )
2023-05-09 13:25:48 +02:00
if err != nil {
2023-11-10 19:29:26 +01:00
return nil , gtserror . Newf ( "error counting replies: %w" , err )
2021-05-08 15:16:24 +02:00
}
2021-04-19 19:42:19 +02:00
2023-09-23 18:44:11 +02:00
reblogsCount , err := c . state . DB . CountStatusBoosts ( ctx , s . ID )
2023-05-09 13:25:48 +02:00
if err != nil {
2023-11-10 19:29:26 +01:00
return nil , gtserror . Newf ( "error counting reblogs: %w" , err )
2021-04-19 19:42:19 +02:00
}
2023-09-23 18:44:11 +02:00
favesCount , err := c . state . DB . CountStatusFaves ( ctx , s . ID )
2023-05-09 13:25:48 +02:00
if err != nil {
2023-11-10 19:29:26 +01:00
return nil , gtserror . Newf ( "error counting faves: %w" , err )
2021-06-17 18:02:33 +02:00
}
2022-11-29 18:59:59 +01:00
apiAttachments , err := c . convertAttachmentsToAPIAttachments ( ctx , s . Attachments , s . AttachmentIDs )
if err != nil {
2023-02-17 12:02:29 +01:00
log . Errorf ( ctx , "error converting status attachments: %v" , err )
2021-04-19 19:42:19 +02:00
}
2022-11-29 18:59:59 +01:00
apiMentions , err := c . convertMentionsToAPIMentions ( ctx , s . Mentions , s . MentionIDs )
if err != nil {
2023-02-17 12:02:29 +01:00
log . Errorf ( ctx , "error converting status mentions: %v" , err )
2021-04-19 19:42:19 +02:00
}
2022-11-29 18:59:59 +01:00
apiTags , err := c . convertTagsToAPITags ( ctx , s . Tags , s . TagIDs )
if err != nil {
2023-02-17 12:02:29 +01:00
log . Errorf ( ctx , "error converting status tags: %v" , err )
2021-04-19 19:42:19 +02:00
}
2022-11-29 18:59:59 +01:00
apiEmojis , err := c . convertEmojisToAPIEmojis ( ctx , s . Emojis , s . EmojiIDs )
if err != nil {
2023-02-17 12:02:29 +01:00
log . Errorf ( ctx , "error converting status emojis: %v" , err )
2021-04-19 19:42:19 +02:00
}
2023-01-02 13:10:50 +01:00
apiStatus := & apimodel . Status {
2021-04-19 19:42:19 +02:00
ID : s . ID ,
2022-05-24 18:21:27 +02:00
CreatedAt : util . FormatISO8601 ( s . CreatedAt ) ,
2023-12-01 15:27:15 +01:00
InReplyToID : nil , // Set below.
InReplyToAccountID : nil , // Set below.
2022-08-15 12:35:05 +02:00
Sensitive : * s . Sensitive ,
2021-04-19 19:42:19 +02:00
SpoilerText : s . ContentWarning ,
2021-10-04 15:24:19 +02:00
Visibility : c . VisToAPIVis ( ctx , s . Visibility ) ,
2023-12-01 15:27:15 +01:00
Language : nil , // Set below.
2021-04-19 19:42:19 +02:00
URI : s . URI ,
URL : s . URL ,
RepliesCount : repliesCount ,
ReblogsCount : reblogsCount ,
FavouritesCount : favesCount ,
Content : s . Content ,
2023-12-01 15:27:15 +01:00
Reblog : nil , // Set below.
Application : nil , // Set below.
2021-10-04 15:24:19 +02:00
Account : apiAuthorAccount ,
MediaAttachments : apiAttachments ,
Mentions : apiMentions ,
Tags : apiTags ,
Emojis : apiEmojis ,
2022-09-02 17:00:11 +02:00
Card : nil , // TODO: implement cards
2021-04-19 19:42:19 +02:00
Text : s . Text ,
2021-08-02 19:06:44 +02:00
}
2023-05-09 13:25:48 +02:00
// Nullable fields.
2022-09-02 17:00:11 +02:00
if s . InReplyToID != "" {
2023-12-01 15:27:15 +01:00
apiStatus . InReplyToID = util . Ptr ( s . InReplyToID )
2022-09-02 17:00:11 +02:00
}
if s . InReplyToAccountID != "" {
2023-12-01 15:27:15 +01:00
apiStatus . InReplyToAccountID = util . Ptr ( s . InReplyToAccountID )
2022-09-02 17:00:11 +02:00
}
2023-05-09 13:25:48 +02:00
if s . Language != "" {
2023-12-01 15:27:15 +01:00
apiStatus . Language = util . Ptr ( s . Language )
2023-05-09 13:25:48 +02:00
}
if s . BoostOf != nil {
2024-05-06 13:49:08 +02:00
reblog , err := c . StatusToAPIStatus ( ctx , s . BoostOf , requestingAccount , filterContext , filters )
if errors . Is ( err , statusfilter . ErrHideStatus ) {
// If we'd hide the original status, hide the boost.
return nil , err
}
2023-05-09 13:25:48 +02:00
if err != nil {
2023-11-10 19:29:26 +01:00
return nil , gtserror . Newf ( "error converting boosted status: %w" , err )
2023-05-09 13:25:48 +02:00
}
2023-12-01 15:27:15 +01:00
apiStatus . Reblog = & apimodel . StatusReblogged { reblog }
2023-05-09 13:25:48 +02:00
}
2023-12-01 15:27:15 +01:00
if app := s . CreatedWithApplication ; app != nil {
apiStatus . Application , err = c . AppToAPIAppPublic ( ctx , app )
2023-05-09 13:25:48 +02:00
if err != nil {
2023-12-01 15:27:15 +01:00
return nil , gtserror . Newf (
"error converting application %s: %w" ,
s . CreatedWithApplicationID , err ,
)
2023-05-09 13:25:48 +02:00
}
}
2023-11-08 15:32:17 +01:00
if s . Poll != nil {
// Set originating
// status on the poll.
poll := s . Poll
poll . Status = s
apiStatus . Poll , err = c . PollToAPIPoll ( ctx , requestingAccount , poll )
if err != nil {
return nil , fmt . Errorf ( "error converting poll: %w" , err )
}
}
2024-04-17 12:41:40 +02:00
// Status interactions.
//
// Take from boosted status if set,
// otherwise take from status itself.
if apiStatus . Reblog != nil {
apiStatus . Favourited = apiStatus . Reblog . Favourited
apiStatus . Bookmarked = apiStatus . Reblog . Bookmarked
apiStatus . Muted = apiStatus . Reblog . Muted
apiStatus . Reblogged = apiStatus . Reblog . Reblogged
apiStatus . Pinned = apiStatus . Reblog . Pinned
} else {
interacts , err := c . interactionsWithStatusForAccount ( ctx , s , requestingAccount )
if err != nil {
log . Errorf ( ctx ,
"error getting interactions for status %s for account %s: %v" ,
s . ID , requestingAccount . ID , err ,
)
// Ensure non-nil object.
interacts = new ( statusInteractions )
}
apiStatus . Favourited = interacts . Favourited
apiStatus . Bookmarked = interacts . Bookmarked
apiStatus . Muted = interacts . Muted
apiStatus . Reblogged = interacts . Reblogged
apiStatus . Pinned = interacts . Pinned
}
2023-11-10 19:29:26 +01:00
// If web URL is empty for whatever
// reason, provide AP URI as fallback.
2023-05-09 13:25:48 +02:00
if s . URL == "" {
s . URL = s . URI
2021-08-02 19:06:44 +02:00
}
2024-05-06 13:49:08 +02:00
// Apply filters.
filterResults , err := c . statusToAPIFilterResults ( ctx , s , requestingAccount , filterContext , filters )
if err != nil {
return nil , fmt . Errorf ( "error applying filters: %w" , err )
}
apiStatus . Filtered = filterResults
2021-08-02 19:06:44 +02:00
return apiStatus , nil
2021-04-19 19:42:19 +02:00
}
2021-05-08 14:25:55 +02:00
2023-09-23 18:44:11 +02:00
// VisToAPIVis converts a gts visibility into its api equivalent
func ( c * Converter ) VisToAPIVis ( ctx context . Context , m gtsmodel . Visibility ) apimodel . Visibility {
2021-05-08 14:25:55 +02:00
switch m {
case gtsmodel . VisibilityPublic :
2023-01-02 13:10:50 +01:00
return apimodel . VisibilityPublic
2021-05-08 14:25:55 +02:00
case gtsmodel . VisibilityUnlocked :
2023-01-02 13:10:50 +01:00
return apimodel . VisibilityUnlisted
2021-05-08 14:25:55 +02:00
case gtsmodel . VisibilityFollowersOnly , gtsmodel . VisibilityMutualsOnly :
2023-01-02 13:10:50 +01:00
return apimodel . VisibilityPrivate
2021-05-08 14:25:55 +02:00
case gtsmodel . VisibilityDirect :
2023-01-02 13:10:50 +01:00
return apimodel . VisibilityDirect
2021-05-08 14:25:55 +02:00
}
return ""
}
2021-05-09 14:06:06 +02:00
2023-09-23 18:44:11 +02:00
// InstanceRuleToAdminAPIRule converts a local instance rule into its api equivalent for serving at /api/v1/admin/instance/rules/:id
func ( c * Converter ) InstanceRuleToAPIRule ( r gtsmodel . Rule ) apimodel . InstanceRule {
2023-08-19 14:33:15 +02:00
return apimodel . InstanceRule {
ID : r . ID ,
Text : r . Text ,
}
}
2023-09-23 18:44:11 +02:00
// InstanceRulesToAPIRules converts all local instance rules into their api equivalent for serving at /api/v1/instance/rules
func ( c * Converter ) InstanceRulesToAPIRules ( r [ ] gtsmodel . Rule ) [ ] apimodel . InstanceRule {
2023-08-19 14:33:15 +02:00
rules := make ( [ ] apimodel . InstanceRule , len ( r ) )
for i , v := range r {
rules [ i ] = c . InstanceRuleToAPIRule ( v )
}
return rules
}
2023-09-23 18:44:11 +02:00
// InstanceRuleToAdminAPIRule converts a local instance rule into its api equivalent for serving at /api/v1/admin/instance/rules/:id
func ( c * Converter ) InstanceRuleToAdminAPIRule ( r * gtsmodel . Rule ) * apimodel . AdminInstanceRule {
2023-08-19 14:33:15 +02:00
return & apimodel . AdminInstanceRule {
ID : r . ID ,
CreatedAt : util . FormatISO8601 ( r . CreatedAt ) ,
UpdatedAt : util . FormatISO8601 ( r . UpdatedAt ) ,
Text : r . Text ,
}
}
2023-09-23 18:44:11 +02:00
// InstanceToAPIV1Instance converts a gts instance into its api equivalent for serving at /api/v1/instance
func ( c * Converter ) InstanceToAPIV1Instance ( ctx context . Context , i * gtsmodel . Instance ) ( * apimodel . InstanceV1 , error ) {
2023-02-02 14:08:13 +01:00
instance := & apimodel . InstanceV1 {
2024-01-05 13:39:31 +01:00
URI : i . URI ,
AccountDomain : config . GetAccountDomain ( ) ,
Title : i . Title ,
Description : i . Description ,
DescriptionText : i . DescriptionText ,
ShortDescription : i . ShortDescription ,
ShortDescriptionText : i . ShortDescriptionText ,
Email : i . ContactEmail ,
Version : config . GetSoftwareVersion ( ) ,
Languages : config . GetInstanceLanguages ( ) . TagStrs ( ) ,
Registrations : config . GetAccountsRegistrationOpen ( ) ,
2024-04-11 11:45:53 +02:00
ApprovalRequired : true , // approval always required
2024-01-05 13:39:31 +01:00
InvitesEnabled : false , // todo: not supported yet
MaxTootChars : uint ( config . GetStatusesMaxChars ( ) ) ,
Rules : c . InstanceRulesToAPIRules ( i . Rules ) ,
Terms : i . Terms ,
TermsRaw : i . TermsText ,
2023-02-02 14:08:13 +01:00
}
2023-07-21 19:49:13 +02:00
if config . GetInstanceInjectMastodonVersion ( ) {
instance . Version = toMastodonVersion ( instance . Version )
}
2024-06-03 11:20:53 +02:00
if debug . DEBUG {
instance . Debug = util . Ptr ( true )
}
2023-02-02 14:08:13 +01:00
// configuration
instance . Configuration . Statuses . MaxCharacters = config . GetStatusesMaxChars ( )
instance . Configuration . Statuses . MaxMediaAttachments = config . GetStatusesMediaMaxFiles ( )
instance . Configuration . Statuses . CharactersReservedPerURL = instanceStatusesCharactersReservedPerURL
2023-03-02 12:06:40 +01:00
instance . Configuration . Statuses . SupportedMimeTypes = instanceStatusesSupportedMimeTypes
2023-02-02 14:08:13 +01:00
instance . Configuration . MediaAttachments . SupportedMimeTypes = media . SupportedMIMETypes
instance . Configuration . MediaAttachments . ImageSizeLimit = int ( config . GetMediaImageMaxSize ( ) )
instance . Configuration . MediaAttachments . ImageMatrixLimit = instanceMediaAttachmentsImageMatrixLimit
instance . Configuration . MediaAttachments . VideoSizeLimit = int ( config . GetMediaVideoMaxSize ( ) )
instance . Configuration . MediaAttachments . VideoFrameRateLimit = instanceMediaAttachmentsVideoFrameRateLimit
instance . Configuration . MediaAttachments . VideoMatrixLimit = instanceMediaAttachmentsVideoMatrixLimit
instance . Configuration . Polls . MaxOptions = config . GetStatusesPollMaxOptions ( )
instance . Configuration . Polls . MaxCharactersPerOption = config . GetStatusesPollOptionMaxChars ( )
instance . Configuration . Polls . MinExpiration = instancePollsMinExpiration
instance . Configuration . Polls . MaxExpiration = instancePollsMaxExpiration
instance . Configuration . Accounts . AllowCustomCSS = config . GetAccountsAllowCustomCSS ( )
instance . Configuration . Accounts . MaxFeaturedTags = instanceAccountsMaxFeaturedTags
2023-06-13 12:21:26 +02:00
instance . Configuration . Accounts . MaxProfileFields = instanceAccountsMaxProfileFields
2023-02-02 14:08:13 +01:00
instance . Configuration . Emojis . EmojiSizeLimit = int ( config . GetMediaEmojiLocalMaxSize ( ) )
// URLs
instance . URLs . StreamingAPI = "wss://" + i . Domain
// statistics
2024-02-19 13:17:14 +01:00
stats := make ( map [ string ] * int , 3 )
2023-09-23 18:44:11 +02:00
userCount , err := c . state . DB . CountInstanceUsers ( ctx , i . Domain )
2023-02-02 14:08:13 +01:00
if err != nil {
return nil , fmt . Errorf ( "InstanceToAPIV1Instance: db error getting counting instance users: %w" , err )
}
2024-02-19 13:17:14 +01:00
stats [ "user_count" ] = util . Ptr ( userCount )
2023-02-02 14:08:13 +01:00
2023-09-23 18:44:11 +02:00
statusCount , err := c . state . DB . CountInstanceStatuses ( ctx , i . Domain )
2023-02-02 14:08:13 +01:00
if err != nil {
return nil , fmt . Errorf ( "InstanceToAPIV1Instance: db error getting counting instance statuses: %w" , err )
}
2024-02-19 13:17:14 +01:00
stats [ "status_count" ] = util . Ptr ( statusCount )
2023-02-02 14:08:13 +01:00
2023-09-23 18:44:11 +02:00
domainCount , err := c . state . DB . CountInstanceDomains ( ctx , i . Domain )
2023-02-02 14:08:13 +01:00
if err != nil {
return nil , fmt . Errorf ( "InstanceToAPIV1Instance: db error getting counting instance domains: %w" , err )
}
2024-02-19 13:17:14 +01:00
stats [ "domain_count" ] = util . Ptr ( domainCount )
2023-02-02 14:08:13 +01:00
instance . Stats = stats
// thumbnail
2023-09-23 18:44:11 +02:00
iAccount , err := c . state . DB . GetInstanceAccount ( ctx , "" )
2023-02-02 14:08:13 +01:00
if err != nil {
return nil , fmt . Errorf ( "InstanceToAPIV1Instance: db error getting instance account: %w" , err )
}
if iAccount . AvatarMediaAttachmentID != "" {
if iAccount . AvatarMediaAttachment == nil {
2023-09-23 18:44:11 +02:00
avi , err := c . state . DB . GetAttachmentByID ( ctx , iAccount . AvatarMediaAttachmentID )
2023-02-02 14:08:13 +01:00
if err != nil {
return nil , fmt . Errorf ( "InstanceToAPIInstance: error getting instance avatar attachment with id %s: %w" , iAccount . AvatarMediaAttachmentID , err )
2022-06-26 12:33:11 +02:00
}
2023-02-02 14:08:13 +01:00
iAccount . AvatarMediaAttachment = avi
2022-06-26 12:33:11 +02:00
}
2023-02-02 14:08:13 +01:00
instance . Thumbnail = iAccount . AvatarMediaAttachment . URL
instance . ThumbnailType = iAccount . AvatarMediaAttachment . File . ContentType
instance . ThumbnailDescription = iAccount . AvatarMediaAttachment . Description
} else {
instance . Thumbnail = config . GetProtocol ( ) + "://" + i . Domain + "/assets/logo.png" // default thumb
}
2021-06-23 16:35:57 +02:00
2023-02-02 14:08:13 +01:00
// contact account
if i . ContactAccountID != "" {
if i . ContactAccount == nil {
2023-09-23 18:44:11 +02:00
contactAccount , err := c . state . DB . GetAccountByID ( ctx , i . ContactAccountID )
2023-02-02 14:08:13 +01:00
if err != nil {
return nil , fmt . Errorf ( "InstanceToAPIV1Instance: db error getting instance contact account %s: %w" , i . ContactAccountID , err )
}
i . ContactAccount = contactAccount
2021-06-23 16:35:57 +02:00
}
2023-02-02 14:08:13 +01:00
account , err := c . AccountToAPIAccountPublic ( ctx , i . ContactAccount )
if err != nil {
return nil , fmt . Errorf ( "InstanceToAPIV1Instance: error converting instance contact account %s: %w" , i . ContactAccountID , err )
2021-06-23 16:35:57 +02:00
}
2023-02-02 14:08:13 +01:00
instance . ContactAccount = account
}
2021-06-23 16:35:57 +02:00
2023-02-02 14:08:13 +01:00
return instance , nil
}
2023-09-23 18:44:11 +02:00
// InstanceToAPIV2Instance converts a gts instance into its api equivalent for serving at /api/v2/instance
func ( c * Converter ) InstanceToAPIV2Instance ( ctx context . Context , i * gtsmodel . Instance ) ( * apimodel . InstanceV2 , error ) {
2023-02-02 14:08:13 +01:00
instance := & apimodel . InstanceV2 {
2024-01-05 13:39:31 +01:00
Domain : i . Domain ,
AccountDomain : config . GetAccountDomain ( ) ,
Title : i . Title ,
Version : config . GetSoftwareVersion ( ) ,
SourceURL : instanceSourceURL ,
Description : i . Description ,
DescriptionText : i . DescriptionText ,
Usage : apimodel . InstanceV2Usage { } , // todo: not implemented
Languages : config . GetInstanceLanguages ( ) . TagStrs ( ) ,
Rules : c . InstanceRulesToAPIRules ( i . Rules ) ,
Terms : i . Terms ,
TermsText : i . TermsText ,
2023-02-02 14:08:13 +01:00
}
2023-07-21 19:49:13 +02:00
if config . GetInstanceInjectMastodonVersion ( ) {
instance . Version = toMastodonVersion ( instance . Version )
}
2024-06-03 11:20:53 +02:00
if debug . DEBUG {
instance . Debug = util . Ptr ( true )
}
2023-02-02 14:08:13 +01:00
// thumbnail
thumbnail := apimodel . InstanceV2Thumbnail { }
2023-09-23 18:44:11 +02:00
iAccount , err := c . state . DB . GetInstanceAccount ( ctx , "" )
2023-02-02 14:08:13 +01:00
if err != nil {
return nil , fmt . Errorf ( "InstanceToAPIV2Instance: db error getting instance account: %w" , err )
2021-05-09 14:06:06 +02:00
}
2023-02-02 14:08:13 +01:00
if iAccount . AvatarMediaAttachmentID != "" {
if iAccount . AvatarMediaAttachment == nil {
2023-09-23 18:44:11 +02:00
avi , err := c . state . DB . GetAttachmentByID ( ctx , iAccount . AvatarMediaAttachmentID )
2023-02-02 14:08:13 +01:00
if err != nil {
return nil , fmt . Errorf ( "InstanceToAPIV2Instance: error getting instance avatar attachment with id %s: %w" , iAccount . AvatarMediaAttachmentID , err )
}
iAccount . AvatarMediaAttachment = avi
}
thumbnail . URL = iAccount . AvatarMediaAttachment . URL
thumbnail . Type = iAccount . AvatarMediaAttachment . File . ContentType
thumbnail . Description = iAccount . AvatarMediaAttachment . Description
thumbnail . Blurhash = iAccount . AvatarMediaAttachment . Blurhash
} else {
thumbnail . URL = config . GetProtocol ( ) + "://" + i . Domain + "/assets/logo.png" // default thumb
}
instance . Thumbnail = thumbnail
// configuration
instance . Configuration . URLs . Streaming = "wss://" + i . Domain
instance . Configuration . Statuses . MaxCharacters = config . GetStatusesMaxChars ( )
instance . Configuration . Statuses . MaxMediaAttachments = config . GetStatusesMediaMaxFiles ( )
instance . Configuration . Statuses . CharactersReservedPerURL = instanceStatusesCharactersReservedPerURL
2023-03-02 12:06:40 +01:00
instance . Configuration . Statuses . SupportedMimeTypes = instanceStatusesSupportedMimeTypes
2023-02-02 14:08:13 +01:00
instance . Configuration . MediaAttachments . SupportedMimeTypes = media . SupportedMIMETypes
instance . Configuration . MediaAttachments . ImageSizeLimit = int ( config . GetMediaImageMaxSize ( ) )
instance . Configuration . MediaAttachments . ImageMatrixLimit = instanceMediaAttachmentsImageMatrixLimit
instance . Configuration . MediaAttachments . VideoSizeLimit = int ( config . GetMediaVideoMaxSize ( ) )
instance . Configuration . MediaAttachments . VideoFrameRateLimit = instanceMediaAttachmentsVideoFrameRateLimit
instance . Configuration . MediaAttachments . VideoMatrixLimit = instanceMediaAttachmentsVideoMatrixLimit
instance . Configuration . Polls . MaxOptions = config . GetStatusesPollMaxOptions ( )
instance . Configuration . Polls . MaxCharactersPerOption = config . GetStatusesPollOptionMaxChars ( )
instance . Configuration . Polls . MinExpiration = instancePollsMinExpiration
instance . Configuration . Polls . MaxExpiration = instancePollsMaxExpiration
instance . Configuration . Accounts . AllowCustomCSS = config . GetAccountsAllowCustomCSS ( )
instance . Configuration . Accounts . MaxFeaturedTags = instanceAccountsMaxFeaturedTags
2023-06-13 12:21:26 +02:00
instance . Configuration . Accounts . MaxProfileFields = instanceAccountsMaxProfileFields
2023-02-02 14:08:13 +01:00
instance . Configuration . Emojis . EmojiSizeLimit = int ( config . GetMediaEmojiLocalMaxSize ( ) )
// registrations
instance . Registrations . Enabled = config . GetAccountsRegistrationOpen ( )
2024-04-11 11:45:53 +02:00
instance . Registrations . ApprovalRequired = true // always required
instance . Registrations . Message = nil // todo: not implemented
2023-02-02 14:08:13 +01:00
// contact
instance . Contact . Email = i . ContactEmail
2021-05-09 14:06:06 +02:00
if i . ContactAccountID != "" {
2021-08-25 15:34:33 +02:00
if i . ContactAccount == nil {
2023-09-23 18:44:11 +02:00
contactAccount , err := c . state . DB . GetAccountByID ( ctx , i . ContactAccountID )
2023-02-02 14:08:13 +01:00
if err != nil {
return nil , fmt . Errorf ( "InstanceToAPIV2Instance: db error getting instance contact account %s: %w" , i . ContactAccountID , err )
2021-05-09 14:06:06 +02:00
}
2023-02-02 14:08:13 +01:00
i . ContactAccount = contactAccount
2021-05-09 14:06:06 +02:00
}
2023-02-02 14:08:13 +01:00
account , err := c . AccountToAPIAccountPublic ( ctx , i . ContactAccount )
if err != nil {
return nil , fmt . Errorf ( "InstanceToAPIV2Instance: error converting instance contact account %s: %w" , i . ContactAccountID , err )
2021-08-25 15:34:33 +02:00
}
2023-02-02 14:08:13 +01:00
instance . Contact . Account = account
2021-05-09 14:06:06 +02:00
}
2023-02-02 14:08:13 +01:00
return instance , nil
2021-05-09 14:06:06 +02:00
}
2021-05-21 15:48:26 +02:00
2023-09-23 18:44:11 +02:00
// RelationshipToAPIRelationship converts a gts relationship into its api equivalent for serving in various places
func ( c * Converter ) RelationshipToAPIRelationship ( ctx context . Context , r * gtsmodel . Relationship ) ( * apimodel . Relationship , error ) {
2023-01-02 13:10:50 +01:00
return & apimodel . Relationship {
2021-05-21 23:04:59 +02:00
ID : r . ID ,
Following : r . Following ,
ShowingReblogs : r . ShowingReblogs ,
Notifying : r . Notifying ,
FollowedBy : r . FollowedBy ,
Blocking : r . Blocking ,
BlockedBy : r . BlockedBy ,
Muting : r . Muting ,
2021-05-21 15:48:26 +02:00
MutingNotifications : r . MutingNotifications ,
2021-05-21 23:04:59 +02:00
Requested : r . Requested ,
2024-02-20 18:50:54 +01:00
RequestedBy : r . RequestedBy ,
2021-05-21 23:04:59 +02:00
DomainBlocking : r . DomainBlocking ,
Endorsed : r . Endorsed ,
Note : r . Note ,
2021-05-21 15:48:26 +02:00
} , nil
}
2021-05-27 16:06:24 +02:00
2023-09-23 18:44:11 +02:00
// NotificationToAPINotification converts a gts notification into a api notification
2024-05-06 13:49:08 +02:00
func ( c * Converter ) NotificationToAPINotification ( ctx context . Context , n * gtsmodel . Notification , filters [ ] * gtsmodel . Filter ) ( * apimodel . Notification , error ) {
2021-08-20 12:26:56 +02:00
if n . TargetAccount == nil {
2023-09-23 18:44:11 +02:00
tAccount , err := c . state . DB . GetAccountByID ( ctx , n . TargetAccountID )
2021-08-20 12:26:56 +02:00
if err != nil {
2021-10-04 15:24:19 +02:00
return nil , fmt . Errorf ( "NotificationToapi: error getting target account with id %s from the db: %s" , n . TargetAccountID , err )
2021-05-27 16:06:24 +02:00
}
2021-08-20 12:26:56 +02:00
n . TargetAccount = tAccount
2021-05-27 16:06:24 +02:00
}
2021-08-20 12:26:56 +02:00
if n . OriginAccount == nil {
2023-09-23 18:44:11 +02:00
ogAccount , err := c . state . DB . GetAccountByID ( ctx , n . OriginAccountID )
2021-08-20 12:26:56 +02:00
if err != nil {
2021-10-04 15:24:19 +02:00
return nil , fmt . Errorf ( "NotificationToapi: error getting origin account with id %s from the db: %s" , n . OriginAccountID , err )
2021-05-27 16:06:24 +02:00
}
2021-08-20 12:26:56 +02:00
n . OriginAccount = ogAccount
2021-05-27 16:06:24 +02:00
}
2021-08-20 12:26:56 +02:00
2021-10-04 15:24:19 +02:00
apiAccount , err := c . AccountToAPIAccountPublic ( ctx , n . OriginAccount )
2021-05-27 16:06:24 +02:00
if err != nil {
2021-10-04 15:24:19 +02:00
return nil , fmt . Errorf ( "NotificationToapi: error converting account to api: %s" , err )
2021-05-27 16:06:24 +02:00
}
2023-01-02 13:10:50 +01:00
var apiStatus * apimodel . Status
2021-05-27 16:06:24 +02:00
if n . StatusID != "" {
2021-08-20 12:26:56 +02:00
if n . Status == nil {
2023-09-23 18:44:11 +02:00
status , err := c . state . DB . GetStatusByID ( ctx , n . StatusID )
2021-08-20 12:26:56 +02:00
if err != nil {
2021-10-04 15:24:19 +02:00
return nil , fmt . Errorf ( "NotificationToapi: error getting status with id %s from the db: %s" , n . StatusID , err )
2021-05-27 16:06:24 +02:00
}
2021-08-20 12:26:56 +02:00
n . Status = status
2021-05-27 16:06:24 +02:00
}
2021-08-20 12:26:56 +02:00
if n . Status . Account == nil {
if n . Status . AccountID == n . TargetAccount . ID {
n . Status . Account = n . TargetAccount
} else if n . Status . AccountID == n . OriginAccount . ID {
n . Status . Account = n . OriginAccount
2021-05-27 16:06:24 +02:00
}
}
var err error
2024-05-06 13:49:08 +02:00
apiStatus , err = c . StatusToAPIStatus ( ctx , n . Status , n . TargetAccount , statusfilter . FilterContextNotifications , filters )
2021-05-27 16:06:24 +02:00
if err != nil {
2021-10-04 15:24:19 +02:00
return nil , fmt . Errorf ( "NotificationToapi: error converting status to api: %s" , err )
2021-05-27 16:06:24 +02:00
}
}
2022-08-29 11:06:37 +02:00
if apiStatus != nil && apiStatus . Reblog != nil {
// use the actual reblog status for the notifications endpoint
apiStatus = apiStatus . Reblog . Status
}
2023-01-02 13:10:50 +01:00
return & apimodel . Notification {
2021-05-27 16:06:24 +02:00
ID : n . ID ,
Type : string ( n . NotificationType ) ,
2022-05-24 18:21:27 +02:00
CreatedAt : util . FormatISO8601 ( n . CreatedAt ) ,
2021-10-04 15:24:19 +02:00
Account : apiAccount ,
Status : apiStatus ,
2021-05-27 16:06:24 +02:00
} , nil
}
2021-07-05 13:23:03 +02:00
2023-09-23 18:44:11 +02:00
// DomainPermToAPIDomainPerm converts a gts model domin block or allow into an api domain permission.
func ( c * Converter ) DomainPermToAPIDomainPerm (
2023-09-21 12:12:04 +02:00
ctx context . Context ,
d gtsmodel . DomainPermission ,
export bool ,
) ( * apimodel . DomainPermission , error ) {
2023-05-07 19:53:21 +02:00
// Domain may be in Punycode,
// de-punify it just in case.
2023-09-21 12:12:04 +02:00
domain , err := util . DePunify ( d . GetDomain ( ) )
2023-05-07 19:53:21 +02:00
if err != nil {
2023-09-21 12:12:04 +02:00
return nil , gtserror . Newf ( "error de-punifying domain %s: %w" , d . GetDomain ( ) , err )
2023-05-07 19:53:21 +02:00
}
2023-09-21 12:12:04 +02:00
domainPerm := & apimodel . DomainPermission {
2023-01-02 13:10:50 +01:00
Domain : apimodel . Domain {
2023-09-21 12:12:04 +02:00
Domain : domain ,
PublicComment : d . GetPublicComment ( ) ,
2022-06-23 16:54:54 +02:00
} ,
2021-07-05 13:23:03 +02:00
}
2023-09-21 12:12:04 +02:00
// If we're exporting, provide
// only bare minimum detail.
if export {
return domainPerm , nil
2021-07-05 13:23:03 +02:00
}
2023-09-21 12:12:04 +02:00
domainPerm . ID = d . GetID ( )
domainPerm . Obfuscate = * d . GetObfuscate ( )
domainPerm . PrivateComment = d . GetPrivateComment ( )
domainPerm . SubscriptionID = d . GetSubscriptionID ( )
domainPerm . CreatedBy = d . GetCreatedByAccountID ( )
domainPerm . CreatedAt = util . FormatISO8601 ( d . GetCreatedAt ( ) )
return domainPerm , nil
2021-07-05 13:23:03 +02:00
}
2022-11-29 18:59:59 +01:00
2023-09-23 18:44:11 +02:00
// ReportToAPIReport converts a gts model report into an api model report, for serving at /api/v1/reports
func ( c * Converter ) ReportToAPIReport ( ctx context . Context , r * gtsmodel . Report ) ( * apimodel . Report , error ) {
2023-01-23 13:14:21 +01:00
report := & apimodel . Report {
ID : r . ID ,
CreatedAt : util . FormatISO8601 ( r . CreatedAt ) ,
ActionTaken : ! r . ActionTakenAt . IsZero ( ) ,
Category : "other" , // todo: only support default 'other' category right now
Comment : r . Comment ,
Forwarded : * r . Forwarded ,
StatusIDs : r . StatusIDs ,
2023-08-19 14:33:15 +02:00
RuleIDs : r . RuleIDs ,
2023-01-23 13:14:21 +01:00
}
if ! r . ActionTakenAt . IsZero ( ) {
actionTakenAt := util . FormatISO8601 ( r . ActionTakenAt )
report . ActionTakenAt = & actionTakenAt
}
if actionComment := r . ActionTaken ; actionComment != "" {
2023-01-25 11:12:17 +01:00
report . ActionTakenComment = & actionComment
2023-01-23 13:14:21 +01:00
}
if r . TargetAccount == nil {
2023-09-23 18:44:11 +02:00
tAccount , err := c . state . DB . GetAccountByID ( ctx , r . TargetAccountID )
2023-01-23 13:14:21 +01:00
if err != nil {
return nil , fmt . Errorf ( "ReportToAPIReport: error getting target account with id %s from the db: %s" , r . TargetAccountID , err )
}
r . TargetAccount = tAccount
}
apiAccount , err := c . AccountToAPIAccountPublic ( ctx , r . TargetAccount )
if err != nil {
return nil , fmt . Errorf ( "ReportToAPIReport: error converting target account to api: %s" , err )
}
report . TargetAccount = apiAccount
return report , nil
}
2023-09-23 18:44:11 +02:00
// ReportToAdminAPIReport converts a gts model report into an admin view report, for serving at /api/v1/admin/reports
func ( c * Converter ) ReportToAdminAPIReport ( ctx context . Context , r * gtsmodel . Report , requestingAccount * gtsmodel . Account ) ( * apimodel . AdminReport , error ) {
2023-01-25 11:12:17 +01:00
var (
err error
actionTakenAt * string
actionTakenComment * string
actionTakenByAccount * apimodel . AdminAccountInfo
)
if ! r . ActionTakenAt . IsZero ( ) {
ata := util . FormatISO8601 ( r . ActionTakenAt )
actionTakenAt = & ata
}
if r . Account == nil {
2023-09-23 18:44:11 +02:00
r . Account , err = c . state . DB . GetAccountByID ( ctx , r . AccountID )
2023-01-25 11:12:17 +01:00
if err != nil {
return nil , fmt . Errorf ( "ReportToAdminAPIReport: error getting account with id %s from the db: %w" , r . AccountID , err )
}
}
account , err := c . AccountToAdminAPIAccount ( ctx , r . Account )
if err != nil {
return nil , fmt . Errorf ( "ReportToAdminAPIReport: error converting account with id %s to adminAPIAccount: %w" , r . AccountID , err )
}
if r . TargetAccount == nil {
2023-09-23 18:44:11 +02:00
r . TargetAccount , err = c . state . DB . GetAccountByID ( ctx , r . TargetAccountID )
2023-01-25 11:12:17 +01:00
if err != nil {
return nil , fmt . Errorf ( "ReportToAdminAPIReport: error getting target account with id %s from the db: %w" , r . TargetAccountID , err )
}
}
targetAccount , err := c . AccountToAdminAPIAccount ( ctx , r . TargetAccount )
if err != nil {
return nil , fmt . Errorf ( "ReportToAdminAPIReport: error converting target account with id %s to adminAPIAccount: %w" , r . TargetAccountID , err )
}
if r . ActionTakenByAccountID != "" {
if r . ActionTakenByAccount == nil {
2023-09-23 18:44:11 +02:00
r . ActionTakenByAccount , err = c . state . DB . GetAccountByID ( ctx , r . ActionTakenByAccountID )
2023-01-25 11:12:17 +01:00
if err != nil {
return nil , fmt . Errorf ( "ReportToAdminAPIReport: error getting action taken by account with id %s from the db: %w" , r . ActionTakenByAccountID , err )
}
}
actionTakenByAccount , err = c . AccountToAdminAPIAccount ( ctx , r . ActionTakenByAccount )
if err != nil {
return nil , fmt . Errorf ( "ReportToAdminAPIReport: error converting action taken by account with id %s to adminAPIAccount: %w" , r . ActionTakenByAccountID , err )
}
}
statuses := make ( [ ] * apimodel . Status , 0 , len ( r . StatusIDs ) )
if len ( r . StatusIDs ) != 0 && len ( r . Statuses ) == 0 {
2023-09-23 18:44:11 +02:00
r . Statuses , err = c . state . DB . GetStatusesByIDs ( ctx , r . StatusIDs )
2023-01-25 11:12:17 +01:00
if err != nil {
return nil , fmt . Errorf ( "ReportToAdminAPIReport: error getting statuses from the db: %w" , err )
}
}
for _ , s := range r . Statuses {
2024-05-06 13:49:08 +02:00
status , err := c . StatusToAPIStatus ( ctx , s , requestingAccount , statusfilter . FilterContextNone , nil )
2023-01-25 11:12:17 +01:00
if err != nil {
return nil , fmt . Errorf ( "ReportToAdminAPIReport: error converting status with id %s to api status: %w" , s . ID , err )
}
statuses = append ( statuses , status )
}
2023-08-19 14:33:15 +02:00
rules := make ( [ ] * apimodel . InstanceRule , 0 , len ( r . RuleIDs ) )
if len ( r . RuleIDs ) != 0 && len ( r . Rules ) == 0 {
2023-09-23 18:44:11 +02:00
r . Rules , err = c . state . DB . GetRulesByIDs ( ctx , r . RuleIDs )
2023-08-19 14:33:15 +02:00
if err != nil {
return nil , fmt . Errorf ( "ReportToAdminAPIReport: error getting rules from the db: %w" , err )
}
}
for _ , v := range r . Rules {
rules = append ( rules , & apimodel . InstanceRule {
ID : v . ID ,
Text : v . Text ,
} )
}
2023-01-25 11:12:17 +01:00
if ac := r . ActionTaken ; ac != "" {
actionTakenComment = & ac
}
return & apimodel . AdminReport {
ID : r . ID ,
ActionTaken : ! r . ActionTakenAt . IsZero ( ) ,
ActionTakenAt : actionTakenAt ,
Category : "other" , // todo: only support default 'other' category right now
Comment : r . Comment ,
Forwarded : * r . Forwarded ,
CreatedAt : util . FormatISO8601 ( r . CreatedAt ) ,
UpdatedAt : util . FormatISO8601 ( r . UpdatedAt ) ,
Account : account ,
TargetAccount : targetAccount ,
AssignedAccount : actionTakenByAccount ,
ActionTakenByAccount : actionTakenByAccount ,
ActionTakenComment : actionTakenComment ,
Statuses : statuses ,
2023-08-19 14:33:15 +02:00
Rules : rules ,
2023-01-25 11:12:17 +01:00
} , nil
}
2023-09-23 18:44:11 +02:00
// ListToAPIList converts one gts model list into an api model list, for serving at /api/v1/lists/{id}
func ( c * Converter ) ListToAPIList ( ctx context . Context , l * gtsmodel . List ) ( * apimodel . List , error ) {
2023-05-25 10:37:38 +02:00
return & apimodel . List {
ID : l . ID ,
Title : l . Title ,
RepliesPolicy : string ( l . RepliesPolicy ) ,
} , nil
}
2023-09-23 18:44:11 +02:00
// MarkersToAPIMarker converts several gts model markers into an api marker, for serving at /api/v1/markers
func ( c * Converter ) MarkersToAPIMarker ( ctx context . Context , markers [ ] * gtsmodel . Marker ) ( * apimodel . Marker , error ) {
2023-07-29 12:49:14 +02:00
apiMarker := & apimodel . Marker { }
for _ , marker := range markers {
apiTimelineMarker := & apimodel . TimelineMarker {
LastReadID : marker . LastReadID ,
UpdatedAt : util . FormatISO8601 ( marker . UpdatedAt ) ,
Version : marker . Version ,
}
switch apimodel . MarkerName ( marker . Name ) {
case apimodel . MarkerNameHome :
apiMarker . Home = apiTimelineMarker
case apimodel . MarkerNameNotifications :
apiMarker . Notifications = apiTimelineMarker
default :
return nil , fmt . Errorf ( "unknown marker timeline name: %s" , marker . Name )
}
}
return apiMarker , nil
}
2023-11-08 15:32:17 +01:00
// PollToAPIPoll converts a database (gtsmodel) Poll into an API model representation appropriate for the given requesting account.
func ( c * Converter ) PollToAPIPoll ( ctx context . Context , requester * gtsmodel . Account , poll * gtsmodel . Poll ) ( * apimodel . Poll , error ) {
// Ensure the poll model is fully populated for src status.
if err := c . state . DB . PopulatePoll ( ctx , poll ) ; err != nil {
return nil , gtserror . Newf ( "error populating poll: %w" , err )
}
var (
2023-11-08 23:37:35 +01:00
options [ ] apimodel . PollOption
2023-11-08 15:32:17 +01:00
totalVotes int
2023-12-12 14:47:07 +01:00
totalVoters * int
hasVoted * bool
2023-11-09 13:06:37 +01:00
ownChoices * [ ] int
2023-11-08 15:32:17 +01:00
isAuthor bool
2023-12-12 14:47:07 +01:00
expiresAt * string
2023-11-09 13:06:37 +01:00
emojis [ ] apimodel . Emoji
2023-11-08 15:32:17 +01:00
)
2023-11-08 23:37:35 +01:00
// Preallocate a slice of frontend model poll choices.
options = make ( [ ] apimodel . PollOption , len ( poll . Options ) )
// Add the titles to all of the options.
for i , title := range poll . Options {
options [ i ] . Title = title
}
2023-11-08 15:32:17 +01:00
if requester != nil {
// Get vote by requester in poll (if any).
vote , err := c . state . DB . GetPollVoteBy ( ctx ,
poll . ID ,
requester . ID ,
)
if err != nil && ! errors . Is ( err , db . ErrNoEntries ) {
return nil , gtserror . Newf ( "error getting vote for poll %s: %w" , poll . ID , err )
}
if vote != nil {
// Set choices by requester.
2023-11-09 13:06:37 +01:00
ownChoices = & vote . Choices
2023-11-08 15:32:17 +01:00
2023-12-12 14:47:07 +01:00
// Update default total in the
// case that counts are hidden
// (so we just show our own).
2023-11-08 15:32:17 +01:00
totalVotes = len ( vote . Choices )
2023-11-09 13:06:37 +01:00
} else {
2023-12-12 14:47:07 +01:00
// Requester hasn't yet voted, use
// empty slice to serialize as `[]`.
ownChoices = & [ ] int { }
2023-11-08 15:32:17 +01:00
}
// Check if requester is author of source status.
isAuthor = ( requester . ID == poll . Status . AccountID )
2023-11-09 13:06:37 +01:00
2023-12-12 14:47:07 +01:00
// Set whether requester has voted in poll (or = author).
hasVoted = util . Ptr ( ( isAuthor || len ( * ownChoices ) > 0 ) )
2023-11-08 15:32:17 +01:00
}
if isAuthor || ! * poll . HideCounts {
2023-12-12 14:47:07 +01:00
// Only in the case that hide counts is
// disabled, or the requester is the author
// do we actually populate the vote counts.
2023-12-16 20:12:25 +01:00
// If we voted in this poll, we'll have set totalVotes
// earlier. Reset here to avoid double counting.
totalVotes = 0
2023-12-12 14:47:07 +01:00
if * poll . Multiple {
// The total number of voters are only
// provided in the case of a multiple
// choice poll. All else leaves it nil.
totalVoters = poll . Voters
}
// Populate per-vote counts
// and overall total vote count.
2023-11-08 23:37:35 +01:00
for i , count := range poll . Votes {
2023-12-12 14:47:07 +01:00
if options [ i ] . VotesCount == nil {
options [ i ] . VotesCount = new ( int )
}
( * options [ i ] . VotesCount ) += count
2023-11-08 23:37:35 +01:00
totalVotes += count
2023-11-08 15:32:17 +01:00
}
}
2023-11-11 11:15:04 +01:00
if ! poll . ExpiresAt . IsZero ( ) {
// Calculate poll expiry string (if set).
2023-12-12 14:47:07 +01:00
str := util . FormatISO8601 ( poll . ExpiresAt )
expiresAt = & str
2023-11-11 11:15:04 +01:00
}
2023-12-12 14:47:07 +01:00
var err error
// Try to inherit emojis from parent status.
emojis , err = c . convertEmojisToAPIEmojis ( ctx ,
poll . Status . Emojis ,
poll . Status . EmojiIDs ,
)
if err != nil {
log . Errorf ( ctx , "error converting emojis from parent status: %v" , err )
emojis = [ ] apimodel . Emoji { } // fallback to empty slice.
2023-11-22 12:17:42 +01:00
}
2023-11-09 13:06:37 +01:00
2023-11-08 15:32:17 +01:00
return & apimodel . Poll {
ID : poll . ID ,
2023-11-11 11:15:04 +01:00
ExpiresAt : expiresAt ,
2023-11-08 15:32:17 +01:00
Expired : poll . Closed ( ) ,
2023-11-08 23:37:35 +01:00
Multiple : ( * poll . Multiple ) ,
2023-11-08 15:32:17 +01:00
VotesCount : totalVotes ,
VotersCount : totalVoters ,
2023-12-12 14:47:07 +01:00
Voted : hasVoted ,
2023-11-08 15:32:17 +01:00
OwnVotes : ownChoices ,
Options : options ,
2023-11-09 13:06:37 +01:00
Emojis : emojis ,
2023-11-08 15:32:17 +01:00
} , nil
}
2022-11-29 18:59:59 +01:00
// convertAttachmentsToAPIAttachments will convert a slice of GTS model attachments to frontend API model attachments, falling back to IDs if no GTS models supplied.
2023-12-09 16:54:38 +01:00
func ( c * Converter ) convertAttachmentsToAPIAttachments ( ctx context . Context , attachments [ ] * gtsmodel . MediaAttachment , attachmentIDs [ ] string ) ( [ ] * apimodel . Attachment , error ) {
2022-12-22 11:48:28 +01:00
var errs gtserror . MultiError
2022-11-29 18:59:59 +01:00
2024-01-19 13:57:29 +01:00
if len ( attachments ) == 0 && len ( attachmentIDs ) > 0 {
2022-11-29 18:59:59 +01:00
// GTS model attachments were not populated
2024-01-19 13:57:29 +01:00
var err error
2022-11-29 18:59:59 +01:00
// Fetch GTS models for attachment IDs
2024-01-19 13:57:29 +01:00
attachments , err = c . state . DB . GetAttachmentsByIDs ( ctx , attachmentIDs )
if err != nil {
errs . Appendf ( "error fetching attachments from database: %w" , err )
2022-11-29 18:59:59 +01:00
}
}
// Preallocate expected frontend slice
2023-12-09 16:54:38 +01:00
apiAttachments := make ( [ ] * apimodel . Attachment , 0 , len ( attachments ) )
2022-11-29 18:59:59 +01:00
// Convert GTS models to frontend models
for _ , attachment := range attachments {
apiAttachment , err := c . AttachmentToAPIAttachment ( ctx , attachment )
if err != nil {
2024-01-19 13:57:29 +01:00
errs . Appendf ( "error converting attchment %s to api attachment: %w" , attachment . ID , err )
2022-11-29 18:59:59 +01:00
continue
}
2023-12-09 16:54:38 +01:00
apiAttachments = append ( apiAttachments , & apiAttachment )
2022-11-29 18:59:59 +01:00
}
return apiAttachments , errs . Combine ( )
}
2024-03-06 11:15:58 +01:00
// FilterToAPIFiltersV1 converts one GTS model filter into an API v1 filter list
func ( c * Converter ) FilterToAPIFiltersV1 ( ctx context . Context , filter * gtsmodel . Filter ) ( [ ] * apimodel . FilterV1 , error ) {
apiFilters := make ( [ ] * apimodel . FilterV1 , 0 , len ( filter . Keywords ) )
for _ , filterKeyword := range filter . Keywords {
apiFilter , err := c . FilterKeywordToAPIFilterV1 ( ctx , filterKeyword )
if err != nil {
return nil , err
}
apiFilters = append ( apiFilters , apiFilter )
}
return apiFilters , nil
}
// FilterKeywordToAPIFilterV1 converts one GTS model filter and filter keyword into an API v1 filter
func ( c * Converter ) FilterKeywordToAPIFilterV1 ( ctx context . Context , filterKeyword * gtsmodel . FilterKeyword ) ( * apimodel . FilterV1 , error ) {
if filterKeyword . Filter == nil {
return nil , gtserror . New ( "FilterKeyword model's Filter field isn't populated, but needs to be" )
}
filter := filterKeyword . Filter
2024-05-06 13:49:08 +02:00
return & apimodel . FilterV1 {
// v1 filters have a single keyword each, so we use the filter keyword ID as the v1 filter ID.
ID : filterKeyword . ID ,
Phrase : filterKeyword . Keyword ,
Context : filterToAPIFilterContexts ( filter ) ,
WholeWord : util . PtrValueOr ( filterKeyword . WholeWord , false ) ,
ExpiresAt : filterExpiresAtToAPIFilterExpiresAt ( filter . ExpiresAt ) ,
Irreversible : filter . Action == gtsmodel . FilterActionHide ,
} , nil
}
// FilterToAPIFilterV2 converts one GTS model filter into an API v2 filter.
func ( c * Converter ) FilterToAPIFilterV2 ( ctx context . Context , filter * gtsmodel . Filter ) ( * apimodel . FilterV2 , error ) {
apiFilterKeywords := make ( [ ] apimodel . FilterKeyword , 0 , len ( filter . Keywords ) )
for _ , filterKeyword := range filter . Keywords {
2024-05-31 12:55:56 +02:00
apiFilterKeywords = append ( apiFilterKeywords , * c . FilterKeywordToAPIFilterKeyword ( ctx , filterKeyword ) )
2024-05-06 13:49:08 +02:00
}
apiFilterStatuses := make ( [ ] apimodel . FilterStatus , 0 , len ( filter . Keywords ) )
for _ , filterStatus := range filter . Statuses {
2024-05-31 12:55:56 +02:00
apiFilterStatuses = append ( apiFilterStatuses , * c . FilterStatusToAPIFilterStatus ( ctx , filterStatus ) )
2024-05-06 13:49:08 +02:00
}
return & apimodel . FilterV2 {
ID : filter . ID ,
Title : filter . Title ,
Context : filterToAPIFilterContexts ( filter ) ,
ExpiresAt : filterExpiresAtToAPIFilterExpiresAt ( filter . ExpiresAt ) ,
FilterAction : filterActionToAPIFilterAction ( filter . Action ) ,
Keywords : apiFilterKeywords ,
Statuses : apiFilterStatuses ,
} , nil
}
func filterExpiresAtToAPIFilterExpiresAt ( expiresAt time . Time ) * string {
if expiresAt . IsZero ( ) {
return nil
}
return util . Ptr ( util . FormatISO8601 ( expiresAt ) )
}
func filterToAPIFilterContexts ( filter * gtsmodel . Filter ) [ ] apimodel . FilterContext {
2024-03-06 11:15:58 +01:00
apiContexts := make ( [ ] apimodel . FilterContext , 0 , apimodel . FilterContextNumValues )
if util . PtrValueOr ( filter . ContextHome , false ) {
apiContexts = append ( apiContexts , apimodel . FilterContextHome )
}
if util . PtrValueOr ( filter . ContextNotifications , false ) {
apiContexts = append ( apiContexts , apimodel . FilterContextNotifications )
}
if util . PtrValueOr ( filter . ContextPublic , false ) {
apiContexts = append ( apiContexts , apimodel . FilterContextPublic )
}
if util . PtrValueOr ( filter . ContextThread , false ) {
apiContexts = append ( apiContexts , apimodel . FilterContextThread )
}
if util . PtrValueOr ( filter . ContextAccount , false ) {
apiContexts = append ( apiContexts , apimodel . FilterContextAccount )
}
2024-05-06 13:49:08 +02:00
return apiContexts
}
2024-03-06 11:15:58 +01:00
2024-05-06 13:49:08 +02:00
func filterActionToAPIFilterAction ( m gtsmodel . FilterAction ) apimodel . FilterAction {
switch m {
case gtsmodel . FilterActionWarn :
return apimodel . FilterActionWarn
case gtsmodel . FilterActionHide :
return apimodel . FilterActionHide
2024-03-06 11:15:58 +01:00
}
2024-05-06 13:49:08 +02:00
return apimodel . FilterActionNone
2024-03-06 11:15:58 +01:00
}
2024-05-31 12:55:56 +02:00
// FilterKeywordToAPIFilterKeyword converts a GTS model filter status into an API filter status.
func ( c * Converter ) FilterKeywordToAPIFilterKeyword ( ctx context . Context , filterKeyword * gtsmodel . FilterKeyword ) * apimodel . FilterKeyword {
return & apimodel . FilterKeyword {
ID : filterKeyword . ID ,
Keyword : filterKeyword . Keyword ,
WholeWord : util . PtrValueOr ( filterKeyword . WholeWord , false ) ,
}
}
// FilterStatusToAPIFilterStatus converts a GTS model filter status into an API filter status.
func ( c * Converter ) FilterStatusToAPIFilterStatus ( ctx context . Context , filterStatus * gtsmodel . FilterStatus ) * apimodel . FilterStatus {
return & apimodel . FilterStatus {
ID : filterStatus . ID ,
StatusID : filterStatus . StatusID ,
}
}
2022-11-29 18:59:59 +01:00
// convertEmojisToAPIEmojis will convert a slice of GTS model emojis to frontend API model emojis, falling back to IDs if no GTS models supplied.
2023-09-23 18:44:11 +02:00
func ( c * Converter ) convertEmojisToAPIEmojis ( ctx context . Context , emojis [ ] * gtsmodel . Emoji , emojiIDs [ ] string ) ( [ ] apimodel . Emoji , error ) {
2022-12-22 11:48:28 +01:00
var errs gtserror . MultiError
2022-11-29 18:59:59 +01:00
2024-01-19 13:57:29 +01:00
if len ( emojis ) == 0 && len ( emojiIDs ) > 0 {
2022-11-29 18:59:59 +01:00
// GTS model attachments were not populated
2024-01-19 13:57:29 +01:00
var err error
2022-11-29 18:59:59 +01:00
// Fetch GTS models for emoji IDs
2024-01-19 13:57:29 +01:00
emojis , err = c . state . DB . GetEmojisByIDs ( ctx , emojiIDs )
if err != nil {
errs . Appendf ( "error fetching emojis from database: %w" , err )
2022-11-29 18:59:59 +01:00
}
}
// Preallocate expected frontend slice
2023-01-02 13:10:50 +01:00
apiEmojis := make ( [ ] apimodel . Emoji , 0 , len ( emojis ) )
2022-11-29 18:59:59 +01:00
// Convert GTS models to frontend models
for _ , emoji := range emojis {
apiEmoji , err := c . EmojiToAPIEmoji ( ctx , emoji )
if err != nil {
2024-01-19 13:57:29 +01:00
errs . Appendf ( "error converting emoji %s to api emoji: %w" , emoji . ID , err )
2022-11-29 18:59:59 +01:00
continue
}
apiEmojis = append ( apiEmojis , apiEmoji )
}
return apiEmojis , errs . Combine ( )
}
// convertMentionsToAPIMentions will convert a slice of GTS model mentions to frontend API model mentions, falling back to IDs if no GTS models supplied.
2023-09-23 18:44:11 +02:00
func ( c * Converter ) convertMentionsToAPIMentions ( ctx context . Context , mentions [ ] * gtsmodel . Mention , mentionIDs [ ] string ) ( [ ] apimodel . Mention , error ) {
2022-12-22 11:48:28 +01:00
var errs gtserror . MultiError
2022-11-29 18:59:59 +01:00
2024-01-19 13:57:29 +01:00
if len ( mentions ) == 0 && len ( mentionIDs ) > 0 {
2022-11-29 18:59:59 +01:00
var err error
// GTS model mentions were not populated
//
// Fetch GTS models for mention IDs
2023-09-23 18:44:11 +02:00
mentions , err = c . state . DB . GetMentions ( ctx , mentionIDs )
2022-11-29 18:59:59 +01:00
if err != nil {
2024-01-19 13:57:29 +01:00
errs . Appendf ( "error fetching mentions from database: %w" , err )
2022-11-29 18:59:59 +01:00
}
}
// Preallocate expected frontend slice
2023-01-02 13:10:50 +01:00
apiMentions := make ( [ ] apimodel . Mention , 0 , len ( mentions ) )
2022-11-29 18:59:59 +01:00
// Convert GTS models to frontend models
for _ , mention := range mentions {
apiMention , err := c . MentionToAPIMention ( ctx , mention )
if err != nil {
2024-01-19 13:57:29 +01:00
errs . Appendf ( "error converting mention %s to api mention: %w" , mention . ID , err )
2022-11-29 18:59:59 +01:00
continue
}
apiMentions = append ( apiMentions , apiMention )
}
return apiMentions , errs . Combine ( )
}
// convertTagsToAPITags will convert a slice of GTS model tags to frontend API model tags, falling back to IDs if no GTS models supplied.
2023-09-23 18:44:11 +02:00
func ( c * Converter ) convertTagsToAPITags ( ctx context . Context , tags [ ] * gtsmodel . Tag , tagIDs [ ] string ) ( [ ] apimodel . Tag , error ) {
2022-12-22 11:48:28 +01:00
var errs gtserror . MultiError
2022-11-29 18:59:59 +01:00
2024-01-19 13:57:29 +01:00
if len ( tags ) == 0 && len ( tagIDs ) > 0 {
2023-07-31 15:47:35 +02:00
var err error
2022-11-29 18:59:59 +01:00
2023-09-23 18:44:11 +02:00
tags , err = c . state . DB . GetTags ( ctx , tagIDs )
2023-07-31 15:47:35 +02:00
if err != nil {
2024-01-19 13:57:29 +01:00
errs . Appendf ( "error fetching tags from database: %w" , err )
2022-11-29 18:59:59 +01:00
}
}
// Preallocate expected frontend slice
2023-01-02 13:10:50 +01:00
apiTags := make ( [ ] apimodel . Tag , 0 , len ( tags ) )
2022-11-29 18:59:59 +01:00
// Convert GTS models to frontend models
for _ , tag := range tags {
2023-07-31 15:47:35 +02:00
apiTag , err := c . TagToAPITag ( ctx , tag , false )
2022-11-29 18:59:59 +01:00
if err != nil {
2024-01-19 13:57:29 +01:00
errs . Appendf ( "error converting tag %s to api tag: %w" , tag . ID , err )
2022-11-29 18:59:59 +01:00
continue
}
apiTags = append ( apiTags , apiTag )
}
return apiTags , errs . Combine ( )
}
2024-03-25 18:32:24 +01:00
// ThemesToAPIThemes converts a slice of gtsmodel Themes into apimodel Themes.
func ( c * Converter ) ThemesToAPIThemes ( themes [ ] * gtsmodel . Theme ) [ ] apimodel . Theme {
apiThemes := make ( [ ] apimodel . Theme , len ( themes ) )
for i , theme := range themes {
apiThemes [ i ] = apimodel . Theme {
Title : theme . Title ,
Description : theme . Description ,
FileName : theme . FileName ,
}
}
return apiThemes
}