summaryrefslogtreecommitdiff
path: root/packages/rss/lektor_rss.py
blob: 224d6f8f1a492fc2721342529c301054d2517019 (plain) (blame)
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
from __future__ import annotations

from datetime import date, datetime, time, timezone
from typing import Any

from feedgenerator.django.utils.feedgenerator import Rss201rev2Feed
from lektor.build_programs import BuildProgram
from lektor.context import get_ctx, url_to
from lektor.db import F
from lektor.environment import Expression
from lektor.pluginsystem import Plugin
from lektor.sourceobj import VirtualSourceObject
from lektor.utils import build_url


def get_field(record: Any, field: str, default: Any = None) -> Any:
    if field in record:
        return record[field]
    return default


def get_item_title(item: Any, field: str) -> str:
    if field in item:
        return str(item[field])
    return item.record_label


def get_item_body(item: Any, field: str) -> str:
    if field not in item:
        raise RuntimeError(f"Body field {field!r} not found in {item!r}")

    with get_ctx().changed_base_url(item.url_path):
        body = item[field]

        if hasattr(body, "__html__"):
            return str(body.__html__())

        return str(body)


def get_item_date(item: Any, field: str) -> datetime:
    value = get_field(item, field)

    if value is None:
        raise RuntimeError(f"Publication date field {field!r} not found in {item!r}")

    if isinstance(value, datetime):
        if value.tzinfo is None:
            return value.replace(tzinfo=timezone.utc)
        return value

    if isinstance(value, date):
        return datetime.combine(value, time.min, tzinfo=timezone.utc)

    raise TypeError(f"Publication date field {field!r} must be a date or datetime")


class RssFeedSource(VirtualSourceObject):
    def __init__(
        self,
        parent: Any,
        feed_id: str,
        plugin: RssPlugin,
    ) -> None:
        super().__init__(parent)
        self.feed_id = feed_id
        self.plugin = plugin

    @property
    def path(self) -> str:
        return f"{self.parent.path}@rss/{self.feed_id}"

    @property
    def url_path(self) -> str:
        configured_path = self.plugin.get_rss_config(
            self.feed_id,
            "url_path",
        )

        if configured_path:
            return configured_path

        return build_url([self.parent.url_path, self.filename])

    @property
    def feed_name(self) -> str:
        return self.plugin.get_rss_config(self.feed_id, "name") or self.feed_id

    def iter_source_filenames(self):
        return self.parent.iter_source_filenames()

    def __getattr__(self, name: str) -> Any:
        try:
            return self.plugin.get_rss_config(self.feed_id, name)
        except KeyError as exc:
            raise AttributeError(name) from exc


class RssFeedBuilderProgram(BuildProgram):
    def produce_artifacts(self) -> None:
        self.declare_artifact(
            self.source.url_path,
            sources=list(self.source.iter_source_filenames()),
        )

    def build_artifact(self, artifact: Any) -> None:
        ctx = get_ctx()
        source = self.source
        blog = source.parent

        summary = get_field(
            blog,
            source.blog_summary_field,
            "",
        )

        if hasattr(summary, "__html__"):
            summary = str(summary.__html__())
        else:
            summary = str(summary)

        blog_author = str(
            get_field(
                blog,
                source.blog_author_field,
                "",
            )
            or ""
        )

        feed = Rss201rev2Feed(
            title=source.feed_name,
            link=url_to(blog, external=True),
            description=summary,
            feed_url=url_to(source, external=True),
            language="en",
        )

        if source.items:
            expression = Expression(ctx.env, source.items)
            items = expression.evaluate(ctx.pad)
        else:
            items = blog.children

        if source.item_model:
            items = items.filter(F._model == source.item_model)

        items = items.order_by(f"-{source.item_date_field}").limit(int(source.limit))

        for item in items:
            item_url = url_to(item, external=True)

            item_author = (
                get_field(
                    item,
                    source.item_author_field,
                )
                or blog_author
            )

            feed.add_item(
                title=get_item_title(
                    item,
                    source.item_title_field,
                ),
                link=item_url,
                description=get_item_body(
                    item,
                    source.item_body_field,
                ),
                author_name=str(item_author),
                pubdate=get_item_date(
                    item,
                    source.item_date_field,
                ),
                unique_id=item_url,
                unique_id_is_permalink=True,
            )

        with artifact.open("wb") as file:
            feed.write(file, "utf-8")


class RssPlugin(Plugin):
    name = "RSS"
    description = "Generate RSS 2.0 feeds."

    defaults = {
        "source_path": "/",
        "name": None,
        "url_path": None,
        "filename": "feed.rss",
        "blog_author_field": "author",
        "blog_summary_field": "summary",
        "items": None,
        "limit": 50,
        "item_title_field": "title",
        "item_body_field": "body",
        "item_author_field": "author",
        "item_date_field": "pub_date",
        "item_model": None,
    }

    def get_rss_config(
        self,
        feed_id: str,
        key: str,
    ) -> Any:
        return self.get_config().get(
            f"{feed_id}.{key}",
            self.defaults[key],
        )

    def on_setup_env(self, **extra: Any) -> None:
        self.env.add_build_program(
            RssFeedSource,
            RssFeedBuilderProgram,
        )

        @self.env.virtualpathresolver("rss")
        def rss_path_resolver(
            node: Any,
            pieces: list[str],
        ) -> RssFeedSource | None:
            if len(pieces) != 1:
                return None

            feed_id = pieces[0]

            if feed_id not in self.get_config().sections():
                return None

            source_path = self.get_rss_config(
                feed_id,
                "source_path",
            )

            if node.path != source_path:
                return None

            return RssFeedSource(
                node,
                feed_id,
                self,
            )

        @self.env.generator
        def generate_rss_feeds(source: Any):
            for feed_id in self.get_config().sections():
                source_path = self.get_rss_config(
                    feed_id,
                    "source_path",
                )

                if source.path == source_path:
                    yield RssFeedSource(
                        source,
                        feed_id,
                        self,
                    )