/
tistory.go
681 lines (579 loc) · 18.1 KB
/
tistory.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
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
// Package tistory implements a Tistory API Client.
//
// Tistory API Reference: https://tistory.github.io/document-tistory-apis/apis/
package tistory
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/chromedp/chromedp"
"github.com/pkg/errors"
)
const (
loginURL = `https://www.tistory.com/auth/login`
loginKakaoButtonXPath = `//*[@id="cMain"]/div/div/div/a[2]`
loginKaKaoIdXPath = `//*[@id="loginId--1"]`
loginKakaoPwXPath = `//*[@id="password--2"]`
submitKaKaoButtonXPath = `//*[@id="mainContent"]/div/div/form/div[4]/button[1]`
loginTistoryButtonXPath = `//*[@id="cMain"]/div/div/div/a[3]`
loginTistoryIdXPath = `//*[@id="loginId"]`
loginTistoryPwXPath = `//*[@id="loginPw"]`
submitTistoryButtonXPath = `//*[@id="authForm"]/fieldset/button`
authButtonXPath = `//*[@id="contents"]/div[4]/button[1]`
loginAfterURL = `https://www.tistory.com/`
output = `json`
)
type Tistory struct {
BlogURL string
BlogName string
ClientId string
ClientSecret string
AccessToken string
AuthenticationURL string
RedirectAuthURL string
AuthenticationCode string
}
func NewTistory(blogURL, clientId, clientSecret string) (*Tistory, error) {
if blogURL == "" || clientId == "" || clientSecret == "" {
return nil, errors.New("blogURL or clientId or clientSecret is empty")
}
if len(strings.Split(blogURL, "//")) < 2 {
return nil, errors.New("blogURL is invalid")
}
if !strings.HasPrefix(blogURL, "https://") {
return nil, errors.New("blogURL is invalid")
}
return &Tistory{
BlogURL: blogURL,
BlogName: strings.Split(strings.Split(blogURL, "//")[1], ".")[0],
ClientId: clientId,
ClientSecret: clientSecret,
AuthenticationURL: fmt.Sprintf(
"https://www.tistory.com/oauth/authorize?client_id=%s&redirect_uri=%s&response_type=code", clientId, blogURL),
}, nil
}
/*
Login & Get AuthorizationCode
https://tistory.github.io/document-tistory-apis/auth/authorization_code.html
*/
func (t *Tistory) GetAuthorizationCode(id, password string) (string, error) {
if id == "" || password == "" {
return "", errors.New("id or password is empty")
}
/*
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.Flag("headless", false),
chromedp.Flag("disable-gpu", true),
chromedp.Flag("no-sandbox", true),
chromedp.Flag("disable-dev-shm-usage", true),
)
allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
defer cancel()
*/
// Create chrome instance
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
// Navigate to tistory login page
if err := chromedp.Run(ctx,
chromedp.Navigate(loginURL),
); err != nil {
return "", errors.Wrap(err, "Failed to Navigate to tistory login page")
}
var confirmURL string
// KAKAO_ID, KAKAO_PASSWORD
if err := chromedp.Run(ctx,
chromedp.Click(loginKakaoButtonXPath), // class="btn_login link_tistory_id"
chromedp.Sleep(1*time.Second),
chromedp.SendKeys(loginKaKaoIdXPath, id),
chromedp.SendKeys(loginKakaoPwXPath, password),
chromedp.Sleep(1*time.Second),
chromedp.Click(submitKaKaoButtonXPath), // class="btn_g highlight submit"
chromedp.Sleep(2*time.Second),
chromedp.Location(&confirmURL),
); err != nil {
return "", errors.Wrap(err, "Failed to Login with KAKAO_ID, KAKAO_PASSWORD")
}
if confirmURL != loginAfterURL {
return "", errors.New("Failed to Login")
}
// Get AuthenticationCode
if err := chromedp.Run(ctx,
chromedp.Navigate(t.AuthenticationURL),
chromedp.Sleep(1*time.Second),
chromedp.Click(authButtonXPath),
chromedp.Sleep(1*time.Second),
chromedp.Location(&t.RedirectAuthURL),
); err != nil {
return "", errors.Wrap(err, "Failed to GetAuthenticationCode")
}
if t.RedirectAuthURL == "" {
return "", errors.New("Failed to RedirectAuthURL")
}
// http://client.redirect.uri?code=authorizationCode&state=someValue
if len(strings.Split(t.RedirectAuthURL, "code=")) < 2 {
return "", errors.New("Failed to GetAuthenticationCode")
}
t.AuthenticationCode = strings.Split(t.RedirectAuthURL, "code=")[1]
if len(strings.Split(t.AuthenticationCode, "&state")) < 2 {
return "", errors.New("Failed to GetAuthenticationCode")
}
t.AuthenticationCode = strings.Split(t.AuthenticationCode, "&state")[0]
return t.AuthenticationCode, nil
}
/*
GetAccessToken
https://tistory.github.io/document-tistory-apis/auth/authorization_code.html
*/
func (t *Tistory) GetAccessToken() (string, error) {
params := url.Values{
"client_id": {t.ClientId},
"client_secret": {t.ClientSecret},
"redirect_uri": {t.BlogURL},
"code": {t.AuthenticationCode},
"grant_type": {"authorization_code"},
}
accessTokenURL := fmt.Sprintf(
"https://www.tistory.com/oauth/access_token?%s", params.Encode())
resp, err := http.Get(accessTokenURL)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
respBytes, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
bodyString := string(respBytes)
if len(strings.Split(bodyString, "=")) < 2 {
return "", errors.New(
"Failed to GetAccessToken from bodyString (len(strings.Split(bodyString, \"=\")) < 2)")
}
if !strings.HasPrefix(bodyString, "access_token") {
return "", errors.New(
"Failed to GetAccessToken from bodyString (strings.Contains(bodyString, \"access_token\")")
}
t.AccessToken = strings.Split(bodyString, "=")[1]
return t.AccessToken, nil
}
/*
GetBlogInfo 블로그 정보
access_token: 발급받은 access_token
output: 출력방식
https://tistory.github.io/document-tistory-apis/apis/v1/blog/list.html
*/
func (t *Tistory) GetBlogInfo() (map[string]interface{}, error) {
t.AccessToken = "ce196a9e476dd617519f2074286aa5c9_6a5d731ffc6022608f75393a7ea87cf4"
params := url.Values{
"access_token": {t.AccessToken},
"output": {output},
}
blogInfoURL := fmt.Sprintf(
"https://www.tistory.com/apis/blog/info?%s", params.Encode())
resp, err := http.Get(blogInfoURL)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New(
fmt.Sprintf("Failed to GetBlogInfo (resp.StatusCode: %d)", resp.StatusCode))
}
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
return result, nil
}
/*
GetPostList 글 목록
blogName: Blog Name (필수)
page: 불러올 페이지 번호
https://tistory.github.io/document-tistory-apis/apis/v1/post/list.html
*/
func (t *Tistory) GetPostList(pageNumber int) (map[string]interface{}, error) {
params := url.Values{
"access_token": {t.AccessToken},
"output": {output},
"blogName": {t.BlogName},
"page": {fmt.Sprintf("%d", pageNumber)},
}
postListURL := fmt.Sprintf(
"https://www.tistory.com/apis/post/list?%s", params.Encode())
resp, err := http.Get(postListURL)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New(
fmt.Sprintf("Failed to GetPostList (resp.StatusCode: %d)", resp.StatusCode))
}
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
return result, nil
}
/*
GetPost 글 읽기
blogName: Blog Name (필수)
postId: 글 번호 (필수)
https://tistory.github.io/document-tistory-apis/apis/v1/post/read.html
*/
func (t *Tistory) GetPost(postId int) (map[string]interface{}, error) {
params := url.Values{
"access_token": {t.AccessToken},
"output": {output},
"blogName": {t.BlogName},
"postId": {fmt.Sprintf("%d", postId)}}
postURL := fmt.Sprintf(
"https://www.tistory.com/apis/post/read?%s", params.Encode())
resp, err := http.Get(postURL)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New(
fmt.Sprintf("Failed to GetPost (resp.StatusCode: %d)", resp.StatusCode))
}
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
return result, nil
}
/*
WritePost 글 작성
blogName: Blog Name (필수)
title: 글 제목 (필수)
content: 글 내용
visibility: 발행상태 (0: 비공개 - 기본값, 1: 보호, 3: 발행)
category: 카테고리 아이디 (기본값: 0)
published: 발행시간 (TIMESTAMP 이며 미래의 시간을 넣을 경우 예약. 기본값: 현재시간)
slogan: 문자 주소
tag: 태그 (',' 로 구분)
acceptComment: 댓글 허용 (0, 1 - 기본값)
password: 보호글 비밀번호
https://tistory.github.io/document-tistory-apis/apis/v1/post/write.html
*/
func (t *Tistory) WritePost(option map[string]interface{}) (map[string]interface{}, error) {
params := url.Values{
"access_token": {t.AccessToken},
"output": {output},
"blogName": {t.BlogName},
}
for key, value := range option {
params.Add(key, fmt.Sprintf("%v", value))
}
writePostURL := "https://www.tistory.com/apis/post/write?"
resp, err := http.PostForm(writePostURL, params)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New(
fmt.Sprintf("Failed to WritePost (resp.StatusCode: %d)", resp.StatusCode))
}
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
return result, nil
}
/*
ModifyPost 글 수정
blogName: Blog Name (필수)
postId: 글 번호 (필수)
title: 글 제목 (필수)
content: 글 내용
visibility: 발행상태 (0: 비공개 - 기본값, 1: 보호, 3: 발행)
category: 카테고리 아이디 (기본값: 0)
published: 발행시간 (TIMESTAMP 이며 미래의 시간을 넣을 경우 예약. 기본값: 현재시간)
slogan: 문자 주소
tag: 태그 (',' 로 구분)
acceptComment: 댓글 허용 (0, 1 - 기본값)
password: 보호글 비밀번호
https://tistory.github.io/document-tistory-apis/apis/v1/post/modify.html
*/
func (t *Tistory) ModifyPost(option map[string]interface{}) (map[string]interface{}, error) {
params := url.Values{
"access_token": {t.AccessToken},
"output": {output},
"blogName": {t.BlogName},
}
for key, value := range option {
params.Add(key, fmt.Sprintf("%v", value))
}
modifyPostURL := "https://www.tistory.com/apis/post/modify?"
resp, err := http.PostForm(modifyPostURL, params)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New(
fmt.Sprintf("Failed to ModifyPost (resp.StatusCode: %d)", resp.StatusCode))
}
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
return result, nil
}
/*
AttachPost 파일 첨부
blogName: Blog Name
uploadedfile: 업로드할 파일 (multipart/form-data)
https://tistory.github.io/document-tistory-apis/apis/v1/post/attach.html
*/
func (t *Tistory) AttachPost(filePath string) (map[string]interface{}, error) {
params := url.Values{
"access_token": {t.AccessToken},
"output": {output},
"blogName": {t.BlogName},
}
file, err := os.Open(filePath)
if err != nil {
return nil, errors.Wrap(err, "Failed os open")
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("uploadedfile", file.Name())
if err != nil {
return nil, errors.Wrap(err, "Failed create form file")
}
_, err = io.Copy(part, file)
if err != nil {
return nil, errors.Wrap(err, "Failed io copy")
}
// Close the multipart writer
err = writer.Close()
if err != nil {
return nil, errors.Wrap(err, "Failed writer close")
}
contentType := writer.FormDataContentType()
content := bytes.NewReader(body.Bytes())
attachPostURL := fmt.Sprintf(
"https://www.tistory.com/apis/post/attach?%s", params.Encode())
resp, err := http.Post(attachPostURL, contentType, content)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, errors.New(
fmt.Sprintf("Failed to AttachPost (resp.StatusCode: %d, body: %s)", resp.StatusCode, string(body)))
}
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
return result, nil
}
/*
CategoryList 카테고리 목록
id: 카테고리 ID
name: 카테고리 이름
parent: 부모 카테고리 ID
label: 부모 카테고리를 포함한 전체 이름 ('/'로 구분)
entries: 카테고리내 글 수
*/
func (t *Tistory) CategoryList() (map[string]interface{}, error) {
params := url.Values{
"access_token": {t.AccessToken},
"output": {output},
"blogName": {t.BlogName},
}
categoryListURL := fmt.Sprintf(
"https://www.tistory.com/apis/category/list?%s", params.Encode())
resp, err := http.Get(categoryListURL)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New(
fmt.Sprintf("Failed to CategoryList (resp.StatusCode: %d)", resp.StatusCode))
}
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
return result, nil
}
/*
GetComment 최신 댓글 목록 가져오기
blogName: Blog Name
page: 가져올 페이지 (기본값: 1)
count: 페이지당 댓글 수 (기본값: 10, 최대값: 10)
https://tistory.github.io/document-tistory-apis/apis/v1/comment/recent.html
*/
func (t *Tistory) GetRecentCommentList(page, count int) (map[string]interface{}, error) {
params := url.Values{
"access_token": {t.AccessToken},
"output": {output},
"blogName": {t.BlogName},
"page": {fmt.Sprintf("%d", page)},
"count": {fmt.Sprintf("%d", count)},
}
getNewCommentListURL := fmt.Sprintf(
"https://www.tistory.com/apis/comment/newest?%s", params.Encode())
resp, err := http.Get(getNewCommentListURL)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New(
fmt.Sprintf("Failed to GetNewCommentList (resp.StatusCode: %d)", resp.StatusCode))
}
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
return result, nil
}
/*
GetCommentList 댓글 목록 가져오기
blogName: Blog Name
postId: 글 번호 (ID)
https://tistory.github.io/document-tistory-apis/apis/v1/comment/list.html
*/
func (t *Tistory) GetCommentList(postId int) (map[string]interface{}, error) {
params := url.Values{
"access_token": {t.AccessToken},
"output": {output},
"blogName": {t.BlogName},
"postId": {fmt.Sprintf("%d", postId)},
}
getCommentListURL := fmt.Sprintf(
"https://www.tistory.com/apis/comment/list?%s", params.Encode())
resp, err := http.Get(getCommentListURL)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New(
fmt.Sprintf("Failed to GetCommentList (resp.StatusCode: %d)", resp.StatusCode))
}
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
return result, nil
}
/*
WriteComment 댓글 작성
blogName: Blog Name (필수)
postId: 글 ID (필수)
parentId: 부모 댓글 ID (대댓글인 경우 사용)
content: 댓글 내용
secret: 비밀 댓글 여부 (1: 비밀댓글, 0: 공개댓글 - 기본 값)
https://tistory.github.io/document-tistory-apis/apis/v1/comment/write.html
*/
func (t *Tistory) WriteComment(option map[string]interface{}) (map[string]interface{}, error) {
params := url.Values{
"access_token": {t.AccessToken},
"output": {output},
"blogName": {t.BlogName},
}
for key, value := range option {
params.Add(key, fmt.Sprintf("%v", value))
}
writeCommentURL := "https://www.tistory.com/apis/comment/write?"
resp, err := http.PostForm(writeCommentURL, params)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New(
fmt.Sprintf("Failed to WriteComment (resp.StatusCode: %d)", resp.StatusCode))
}
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
return result, nil
}
/*
ModifyComment 댓글 수정
blogName: Blog Name (필수)
postId: 글 ID (필수)
commentId: 댓글 ID (필수)
parentId: 부모 댓글 ID (대댓글인 경우 사용)
content: 댓글 내용
secret: 비밀 댓글 여부 (1: 비밀댓글, 0: 공개댓글 - 기본 값)
https://tistory.github.io/document-tistory-apis/apis/v1/comment/modify.html
*/
func (t *Tistory) ModifyComment(option map[string]interface{}) (map[string]interface{}, error) {
params := url.Values{
"access_token": {t.AccessToken},
"output": {output},
"blogName": {t.BlogName},
}
for key, value := range option {
params.Add(key, fmt.Sprintf("%v", value))
}
modifyCommentURL := "https://www.tistory.com/apis/comment/modify?"
resp, err := http.PostForm(modifyCommentURL, params)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New(
fmt.Sprintf("Failed to ModifyComment (resp.StatusCode: %d)", resp.StatusCode))
}
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
return result, nil
}
/*
DeleteComment 댓글 삭제
blogName: Blog Name (필수)
postId: 글 ID (필수)
commentId: 댓글 ID (필수)
https://tistory.github.io/document-tistory-apis/apis/v1/comment/delete.html
*/
func (t *Tistory) DeleteComment(option map[string]interface{}) (map[string]interface{}, error) {
params := url.Values{
"access_token": {t.AccessToken},
"output": {output},
"blogName": {t.BlogName},
}
for key, value := range option {
params.Add(key, fmt.Sprintf("%v", value))
}
deleteCommentURL := "https://www.tistory.com/apis/comment/delete?"
resp, err := http.PostForm(deleteCommentURL, params)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New(
fmt.Sprintf("Failed to DeleteComment (resp.StatusCode: %d)", resp.StatusCode))
}
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
return result, nil
}