-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathposts_create.go
More file actions
642 lines (539 loc) · 20.8 KB
/
posts_create.go
File metadata and controls
642 lines (539 loc) · 20.8 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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
package threads
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"strings"
"time"
)
// CreateTextPost creates a new text post on Threads
func (c *Client) CreateTextPost(ctx context.Context, content *TextPostContent) (*Post, error) {
// Validate content according to API limits
if err := c.ValidateTextPostContent(content); err != nil {
return nil, err
}
if strings.TrimSpace(content.Text) == "" {
return nil, NewValidationError(400, "Text content is required", ErrEmptyPostID, "text")
}
// Ensure we have a valid token
if err := c.EnsureValidToken(ctx); err != nil {
return nil, err
}
// Handle auto_publish_text flow differently
if content.AutoPublishText {
return c.createAndPublishTextPostDirectly(ctx, content)
}
// Standard container creation and publishing flow
containerID, err := c.createTextContainer(ctx, content)
if err != nil {
return nil, fmt.Errorf("failed to create text container: %w", err)
}
// Wait for container to be ready
if err := c.waitForContainerReady(ctx, ContainerID(containerID), DefaultContainerPollMaxAttempts, DefaultContainerPollInterval); err != nil {
return nil, fmt.Errorf("container not ready for publishing: %w", err)
}
// Publish the container
post, err := c.publishContainer(ctx, containerID)
if err != nil {
return nil, fmt.Errorf("failed to publish text post: %w", err)
}
return post, nil
}
// CreateImagePost creates a new image post on Threads
func (c *Client) CreateImagePost(ctx context.Context, content *ImagePostContent) (*Post, error) {
// Validate content according to API limits
if err := c.ValidateImagePostContent(content); err != nil {
return nil, err
}
if strings.TrimSpace(content.ImageURL) == "" {
return nil, NewValidationError(400, "Image URL is required", "Post must have an image URL", "image_url")
}
// Ensure we have a valid token
if err := c.EnsureValidToken(ctx); err != nil {
return nil, err
}
// Create container first
containerID, err := c.createImageContainer(ctx, content)
if err != nil {
return nil, fmt.Errorf("failed to create image container: %w", err)
}
// Wait for container to be ready
if err := c.waitForContainerReady(ctx, ContainerID(containerID), DefaultContainerPollMaxAttempts, DefaultContainerPollInterval); err != nil {
return nil, fmt.Errorf("container not ready for publishing: %w", err)
}
// Publish the container
post, err := c.publishContainer(ctx, containerID)
if err != nil {
return nil, fmt.Errorf("failed to publish image post: %w", err)
}
return post, nil
}
// CreateVideoPost creates a new video post on Threads
func (c *Client) CreateVideoPost(ctx context.Context, content *VideoPostContent) (*Post, error) {
// Validate content according to API limits
if err := c.ValidateVideoPostContent(content); err != nil {
return nil, err
}
if strings.TrimSpace(content.VideoURL) == "" {
return nil, NewValidationError(400, "Video URL is required", "Post must have a video URL", "video_url")
}
// Ensure we have a valid token
if err := c.EnsureValidToken(ctx); err != nil {
return nil, err
}
// Create container first
containerID, err := c.createVideoContainer(ctx, content)
if err != nil {
return nil, fmt.Errorf("failed to create video container: %w", err)
}
// Wait for container to be ready
if err := c.waitForContainerReady(ctx, ContainerID(containerID), DefaultContainerPollMaxAttempts, DefaultContainerPollInterval); err != nil {
return nil, fmt.Errorf("container not ready for publishing: %w", err)
}
// Publish the container
post, err := c.publishContainer(ctx, containerID)
if err != nil {
return nil, fmt.Errorf("failed to publish video post: %w", err)
}
return post, nil
}
// CreateCarouselPost creates a new carousel post on Threads
func (c *Client) CreateCarouselPost(ctx context.Context, content *CarouselPostContent) (*Post, error) {
// Validate content according to API limits
if err := c.ValidateCarouselPostContent(content); err != nil {
return nil, err
}
if len(content.Children) == 0 {
return nil, NewValidationError(400, "Children containers are required", "Carousel post must have at least one child container", "children")
}
// Ensure we have a valid token
if err := c.EnsureValidToken(ctx); err != nil {
return nil, err
}
// Wait for all child containers to be ready in parallel
// The Threads API requires child containers to be in FINISHED status
type childResult struct {
index int
id string
err error
}
results := make(chan childResult, len(content.Children))
childCtx, cancelChildren := context.WithCancel(ctx)
defer cancelChildren()
for i, childID := range content.Children {
go func(idx int, cID string) {
err := c.waitForContainerReady(childCtx, ContainerID(cID), DefaultContainerPollMaxAttempts, DefaultContainerPollInterval)
results <- childResult{index: idx, id: cID, err: err}
}(i, childID)
}
// Collect all results; cancel siblings as soon as any failure is seen
errs := make([]error, len(content.Children))
for range content.Children {
result := <-results
errs[result.index] = result.err
if result.err != nil {
cancelChildren()
}
}
// Report the first real failure, skipping cancellation side-effects from siblings
for i, err := range errs {
if err != nil && !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) {
return nil, fmt.Errorf("child container %d (%s) not ready: %w", i+1, content.Children[i], err)
}
}
// Fallback: if only cancellation errors exist, report the first one
for i, err := range errs {
if err != nil {
return nil, fmt.Errorf("child container %d (%s) not ready: %w", i+1, content.Children[i], err)
}
}
// Create container first
containerID, err := c.createCarouselContainer(ctx, content)
if err != nil {
return nil, fmt.Errorf("failed to create carousel container: %w", err)
}
// Wait for container to be ready
if err := c.waitForContainerReady(ctx, ContainerID(containerID), DefaultContainerPollMaxAttempts, DefaultContainerPollInterval); err != nil {
return nil, fmt.Errorf("container not ready for publishing: %w", err)
}
// Publish the container
post, err := c.publishContainer(ctx, containerID)
if err != nil {
return nil, fmt.Errorf("failed to publish carousel post: %w", err)
}
return post, nil
}
// CreateQuotePost creates a new quote post on Threads
// CreateQuotePost creates a quote post using any supported content type with a quoted post ID.
// This method acts as a router, directing to the appropriate creation method based on content type.
//
// Supported content types:
// - *TextPostContent: Creates a text quote post
// - *ImagePostContent: Creates an image quote post
// - *VideoPostContent: Creates a video quote post
// - *CarouselPostContent: Creates a carousel quote post
//
// The quotedPostID parameter specifies which post to quote.
func (c *Client) CreateQuotePost(ctx context.Context, content interface{}, quotedPostID string) (*Post, error) {
if strings.TrimSpace(quotedPostID) == "" {
return nil, NewValidationError(400, "Quoted post ID is required", "Quote post must reference an existing post", "quoted_post_id")
}
switch v := content.(type) {
case *TextPostContent:
// Set the quoted post ID and delegate to text post creation
v.QuotedPostID = quotedPostID
return c.CreateTextPost(ctx, v)
case *ImagePostContent:
// Set the quoted post ID and delegate to image post creation
v.QuotedPostID = quotedPostID
return c.CreateImagePost(ctx, v)
case *VideoPostContent:
// Set the quoted post ID and delegate to video post creation
v.QuotedPostID = quotedPostID
return c.CreateVideoPost(ctx, v)
case *CarouselPostContent:
// Set the quoted post ID and delegate to carousel post creation
v.QuotedPostID = quotedPostID
return c.CreateCarouselPost(ctx, v)
default:
return nil, fmt.Errorf("unsupported content type for quote post: %T", content)
}
}
// RepostPost reposts an existing post on Threads using the direct repost endpoint
func (c *Client) RepostPost(ctx context.Context, postID PostID) (*Post, error) {
if !postID.Valid() {
return nil, NewValidationError(400, ErrEmptyPostID, "Cannot repost without a post ID", "post_id")
}
// Ensure we have a valid token
if err := c.EnsureValidToken(ctx); err != nil {
return nil, err
}
// Use the direct repost endpoint
path := fmt.Sprintf("/%s/repost", postID.String())
resp, err := c.httpClient.POST(path, nil, c.getAccessTokenSafe())
if err != nil {
return nil, fmt.Errorf("failed to create repost: %w", err)
}
if resp.StatusCode != 200 {
return nil, c.handleAPIError(resp)
}
// Parse response to get repost ID
var repostResp struct {
ID string `json:"id"`
}
if err := json.Unmarshal(resp.Body, &repostResp); err != nil {
return nil, NewAPIError(resp.StatusCode, "Failed to parse repost response", err.Error(), resp.RequestID)
}
if repostResp.ID == "" {
return nil, NewAPIError(resp.StatusCode, "Repost ID not returned", "API response missing repost ID", resp.RequestID)
}
// Fetch the created repost details
return c.GetPost(ctx, ConvertToPostID(repostResp.ID))
}
// CreateMediaContainer creates a media container for use in carousel posts
func (c *Client) CreateMediaContainer(ctx context.Context, mediaType, mediaURL, altText string) (ContainerID, error) {
if mediaType == "" {
return "", NewValidationError(400, "Media type is required", "Must specify IMAGE or VIDEO", "media_type")
}
if mediaURL == "" {
return "", NewValidationError(400, "Media URL is required", "Must provide a valid media URL", "media_url")
}
// Validate media URL
validator := NewValidator()
if err := validator.ValidateMediaURL(mediaURL, strings.ToLower(mediaType)); err != nil {
return "", err
}
// Ensure we have a valid token
if err := c.EnsureValidToken(ctx); err != nil {
return "", err
}
// Build container using builder pattern
builder := NewContainerBuilder().
SetMediaType(strings.ToUpper(mediaType)).
SetIsCarouselItem(true).
SetAltText(altText)
// Set the appropriate URL parameter based on media type
switch strings.ToUpper(mediaType) {
case MediaTypeImage:
builder.SetImageURL(mediaURL)
case MediaTypeVideo:
builder.SetVideoURL(mediaURL)
default:
return "", NewValidationError(400, "Invalid media type", "Media type must be IMAGE or VIDEO", "media_type")
}
containerID, err := c.createContainer(ctx, builder.Build())
if err != nil {
return "", err
}
return ConvertToContainerID(containerID), nil
}
// createTextContainer creates a container for text content
func (c *Client) createTextContainer(ctx context.Context, content *TextPostContent) (string, error) {
builder := NewContainerBuilder().
SetMediaType(MediaTypeText).
SetText(content.Text).
SetLinkAttachment(content.LinkAttachment).
SetPollAttachment(content.PollAttachment).
SetReplyControl(content.ReplyControl).
SetReplyTo(content.ReplyTo).
SetTopicTag(content.TopicTag).
SetAllowlistedCountryCodes(content.AllowlistedCountryCodes).
SetLocationID(content.LocationID).
SetTextEntities(content.TextEntities).
SetTextAttachment(content.TextAttachment).
SetGIFAttachment(content.GIFAttachment).
SetIsGhostPost(content.IsGhostPost).
SetEnableReplyApprovals(content.EnableReplyApprovals)
// Add quoted post ID if this is a quote post
if content.QuotedPostID != "" {
builder.SetQuotePostID(content.QuotedPostID)
}
return c.createContainer(ctx, builder.Build())
}
// createImageContainer creates a container for image content
func (c *Client) createImageContainer(ctx context.Context, content *ImagePostContent) (string, error) {
builder := NewContainerBuilder().
SetMediaType(MediaTypeImage).
SetImageURL(content.ImageURL).
SetText(content.Text).
SetAltText(content.AltText).
SetReplyControl(content.ReplyControl).
SetReplyTo(content.ReplyTo).
SetTopicTag(content.TopicTag).
SetAllowlistedCountryCodes(content.AllowlistedCountryCodes).
SetLocationID(content.LocationID).
SetTextEntities(content.TextEntities).
SetIsSpoilerMedia(content.IsSpoilerMedia).
SetEnableReplyApprovals(content.EnableReplyApprovals)
// Add quoted post ID if this is a quote post
if content.QuotedPostID != "" {
builder.SetQuotePostID(content.QuotedPostID)
}
return c.createContainer(ctx, builder.Build())
}
// createVideoContainer creates a container for video content
func (c *Client) createVideoContainer(ctx context.Context, content *VideoPostContent) (string, error) {
builder := NewContainerBuilder().
SetMediaType(MediaTypeVideo).
SetVideoURL(content.VideoURL).
SetText(content.Text).
SetAltText(content.AltText).
SetReplyControl(content.ReplyControl).
SetReplyTo(content.ReplyTo).
SetTopicTag(content.TopicTag).
SetAllowlistedCountryCodes(content.AllowlistedCountryCodes).
SetLocationID(content.LocationID).
SetTextEntities(content.TextEntities).
SetIsSpoilerMedia(content.IsSpoilerMedia).
SetEnableReplyApprovals(content.EnableReplyApprovals)
// Add quoted post ID if this is a quote post
if content.QuotedPostID != "" {
builder.SetQuotePostID(content.QuotedPostID)
}
containerID, err := c.createContainer(ctx, builder.Build())
if err != nil {
return "", err
}
return containerID, nil
}
// createCarouselContainer creates a container for carousel content
func (c *Client) createCarouselContainer(ctx context.Context, content *CarouselPostContent) (string, error) {
builder := NewContainerBuilder().
SetMediaType(MediaTypeCarousel).
SetText(content.Text).
SetChildren(content.Children).
SetReplyControl(content.ReplyControl).
SetReplyTo(content.ReplyTo).
SetTopicTag(content.TopicTag).
SetAllowlistedCountryCodes(content.AllowlistedCountryCodes).
SetLocationID(content.LocationID).
SetTextEntities(content.TextEntities).
SetIsSpoilerMedia(content.IsSpoilerMedia).
SetEnableReplyApprovals(content.EnableReplyApprovals)
// Add quoted post ID if this is a quote post
if content.QuotedPostID != "" {
builder.SetQuotePostID(content.QuotedPostID)
}
return c.createContainer(ctx, builder.Build())
}
// createAndPublishTextPostDirectly creates and publishes a text post directly when auto_publish_text is true
func (c *Client) createAndPublishTextPostDirectly(ctx context.Context, content *TextPostContent) (*Post, error) {
builder := NewContainerBuilder().
SetMediaType(MediaTypeText).
SetText(content.Text).
SetAutoPublishText(true).
SetLinkAttachment(content.LinkAttachment).
SetPollAttachment(content.PollAttachment).
SetReplyControl(content.ReplyControl).
SetReplyTo(content.ReplyTo).
SetTopicTag(content.TopicTag).
SetAllowlistedCountryCodes(content.AllowlistedCountryCodes).
SetLocationID(content.LocationID).
SetTextEntities(content.TextEntities).
SetTextAttachment(content.TextAttachment).
SetGIFAttachment(content.GIFAttachment).
SetIsGhostPost(content.IsGhostPost).
SetEnableReplyApprovals(content.EnableReplyApprovals)
// Get user ID from token info
userID := c.getUserID()
if userID == "" {
return nil, NewAuthenticationError(401, "User ID not available", "Cannot determine user ID from token")
}
// Make API call to create and publish post directly
path := fmt.Sprintf("/%s/threads", userID)
resp, err := c.httpClient.POST(path, builder.Build(), c.getAccessTokenSafe())
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, c.handleAPIError(resp)
}
// Parse response - when auto_publish_text is true, the API returns the post ID directly
var post Post
if err := safeJSONUnmarshal(resp.Body, &post, "direct publish response", resp.RequestID); err != nil {
return nil, err
}
// Validate that we got a valid post ID
if post.ID == "" {
return nil, NewAPIError(resp.StatusCode, "Post ID not returned", "API response missing post ID", resp.RequestID)
}
// Fetch the created post details
return c.GetPost(ctx, ConvertToPostID(post.ID))
}
// createContainer is a helper method to create containers with given parameters
func (c *Client) createContainer(_ context.Context, params url.Values) (string, error) {
// Get user ID from token info
userID := c.getUserID()
if userID == "" {
return "", NewAuthenticationError(401, "User ID not available", "Cannot determine user ID from token")
}
// Make API call to create container
path := fmt.Sprintf("/%s/threads", userID)
resp, err := c.httpClient.POST(path, params, c.getAccessTokenSafe())
if err != nil {
return "", err
}
if resp.StatusCode != 200 {
return "", c.handleAPIError(resp)
}
// Parse response to get container ID
var containerResp struct {
ID string `json:"id"`
}
if err := json.Unmarshal(resp.Body, &containerResp); err != nil {
return "", NewAPIError(resp.StatusCode, "Failed to parse container response", err.Error(), resp.RequestID)
}
if containerResp.ID == "" {
return "", NewAPIError(resp.StatusCode, "Container ID not returned", "API response missing container ID", resp.RequestID)
}
return containerResp.ID, nil
}
// publishContainer publishes a created container
func (c *Client) publishContainer(ctx context.Context, containerID string) (*Post, error) {
if containerID == "" {
return nil, NewValidationError(400, ErrEmptyContainerID, "Cannot publish without container ID", "container_id")
}
// Get user ID from token info
userID := c.getUserID()
if userID == "" {
return nil, NewAuthenticationError(401, "User ID not available", "Cannot determine user ID from token")
}
// Build request parameters
params := url.Values{
"creation_id": {containerID},
}
// Make API call to publish container
path := fmt.Sprintf("/%s/threads_publish", userID)
resp, err := c.httpClient.POST(path, params, c.getAccessTokenSafe())
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, c.handleAPIError(resp)
}
// Parse response to get post ID
var publishResp struct {
ID string `json:"id"`
}
if err := json.Unmarshal(resp.Body, &publishResp); err != nil {
return nil, NewAPIError(resp.StatusCode, "Failed to parse publish response", err.Error(), resp.RequestID)
}
if publishResp.ID == "" {
return nil, NewAPIError(resp.StatusCode, "Post ID not returned", "API response missing post ID", resp.RequestID)
}
// Fetch the created post details
return c.GetPost(ctx, ConvertToPostID(publishResp.ID))
}
// GetContainerStatus retrieves the status of a media container
// This is useful for checking if a video or image container has finished processing
// before attempting to publish it. Returns container status information including:
// - ID: The container ID
// - Status: Current status (IN_PROGRESS, FINISHED, PUBLISHED, ERROR, EXPIRED)
// - ErrorMessage: Error details if status is ERROR
func (c *Client) GetContainerStatus(ctx context.Context, containerID ContainerID) (*ContainerStatus, error) {
if !containerID.Valid() {
return nil, NewValidationError(400, ErrEmptyContainerID, "Cannot check status without container ID", "container_id")
}
// Ensure we have a valid token
if err := c.EnsureValidToken(ctx); err != nil {
return nil, err
}
// Build request parameters with container status fields
params := url.Values{
"fields": {ContainerStatusFields},
}
// Make API call to get container status
path := fmt.Sprintf("/%s", containerID.String())
resp, err := c.httpClient.GET(path, params, c.getAccessTokenSafe())
if err != nil {
return nil, fmt.Errorf("failed to get container status: %w", err)
}
if resp.StatusCode != 200 {
return nil, c.handleAPIError(resp)
}
// Parse response
var status ContainerStatus
if err := safeJSONUnmarshal(resp.Body, &status, "container status response", resp.RequestID); err != nil {
return nil, err
}
// Validate response
if status.ID == "" {
return nil, NewAPIError(resp.StatusCode, "Container ID not returned", "API response missing container ID", resp.RequestID)
}
if status.Status == "" {
return nil, NewAPIError(resp.StatusCode, "Container status not returned", "API response missing container status", resp.RequestID)
}
return &status, nil
}
// waitForContainerReady polls the container status until it's ready to be published
// Returns an error if the container fails or times out. Respects context cancellation
// by using select with ctx.Done() instead of bare time.Sleep.
func (c *Client) waitForContainerReady(ctx context.Context, containerID ContainerID, maxAttempts int, pollInterval time.Duration) error {
for attempt := 0; attempt < maxAttempts; attempt++ {
status, err := c.GetContainerStatus(ctx, containerID)
if err != nil {
return fmt.Errorf("failed to check container status: %w", err)
}
switch status.Status {
case ContainerStatusFinished:
return nil
case ContainerStatusError:
if status.ErrorMessage != "" {
return fmt.Errorf("container processing failed: %s", status.ErrorMessage)
}
return fmt.Errorf("container processing failed with error status")
case ContainerStatusExpired:
return fmt.Errorf("container expired before it could be published")
default:
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(pollInterval):
continue
}
}
}
return fmt.Errorf("timeout waiting for container to be ready after %d attempts", maxAttempts)
}