-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathvalidation.go
More file actions
593 lines (504 loc) · 16.9 KB
/
validation.go
File metadata and controls
593 lines (504 loc) · 16.9 KB
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
package threads
import (
"fmt"
"regexp"
"strings"
"unicode/utf8"
)
// Validator provides common validation methods
type Validator struct{}
// NewValidator creates a new validator instance
func NewValidator() *Validator {
return &Validator{}
}
// ValidatePostContent performs common validation for all post types
func (v *Validator) ValidatePostContent(content interface{}, _ int) error {
if content == nil {
return NewValidationError(400, "Content cannot be nil", "Post content is required", "content")
}
return nil
}
// ValidateTextLength validates text doesn't exceed maximum length.
// The Threads API limits text posts to 500 characters (Unicode code points),
// not 500 bytes. Using utf8.RuneCountInString ensures CJK and other
// multi-byte characters are correctly counted as 1 character each.
func (v *Validator) ValidateTextLength(text string, fieldName string) error {
if utf8.RuneCountInString(text) > MaxTextLength {
return NewValidationError(400,
fmt.Sprintf("%s too long", fieldName),
fmt.Sprintf("%s is limited to %d characters", fieldName, MaxTextLength),
strings.ToLower(fieldName))
}
return nil
}
// ValidateLinkCount validates that the text does not contain more than the allowed number of links
func (v *Validator) ValidateLinkCount(text string, linkAttachmentURL string) error {
// Map to track unique URLs
uniqueURLs := make(map[string]bool)
// Helper to normalize URLs for uniqueness check
// This is a simple normalization (trim spaces/slashes).
normalize := func(u string) string {
u = strings.TrimSpace(u)
return strings.TrimRight(u, "/")
}
// 1. Extract URLs from text
// This regex captures http:// or https:// followed by non-whitespace characters
if text != "" {
re := regexp.MustCompile(`https?://[^\s]+`)
matches := re.FindAllString(text, -1)
for _, match := range matches {
uniqueURLs[normalize(match)] = true
}
}
// 2. Add link_attachment if present
if linkAttachmentURL != "" {
uniqueURLs[normalize(linkAttachmentURL)] = true
}
// 3. Check count
if len(uniqueURLs) > MaxLinks {
return NewValidationError(400,
"Too many links",
fmt.Sprintf("Post cannot contain more than %d unique links (found %d)", MaxLinks, len(uniqueURLs)),
"text")
}
return nil
}
// ValidateTextAttachment validates text attachment structure and content
func (v *Validator) ValidateTextAttachment(textAttachment *TextAttachment) error {
if textAttachment == nil {
return nil // Text attachment is optional
}
// Validate plaintext length (required field, max 10K chars)
if textAttachment.Plaintext == "" {
return NewValidationError(400,
"Text attachment plaintext required",
"Text attachment must have a plaintext field",
"text_attachment.plaintext")
}
if utf8.RuneCountInString(textAttachment.Plaintext) > MaxTextAttachmentLength {
return NewValidationError(400,
"Text attachment plaintext too long",
fmt.Sprintf("Text attachment plaintext is limited to %d characters (currently %d)", MaxTextAttachmentLength, utf8.RuneCountInString(textAttachment.Plaintext)),
"text_attachment.plaintext")
}
// Validate text styling ranges don't overlap
if len(textAttachment.TextWithStylingInfo) > 0 {
if err := v.validateTextStylingRanges(textAttachment.TextWithStylingInfo); err != nil {
return err
}
}
return nil
}
// validateTextStylingRanges checks that text styling ranges don't overlap and that
// each styling entry contains only valid style values.
func (v *Validator) validateTextStylingRanges(stylingInfo []TextStylingInfo) error {
validStyles := map[string]bool{
"bold": true,
"italic": true,
"highlight": true,
"underline": true,
"strikethrough": true,
}
for i := 0; i < len(stylingInfo); i++ {
// Validate style values
for _, style := range stylingInfo[i].StylingInfo {
if !validStyles[style] {
return NewValidationError(400,
"Invalid text styling value",
fmt.Sprintf("Text styling range %d contains invalid style '%s'. Valid styles are: bold, italic, highlight, underline, strikethrough", i, style),
"text_attachment.text_with_styling_info")
}
}
for j := i + 1; j < len(stylingInfo); j++ {
// Check if ranges overlap
start1, end1 := stylingInfo[i].Offset, stylingInfo[i].Offset+stylingInfo[i].Length
start2, end2 := stylingInfo[j].Offset, stylingInfo[j].Offset+stylingInfo[j].Length
if start1 < end2 && end1 > start2 {
return NewValidationError(400,
"Overlapping text styling ranges",
fmt.Sprintf("Text styling ranges cannot overlap: range %d [%d,%d) overlaps with range %d [%d,%d)",
i, start1, end1, j, start2, end2),
"text_attachment.text_with_styling_info")
}
}
}
return nil
}
// ValidatePollAttachment validates poll attachment options.
// The API requires MinPollOptions (2) to MaxPollOptions (4) options.
// Options A and B are required; options C and D are optional.
// Each provided option must be 1-MaxPollOptionLength (25) characters.
func (v *Validator) ValidatePollAttachment(poll *PollAttachment) error {
if poll == nil {
return nil // Poll attachment is optional
}
// Options A and B are required (MinPollOptions = 2)
if poll.OptionA == "" {
return NewValidationError(400,
"Poll option A required",
fmt.Sprintf("Poll attachment must have at least %d options (option_a is required)", MinPollOptions),
"poll_attachment.option_a")
}
if poll.OptionB == "" {
return NewValidationError(400,
"Poll option B required",
fmt.Sprintf("Poll attachment must have at least %d options (option_b is required)", MinPollOptions),
"poll_attachment.option_b")
}
// Options must be sequential: D requires C
if poll.OptionD != "" && poll.OptionC == "" {
return NewValidationError(400,
"Poll option C required before D",
"Cannot set option_d without option_c",
"poll_attachment.option_c")
}
// Validate length of each provided option
options := []struct {
value string
field string
}{
{poll.OptionA, "poll_attachment.option_a"},
{poll.OptionB, "poll_attachment.option_b"},
{poll.OptionC, "poll_attachment.option_c"},
{poll.OptionD, "poll_attachment.option_d"},
}
for _, opt := range options {
if opt.value == "" {
continue // optional options can be empty
}
if strings.TrimSpace(opt.value) == "" {
return NewValidationError(400,
"Poll option cannot be blank",
fmt.Sprintf("Poll option in %s must contain non-whitespace characters", opt.field),
opt.field)
}
if utf8.RuneCountInString(opt.value) > MaxPollOptionLength {
return NewValidationError(400,
"Poll option too long",
fmt.Sprintf("Poll option in %s must be at most %d characters", opt.field, MaxPollOptionLength),
opt.field)
}
}
return nil
}
// ValidateAltText validates alt text for media posts.
// Alt text is optional but cannot exceed MaxAltTextLength characters.
func (v *Validator) ValidateAltText(altText string) error {
if altText == "" {
return nil // Alt text is optional
}
if utf8.RuneCountInString(altText) > MaxAltTextLength {
return NewValidationError(400,
"Alt text too long",
fmt.Sprintf("Alt text is limited to %d characters", MaxAltTextLength),
"alt_text")
}
return nil
}
// ValidateTextEntities validates text spoiler entities
func (v *Validator) ValidateTextEntities(entities []TextEntity) error {
if len(entities) == 0 {
return nil // Optional field
}
// Check max limit
if len(entities) > MaxTextEntities {
return NewValidationError(400,
"Too many text entities",
fmt.Sprintf("Maximum %d text spoiler entities allowed per post (currently %d)", MaxTextEntities, len(entities)),
"text_entities")
}
// Validate each entity
for i, entity := range entities {
if entity.EntityType == "" {
return NewValidationError(400,
"Text entity missing type",
fmt.Sprintf("Text entity at index %d must have an entity_type", i),
"text_entities")
}
if entity.EntityType != "SPOILER" && entity.EntityType != "spoiler" {
return NewValidationError(400,
"Invalid text entity type",
fmt.Sprintf("Text entity at index %d has invalid type '%s' (must be 'SPOILER' or 'spoiler')", i, entity.EntityType),
"text_entities")
}
if entity.Offset < 0 {
return NewValidationError(400,
"Invalid text entity offset",
fmt.Sprintf("Text entity at index %d has negative offset %d", i, entity.Offset),
"text_entities")
}
if entity.Length <= 0 {
return NewValidationError(400,
"Invalid text entity length",
fmt.Sprintf("Text entity at index %d has non-positive length %d", i, entity.Length),
"text_entities")
}
}
return nil
}
// ValidateMediaURL validates media URLs for basic format and accessibility
func (v *Validator) ValidateMediaURL(mediaURL, mediaType string) error {
if mediaURL == "" {
return NewValidationError(400,
"Media URL cannot be empty",
fmt.Sprintf("%s URL is required", mediaType),
"media_url")
}
// Basic URL format validation
if !strings.HasPrefix(mediaURL, "http://") && !strings.HasPrefix(mediaURL, "https://") {
return NewValidationError(400,
"Invalid media URL format",
"Media URL must start with http:// or https://",
"media_url")
}
return nil
}
// ValidateTopicTag validates a topic tag according to Threads API rules
func (v *Validator) ValidateTopicTag(tag string) error {
if tag == "" {
return nil // Empty tag is valid (optional)
}
// Check for forbidden characters
if strings.Contains(tag, ".") {
return NewValidationError(400,
"Invalid topic tag",
"Topic tags cannot contain periods (.)",
"topic_tag")
}
if strings.Contains(tag, "&") {
return NewValidationError(400,
"Invalid topic tag",
"Topic tags cannot contain ampersands (&)",
"topic_tag")
}
return nil
}
// ValidateCountryCodes validates ISO 3166-1 alpha-2 country codes
func (v *Validator) ValidateCountryCodes(codes []string) error {
if len(codes) == 0 {
return nil // Empty list is valid
}
for _, code := range codes {
if len(code) != 2 {
return NewValidationError(400,
"Invalid country code",
fmt.Sprintf("Country code '%s' must be 2 characters (ISO 3166-1 alpha-2)", code),
"country_codes")
}
// Convert to uppercase for consistency
code = strings.ToUpper(code)
// Basic validation - should be alphabetic
for _, char := range code {
if char < 'A' || char > 'Z' {
return NewValidationError(400,
"Invalid country code",
fmt.Sprintf("Country code '%s' must contain only letters", code),
"country_codes")
}
}
}
return nil
}
// ValidateCarouselChildren validates carousel children count
func (v *Validator) ValidateCarouselChildren(childrenCount int) error {
if childrenCount < MinCarouselItems {
return NewValidationError(400,
"Insufficient children",
fmt.Sprintf("Carousel must have at least %d children", MinCarouselItems),
"children")
}
if childrenCount > MaxCarouselItems {
return NewValidationError(400,
"Too many children",
fmt.Sprintf("Carousel cannot have more than %d children", MaxCarouselItems),
"children")
}
return nil
}
// ValidatePaginationOptions validates pagination parameters
func (v *Validator) ValidatePaginationOptions(opts *PaginationOptions) error {
if opts == nil {
return nil
}
if opts.Limit > MaxPostsPerRequest {
return NewValidationError(400,
"Limit too large",
fmt.Sprintf("Maximum limit is %d posts per request", MaxPostsPerRequest),
"limit")
}
return nil
}
// ValidatePostsOptions validates PostsOptions including pagination and timestamp fields.
func (v *Validator) ValidatePostsOptions(opts *PostsOptions) error {
if opts == nil {
return nil
}
if err := v.ValidatePaginationOptions(&PaginationOptions{
Limit: opts.Limit,
Before: opts.Before,
After: opts.After,
}); err != nil {
return err
}
if opts.Since > 0 && opts.Since < MinSearchTimestamp {
return NewValidationError(400, "Invalid since timestamp",
fmt.Sprintf("since timestamp must be >= %d", MinSearchTimestamp), "since")
}
if opts.Until > 0 && opts.Until < MinSearchTimestamp {
return NewValidationError(400, "Invalid until timestamp",
fmt.Sprintf("until timestamp must be >= %d", MinSearchTimestamp), "until")
}
if opts.Since > 0 && opts.Until > 0 && opts.Since > opts.Until {
return NewValidationError(400, "Invalid time range",
"since timestamp must be less than or equal to until timestamp", "since")
}
return nil
}
// ValidateSearchOptions validates search parameters
func (v *Validator) ValidateSearchOptions(opts *SearchOptions) error {
if opts == nil {
return nil
}
if opts.Limit > MaxPostsPerRequest {
return NewValidationError(400,
"Limit too large",
fmt.Sprintf("Maximum limit is %d posts per request", MaxPostsPerRequest),
"limit")
}
if opts.Since > 0 && opts.Since < MinSearchTimestamp {
return NewValidationError(400,
"Invalid since timestamp",
fmt.Sprintf("Since timestamp must be greater than or equal to %d", MinSearchTimestamp),
"since")
}
return nil
}
// ValidateGIFAttachment validates GIF attachment structure and content
func (v *Validator) ValidateGIFAttachment(gifAttachment *GIFAttachment) error {
if gifAttachment == nil {
return nil // GIF attachment is optional
}
// Validate GIF ID is provided
if strings.TrimSpace(gifAttachment.GIFID) == "" {
return NewValidationError(400,
"GIF ID required",
"GIF attachment must have a gif_id field",
"gif_attachment.gif_id")
}
// Validate provider is provided and valid
if gifAttachment.Provider == "" {
return NewValidationError(400,
"GIF provider required",
"GIF attachment must have a provider field",
"gif_attachment.provider")
}
// Validate provider is a supported value
if gifAttachment.Provider != GIFProviderTenor && gifAttachment.Provider != GIFProviderGiphy {
return NewValidationError(400,
"Invalid GIF provider",
fmt.Sprintf("GIF provider '%s' is not supported. Supported providers: 'TENOR', 'GIPHY'", gifAttachment.Provider),
"gif_attachment.provider")
}
return nil
}
// ConfigValidator validates client configuration
type ConfigValidator struct{}
// NewConfigValidator creates a new config validator
func NewConfigValidator() *ConfigValidator {
return &ConfigValidator{}
}
// Validate validates the entire configuration
func (cv *ConfigValidator) Validate(c *Config) error {
validators := []func(*Config) error{
cv.validateRequiredFields,
cv.validateRedirectURI,
cv.validateScopes,
cv.validateHTTPSettings,
cv.validateRetryConfig,
}
for _, validator := range validators {
if err := validator(c); err != nil {
return err
}
}
return nil
}
// validateRequiredFields checks all required fields are present
func (cv *ConfigValidator) validateRequiredFields(c *Config) error {
if c.ClientID == "" {
return fmt.Errorf("ClientID is required")
}
if c.ClientSecret == "" {
return fmt.Errorf("ClientSecret is required")
}
if c.RedirectURI == "" {
return fmt.Errorf("RedirectURI is required")
}
return nil
}
// validateRedirectURI validates the redirect URI format
func (cv *ConfigValidator) validateRedirectURI(c *Config) error {
if !strings.HasPrefix(c.RedirectURI, "http://") && !strings.HasPrefix(c.RedirectURI, "https://") {
return fmt.Errorf("RedirectURI must be a valid HTTP or HTTPS URL")
}
return nil
}
// validateScopes validates the configured scopes
func (cv *ConfigValidator) validateScopes(c *Config) error {
if len(c.Scopes) == 0 {
return fmt.Errorf("at least one scope is required")
}
validScopes := map[string]bool{
"threads_basic": true,
"threads_content_publish": true,
"threads_manage_insights": true,
"threads_manage_replies": true,
"threads_read_replies": true,
"threads_manage_mentions": true,
"threads_keyword_search": true,
"threads_delete": true,
"threads_location_tagging": true,
"threads_profile_discovery": true,
}
for _, scope := range c.Scopes {
if !validScopes[scope] {
return fmt.Errorf("invalid scope: %s", scope)
}
}
return nil
}
// validateHTTPSettings validates HTTP-related configuration
func (cv *ConfigValidator) validateHTTPSettings(c *Config) error {
if c.HTTPTimeout <= 0 {
return fmt.Errorf("HTTPTimeout must be positive")
}
if c.BaseURL == "" {
return fmt.Errorf("BaseURL is required")
}
if !strings.HasPrefix(c.BaseURL, "http://") && !strings.HasPrefix(c.BaseURL, "https://") {
return fmt.Errorf("BaseURL must be a valid HTTP or HTTPS URL")
}
return nil
}
// validateRetryConfig validates retry configuration
func (cv *ConfigValidator) validateRetryConfig(c *Config) error {
if c.RetryConfig == nil {
return nil
}
if c.RetryConfig.MaxRetries < 0 {
return fmt.Errorf("RetryConfig.MaxRetries must be non-negative")
}
if c.RetryConfig.InitialDelay <= 0 {
return fmt.Errorf("RetryConfig.InitialDelay must be positive")
}
if c.RetryConfig.MaxDelay <= 0 {
return fmt.Errorf("RetryConfig.MaxDelay must be positive")
}
if c.RetryConfig.BackoffFactor <= 0 {
return fmt.Errorf("RetryConfig.BackoffFactor must be positive")
}
if c.RetryConfig.InitialDelay > c.RetryConfig.MaxDelay {
return fmt.Errorf("RetryConfig.InitialDelay cannot be greater than MaxDelay")
}
return nil
}