forked from imperatrona/twitter-scraper
-
Notifications
You must be signed in to change notification settings - Fork 1
/
upload.go
230 lines (190 loc) · 5.25 KB
/
upload.go
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
package twitterscraper
import (
"bytes"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
vidio "github.com/AlexEidt/Vidio"
)
type Media struct {
ID int
Type string
Size int
Parts int
ExpiresAt time.Time
}
type uploadInitResponse struct {
ID int `json:"media_id"`
ExpiresAfter int `json:"expires_after_secs"`
}
type ProcessingInfo struct {
State string `json:"state"`
CheckAfter int `json:"check_after_secs"`
Progress int `json:"progress_percent"`
}
type uploadStatusResponse struct {
ProcessingInfo ProcessingInfo `json:"processing_info"`
}
// Uploads photo, video or gif for further posting or scheduling. Expires in 24 hours if not used.
func (s *Scraper) UploadMedia(filePath string) (*Media, error) {
fileContent, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}
media, err := s.uploadInit(filePath, fileContent)
if err != nil {
return nil, err
}
err = s.uploadAppend(media, fileContent)
if err != nil {
return nil, err
}
var status *ProcessingInfo
status, err = s.uploadFinalize(media)
if err != nil {
return nil, err
}
if strings.HasPrefix(media.Type, "image") {
return media, nil
}
for status.State != "succeeded" {
time.Sleep(2 * time.Second)
status, err = s.uploadStatus(media)
if err != nil {
return nil, err
}
}
return media, nil
}
func (s *Scraper) uploadInit(filePath string, fileContent []byte) (*Media, error) {
var (
videoDuration float64
fileType string
mediaCategory = "tweet_"
)
fileType = http.DetectContentType(fileContent)
if fileType == "image/jpeg" || fileType == "image/png" {
mediaCategory += "image"
} else if fileType == "image/gif" {
mediaCategory += "gif"
} else if fileType == "video/mp4" || fileType == "video/quicktime" {
mediaCategory += "video"
video, err := vidio.NewVideo(filePath)
if err != nil {
return nil, err
}
videoDuration = video.Duration()
video.Close()
} else {
return nil, fmt.Errorf("file type %s unsupported by twitter, make sure you uploading photo, video or gif", fileType)
}
req, err := s.newRequest("POST", "https://upload.twitter.com/i/media/upload.json")
if err != nil {
return nil, err
}
query := url.Values{}
query.Set("command", "INIT")
query.Set("total_bytes", strconv.Itoa(len(fileContent)))
query.Set("media_type", fileType)
query.Set("media_category", mediaCategory)
if mediaCategory == "tweet_video" {
query.Set("video_duration_ms", strconv.FormatFloat(videoDuration*1000, 'f', -1, 64))
}
req.URL.RawQuery = query.Encode()
req.Header.Set("Origin", "https://twitter.com")
req.Header.Set("Referer", "https://twitter.com/")
var uploadInit uploadInitResponse
err = s.RequestAPI(req, &uploadInit)
if err != nil {
return nil, err
}
return &Media{
ID: uploadInit.ID,
Type: fileType,
Size: len(fileContent),
ExpiresAt: time.Now().Add(time.Duration(uploadInit.ExpiresAfter) * time.Second),
Parts: len(fileContent) / 2_000_000,
}, nil
}
func (s *Scraper) uploadAppend(media *Media, fileContent []byte) error {
for i := 0; i <= media.Parts; i++ {
var partData []byte
if i+1 <= media.Parts {
partData = fileContent[i*2_000_000 : (i+1)*2_000_000]
} else {
partData = fileContent[i*2_000_000:]
}
var buf bytes.Buffer
w := multipart.NewWriter(&buf)
fw, err := w.CreateFormFile("media", "blob")
if err != nil {
log.Fatal(err)
}
if _, err = io.Copy(fw, bytes.NewReader(partData)); err != nil {
return err
}
w.Close()
req, err := s.newRequest("POST", "https://upload.twitter.com/i/media/upload.json")
if err != nil {
return err
}
query := url.Values{}
query.Set("command", "APPEND")
query.Set("media_id", strconv.Itoa(media.ID))
query.Set("segment_index", strconv.Itoa(i))
req.URL.RawQuery = query.Encode()
req.Header.Set("Content-Type", w.FormDataContentType())
req.Header.Set("Origin", "https://twitter.com")
req.Header.Set("Referer", "https://twitter.com/")
req.Body = io.NopCloser(&buf)
err = s.RequestAPI(req, nil)
if err != nil {
return err
}
}
return nil
}
func (s *Scraper) uploadFinalize(media *Media) (*ProcessingInfo, error) {
req, err := s.newRequest("POST", "https://upload.twitter.com/i/media/upload.json")
if err != nil {
return nil, err
}
query := url.Values{}
query.Set("command", "FINALIZE")
query.Set("media_id", strconv.Itoa(media.ID))
query.Set("allow_async", "true")
req.URL.RawQuery = query.Encode()
req.Header.Set("Origin", "https://twitter.com")
req.Header.Set("Referer", "https://twitter.com/")
var response uploadStatusResponse
err = s.RequestAPI(req, &response)
if err != nil {
return nil, err
}
return &response.ProcessingInfo, nil
}
func (s *Scraper) uploadStatus(media *Media) (*ProcessingInfo, error) {
req, err := s.newRequest("GET", "https://upload.twitter.com/i/media/upload.json")
if err != nil {
return nil, err
}
query := url.Values{}
query.Set("command", "STATUS")
query.Set("media_id", strconv.Itoa(media.ID))
req.URL.RawQuery = query.Encode()
req.Header.Set("Origin", "https://twitter.com")
req.Header.Set("Referer", "https://twitter.com/")
var response uploadStatusResponse
err = s.RequestAPI(req, &response)
if err != nil {
return nil, err
}
return &response.ProcessingInfo, nil
}