NewsDownloader: per-feed max_age option (#15322)
This commit is contained in:
1 parent
76330cae5d
commit
41c9e02b5b
4 files changed
+269
-26
No files matched your search
@@ -31,6 +31,16 @@ return {--do NOT change this line
|
||||
-- 'block_element="name_of_css.element.class" - means to remove the chosen CSS element, it can be easily picked using a modern web browser
|
||||
-- The default value is empty. The default list of common annoyances is used as fallback if this value is set.
|
||||
|
||||
-- 'max_age = "7d"' - skip items older than this duration.
|
||||
-- Format: <integer><unit>. Units: s (second), m (minute), h (hour),
|
||||
-- d (day), w (week), M (month=30d), y (year=365d).
|
||||
-- M and y are fixed-length approximations (not calendar months/leap years).
|
||||
-- Examples: "30m", "12h", "7d", "1M".
|
||||
-- Feed must provide <pubDate> (RSS) or <updated>/<published> (Atom).
|
||||
-- If the feed lacks a date field, sync will error and ask you to remove
|
||||
-- this option.
|
||||
-- Default: not set (no age filter).
|
||||
|
||||
-- Optional 'credentials' element is used to authenticate on subscription based articles.
|
||||
-- It is itself comprised of a 'url' strings, that is the url of the connexion form,
|
||||
-- and an 'auth' table that contains form data used for user authentication {form_key = value, …}.
|
||||
|
||||
@@ -4,6 +4,7 @@ local _ = require("gettext")
|
||||
local FeedView = {
|
||||
URL = "url",
|
||||
LIMIT = "limit",
|
||||
MAX_AGE = "max_age",
|
||||
DOWNLOAD_FULL_ARTICLE = "download_full_article",
|
||||
INCLUDE_IMAGES = "include_images",
|
||||
ENABLE_FILTER = "enable_filter",
|
||||
@@ -99,6 +100,17 @@ function FeedView:getItem(id, feed, edit_feed_callback, delete_feed_callback)
|
||||
)
|
||||
end
|
||||
},
|
||||
{
|
||||
_("Maximum age"),
|
||||
feed.max_age or "",
|
||||
callback = function()
|
||||
edit_feed_callback(
|
||||
id,
|
||||
FeedView.MAX_AGE,
|
||||
feed.max_age
|
||||
)
|
||||
end
|
||||
},
|
||||
{
|
||||
_("Download full article"),
|
||||
download_full_article,
|
||||
|
||||
@@ -42,6 +42,41 @@ local NewsDownloader = WidgetContainer:extend{
|
||||
local FEED_TYPE_RSS = "rss"
|
||||
local FEED_TYPE_ATOM = "atom"
|
||||
|
||||
-- Single-unit duration shorthand parser used for the per-feed `max_age` option.
|
||||
-- Returns (seconds, nil) when enabled, (nil, nil) when disabled (nil/empty),
|
||||
-- (nil, error_string) when invalid.
|
||||
local DURATION_UNITS = {
|
||||
s = 1,
|
||||
m = 60, -- minute (lowercase)
|
||||
h = 3600,
|
||||
d = 86400,
|
||||
w = 604800,
|
||||
M = 2592000, -- month: 30 days (uppercase, distinct from minute)
|
||||
y = 31536000, -- year: 365 days
|
||||
}
|
||||
|
||||
local function parseMaxAge(value)
|
||||
if value == nil or value == "" then
|
||||
return nil, nil
|
||||
end
|
||||
if type(value) ~= "string" then
|
||||
return nil, _("Maximum age must be a string")
|
||||
end
|
||||
local n, u = value:match("^(%d+)([smhdwMy])$")
|
||||
if not n then
|
||||
return nil, _("Invalid maximum age format. Use e.g. 7d, 12h, 30m, 1M.")
|
||||
end
|
||||
return tonumber(n) * DURATION_UNITS[u], nil
|
||||
end
|
||||
|
||||
-- Returns parsed unix timestamp (number) or nil if no parseable date field.
|
||||
local function getFeedItemTimestamp(feed)
|
||||
local raw = feed.updated or feed.pubDate or feed.published
|
||||
if not raw then return nil end
|
||||
local ts = dateparser.parse(raw)
|
||||
return type(ts) == "number" and ts or nil
|
||||
end
|
||||
|
||||
-- If a title looks like <title>blabla</title> it'll just be feed.title.
|
||||
-- If a title looks like <title attr="alb">blabla</title> then we get a table
|
||||
-- where [1] is the title string and the attributes are also available.
|
||||
@@ -320,6 +355,7 @@ function NewsDownloader:loadConfigAndProcessFeeds(touchmenu_instance)
|
||||
local block_element = parseCommaSeparatedOption(feed.block_element)
|
||||
local credentials = feed.credentials
|
||||
local http_auth = feed.http_auth
|
||||
local max_age_str = feed.max_age
|
||||
-- Check if the two required attributes are set.
|
||||
if url and limit then
|
||||
feed_message = T(_("Processing %1/%2:\n%3"), idx, total_feed_entries, BD.url(url))
|
||||
@@ -336,7 +372,8 @@ function NewsDownloader:loadConfigAndProcessFeeds(touchmenu_instance)
|
||||
feed_message,
|
||||
enable_filter,
|
||||
filter_element,
|
||||
block_element)
|
||||
block_element,
|
||||
max_age_str)
|
||||
else
|
||||
logger.warn("NewsDownloader: invalid feed config entry.", feed)
|
||||
end
|
||||
@@ -408,7 +445,7 @@ function NewsDownloader:loadConfigAndProcessFeedsWithUI(touchmenu_instance)
|
||||
end)
|
||||
end
|
||||
|
||||
function NewsDownloader:processFeedSource(url, credentials, http_auth, limit, unsupported_feeds_urls, download_full_article, include_images, message, enable_filter, filter_element, block_element)
|
||||
function NewsDownloader:processFeedSource(url, credentials, http_auth, limit, unsupported_feeds_urls, download_full_article, include_images, message, enable_filter, filter_element, block_element, max_age_str)
|
||||
-- Check if we have a cached response first
|
||||
local cache = DownloadBackend:getCache()
|
||||
local cached_response = cache:check(url)
|
||||
@@ -571,7 +608,8 @@ function NewsDownloader:processFeedSource(url, credentials, http_auth, limit, un
|
||||
message,
|
||||
enable_filter,
|
||||
filter_element,
|
||||
block_element
|
||||
block_element,
|
||||
max_age_str
|
||||
)
|
||||
end)
|
||||
elseif is_rss then
|
||||
@@ -587,7 +625,8 @@ function NewsDownloader:processFeedSource(url, credentials, http_auth, limit, un
|
||||
message,
|
||||
enable_filter,
|
||||
filter_element,
|
||||
block_element
|
||||
block_element,
|
||||
max_age_str
|
||||
)
|
||||
end)
|
||||
end
|
||||
@@ -597,8 +636,17 @@ function NewsDownloader:processFeedSource(url, credentials, http_auth, limit, un
|
||||
if not ok or (not is_rss and not is_atom) then
|
||||
local error_message
|
||||
if not ok then
|
||||
logger.err("NewsDownloader: Error processing feed", error)
|
||||
error_message = _("(Reason: Failed to download content)")
|
||||
if type(error) == "string"
|
||||
and error:find("__max_age_no_date__", 1, true) then
|
||||
error_message = _("(Reason: Maximum age is set but the feed provides no date field (<updated>/<pubDate>/<published>). Remove maximum age from this feed in the config.)")
|
||||
elseif type(error) == "string"
|
||||
and error:find("__max_age_invalid__:", 1, true) then
|
||||
local msg = error:match("__max_age_invalid__:(.*)") or ""
|
||||
error_message = T(_("(Reason: %1)"), msg)
|
||||
else
|
||||
logger.err("NewsDownloader: Error processing feed", error)
|
||||
error_message = _("(Reason: Failed to download content)")
|
||||
end
|
||||
elseif not is_rss then
|
||||
error_message = _("(Reason: Couldn't process RSS)")
|
||||
elseif not is_atom then
|
||||
@@ -632,7 +680,7 @@ function NewsDownloader:deserializeXMLString(xml_str)
|
||||
return xmlhandler.root
|
||||
end
|
||||
|
||||
function NewsDownloader:processFeed(feed_type, feeds, cookies, http_auth, limit, download_full_article, include_images, message, enable_filter, filter_element, block_element)
|
||||
function NewsDownloader:processFeed(feed_type, feeds, cookies, http_auth, limit, download_full_article, include_images, message, enable_filter, filter_element, block_element, max_age_str)
|
||||
local feed_title
|
||||
local feed_item
|
||||
local total_items
|
||||
@@ -658,6 +706,22 @@ function NewsDownloader:processFeed(feed_type, feeds, cookies, http_auth, limit,
|
||||
feed_item = {feed_item}
|
||||
end
|
||||
end
|
||||
-- Parse max_age (if set) and prepare the cutoff timestamp. Invalid format
|
||||
-- and missing-date conditions raise sentinel errors that the caller's
|
||||
-- pcall converts into user-facing messages.
|
||||
local max_age_seconds, max_age_err = parseMaxAge(max_age_str)
|
||||
if max_age_err then
|
||||
error("__max_age_invalid__:" .. max_age_err)
|
||||
end
|
||||
|
||||
local cutoff
|
||||
if max_age_seconds and feed_item[1] then
|
||||
local first_ts = getFeedItemTimestamp(feed_item[1])
|
||||
if not first_ts then
|
||||
error("__max_age_no_date__")
|
||||
end
|
||||
cutoff = os.time() - max_age_seconds
|
||||
end
|
||||
-- Get the path to the output directory.
|
||||
local feed_output_dir = ("%s%s/"):format(
|
||||
self.download_dir,
|
||||
@@ -672,6 +736,17 @@ function NewsDownloader:processFeed(feed_type, feeds, cookies, http_auth, limit,
|
||||
if limit ~= 0 and index - 1 == limit then
|
||||
break
|
||||
end
|
||||
if cutoff then
|
||||
local ts = getFeedItemTimestamp(feed)
|
||||
if ts and ts < cutoff then
|
||||
-- Feeds are chronological newest-first; remaining items are
|
||||
-- older too, so we can stop iterating.
|
||||
break
|
||||
end
|
||||
-- ts == nil after the first-item probe succeeded means the
|
||||
-- publisher omitted a date for this item. Process it normally
|
||||
-- without an age check.
|
||||
end
|
||||
-- Create a message to display during processing.
|
||||
local article_message = T(
|
||||
_("%1\n\nFetching article %2/%3:"),
|
||||
@@ -731,26 +806,11 @@ function NewsDownloader:processFeed(feed_type, feeds, cookies, http_auth, limit,
|
||||
end
|
||||
end
|
||||
|
||||
local function parseDate(dateTime)
|
||||
-- Uses lua-feedparser https://github.com/slact/lua-feedparser
|
||||
-- feedparser is available under the (new) BSD license.
|
||||
-- see: koreader/plugins/newsdownloader.koplugin/lib/LICENCE_lua-feedparser
|
||||
logger.dbg("NewsDownloader: Parsing date:", dateTime)
|
||||
local date = dateparser.parse(dateTime)
|
||||
if type(date) == "number" then
|
||||
return os.date("%y-%m-%d_%H-%M_", date)
|
||||
end
|
||||
return dateTime
|
||||
end
|
||||
|
||||
local function getTitleWithDate(feed)
|
||||
local title = util.getSafeFilename(NewsDownloader.getFeedTitle(feed.title))
|
||||
if feed.updated then
|
||||
title = parseDate(feed.updated) .. title
|
||||
elseif feed.pubDate then
|
||||
title = parseDate(feed.pubDate) .. title
|
||||
elseif feed.published then
|
||||
title = parseDate(feed.published) .. title
|
||||
local ts = getFeedItemTimestamp(feed)
|
||||
if ts then
|
||||
title = os.date("%y-%m-%d_%H-%M_", ts) .. title
|
||||
end
|
||||
return title
|
||||
end
|
||||
@@ -978,6 +1038,7 @@ function NewsDownloader:editFeedAttribute(id, key, value)
|
||||
-- attribute will need and displays the corresponding dialog.
|
||||
if key == FeedView.URL
|
||||
or key == FeedView.LIMIT
|
||||
or key == FeedView.MAX_AGE
|
||||
or key == FeedView.FILTER_ELEMENT
|
||||
or key == FeedView.BLOCK_ELEMENT
|
||||
or key == FeedView.HTTP_AUTH_USERNAME
|
||||
@@ -994,6 +1055,12 @@ function NewsDownloader:editFeedAttribute(id, key, value)
|
||||
title = _("Edit feed limit")
|
||||
description = _("Set to 0 for no limit to how many items are downloaded")
|
||||
input_type = "number"
|
||||
elseif key == FeedView.MAX_AGE then
|
||||
title = _("Edit maximum age")
|
||||
description = _("Download articles no older than this duration. Format: <number><unit>. " ..
|
||||
"Units: s, m (minute), h, d, w, M (month=30d), y (year=365d). " ..
|
||||
"Examples: 30m, 12h, 7d, 1M. Leave empty to disable.")
|
||||
input_type = "string"
|
||||
elseif key == FeedView.FILTER_ELEMENT then
|
||||
title = _("Edit filter element.")
|
||||
description = _("Filter based on the given CSS selector. E.g.: name_of_css.element.class")
|
||||
@@ -1032,8 +1099,16 @@ function NewsDownloader:editFeedAttribute(id, key, value)
|
||||
text = _("Save"),
|
||||
is_enter_default = true,
|
||||
callback = function()
|
||||
local new_value = input_dialog:getInputValue()
|
||||
if key == FeedView.MAX_AGE and new_value ~= "" then
|
||||
local _, err = parseMaxAge(new_value)
|
||||
if err then
|
||||
UIManager:show(InfoMessage:new{ text = err })
|
||||
return
|
||||
end
|
||||
end
|
||||
UIManager:close(input_dialog)
|
||||
self:updateFeedConfig(id, key, input_dialog:getInputValue())
|
||||
self:updateFeedConfig(id, key, new_value)
|
||||
end,
|
||||
},
|
||||
}
|
||||
@@ -1146,6 +1221,8 @@ function NewsDownloader:updateFeedConfig(id, key, value)
|
||||
}
|
||||
)
|
||||
end
|
||||
elseif key == FeedView.MAX_AGE then
|
||||
feed.max_age = value
|
||||
elseif key == FeedView.DOWNLOAD_FULL_ARTICLE then
|
||||
if feed.download_full_article ~= nil then
|
||||
feed.download_full_article = value
|
||||
@@ -1356,4 +1433,7 @@ function NewsDownloader:onCloseDocument()
|
||||
end
|
||||
end
|
||||
|
||||
NewsDownloader._parseMaxAge = parseMaxAge
|
||||
NewsDownloader._getFeedItemTimestamp = getFeedItemTimestamp
|
||||
|
||||
return NewsDownloader
|
||||
@@ -237,4 +237,145 @@ describe("NewsDownloader module", function()
|
||||
NewsDownloader.createFromDescription = old_createFromDescription
|
||||
end)
|
||||
end)
|
||||
|
||||
describe("parseMaxAge", function()
|
||||
local parseMaxAge
|
||||
|
||||
setup(function()
|
||||
parseMaxAge = NewsDownloader._parseMaxAge
|
||||
assert.is_function(parseMaxAge)
|
||||
end)
|
||||
|
||||
it("returns (nil, nil) for nil (disabled)", function()
|
||||
local s, err = parseMaxAge(nil)
|
||||
assert.is_nil(s)
|
||||
assert.is_nil(err)
|
||||
end)
|
||||
|
||||
it("returns (nil, nil) for empty string (disabled)", function()
|
||||
local s, err = parseMaxAge("")
|
||||
assert.is_nil(s)
|
||||
assert.is_nil(err)
|
||||
end)
|
||||
|
||||
it("parses seconds", function()
|
||||
assert.equals(1, parseMaxAge("1s"))
|
||||
end)
|
||||
|
||||
it("parses minutes (lowercase m)", function()
|
||||
assert.equals(1800, parseMaxAge("30m"))
|
||||
end)
|
||||
|
||||
it("parses hours", function()
|
||||
assert.equals(43200, parseMaxAge("12h"))
|
||||
end)
|
||||
|
||||
it("parses days", function()
|
||||
assert.equals(604800, parseMaxAge("7d"))
|
||||
end)
|
||||
|
||||
it("parses weeks", function()
|
||||
assert.equals(1209600, parseMaxAge("2w"))
|
||||
end)
|
||||
|
||||
it("parses months (uppercase M, 30d)", function()
|
||||
assert.equals(2592000, parseMaxAge("1M"))
|
||||
end)
|
||||
|
||||
it("parses years (365d)", function()
|
||||
assert.equals(31536000, parseMaxAge("1y"))
|
||||
end)
|
||||
|
||||
it("rejects bare number", function()
|
||||
local s, err = parseMaxAge("7")
|
||||
assert.is_nil(s)
|
||||
assert.is_string(err)
|
||||
end)
|
||||
|
||||
it("rejects 7days", function()
|
||||
local s, err = parseMaxAge("7days")
|
||||
assert.is_nil(s)
|
||||
assert.is_string(err)
|
||||
end)
|
||||
|
||||
it("rejects uppercase D (case-sensitive)", function()
|
||||
local s, err = parseMaxAge("7D")
|
||||
assert.is_nil(s)
|
||||
assert.is_string(err)
|
||||
end)
|
||||
|
||||
it("rejects negative duration", function()
|
||||
local s, err = parseMaxAge("-1d")
|
||||
assert.is_nil(s)
|
||||
assert.is_string(err)
|
||||
end)
|
||||
|
||||
it("rejects pure garbage", function()
|
||||
local s, err = parseMaxAge("abc")
|
||||
assert.is_nil(s)
|
||||
assert.is_string(err)
|
||||
end)
|
||||
|
||||
it("rejects non-string types", function()
|
||||
local s, err = parseMaxAge(7)
|
||||
assert.is_nil(s)
|
||||
assert.is_string(err)
|
||||
end)
|
||||
end)
|
||||
|
||||
describe("getFeedItemTimestamp", function()
|
||||
local getFeedItemTimestamp
|
||||
|
||||
setup(function()
|
||||
getFeedItemTimestamp = NewsDownloader._getFeedItemTimestamp
|
||||
assert.is_function(getFeedItemTimestamp)
|
||||
end)
|
||||
|
||||
it("parses RSS pubDate", function()
|
||||
local ts = getFeedItemTimestamp({ pubDate = "Mon, 01 Jan 2024 00:00:00 GMT" })
|
||||
assert.is_number(ts)
|
||||
end)
|
||||
|
||||
it("parses Atom updated", function()
|
||||
local ts = getFeedItemTimestamp({ updated = "2024-01-01T00:00:00Z" })
|
||||
assert.is_number(ts)
|
||||
end)
|
||||
|
||||
it("parses Atom published", function()
|
||||
local ts = getFeedItemTimestamp({ published = "2024-01-01T00:00:00Z" })
|
||||
assert.is_number(ts)
|
||||
end)
|
||||
|
||||
it("returns nil when no date fields present", function()
|
||||
assert.is_nil(getFeedItemTimestamp({ title = "no date here" }))
|
||||
end)
|
||||
|
||||
it("returns nil for unparseable date string", function()
|
||||
assert.is_nil(getFeedItemTimestamp({ pubDate = "not a date" }))
|
||||
end)
|
||||
|
||||
it("prefers updated over pubDate and published", function()
|
||||
local ts = getFeedItemTimestamp({
|
||||
updated = "2024-01-01T00:00:00Z",
|
||||
pubDate = "garbage",
|
||||
published = "garbage",
|
||||
})
|
||||
assert.is_number(ts)
|
||||
end)
|
||||
end)
|
||||
|
||||
describe("getFeedItemTimestamp publisher quirk", function()
|
||||
local getFeedItemTimestamp
|
||||
|
||||
setup(function()
|
||||
getFeedItemTimestamp = NewsDownloader._getFeedItemTimestamp
|
||||
end)
|
||||
|
||||
it("returns nil for an item missing all date fields, so the for-loop processes it without filtering", function()
|
||||
-- The for-loop in processFeed treats `ts == nil` as "no age check"
|
||||
-- once the first-item probe has succeeded. This test locks in the
|
||||
-- nil contract that the loop relies on.
|
||||
assert.is_nil(getFeedItemTimestamp({ title = "x", link = "y" }))
|
||||
end)
|
||||
end)
|
||||
end)
|
||||
Reference in new issue
Block a user