-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathsend.go
323 lines (289 loc) · 8.58 KB
/
send.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
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
package fbmsgr
import (
"encoding/json"
"errors"
"io"
"mime"
"mime/multipart"
"net/http"
"net/textproto"
"net/url"
"os"
"path"
"strconv"
"time"
"github.com/unixpickle/essentials"
)
type EmojiSize string
const (
SmallEmoji EmojiSize = "small"
MediumEmoji = "medium"
LargeEmoji = "large"
)
// UploadResult is the result of uploading a file.
type UploadResult struct {
// One of the following strings will be non-nil after
// a successful upload.
VideoID string
FileID string
AudioID string
ImageID string
}
// SendText attempts to send a textual message to the user
// with the given fbid.
func (s *Session) SendText(fbid, message string) (msgID string, err error) {
defer essentials.AddCtxTo("fbmsgr: send text", &err)
reqParams, err := s.textMessageParams(message)
if err != nil {
return "", err
}
reqParams.Add("other_user_fbid", fbid)
return s.sendMessage(reqParams)
}
// SendGroupText is like SendText, but the message is sent
// to a group chat rather than to an individual.
func (s *Session) SendGroupText(groupFBID, message string) (msgID string, err error) {
defer essentials.AddCtxTo("fbmsgr: send group text", &err)
reqParams, err := s.textMessageParams(message)
if err != nil {
return "", err
}
reqParams.Add("thread_fbid", groupFBID)
return s.sendMessage(reqParams)
}
// SendLike is like SendText, but it sends an emoji at a
// given size.
// It is crutial that the emoji is valid and that the size
// is also valid.
// Otherwise, this can trigger a bug in the web client
// that essentially bricks the conversation.
func (s *Session) SendLike(fbid, emoji string, size EmojiSize) (msgID string, err error) {
defer essentials.AddCtxTo("fbmsgr: send like", &err)
reqParams, err := s.textMessageParams(emoji)
if err != nil {
return "", err
}
reqParams.Add("other_user_fbid", fbid)
reqParams.Add("tags[0]", "hot_emoji_size:"+string(size))
reqParams.Add("tags[1]", "hot_emoji_source:hot_like")
return s.sendMessage(reqParams)
}
// SendGroupLike is like SendLike, but for a group thread.
func (s *Session) SendGroupLike(groupFBID, emoji string, size EmojiSize) (msgID string, err error) {
defer essentials.AddCtxTo("fbmsgr: send group like", &err)
reqParams, err := s.textMessageParams(emoji)
if err != nil {
return "", err
}
reqParams.Add("thread_fbid", groupFBID)
reqParams.Add("tags[0]", "hot_emoji_size:"+string(size))
reqParams.Add("tags[1]", "hot_emoji_source:hot_like")
return s.sendMessage(reqParams)
}
// SendReadReceipt sends a read receipt to a group chat or
// a chat with an individual user.
func (s *Session) SendReadReceipt(fbid string) (err error) {
defer essentials.AddCtxTo("fbmsgr: send read receipt", &err)
url := BaseURL + "/ajax/mercury/change_read_status.php?dpr=1"
values, err := s.commonParams()
if err != nil {
return err
}
values.Set("ids["+fbid+"]", "true")
values.Set("shouldSendReadReceipt", "true")
values.Set("watermarkTimestamp", strconv.FormatInt(time.Now().UnixNano()/1000000, 10))
values.Set("commerce_last_message_type", "non_ad")
_, err = s.jsonForPost(url, values)
return err
}
// SendTyping sends a typing notification to a user.
// For group chats, use SendGroupTyping.
func (s *Session) SendTyping(userFBID string, typing bool) (err error) {
defer essentials.AddCtxTo("fbmsgr: send typing", &err)
return s.sendTyping(userFBID, userFBID, typing)
}
// SendGroupTyping sends a typing notification to a group.
func (s *Session) SendGroupTyping(groupFBID string, typing bool) (err error) {
defer essentials.AddCtxTo("fbmsgr: send group typing", &err)
return s.sendTyping(groupFBID, "", typing)
}
// SendAttachment sends an attachment to another user.
// For group chats, use SendGroupAttachment.
func (s *Session) SendAttachment(userFBID string, a *UploadResult) (mid string, err error) {
defer essentials.AddCtxTo("fbmsgr: send attachment", &err)
reqParams, err := s.attachmentMessageParams(a)
if err != nil {
return "", err
}
reqParams.Add("other_user_fbid", userFBID)
return s.sendMessage(reqParams)
}
// SendGroupAttachment is like SendAttachment for groups.
func (s *Session) SendGroupAttachment(groupFBID string, a *UploadResult) (mid string, err error) {
defer essentials.AddCtxTo("fbmsgr: send group attachment", &err)
reqParams, err := s.attachmentMessageParams(a)
if err != nil {
return "", err
}
reqParams.Add("thread_fbid", groupFBID)
return s.sendMessage(reqParams)
}
// Upload uploads a file to be sent as an attachment.
func (s *Session) Upload(filename string, file io.Reader) (res *UploadResult, err error) {
defer essentials.AddCtxTo("fbmsgr: upload", &err)
values, err := s.commonParams()
if err != nil {
return nil, err
}
values.Set("dpr", "1")
reader, writer, err := os.Pipe()
if err != nil {
return nil, err
}
defer reader.Close()
mp := multipart.NewWriter(writer)
url := BaseURL + "/ajax/mercury/upload.php?" + values.Encode()
req, err := http.NewRequest("POST", url, reader)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", mp.FormDataContentType())
errChan := make(chan error, 1)
go func() {
var err error
defer func() {
if err != nil {
errChan <- err
}
closeErr := mp.Close()
if err == nil && closeErr != nil {
errChan <- closeErr
}
close(errChan)
writer.Close()
}()
header := textproto.MIMEHeader{}
ext := path.Ext(filename)
header.Set("Content-Disposition", "form-data; name=\"upload_1000\"; filename=\"file"+
ext+"\"")
header.Set("Content-Type", mime.TypeByExtension(ext))
sender, err := mp.CreatePart(header)
if err != nil {
return
}
_, err = io.Copy(sender, file)
}()
body, err := jsonForResp(s.Client.Do(req))
if err != nil {
return nil, err
}
if err := <-errChan; err != nil {
return nil, err
}
var msg struct {
Payload struct {
Meta []struct {
VideoID float64 `json:"video_id"`
FileID float64 `json:"file_id"`
AudioID float64 `json:"audio_id"`
ImageID float64 `json:"image_id"`
} `json:"metadata"`
} `json:"payload"`
}
if err := json.Unmarshal(body, &msg); err != nil {
return nil, err
}
if len(msg.Payload.Meta) != 1 {
return nil, errors.New("unexpected result")
}
return &UploadResult{
VideoID: floatIDToString(msg.Payload.Meta[0].VideoID),
AudioID: floatIDToString(msg.Payload.Meta[0].AudioID),
ImageID: floatIDToString(msg.Payload.Meta[0].ImageID),
FileID: floatIDToString(msg.Payload.Meta[0].FileID),
}, nil
}
func (s *Session) sendTyping(thread, to string, typ bool) error {
url := BaseURL + "/ajax/messaging/typ.php?dpr=1"
values, err := s.commonParams()
if err != nil {
return err
}
values.Set("source", "source:messenger:web")
values.Set("thread", thread)
values.Set("to", to)
if typ {
values.Set("typ", "1")
} else {
values.Set("type", "0")
}
_, err = s.jsonForPost(url, values)
return err
}
func (s *Session) textMessageParams(body string) (url.Values, error) {
reqParams, err := s.commonParams()
if err != nil {
return nil, err
}
reqParams.Add("action_type", "ma-type:user-generated-message")
reqParams.Add("body", body)
reqParams.Add("ephemeral_ttl_mode", "0")
reqParams.Add("has_attachment", "false")
msgID := s.randomMessageID()
reqParams.Add("message_id", msgID)
reqParams.Add("offline_threading_id", msgID)
reqParams.Add("source", "source:messenger:web")
timestamp := time.Now().UnixNano() / 1000000
ts := strconv.FormatInt(timestamp, 10)
reqParams.Add("timestamp", ts)
return reqParams, nil
}
func (s *Session) attachmentMessageParams(a *UploadResult) (url.Values, error) {
values, err := s.textMessageParams("")
if err != nil {
return nil, err
}
values.Del("body")
values.Set("has_attachment", "true")
if a.FileID != "" {
values.Set("file_ids[0]", a.FileID)
} else if a.AudioID != "" {
values.Set("audio_ids[0]", a.AudioID)
} else if a.ImageID != "" {
values.Set("image_ids[0]", a.ImageID)
} else if a.VideoID != "" {
values.Set("video_ids[0]", a.VideoID)
} else {
return nil, errors.New("no attachment ID")
}
return values, nil
}
func (s *Session) sendMessage(values url.Values) (mid string, err error) {
response, err := s.jsonForPost(BaseURL+"/messaging/send/?dpr=1", values)
if err != nil {
return "", err
}
var obj struct {
Payload struct {
Actions []struct {
MessageID string `json:"message_id"`
} `json:"actions"`
} `json:"payload"`
}
json.Unmarshal(response, &obj)
for _, x := range obj.Payload.Actions {
if x.MessageID != "" {
return x.MessageID, nil
}
}
return "", errors.New("no message ID in response")
}
func (s *Session) randomMessageID() string {
res := "6"
s.randLock.Lock()
for i := 1; i < 18; i++ {
res += strconv.Itoa(s.randGen.Intn(10))
}
s.randLock.Unlock()
return res
}