aboutsummaryrefslogtreecommitdiff
path: root/rss/atom_feed.py
blob: 622ecc081455ce35442cd3915e96b9b6aceb5d66 (plain)
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
#!/usr/bin/env python3

import lxml.etree as ET

class AtomFeed(object):
    """Class for storing atom:feed data and metadata.

    https://tools.ietf.org/html/rfc4287.

    """

    # pylint: disable=invalid-name,too-many-instance-attributes

    def __init__(self):
        """Define available attributes."""
        self.author = None  # atom:author
        self.generator = None  # atom:generator, optional
        self.icon = None  # atom:icon, optional
        self.logo = None  # atom:logo, optional
        self.id_text = None  # atom:id, just use URI
        self.id = None  # atom:id
        self.links = []  # list of atom:link
        self.title_text = None  # the text of atom:title
        self.title = None  # atom:title
        self.subtitle_text = None  # the text of atom:subtitle
        self.subtitle = None  # atom:subtitle
        self.updated_datetime = None  # update time as a datetime object
        self.updated = None  # atom:updated
        self.entries = []  # list of atom:entry, in reverse time order
        self.feed = None  # atom:feed, assembled

    def assemble_feed(self, FEED_MAX_ENTRIES):
        """Assemble atom:feed."""
        # pylint: disable=multiple-statements
        self.feed = ET.Element("feed", xmlns="http://www.w3.org/2005/Atom")
        self.feed.append(self.title)
        if self.subtitle is not None: self.feed.append(self.subtitle)
        for link in self.links:
            self.feed.append(link)
        self.feed.append(self.updated)
        self.feed.append(self.id)
        self.feed.append(self.author)
        if self.icon is not None: self.feed.append(self.icon)
        if self.logo is not None: self.feed.append(self.icon)
        if self.generator is not None: self.feed.append(self.generator)
        # include at most FEED_MAX_ENTRIES entries in the feed
        for entry in self.entries[:FEED_MAX_ENTRIES]:
            self.feed.append(entry.entry)

    def dump_feed(self, FEED_MAX_ENTRIES):
        """Dump atom:feed XML."""
        if self.feed is None:
            self.assemble_feed(FEED_MAX_ENTRIES)
        return ET.tostring(self.feed).decode("utf-8")