summaryrefslogtreecommitdiff
path: root/internal/processing/status/common.go
blob: 3f2b7b6cbfe2d3ae1036edffa4ee0b5df3f35b3e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package status

import (
	"context"
	"errors"
	"fmt"
	"time"

	apimodel "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/id"
	"github.com/superseriousbusiness/gotosocial/internal/text"
	"github.com/superseriousbusiness/gotosocial/internal/util/xslices"
	"github.com/superseriousbusiness/gotosocial/internal/validate"
)

// validateStatusContent will validate the common
// content fields across status write endpoints against
// current server configuration (e.g. max char counts).
func validateStatusContent(
	status string,
	spoiler string,
	mediaIDs []string,
	poll *apimodel.PollRequest,
) gtserror.WithCode {
	totalChars := len([]rune(status)) +
		len([]rune(spoiler))

	if totalChars == 0 && len(mediaIDs) == 0 && poll == nil {
		const text = "status contains no text, media or poll"
		return gtserror.NewErrorBadRequest(errors.New(text), text)
	}

	if max := config.GetStatusesMaxChars(); totalChars > max {
		text := fmt.Sprintf("text with spoiler exceed max chars (%d)", max)
		return gtserror.NewErrorBadRequest(errors.New(text), text)
	}

	if max := config.GetStatusesMediaMaxFiles(); len(mediaIDs) > max {
		text := fmt.Sprintf("media files exceed max count (%d)", max)
		return gtserror.NewErrorBadRequest(errors.New(text), text)
	}

	if poll != nil {
		switch max := config.GetStatusesPollMaxOptions(); {
		case len(poll.Options) == 0:
			const text = "poll cannot have no options"
			return gtserror.NewErrorBadRequest(errors.New(text), text)

		case len(poll.Options) > max:
			text := fmt.Sprintf("poll options exceed max count (%d)", max)
			return gtserror.NewErrorBadRequest(errors.New(text), text)
		}

		max := config.GetStatusesPollOptionMaxChars()
		for i, option := range poll.Options {
			switch l := len([]rune(option)); {
			case l == 0:
				const text = "poll option cannot be empty"
				return gtserror.NewErrorBadRequest(errors.New(text), text)

			case l > max:
				text := fmt.Sprintf("poll option %d exceed max chars (%d)", i, max)
				return gtserror.NewErrorBadRequest(errors.New(text), text)
			}
		}
	}

	return nil
}

// statusContent encompasses the set of common processed
// status content fields from status write operations for
// an easily returnable type, without needing to allocate
// an entire gtsmodel.Status{} model.
type statusContent struct {
	Content        string
	ContentWarning string
	PollOptions    []string
	Language       string
	MentionIDs     []string
	Mentions       []*gtsmodel.Mention
	EmojiIDs       []string
	Emojis         []*gtsmodel.Emoji
	TagIDs         []string
	Tags           []*gtsmodel.Tag
}

func (p *Processor) processContent(
	ctx context.Context,
	author *gtsmodel.Account,
	statusID string,
	contentType string,
	content string,
	contentWarning string,
	language string,
	poll *apimodel.PollRequest,
) (
	*statusContent,
	gtserror.WithCode,
) {
	if language == "" {
		// Ensure we have a status language.
		language = author.Settings.Language
		if language == "" {
			const text = "account default language unset"
			return nil, gtserror.NewErrorInternalError(
				errors.New(text),
			)
		}
	}

	var err error

	// Validate + normalize determined language.
	language, err = validate.Language(language)
	if err != nil {
		text := fmt.Sprintf("invalid language tag: %v", err)
		return nil, gtserror.NewErrorBadRequest(
			errors.New(text),
			text,
		)
	}

	// format is the currently set text formatting
	// function, according to the provided content-type.
	var format text.FormatFunc

	if contentType == "" {
		// If content type wasn't specified, use
		// the author's preferred content-type.
		contentType = author.Settings.StatusContentType
	}

	switch contentType {

	// Format status according to text/plain.
	case "", string(apimodel.StatusContentTypePlain):
		format = p.formatter.FromPlain

	// Format status according to text/markdown.
	case string(apimodel.StatusContentTypeMarkdown):
		format = p.formatter.FromMarkdown

	// Unknown.
	default:
		const text = "invalid status format"
		return nil, gtserror.NewErrorBadRequest(
			errors.New(text),
			text,
		)
	}

	// Allocate a structure to hold the
	// majority of formatted content without
	// needing to alloc a whole gtsmodel.Status{}.
	var status statusContent
	status.Language = language

	// formatInput is a shorthand function to format the given input string with the
	// currently set 'formatFunc', passing in all required args and returning result.
	formatInput := func(formatFunc text.FormatFunc, input string) *text.FormatResult {
		return formatFunc(ctx, p.parseMention, author.ID, statusID, input)
	}

	// Sanitize input status text and format.
	contentRes := formatInput(format, content)

	// Gather results of formatted.
	status.Content = contentRes.HTML
	status.Mentions = contentRes.Mentions
	status.Emojis = contentRes.Emojis
	status.Tags = contentRes.Tags

	// From here-on-out just use emoji-only
	// plain-text formatting as the FormatFunc.
	format = p.formatter.FromPlainEmojiOnly

	// Sanitize content warning and format.
	warning := text.SanitizeToPlaintext(contentWarning)
	warningRes := formatInput(format, warning)

	// Gather results of the formatted.
	status.ContentWarning = warningRes.HTML
	status.Emojis = append(status.Emojis, warningRes.Emojis...)

	if poll != nil {
		// Pre-allocate slice of poll options of expected length.
		status.PollOptions = make([]string, len(poll.Options))
		for i, option := range poll.Options {

			// Sanitize each poll option and format.
			option = text.SanitizeToPlaintext(option)
			optionRes := formatInput(format, option)

			// Gather results of the formatted.
			status.PollOptions[i] = optionRes.HTML
			status.Emojis = append(status.Emojis, optionRes.Emojis...)
		}

		// Also update options on the form.
		poll.Options = status.PollOptions
	}

	// We may have received multiple copies of the same emoji, deduplicate these first.
	status.Emojis = xslices.DeduplicateFunc(status.Emojis, func(e *gtsmodel.Emoji) string {
		return e.ID
	})

	// Gather up the IDs of mentions from parsed content.
	status.MentionIDs = xslices.Gather(nil, status.Mentions,
		func(m *gtsmodel.Mention) string {
			return m.ID
		},
	)

	// Gather up the IDs of tags from parsed content.
	status.TagIDs = xslices.Gather(nil, status.Tags,
		func(t *gtsmodel.Tag) string {
			return t.ID
		},
	)

	// Gather up the IDs of emojis in updated content.
	status.EmojiIDs = xslices.Gather(nil, status.Emojis,
		func(e *gtsmodel.Emoji) string {
			return e.ID
		},
	)

	return &status, nil
}

func (p *Processor) processMedia(
	ctx context.Context,
	authorID string,
	statusID string,
	mediaIDs []string,
) (
	[]*gtsmodel.MediaAttachment,
	gtserror.WithCode,
) {
	// No media provided!
	if len(mediaIDs) == 0 {
		return nil, nil
	}

	// Get configured min/max supported descr chars.
	minChars := config.GetMediaDescriptionMinChars()
	maxChars := config.GetMediaDescriptionMaxChars()

	// Pre-allocate slice of media attachments of expected length.
	attachments := make([]*gtsmodel.MediaAttachment, len(mediaIDs))
	for i, id := range mediaIDs {

		// Look for media attachment by ID in database.
		media, err := p.state.DB.GetAttachmentByID(ctx, id)
		if err != nil && !errors.Is(err, db.ErrNoEntries) {
			err := gtserror.Newf("error getting media from db: %w", err)
			return nil, gtserror.NewErrorInternalError(err)
		}

		// Check media exists and is owned by author
		// (this masks finding out media ownership info).
		if media == nil || media.AccountID != authorID {
			text := fmt.Sprintf("media not found: %s", id)
			return nil, gtserror.NewErrorBadRequest(errors.New(text), text)
		}

		// Check media isn't already attached to another status.
		if (media.StatusID != "" && media.StatusID != statusID) ||
			(media.ScheduledStatusID != "" && media.ScheduledStatusID != statusID) {
			text := fmt.Sprintf("media already attached to status: %s", id)
			return nil, gtserror.NewErrorBadRequest(errors.New(text), text)
		}

		// Check media description chars within range,
		// this needs to be done here as lots of clients
		// only update media description on status post.
		switch chars := len([]rune(media.Description)); {
		case chars < minChars:
			text := fmt.Sprintf("media description less than min chars (%d)", minChars)
			return nil, gtserror.NewErrorBadRequest(errors.New(text), text)

		case chars > maxChars:
			text := fmt.Sprintf("media description exceeds max chars (%d)", maxChars)
			return nil, gtserror.NewErrorBadRequest(errors.New(text), text)
		}

		// Set media at index.
		attachments[i] = media
	}

	return attachments, nil
}

func (p *Processor) processPoll(
	ctx context.Context,
	statusID string,
	form *apimodel.PollRequest,
	now time.Time, // used for expiry time
) (
	*gtsmodel.Poll,
	gtserror.WithCode,
) {
	var expiresAt time.Time

	// Set an expiry time if one given.
	if in := form.ExpiresIn; in > 0 {
		expiresIn := time.Duration(in)
		expiresAt = now.Add(expiresIn * time.Second)
	}

	// Create new poll model.
	poll := &gtsmodel.Poll{
		ID:         id.NewULIDFromTime(now),
		Multiple:   &form.Multiple,
		HideCounts: &form.HideTotals,
		Options:    form.Options,
		StatusID:   statusID,
		ExpiresAt:  expiresAt,
	}

	// Insert the newly created poll model in the database.
	if err := p.state.DB.PutPoll(ctx, poll); err != nil {
		err := gtserror.Newf("error inserting poll in db: %w", err)
		return nil, gtserror.NewErrorInternalError(err)
	}

	return poll, nil
}