Repository navigation
Expand file tree
/
Copy pathrssreader_freshrss.lua
More file actions
602 lines (526 loc) · 19.4 KB
/
Copy pathrssreader_freshrss.lua
File metadata and controls
602 lines (526 loc) · 19.4 KB
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
-- rssreader_freshrss.lua
local http = require("socket.http")
local https = require("ssl.https")
local json = require("json")
local logger = require("logger")
local ltn12 = require("ltn12")
local socketutil = require("socketutil")
local url = require("socket.url")
local mime = require("mime")
local FreshRSS = {}
FreshRSS.__index = FreshRSS
local USER_AGENT = "KOReader RSSReader"
-- Google Reader API state tags. FreshRSS keeps "read" and "starred"
-- (favourite) as tags on an entry, set and cleared through the same
-- edit-tag endpoint.
local READ_TAG = "user/-/state/com.google/read"
-- Also the id of the stream that lists every favourite.
local STARRED_TAG = "user/-/state/com.google/starred"
-- Every entry of every subscription.
local READING_LIST = "user/-/state/com.google/reading-list"
local function requestWithScheme(options)
local parsed_url = url.parse(options.url)
local scheme = parsed_url and parsed_url.scheme or "http"
if scheme == "https" then
return https.request(options)
end
return http.request(options)
end
local function safe_json_decode(payload)
if not payload or payload == "" then
return {}
end
local ok, decoded = pcall(json.decode, payload)
if ok then
return decoded
end
return nil
end
local function encodeQuery(params)
local components = {}
local keys = {}
for key in pairs(params or {}) do
table.insert(keys, key)
end
table.sort(keys)
for _, key in ipairs(keys) do
local value = params[key]
if value ~= nil then
table.insert(components, string.format("%s=%s", url.escape(tostring(key)), url.escape(tostring(value))))
end
end
if #components > 0 then
return "?" .. table.concat(components, "&")
end
return ""
end
-- Stream ids are path *structure*, not one opaque value: FreshRSS feed ids
-- look like "feed/221" (Google Reader style servers use "feed/http://…")
-- and folders like "user/-/label/News". url.escape() would turn those
-- separators into %2F, which most web servers refuse to decode inside a
-- path (Apache's AllowEncodedSlashes is Off by default), so the request
-- comes back as a 404. Escape only what has to be escaped and leave the
-- path separators — and the sub-delims that are legal in a path segment —
-- alone.
local function escapeStreamId(stream_id)
return (tostring(stream_id):gsub("[^%w%-%._~/:@]", function(char)
return string.format("%%%02X", string.byte(char))
end))
end
local function sanitizeBaseUrl(raw)
if type(raw) ~= "string" then
return nil
end
local trimmed = raw:gsub("^%s+", ""):gsub("%s+$", ""):gsub("/+$", "")
if trimmed == "" then
return nil
end
return trimmed
end
local function joinUrl(base, path, query_params)
local normalized_base = sanitizeBaseUrl(base)
if not normalized_base then
return nil
end
local normalized_path = path or ""
if not normalized_path:match("^/") then
normalized_path = "/" .. normalized_path
end
local query_string = encodeQuery(query_params)
return normalized_base .. normalized_path .. query_string
end
function FreshRSS:new(account)
local instance = {
account = account or {},
auth_token = nil,
last_login = nil,
tree_cache = nil,
token_cache = nil, -- For edit-tag operations
}
setmetatable(instance, self)
return instance
end
function FreshRSS:getCredentials()
local auth = self.account and self.account.auth
if type(auth) ~= "table" then
return nil, nil, nil
end
local base_url = sanitizeBaseUrl(auth.base_url)
local username = auth.username
local password = auth.password -- This should be the API password set in FreshRSS
return base_url, username, password
end
-- Authenticate using the ClientLogin flow
function FreshRSS:authenticate()
if self.auth_token and self.last_login and (os.time() - self.last_login) < 1800 then
return true -- Token is fresh
end
local base_url, username, password = self:getCredentials()
if not base_url or not username or not password then
return false, "Missing FreshRSS credentials."
end
-- The path must be /api/greader.php/accounts/ClientLogin
local target_url = joinUrl(base_url, "/api/greader.php/accounts/ClientLogin")
-- All parameters go into the POST body, as confirmed by capyreader
local form_data = string.format("Email=%s&Passwd=%s&client=%s&service=%s",
url.escape(username),
url.escape(password),
url.escape(USER_AGENT),
url.escape("reader")
)
local response_chunks = {}
socketutil:set_timeout(socketutil.LARGE_BLOCK_TIMEOUT, socketutil.LARGE_TOTAL_TIMEOUT)
local _, code, headers, status = requestWithScheme({
url = target_url,
method = "POST",
headers = {
["Content-Type"] = "application/x-www-form-urlencoded",
["Content-Length"] = tostring(#form_data),
["User-Agent"] = USER_AGENT,
},
source = ltn12.source.string(form_data),
sink = ltn12.sink.table(response_chunks),
})
socketutil:reset_timeout()
local numeric_code = tonumber(code)
if not numeric_code or numeric_code < 200 or numeric_code >= 300 then
return false, string.format("FreshRSS login failed (HTTP %s - %s)", code, status)
end
local body = table.concat(response_chunks)
local auth_token = body:match("Auth=([%w%-/_]+)")
if not auth_token then
return false, "Failed to get Auth token from FreshRSS response."
end
self.auth_token = auth_token
self.last_login = os.time()
self.token_cache = nil -- Clear edit-token
return true
end
-- Get the edit-token required for marking items
function FreshRSS:getEditToken()
if self.token_cache then
return true, self.token_cache
end
local ok, token_or_err = self:authorizedRequest("GET", "/api/greader.php/reader/api/0/token")
if not ok then
return false, token_or_err
end
if type(token_or_err) ~= "string" or token_or_err == "" then
return false, "Did not receive valid edit-token"
end
self.token_cache = token_or_err
return true, self.token_cache
end
-- Perform an authorized API request
function FreshRSS:authorizedRequest(method, path, query_params, body, is_retry)
local ok, err = self:authenticate()
if not ok then
return false, err
end
local base_url = self.account.auth.base_url
local target_url = joinUrl(base_url, path, query_params)
local headers = {
["User-Agent"] = USER_AGENT,
["Authorization"] = "GoogleLogin auth=" .. self.auth_token,
}
if body then
headers["Content-Type"] = "application/x-www-form-urlencoded"
headers["Content-Length"] = tostring(#body)
end
local response_chunks = {}
socketutil:set_timeout(socketutil.LARGE_BLOCK_TIMEOUT, socketutil.LARGE_TOTAL_TIMEOUT)
local _, code, _, status = requestWithScheme({
url = target_url,
method = method or "GET",
headers = headers,
source = body and ltn12.source.string(body) or nil,
sink = ltn12.sink.table(response_chunks),
})
socketutil:reset_timeout()
local numeric_code = tonumber(code)
if not numeric_code or numeric_code < 200 or numeric_code >= 300 then
-- If unauthorized, clear token and retry once
-- Only once: a 401 that survives a fresh login (a rejected edit-token
-- answers 401 too) would otherwise retry forever.
if numeric_code == 401 and self.last_login ~= nil and not is_retry then
self.auth_token = nil
self.last_login = nil
logger.warn("FreshRSS auth token expired, retrying...")
return self:authorizedRequest(method, path, query_params, body, true)
end
return false, string.format("FreshRSS request failed (HTTP %s - %s)", code, status)
end
local text = table.concat(response_chunks)
-- For edit-tag and mark-all-as-read, response is just "OK"
if path == "/api/greader.php/reader/api/0/edit-tag"
or path == "/api/greader.php/reader/api/0/mark-all-as-read"
or path == "/api/greader.php/reader/api/0/token" then
return true, text
end
local decoded = safe_json_decode(text)
if not decoded then
return false, "Unable to parse FreshRSS JSON response"
end
return true, decoded
end
function FreshRSS:fetchStructure(force)
if self.tree_cache and not force then
return true, self.tree_cache
end
-- 1. Get all subscriptions
local ok, subs_data = self:authorizedRequest("GET", "/api/greader.php/reader/api/0/subscription/list", { output = "json" })
if not ok then
return false, subs_data
end
-- 2. Get all tags (labels / folders)
local ok2, tags_data = self:authorizedRequest("GET", "/api/greader.php/reader/api/0/tag/list", { output = "json" })
if not ok2 then
return false, tags_data
end
self.tree_cache = self:buildTreeFromData(subs_data, tags_data)
return true, self.tree_cache
end
function FreshRSS:buildTreeFromData(subs_data, tags_data)
local feeds_map = {}
local folders = {}
local folders_map = {}
local tag_labels = {}
-- Collect human-friendly labels from tag list
for _, tag in ipairs(tags_data.tags or {}) do
local tag_id = tag.id
if type(tag_id) == "string" and tag_id:match("^user/%-/label/") then
local label = tag.label or tag_id:match("user/%-/label/(.*)")
if type(label) == "string" and label ~= "" then
tag_labels[tag_id] = label
end
end
end
local function ensureFolder(category)
if type(category) ~= "table" then
return nil
end
local cat_id = category.id
if type(cat_id) ~= "string" then
return nil
end
-- Only treat user labels as folders, ignore state tags like .../state/...
if not cat_id:match("^user/%-/label/") then
return nil
end
local folder = folders_map[cat_id]
if folder then
return folder
end
local title = category.label
or tag_labels[cat_id]
or cat_id:match("user/%-/label/(.*)")
or "Folder"
folder = {
kind = "folder",
id = cat_id,
title = title,
children = {},
}
folders_map[cat_id] = folder
table.insert(folders, folder)
return folder
end
-- Process subscriptions (feeds)
for _, feed in ipairs(subs_data.subscriptions or {}) do
local feed_node = {
kind = "feed",
id = feed.id, -- e.g., "feed/http://..."
title = feed.title or "Untitled Feed",
feed = {
id = feed.id,
title = feed.title,
url = feed.htmlUrl,
feed_url = (type(feed.id) == "string" and feed.id:gsub("^feed/", "")) or feed.id,
unreadCount = feed.unreadCount or 0,
},
}
feeds_map[feed.id] = feed_node
local added_to_folder = false
for _, category in ipairs(feed.categories or {}) do
local folder = ensureFolder(category)
if folder then
table.insert(folder.children, feed_node)
added_to_folder = true
end
end
if not added_to_folder then
-- Feeds without any label appear at the root level
table.insert(folders, feed_node)
end
end
return {
kind = "root",
title = (self.account and self.account.name) or "FreshRSS",
children = folders,
feeds = feeds_map,
}
end
function FreshRSS:buildTree(force)
return self:fetchStructure(force)
end
local function normalizeEntry(entry)
if type(entry) ~= "table" then return {} end
local is_read = false
local is_starred = false
for _, category in ipairs(entry.categories or {}) do
if category:find("/state/com.google/read$") then
is_read = true
elseif category:find("/state/com.google/starred$") then
is_starred = true
end
end
local content = (entry.content and entry.content.content) or (entry.summary and entry.summary.content) or ""
local permalink = (entry.alternate and entry.alternate[1] and entry.alternate[1].href) or entry.id
local feed_title = nil
if entry.origin and entry.origin.title then
feed_title = entry.origin.title
end
return {
id = entry.id,
story_id = entry.id,
feed_id = entry.origin and entry.origin.streamId,
feed_title = feed_title,
title = entry.title or "Untitled",
story_title = entry.title or "Untitled",
permalink = permalink,
story_permalink = permalink,
content = content,
story_content = content,
timestamp = (entry.published or entry.updated or 0) * 1000,
read = is_read,
read_status = is_read,
story_read = is_read,
starred = is_starred,
author = entry.author,
}
end
function FreshRSS:fetchStories(feed_id, options)
if not feed_id then
return false, "Missing feed identifier."
end
options = options or {}
local page = options.page or 1
local query = {
output = "json",
n = tonumber(options.n) or 15, -- how many items to fetch per page
}
if options.continuation then
query.c = options.continuation
end
if options.published_since then
-- 'nt' means "newer than"
query.nt = options.published_since
end
if options.read_filter == "unread_only" then
-- 'xt' means "exclude tag". We exclude items with the "read" state.
query.xt = READ_TAG
elseif options.read_filter == "read_only" then
-- 'it' means "include tag".
query.it = READ_TAG
end
-- FreshRSS has no page numbers: the caller pages by handing back the
-- continuation token from the previous response (options.continuation).
local ok, data_or_err = self:authorizedRequest("GET", "/api/greader.php/reader/api/0/stream/contents/" .. escapeStreamId(feed_id), query)
if not ok then
return false, data_or_err
end
-- Everything that is not a single feed ("feed/…") aggregates entries from
-- several feeds: the starred list, the reading list, a label. Flag those
-- so the story list prefixes each entry with the feed it came from.
local is_aggregated_stream = not tostring(feed_id):match("^feed/")
local stories = {}
for _, entry in ipairs(data_or_err.items or {}) do
local story = normalizeEntry(entry)
if is_aggregated_stream then
story._from_virtual_feed = true
end
table.insert(stories, story)
end
return true, {
stories = stories,
more_stories = data_or_err.continuation and true or false,
continuation = data_or_err.continuation,
}
end
function FreshRSS:markStory(story, add_tag, remove_tag)
local ok, token = self:getEditToken()
if not ok then return false, token end
local story_id = (story and (story.id or story.story_id))
if not story_id then return false, "Missing story ID" end
-- Data for a POST request must be in the body, not the query string.
local post_data = {
client = USER_AGENT,
T = token,
i = story_id,
}
if add_tag then
post_data.a = add_tag
end
if remove_tag then
post_data.r = remove_tag
end
-- We must manually encode the body for a POST request.
-- We pass 'nil' for the query_params.
local body_string = encodeQuery(post_data):gsub("^%?", "") -- remove leading '?' from encodeQuery
local ok, err = self:authorizedRequest("POST", "/api/greader.php/reader/api/0/edit-tag", nil, body_string)
if not ok then
-- If token was bad, clear it and retry
if tostring(err):find("Token") then
self.token_cache = nil
return self:markStory(story, add_tag, remove_tag)
end
return false, err
end
return true
end
-- Offline Mode's read-state sync: edit-tag takes the i= parameter repeated,
-- so one request covers up to 100 stories.
function FreshRSS:markStoriesAsRead(stories, is_retry)
local ok, token = self:getEditToken()
if not ok then return false, token end
local ids = {}
for _, story in ipairs(stories or {}) do
local story_id = story and (story.id or story.story_id)
if story_id then
table.insert(ids, tostring(story_id))
end
end
for start = 1, #ids, 100 do
local parts = {
"client=" .. url.escape(USER_AGENT),
"T=" .. url.escape(token),
"a=" .. url.escape(READ_TAG),
}
for i = start, math.min(start + 99, #ids) do
table.insert(parts, "i=" .. url.escape(ids[i]))
end
local request_ok, err = self:authorizedRequest("POST", "/api/greader.php/reader/api/0/edit-tag", nil, table.concat(parts, "&"))
if not request_ok then
-- A stale token: fetch a new one and send everything again
-- (marking a story read twice is harmless).
if not is_retry and tostring(err):find("Token") then
self.token_cache = nil
return self:markStoriesAsRead(stories, true)
end
return false, err
end
end
return true
end
function FreshRSS:markStoryAsRead(feed_id, story)
return self:markStory(story, READ_TAG, nil)
end
function FreshRSS:markStoryAsUnread(feed_id, story)
return self:markStory(story, nil, READ_TAG)
end
-- Marks every entry of a stream read in one call: a feed ("feed/221"), a
-- label ("user/-/label/News") or a state stream (reading-list, starred).
-- edit-tag cannot do this — it reads "feed/221" as the entry id 0x221.
-- ts is the newest entry id to mark; FreshRSS entry ids are microsecond
-- timestamps, so "now" leaves entries that arrive meanwhile unread.
function FreshRSS:markStreamAsRead(stream_id, is_retry)
if not stream_id then return false, "Missing stream ID" end
local ok, token = self:getEditToken()
if not ok then return false, token end
local body_string = encodeQuery({
T = token,
s = stream_id,
ts = tostring(os.time()) .. "000000",
}):gsub("^%?", "")
local ok2, err = self:authorizedRequest("POST", "/api/greader.php/reader/api/0/mark-all-as-read", nil, body_string)
if not ok2 then
-- A rejected edit-token answers 401: fetch a new one, once.
if not is_retry and tostring(err):find("HTTP 401") then
self.token_cache = nil
return self:markStreamAsRead(stream_id, true)
end
return false, err
end
return true
end
function FreshRSS:markFeedAsRead(feed_id)
return self:markStreamAsRead(feed_id)
end
function FreshRSS:markCategoryAsRead(label_id)
return self:markStreamAsRead(label_id)
end
function FreshRSS:getReadingListStreamId()
return READING_LIST
end
-- Favourites. The generic story menu shows the Star / Unstar button, and the
-- story list its star prefix, for any client exposing this pair.
function FreshRSS:markStoryAsStarred(feed_id, story)
return self:markStory(story, STARRED_TAG, nil)
end
function FreshRSS:markStoryAsUnstarred(feed_id, story)
return self:markStory(story, nil, STARRED_TAG)
end
function FreshRSS:getStarredStreamId()
return STARRED_TAG
end
return FreshRSS