/
handler.go
251 lines (205 loc) · 6.1 KB
/
handler.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
package ttrss
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strconv"
"time"
"github.com/pkg/errors"
"github.com/urandom/readeef"
"github.com/urandom/readeef/content"
"github.com/urandom/readeef/content/processor"
"github.com/urandom/readeef/content/repo"
"github.com/urandom/readeef/content/search"
"github.com/urandom/readeef/log"
)
type request struct {
Op string `json:"op"`
Sid string `json:"sid"`
Seq int `json:"seq"`
User string `json:"user"`
Password string `json:"password"`
OutputMode string `json:"output_mode"`
UnreadOnly bool `json:"unread_only"`
IncludeEmpty bool `json:"include_empty"`
Limit int `json:"limit"`
Offset int `json:"offset"`
CatId content.TagID `json:"cat_id"`
FeedId content.FeedID `json:"feed_id"`
Skip int `json:"skip"`
IsCat bool `json:"is_cat"`
ShowContent bool `json:"show_content"`
ShowExcerpt bool `json:"show_excerpt"`
ViewMode string `json:"view_mode"`
SinceId content.ArticleID `json:"since_id"`
Sanitize bool `json:"sanitize"`
HasSandbox bool `json:"has_sandbox"`
IncludeHeader bool `json:"include_header"`
OrderBy string `json:"order_by"`
Search string `json:"search"`
ArticleIds []content.ArticleID `json:"article_ids"`
Mode int `json:"mode"`
Field int `json:"field"`
Data string `json:"data"`
ArticleId []content.ArticleID `json:"article_id"`
PrefName string `json:"pref_name"`
FeedUrl string `json:"feed_url"`
}
type response struct {
Seq int `json:"seq"`
Status int `json:"status"`
Content json.RawMessage `json:"content"`
}
type action func(request, content.User, repo.Service) (interface{}, error)
type errorContent struct {
Error string `json:"error"`
}
const (
API_STATUS_OK = 0
API_STATUS_ERR = 1
API_VERSION = "1.8.0"
API_LEVEL = 12
ARCHIVED_ID = 0
FAVORITE_ID = -1
PUBLISHED_ID = -2
FRESH_ID = -3
ALL_ID = -4
RECENTLY_READ_ID = -6
FRESH_DURATION = -24 * time.Hour
CAT_UNCATEGORIZED = 0
CAT_SPECIAL = -1 // Starred, Published, Archived, etc.
CAT_LABELS = -2
CAT_ALL_EXCEPT_VIRTUAL = -3 // i.e: labels
CAT_ALL = -4
)
var (
actions = make(map[string]action)
)
func Handler(
ctx context.Context,
service repo.Service,
searchProvider search.Provider,
feedManager *readeef.FeedManager,
processors []processor.Article,
secret []byte,
update time.Duration,
log log.Log,
) http.HandlerFunc {
sessionManager := newSession(ctx)
processors = filterProcessors(processors)
registerAuthActions(sessionManager, secret)
registerArticleActions(searchProvider, processors)
registerSettingActions(feedManager, update)
return func(w http.ResponseWriter, r *http.Request) {
resp := response{}
req, stop := readJSON(w, r.Body)
if stop {
return
}
var err error
var user content.User
var con interface{}
log.Debugf("Request: %#v\n", req)
resp.Seq = req.Seq
userRepo := service.UserRepo()
if req.Op == "login" {
user, err = userRepo.Get(content.Login(req.User))
} else if req.Op != "isLoggedIn" {
if sess := sessionManager.get(req.Sid); sess.login != "" {
user, err = userRepo.Get(content.Login(sess.login))
if err == nil {
sess.lastVisit = time.Now()
sessionManager.set(req.Sid, sess)
}
} else {
err = errors.WithStack(newErr("no session", "NOT_LOGGED_IN"))
}
}
if err != nil {
err = errors.WithStack(newErr(err.Error(), "NOT_LOGGED_IN"))
}
if err == nil {
log.Debugf("TT-RSS OP: %s\n", req.Op)
a, ok := actions[req.Op]
if !ok {
a = unknown
}
con, err = a(req, user, service)
}
if err == nil {
resp.Status = API_STATUS_OK
} else {
log.Infof("Error processing TT-RSS API request: %+v\n", err)
resp.Status = API_STATUS_ERR
con = errorContent{Error: errorKind(err)}
}
writeJson(w, req, resp, con, log)
}
}
func FakeWebHandler(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusMovedPermanently)
}
func readJSON(w http.ResponseWriter, r io.Reader) (req request, stop bool) {
in := map[string]interface{}{}
if b, err := ioutil.ReadAll(r); err == nil {
if err = json.Unmarshal(b, &in); err != nil {
http.Error(w, "Error decoding JSON request: "+err.Error(), http.StatusBadRequest)
return req, true
}
} else {
http.Error(w, "Error reading request body: "+err.Error(), http.StatusInternalServerError)
return req, true
}
return convertRequest(in), false
}
func writeJson(w http.ResponseWriter, req request, resp response, data interface{}, log log.Log) {
b, err := json.Marshal(data)
if err == nil {
resp.Content = json.RawMessage(b)
}
b, err = json.Marshal(&resp)
if err == nil {
w.Header().Set("Content-Type", "text/json")
w.Header().Set("Api-Content-Length", strconv.Itoa(len(b)))
w.Write(b)
log.Debugf("Output for %s: %s\n", req.Op, string(b))
} else {
log.Print(fmt.Errorf("TT-RSS error %s: %v", req.Op, err))
w.WriteHeader(http.StatusInternalServerError)
}
}
func filterProcessors(input []processor.Article) []processor.Article {
processors := make([]processor.Article, 0, len(input))
for i := range input {
if _, ok := input[i].(processor.ProxyHTTP); ok {
continue
}
processors = append(processors, input[i])
}
return processors
}
type err struct {
message string
kind string
}
func newErr(message, kind string) err {
return err{message: message, kind: kind}
}
func (e err) Error() string {
return e.message
}
func (e err) Kind() string {
return e.kind
}
func errorKind(err error) string {
type kinder interface {
Kind() string
}
if v, ok := err.(kinder); ok {
return v.Kind()
}
return ""
}