-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmethods.go
432 lines (370 loc) · 10.6 KB
/
methods.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
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
package telegraph
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
"golang.org/x/net/html"
)
////////////////
// methods
// CreateAccount creates a new Telegraph account.
//
// shortName: 1-32 characters
// authorName: 0-128 characters (optional)
// authorURL: 0-512 characters (optional)
//
// http://telegra.ph/api#createAccount
func (c *Client) CreateAccount(shortName, authorName, authorURL string) (acc Account, err error) {
url := fmt.Sprintf("%s/%s", apiBaseURL, "createAccount")
// params
params := map[string]any{
"short_name": shortName,
}
if len(authorName) > 0 { // optional
params["author_name"] = authorName
}
if len(authorURL) > 0 { // optional
params["author_url"] = authorURL
}
return request[Account](url, params)
}
// EditAccountInfo updates information about a Telegraph account.
//
// shortName: 1-32 characters
// authorName: 0-128 characters (optional)
// authorURL: 0-512 characters (optional)
//
// http://telegra.ph/api#editAccountInfo
func (c *Client) EditAccountInfo(shortName, authorName, authorURL string) (acc Account, err error) {
url := fmt.Sprintf("%s/%s", apiBaseURL, "editAccountInfo")
// params
params := map[string]any{
"access_token": c.AccessToken,
"short_name": shortName,
}
if len(authorName) > 0 { // optional
params["author_name"] = authorName
}
if len(authorURL) > 0 { // optional
params["author_url"] = authorURL
}
return request[Account](url, params)
}
// GetAccountInfo fetches information about a Telegraph account.
//
// fields: Available fields: "short_name", "author_name", "author_url", "auth_url", and "page_count"
// (default = ["short_name", "author_name", "author_url"])
//
// http://telegra.ph/api#getAccountInfo
func (c *Client) GetAccountInfo(fields []string) (acc Account, err error) {
url := fmt.Sprintf("%s/%s", apiBaseURL, "getAccountInfo")
// params
params := map[string]any{
"access_token": c.AccessToken,
}
if len(fields) > 0 { // optional
params["fields"] = fields
} else {
params["fields"] = []string{"short_name", "author_name", "author_url"} // default
}
return request[Account](url, params)
}
// RevokeAccessToken revokes access token and generate a new one.
//
// http://telegra.ph/api#revokeAccessToken
func (c *Client) RevokeAccessToken() (acc Account, err error) {
url := fmt.Sprintf("%s/%s", apiBaseURL, "revokeAccessToken")
// params
params := map[string]any{
"access_token": c.AccessToken,
}
return request[Account](url, params)
}
// CreatePage creates a new Telegraph page.
//
// title: 1-256 characters
// authorName: 0-128 characters (optional)
// authorURL: 0-512 characters (optional)
// content: Array of Node
// returnContent: return created Page object or not
//
// http://telegra.ph/api#createPage
func (c *Client) CreatePage(title, authorName, authorURL string, content []Node, returnContent bool) (page Page, err error) {
url := fmt.Sprintf("%s/%s", apiBaseURL, "createPage")
// params
params := map[string]any{
"access_token": c.AccessToken,
"title": title,
"content": castNodes(content),
}
if len(authorName) > 0 { // optional
params["author_name"] = authorName
}
if len(authorURL) > 0 { // optional
params["author_url"] = authorURL
}
if returnContent { // optional
params["return_content"] = returnContent
}
return request[Page](url, params)
}
// CreatePageWithHTML creates a new page with HTML.
func (c *Client) CreatePageWithHTML(title, authorName, authorURL, htmlContent string, returnContent bool) (page Page, err error) {
nodes, err := NewNodesWithHTML(htmlContent)
if err == nil {
return c.CreatePage(title, authorName, authorURL, nodes, returnContent)
}
return Page{}, err
}
// EditPage edits an existing Telegraph page.
//
// path: Path to the page
// title: 1-256 characters
// content: Array of Node
// authorName: 0-128 characters (optional)
// authorURL: 0-512 characters (optional)
// returnContent: return edited Page object or not
//
// http://telegra.ph/api#editPage
func (c *Client) EditPage(path, title string, content []Node, authorName, authorURL string, returnContent bool) (page Page, err error) {
url := fmt.Sprintf("%s/%s/%s", apiBaseURL, "editPage", path)
// params
params := map[string]any{
"access_token": c.AccessToken,
"title": title,
"content": castNodes(content),
}
if len(authorName) > 0 { // optional
params["author_name"] = authorName
}
if len(authorURL) > 0 { // optional
params["author_url"] = authorURL
}
if returnContent { // optional
params["return_content"] = returnContent
}
return request[Page](url, params)
}
// GetPage fetches a Telegraph page.
//
// path: Path to the Telegraph page
// returnContent: return the Page object or not
//
// http://telegra.ph/api#getPage
func (c *Client) GetPage(path string, returnContent bool) (page Page, err error) {
url := fmt.Sprintf("%s/%s/%s", apiBaseURL, "getPage", path)
// params
params := map[string]any{
"return_content": returnContent,
}
return request[Page](url, params)
}
// GetPageList fetches a list of pages belonging to a Telegraph account.
//
// offset: Sequential number of the first page (default = 0)
// limit: Number of pages to be returned (0-200, default = 50)
//
// http://telegra.ph/api#getPageList
func (c *Client) GetPageList(offset, limit int) (list PageList, err error) {
url := fmt.Sprintf("%s/%s", apiBaseURL, "getPageList")
// params
params := map[string]any{
"access_token": c.AccessToken,
}
if offset > 0 { // optional
params["offset"] = offset
}
if limit >= 0 { // optional
params["limit"] = limit
}
return request[PageList](url, params)
}
// GetViews fetches the number of views for a Telegraph page.
//
// path: Path to the Telegraph page
// year: 2000-2100 (required when 'month' is passed)
// month: 1-12 (required when 'day' is passed)
// day: 1-31 (required when 'hour' is passed)
// hour: 0-24 (pass -1 if none)
//
// http://telegra.ph/api#getViews
func (c *Client) GetViews(path string, year, month, day, hour int) (views PageViews, err error) {
url := fmt.Sprintf("%s/%s/%s", apiBaseURL, "getViews", path)
// params
params := map[string]any{}
if year > 0 { // optional
params["year"] = year
}
if month > 0 { // optional
params["month"] = month
}
if day > 0 { // optional
params["day"] = day
}
if hour >= 0 { // optional
params["hour"] = hour
}
return request[PageViews](url, params)
}
// NewNodeWithString creates a new node with given string.
func NewNodeWithString(str string) Node {
return Node(str)
}
// NewNodeWithElement creates a new node with given element.
func NewNodeWithElement(tag string, attrs map[string]string, children []Node) Node {
return Node(NodeElement{
Tag: tag,
Attrs: attrs,
Children: children,
})
}
// NewNodesWithHTML creates new nodes with given HTML string.
func NewNodesWithHTML(html string) ([]Node, error) {
doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
if err == nil {
return traverseNodes(doc.Find("body").Contents()), nil
}
return nil, err
}
// traverse DOM for creating new nodes
func traverseNodes(selections *goquery.Selection) []Node {
nodes := []Node{}
var tag string
var attrs map[string]string
var element NodeElement
selections.Each(func(_ int, child *goquery.Selection) {
for _, node := range child.Nodes {
switch node.Type {
case html.TextNode:
nodes = append(nodes, node.Data) // append text
case html.ElementNode:
// attributes
attrs = map[string]string{}
for _, attr := range node.Attr {
attrs[attr.Key] = attr.Val
}
// new node element
if len(node.Namespace) > 0 {
tag = fmt.Sprintf("%s.%s", node.Namespace, node.Data)
} else {
tag = node.Data
}
element = NodeElement{
Tag: tag,
Attrs: attrs,
Children: traverseNodes(child.Contents()),
}
nodes = append(nodes, element) // append element
default:
continue // skip other things
}
}
})
return nodes
}
// send HTTP POST request (www-form urlencoded)
func httpPost(apiURL string, params map[string]any) (jsonBytes []byte, err error) {
v("sending post request to url: %s, params: %#v", apiURL, params)
var js []byte
paramValues := url.Values{}
for key, value := range params {
if v, ok := value.(string); ok {
paramValues[key] = []string{v}
} else {
if js, err = json.Marshal(value); err == nil {
paramValues[key] = []string{string(js)}
} else {
l("param marshalling error for: %s (%s)", key, err)
return []byte{}, err
}
}
}
encoded := paramValues.Encode()
var req *http.Request
if req, err = http.NewRequest("POST", apiURL, bytes.NewBufferString(encoded)); err == nil {
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(encoded)))
var res *http.Response
client := &http.Client{
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 300 * time.Second,
}).Dial,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}
res, err = client.Do(req)
if res != nil {
defer res.Body.Close()
}
if err == nil {
if jsonBytes, err = io.ReadAll(res.Body); err == nil {
return jsonBytes, nil
}
l("resonse read error: %s", err.Error())
} else {
l("request error: %s", err.Error())
}
} else {
l("building request error: %s", err.Error())
}
return []byte{}, err
}
// cast nodes for marshalling
func castNodes(nodes []Node) []any {
castNodes := []any{}
for _, node := range nodes {
switch node.(type) {
case NodeElement:
castNodes = append(castNodes, node)
default:
if cast, ok := node.(string); ok {
castNodes = append(castNodes, cast)
} else {
l("param casting error: %#+v", node)
}
}
}
return castNodes
}
// for logging
func l(format string, v ...any) {
log.Printf(format, v...)
}
// for logging verbosely
func v(format string, v ...any) {
if Verbose {
l(format, v...)
}
}
// send HTTP request for APIResponse[T] and fetch its result.
func request[T any](url string, params map[string]any) (result T, err error) {
var bytes []byte
if bytes, err = httpPost(url, params); err == nil {
var res APIResponse[T]
if err = json.Unmarshal(bytes, &res); err == nil {
if res.Ok {
return res.Result, nil
} else {
return result /* = empty */, fmt.Errorf("erroneous response: %s", res.Error)
}
}
err = fmt.Errorf("json parse error: %s (%s)", err, string(bytes))
} else {
err = fmt.Errorf("request to '%s' failed with error: %s", url, err)
}
return result /* = empty */, err
}