-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathutil.go
204 lines (186 loc) · 4.93 KB
/
util.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
package fbmsgr
import (
"context"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"golang.org/x/net/html"
)
const dtsgTimeout = time.Hour * 8
// fetchDTSG fetches a usable value for the fb_dtsg field
// present in many AJAX requests.
//
// The value is cached, so this may not block.
func (s *Session) fetchDTSG() (string, error) {
s.fbDTSGLock.Lock()
defer s.fbDTSGLock.Unlock()
if s.fbDTSG != "" {
if time.Since(s.fbDTSGTime) > dtsgTimeout {
s.fbDTSG = ""
} else {
return s.fbDTSG, nil
}
}
homepage, err := s.Client.Get(BaseURL)
if homepage != nil {
defer homepage.Body.Close()
}
if err != nil {
return "", errors.New("fetch dtsg: " + err.Error())
}
parsed, err := html.Parse(homepage.Body)
if err != nil {
return "", errors.New("fetch dtsg: " + err.Error())
}
const fieldName = `DTSGInitialData",\[\],{"token`
keyVal, err := findJSField(parsed, fieldName)
if err != nil {
return "", errors.New("fetch dtsg: " + err.Error())
}
s.fbDTSG = keyVal
s.fbDTSGTime = time.Now()
return s.fbDTSG, nil
}
// commonParams generates a set of parameters which are
// passed to most observed JSON endpoints.
func (s *Session) commonParams() (url.Values, error) {
dtsg, err := s.fetchDTSG()
if err != nil {
return nil, err
}
reqParams := url.Values{}
reqParams.Add("__a", "1")
reqParams.Add("__af", "o")
reqParams.Add("__be", "-1")
reqParams.Add("__pc", "EXP1:messengerdotcom_pkg")
reqParams.Add("__req", "14")
reqParams.Add("__rev", "2643465")
reqParams.Add("__srp_t", "1477432416")
reqParams.Add("__user", s.userID)
reqParams.Add("client", "mercury")
reqParams.Add("fb_dtsg", dtsg)
return reqParams, nil
}
// graphQLDoc runs a GraphQL query with a "doc_id".
//
// If the query is successful, the resulting data is
// unmarshalled into dataOut.
func (s *Session) graphQLDoc(docID string, params map[string]interface{},
dataOut interface{}) error {
reqParams, err := s.commonParams()
if err != nil {
return err
}
reqObj := map[string]interface{}{"doc_id": docID, "query_params": params}
reqJSON, err := json.Marshal(map[string]interface{}{"o0": reqObj})
if err != nil {
return err
}
reqParams.Add("queries", string(reqJSON))
resp, err := s.Client.PostForm(BaseURL+"/api/graphqlbatch", reqParams)
if err != nil {
return err
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
var respObj struct {
Object struct {
Data interface{} `json:"data"`
Errors []struct {
Message string `json:"message"`
} `json:"errors"`
} `json:"o0"`
Error struct {
Message string `json:"description"`
} `json:"error"`
}
respObj.Object.Data = dataOut
if err := decoder.Decode(&respObj); err != nil {
return err
}
if len(respObj.Object.Errors) > 0 {
return errors.New("GraphQL error: " + respObj.Object.Errors[0].Message)
} else if respObj.Error.Message != "" {
return errors.New("GraphQL error: " + respObj.Error.Message)
}
return nil
}
// jsonForPost posts the form and returns the raw JSON
// from the response.
func (s *Session) jsonForPost(url string, params url.Values) ([]byte, error) {
return jsonForResp(s.Client.PostForm(url, params))
}
// jsonForGet runs a get and returns the raw JSON.
func (s *Session) jsonForGet(url string) ([]byte, error) {
return jsonForResp(s.Client.Get(url))
}
// jsonForGetContext is like jsonForGet but with an added
// request context.
func (s *Session) jsonForGetContext(ctx context.Context, url string) ([]byte, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
return jsonForResp(s.Client.Do(req))
}
// jsonForResp returns the json for the response.
func jsonForResp(resp *http.Response, err error) ([]byte, error) {
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if len(body) < 9 {
return nil, errors.New("jsonForResp: response too short")
}
return body[9:], nil
}
// putJSONIntoObject turns source into JSON, then
// unmarshals it back into the destination.
func putJSONIntoObject(source, dest interface{}) error {
encoded, err := json.Marshal(source)
if err != nil {
return err
}
return json.Unmarshal(encoded, &dest)
}
// stripFBIDPrefix turns strings like "fbid:12" into "12".
// If the string does not start with "fbid:", no change is
// performed.
func stripFBIDPrefix(s string) string {
if strings.HasPrefix(s, "fbid:") {
return s[5:]
}
return s
}
// floatIDToString converts a floating point to an integer
// string.
// If id is 0, it returns "" for convenience.
func floatIDToString(id float64) string {
if id == 0 {
return ""
}
return strconv.FormatInt(int64(id), 10)
}
// canonicalFBID converts a float64 or a string into a
// textual FBID with no prefix.
func canonicalFBID(val interface{}) string {
switch val := val.(type) {
case string:
return stripFBIDPrefix(val)
case float64:
return floatIDToString(val)
}
return ""
}