RSS: Add fallback on sorting by update timestamp + add outdatedFirst and updatedFirst sorts. Closes GH-1139.

This commit is contained in:
Valentin Lorentz 2015-09-02 10:04:04 +02:00
parent 29ca3eb5e4
commit 1c218592af
2 changed files with 23 additions and 10 deletions

View File

@ -47,7 +47,8 @@ class FeedNames(registry.SpaceSeparatedListOfStrings):
class FeedItemSortOrder(registry.OnlySomeStrings): class FeedItemSortOrder(registry.OnlySomeStrings):
"""Valid values include 'asInFeed', 'oldestFirst', 'newestFirst'.""" """Valid values include 'asInFeed', 'oldestFirst', 'newestFirst'."""
validStrings = ('asInFeed', 'oldestFirst', 'newestFirst') validStrings = ('asInFeed', 'oldestFirst', 'newestFirst', 'outdatedFirst',
'updatedFirst')
RSS = conf.registerPlugin('RSS') RSS = conf.registerPlugin('RSS')
@ -87,8 +88,8 @@ conf.registerGlobalValue(RSS, 'waitPeriod',
return cached results."""))) return cached results.""")))
conf.registerGlobalValue(RSS, 'sortFeedItems', conf.registerGlobalValue(RSS, 'sortFeedItems',
FeedItemSortOrder('asInFeed', _("""Determines whether feed items should be FeedItemSortOrder('asInFeed', _("""Determines whether feed items should be
sorted by their update timestamp or kept in the same order as they appear sorted by their publication/update timestamp or kept in the same order as
in a feed."""))) they appear in a feed.""")))
#################### ####################
# Headlines filtering # Headlines filtering

View File

@ -123,19 +123,31 @@ class Feed:
f = types.MethodType(f, plugin) f = types.MethodType(f, plugin)
return f return f
_sort_parameters = {
'oldestFirst': (('published_parsed', 'updated_parsed'), False),
'newestFirst': (('published_parsed', 'updated_parsed'), True),
'outdatedFirst': (('updated_parsed', 'published_parsed'), False),
'updatedFirst': (('updated_parsed', 'published_parsed'), True),
}
def _sort_arguments(order):
(fields, reverse) = _sort_parameters[order]
def key(entry):
for field in fields:
if field in entry:
return entry[field]
raise KeyError('No date field in entry.')
return (key, reverse)
def sort_feed_items(items, order): def sort_feed_items(items, order):
"""Return feed items, sorted according to sortFeedItems.""" """Return feed items, sorted according to sortFeedItems."""
if order not in ['oldestFirst', 'newestFirst']: if order == 'asInFeed':
return items return items
if order == 'oldestFirst': (key, reverse) = _sort_arguments(order)
reverse = False
if order == 'newestFirst':
reverse = True
try: try:
sitems = sorted(items, key=lambda i: i['published_parsed'], reverse=reverse) sitems = sorted(items, key=key, reverse=reverse)
except KeyError: except KeyError:
# feedparser normalizes required timestamp fields in ATOM and RSS # feedparser normalizes required timestamp fields in ATOM and RSS
# to the "published" field. Feeds missing it are unsortable by date. # to the "published"/"updated" fields. Feeds missing it are unsortable by date.
return items return items
return sitems return sitems