-
Notifications
You must be signed in to change notification settings - Fork 33
/
wallabag.go
174 lines (151 loc) · 4.42 KB
/
wallabag.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
package wallabag
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"github.com/ncarlier/readflow/pkg/config"
"github.com/ncarlier/readflow/pkg/constant"
"github.com/ncarlier/readflow/pkg/integration/webhook"
"github.com/ncarlier/readflow/pkg/model"
)
// wallabagEntry is the structure definition of a Wallabag article
type wallabagEntry struct {
Title string `json:"title,omitempty"`
URL *string `json:"url,omitempty"`
Content *string `json:"content,omitempty"`
}
// wallabagTokenResponse is the structure of a OAuth token
type wallabagTokenResponse struct {
AccessToken string `json:"access_token"`
Expires int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
TokenType string `json:"token_type"`
}
// wallabagProviderConfig is the structure definition of a Wallabag API configuration
type wallabagProviderConfig struct {
Endpoint string `json:"endpoint"`
ClientID string `json:"client_id"`
Username string `json:"username"`
}
// wallabagProvider is the structure definition of a Wallabag webhook provider
type wallabagProvider struct {
config wallabagProviderConfig
endpoint *url.URL
clientSecret string
password string
}
func newWallabagProvider(srv model.OutgoingWebhook, conf config.Config) (webhook.Provider, error) {
cfg := wallabagProviderConfig{}
if err := json.Unmarshal([]byte(srv.Config), &cfg); err != nil {
return nil, err
}
// Validate endpoint URL
endpoint, err := url.ParseRequestURI(cfg.Endpoint)
if err != nil {
return nil, err
}
// Validate secrets
clientSecret, ok := srv.Secrets["client_secret"]
if !ok {
return nil, fmt.Errorf("missing client secret")
}
password, ok := srv.Secrets["password"]
if !ok {
return nil, fmt.Errorf("missing password")
}
// Validate credentials
if cfg.ClientID == "" || cfg.Username == "" {
return nil, fmt.Errorf("wallabag: missing credentials")
}
provider := &wallabagProvider{
config: cfg,
endpoint: endpoint,
clientSecret: clientSecret,
password: password,
}
return provider, nil
}
// Send article to Wallabag endpoint.
func (wp *wallabagProvider) Send(ctx context.Context, article model.Article) (*webhook.Result, error) {
token, err := wp.getAccessToken()
if err != nil {
return nil, err
}
entry := wallabagEntry{
Title: article.Title,
URL: article.URL,
Content: article.HTML,
}
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(entry)
req, err := http.NewRequestWithContext(ctx, "POST", wp.getAPIEndpoint("/api/entries.json"), b)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", constant.ContentTypeJSON)
req.Header.Set("Authorization", "Bearer "+token.AccessToken)
client := constant.DefaultClient
if _, ok := ctx.Deadline(); ok {
client = &http.Client{}
}
resp, err := client.Do(req)
if err != nil || resp.StatusCode >= 300 {
if err == nil {
err = fmt.Errorf("bad status code: %d", resp.StatusCode)
}
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
obj := make(map[string]interface{})
if err := json.Unmarshal(body, &obj); err != nil {
return nil, nil
}
id := uint(obj["id"].(float64))
link := wp.getAPIEndpoint(fmt.Sprintf("/view/%d", id))
result := &webhook.Result{
URL: &link,
}
return result, nil
}
func (wp *wallabagProvider) getAPIEndpoint(path string) string {
baseURL := *wp.endpoint
baseURL.Path = path
return baseURL.String()
}
func (wp *wallabagProvider) getAccessToken() (*wallabagTokenResponse, error) {
values := url.Values{}
values.Add("grant_type", "password")
values.Add("client_id", wp.config.ClientID)
values.Add("client_secret", wp.clientSecret)
values.Add("username", wp.config.Username)
values.Add("password", wp.password)
res, err := http.PostForm(wp.getAPIEndpoint("/oauth/v2/token"), values)
if err != nil {
return nil, fmt.Errorf("wallabag: unable to get access token: %v", err)
}
if res.StatusCode != 200 {
return nil, fmt.Errorf("wallabag: request failed, status=%d", res.StatusCode)
}
var token wallabagTokenResponse
decoder := json.NewDecoder(res.Body)
if err := decoder.Decode(&token); err != nil {
return nil, fmt.Errorf("wallabag: unable to decode token response: %v", err)
}
return &token, nil
}
func init() {
webhook.Register("wallabag", &webhook.Def{
Name: "Wallabag",
Desc: "Send article(s) to Wallabag instance.",
Create: newWallabagProvider,
})
}