generated from padok-team/yatas-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNotionClientV3.go
213 lines (184 loc) · 5.31 KB
/
NotionClientV3.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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
kjk "github.com/kjk/notionapi"
)
const (
notionHost = "https://www.notion.so"
userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.3"
acceptLang = "en-GB,en-US;q=0.9,en;q=0.8"
)
type NotionClientV3 struct {
AuthToken string
HTTPClient *http.Client
MinRequestDelay time.Duration
lastRequestTime time.Time
httpPostOverride func(uri string, body []byte) ([]byte, error)
SpaceID string
KjkClient *kjk.Client
}
func NewClientV3(clientToken, pageID string) *NotionClientV3 {
// Create client with token
client := &NotionClientV3{
AuthToken: clientToken,
}
// Create kjk/notionapi client from token
kjkClient := &kjk.Client{
AuthToken: clientToken,
}
client.KjkClient = kjkClient
// Get Client workspace for the NotionClientV3
page, err := client.KjkClient.DownloadPage(pageID)
if err != nil {
log.Printf("Error while triing to get spaceId: %v", err)
} else {
client.SpaceID = page.Root().SpaceID
}
return client
}
func (c *NotionClientV3) getHTTPClient() *http.Client {
if c.HTTPClient != nil {
return c.HTTPClient
}
httpNotionClientV3 := *http.DefaultClient
httpNotionClientV3.Timeout = time.Second * 30
return &httpNotionClientV3
}
func (c *NotionClientV3) doPost(uri string, body []byte) ([]byte, error) {
if c.httpPostOverride != nil {
return c.httpPostOverride(uri, body)
}
return c.doPostInternal(uri, body)
}
func (c *NotionClientV3) doPostInternal(uri string, body []byte) ([]byte, error) {
nRepeats := 0
timeouts := []time.Duration{time.Second * 3, time.Second * 5, time.Second * 10}
repeatRequest:
br := bytes.NewBuffer(body)
req, err := http.NewRequest("POST", uri, br)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Accept-Language", acceptLang)
if c.AuthToken != "" {
req.Header.Set("cookie", fmt.Sprintf("token_v2=%v", c.AuthToken))
}
var rsp *http.Response
httpNotionClientV3 := c.getHTTPClient()
rsp, err = httpNotionClientV3.Do(req)
if err != nil {
log.Printf("httpNotionClientV3.Do() failed with %s\n", err)
return nil, err
}
if rsp.StatusCode == http.StatusTooManyRequests {
if nRepeats < 3 {
log.Printf("retrying '%s' because httpNotionClientV3.Do() returned %d (%s)\n", uri, rsp.StatusCode, rsp.Status)
time.Sleep(timeouts[nRepeats])
nRepeats++
goto repeatRequest
}
}
if rsp.StatusCode != 200 {
d, _ := ioutil.ReadAll(rsp.Body)
log.Printf("Error: status code %s\nBody:\n%s\n", rsp.Status, PrettyPrintJS(d))
return nil, fmt.Errorf("http.Post('%s') returned non-200 status code of %d", uri, rsp.StatusCode)
}
d, err := ioutil.ReadAll(rsp.Body)
if err != nil {
log.Printf("Error: ioutil.ReadAll() failed with %s\n", err)
return nil, err
}
return d, nil
}
func (c *NotionClientV3) doNotionAPI(apiURL string, requestData interface{}, result interface{}, rawJSON *map[string]interface{}) error {
var body []byte
var err error
if requestData != nil {
body, err = jsonit.MarshalIndent(requestData, "", " ")
if err != nil {
return err
}
}
uri := notionHost + apiURL
d, err := c.doPost(uri, body)
if err != nil {
return err
}
err = jsonit.Unmarshal(d, result)
if err != nil {
log.Printf("Error: json.Unmarshal() failed with %s\n. Body:\n%s\n", err, string(d))
return err
}
if rawJSON != nil {
err = jsonit.Unmarshal(d, rawJSON)
}
return err
}
func (client *NotionClientV3) saveTransactions(req UpdateRequest) (*UpdateResponse, error) {
var rsp UpdateResponse
var err error
apiURL := "/api/v3/saveTransactions"
if err = client.doNotionAPI(apiURL, req, &rsp, &rsp.RawJSON); err != nil {
return nil, err
}
return &rsp, nil
}
func (client *NotionClientV3) GetTableViewType(databaseID string) (string, string, bool) {
kjkClient := client.KjkClient
page, err := kjkClient.DownloadPage(databaseID)
if err != nil {
log.Printf("Error while getting Database TableView: %v", err)
} else {
if len(page.TableViews) > 0 {
collectionView := page.TableViews[0].CollectionView
return collectionView.ID, collectionView.Type, true
}
}
return "", "", false
}
func (client *NotionClientV3) GetTableViewProperties(databaseID string) []string {
kjkClient := client.KjkClient
page, err := kjkClient.DownloadPage(databaseID)
var properties []string
if err != nil {
log.Printf("Error while getting Database TableView: %v", err)
} else {
if len(page.TableViews) > 0 {
for key := range page.TableViews[0].Collection.Schema {
properties = append(properties, key)
}
}
}
return properties
}
func (client *NotionClientV3) UpdateTableViewList(viewID, desiredType string) error {
req := TableViewTypeUpdateRequest(client.SpaceID, viewID, desiredType)
_, err := client.saveTransactions(req)
if err != nil {
return err
}
return nil
}
func (client *NotionClientV3) LockPage(pageID string) error {
req := LockPageUpdateRequest(client.SpaceID, pageID)
_, err := client.saveTransactions(req)
if err != nil {
return err
}
return nil
}
func (client *NotionClientV3) ShowProperties(viewID string, properties []string) error {
req := ShowPropertiesUpdateRequest(client.SpaceID, viewID, properties)
_, err := client.saveTransactions(req)
if err != nil {
return err
}
return nil
}