invenio-feeds 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,148 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # pdm
98
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
99
+ #pdm.lock
100
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
101
+ # in version control.
102
+ # https://pdm.fming.dev/#use-with-ide
103
+ .pdm.toml
104
+
105
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
106
+ __pypackages__/
107
+
108
+ # Celery stuff
109
+ celerybeat-schedule
110
+ celerybeat.pid
111
+
112
+ # SageMath parsed files
113
+ *.sage.py
114
+
115
+ # Environments
116
+ .env
117
+ .venv
118
+ env/
119
+ venv/
120
+ ENV/
121
+ env.bak/
122
+ venv.bak/
123
+
124
+ # Spyder project settings
125
+ .spyderproject
126
+ .spyproject
127
+
128
+ # Rope project settings
129
+ .ropeproject
130
+
131
+ # mkdocs documentation
132
+ /site
133
+
134
+ # mypy
135
+ .mypy_cache/
136
+ .dmypy.json
137
+ dmypy.json
138
+
139
+ # Pyre type checker
140
+ .pyre/
141
+
142
+ # pytype static type analyzer
143
+ .pytype/
144
+
145
+ # Cython debug symbols
146
+ cython_debug/
147
+
148
+ work.md
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023-2026 Front Matter
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.4
2
+ Name: invenio-feeds
3
+ Version: 0.1.0
4
+ Summary: Celery-based feed processing extension for InvenioRDM (Rogue Scholar).
5
+ Project-URL: Homepage, https://rogue-scholar.org
6
+ Project-URL: Repository, https://codeberg.org/front-matter/rogue-scholar-api
7
+ Project-URL: Documentation, https://docs.rogue-scholar.org
8
+ Author-email: Martin Fenner <martin@front-matter.de>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: blogging,celery,inveniordm,science
12
+ Requires-Python: ~=3.14.0
13
+ Requires-Dist: babel<3,>=2.14.0
14
+ Requires-Dist: backoff<3,>=2.2.1
15
+ Requires-Dist: beautifulsoup4<5,>=4.12.2
16
+ Requires-Dist: celery<6,>=5.3
17
+ Requires-Dist: commonmeta-py<1,>=0.223
18
+ Requires-Dist: dateutils<0.7,>=0.6.12
19
+ Requires-Dist: feedparser<7,>=6.0.10
20
+ Requires-Dist: furl<3,>=2.1.3
21
+ Requires-Dist: iso8601<3,>=2.1.0
22
+ Requires-Dist: langdetect<2,>=1.0.9
23
+ Requires-Dist: levenshtein<0.28,>=0.26.0
24
+ Requires-Dist: lxml<7,>=5.1.0
25
+ Requires-Dist: nh3<0.3,>=0.2.14
26
+ Requires-Dist: orjson<4,>=3.9.14
27
+ Requires-Dist: panflute>=2.3.1
28
+ Requires-Dist: paramiko<5,>=4.0.0
29
+ Requires-Dist: pydash~=7.0
30
+ Requires-Dist: pypandoc>=1.17
31
+ Requires-Dist: python-frontmatter~=1.1
32
+ Requires-Dist: requests<3,>=2.32
33
+ Requires-Dist: setuptools>=0.70
34
+ Requires-Dist: structlog>=25.5.0
35
+ Requires-Dist: weasyprint<69,>=67
36
+ Requires-Dist: xmltodict<0.13,>=0.12.0
37
+ Description-Content-Type: text/markdown
38
+
39
+ [![PyPI version](https://img.shields.io/pypi/v/invenio-feeds.svg)](https://pypi.org/project/invenio-feeds/)
40
+ [![docs](https://img.shields.io/badge/docs-passing-blue)](https://docs.rogue-scholar.org)
41
+ ![License](https://img.shields.io/badge/license-MIT-blue?logo=codeberg)
42
+ [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.8433679.svg)](https://doi.org/10.5281/zenodo.8433679)
43
+
44
+ # invenio-feeds
45
+
46
+ Celery-based feed processing extension for [InvenioRDM](https://inveniosoftware.org/products/rdm/), powering the [Rogue Scholar](https://rogue-scholar.org) science blog archive.
47
+
48
+ `invenio-feeds` replaces the former Flask/REST API with Celery workers that periodically fetch blog feeds, normalise posts, and upsert them as InvenioRDM records and communities. It follows the standard `invenio-base` extension pattern and integrates into any InvenioRDM instance.
49
+
50
+ ## Installation
51
+
52
+ Requires Python 3.14. Uses [uv](https://github.com/astral-sh/uv) for dependency management.
53
+
54
+ ```bash
55
+ uv sync
56
+ ```
57
+
58
+ ### Environment variables
59
+
60
+ ```bash
61
+ # InvenioRDM instance to read/write
62
+ FLASK_INVENIORDM_API=https://rogue-scholar.org # default
63
+ FLASK_INVENIORDM_TOKEN=<bearer-token>
64
+ ```
65
+
66
+ ## Running
67
+
68
+ ### Celery worker
69
+
70
+ ```bash
71
+ celery -A invenio_feeds.tasks worker --loglevel=info
72
+ ```
73
+
74
+ ### Celery beat scheduler (periodic tasks)
75
+
76
+ ```bash
77
+ celery -A invenio_feeds.tasks beat --loglevel=info
78
+ ```
79
+
80
+ ### Trigger a feed import manually
81
+
82
+ ```bash
83
+ celery -A invenio_feeds.tasks call invenio_feeds.process_blog_feed --args='["<blog-slug>"]'
84
+ ```
85
+
86
+ ## Scheduled tasks
87
+
88
+ | Task | Schedule | Description |
89
+ |---|---|---|
90
+ | `invenio_feeds.process_all_feeds` | every 30 min | Fan-out: one `process_blog_feed` per active blog |
91
+ | `invenio_feeds.process_blog_feed` | on-demand | Fetch and upsert all new posts for one blog |
92
+ | `invenio_feeds.classify_all_blogs` | daily 03:00 UTC | Fan-out: classify untagged posts per blog |
93
+
94
+ ## Development
95
+
96
+ We use pytest for testing:
97
+
98
+ ```bash
99
+ uv run pytest
100
+ ```
101
+
102
+ Follow along via [Codeberg Issues](https://codeberg.org/front-matter/rogue-scholar-api/issues). Please open an issue if you encounter a bug or have a feature request.
103
+
104
+ ### Note on Patches/Pull Requests
105
+
106
+ - Fork the project
107
+ - Write tests for your new feature or a test that reproduces a bug
108
+ - Implement your feature or make a bug fix
109
+ - Do not mess with Rakefile, version or history
110
+ - Commit, push and make a pull request. Bonus points for topical branches.
111
+
112
+ ## Documentation
113
+
114
+ Documentation (work in progress) for using Rogue Scholar is available at the [Rogue Scholar Documentation](https://docs.rogue-scholar.org/) website.
115
+
116
+ ## Meta
117
+
118
+ Please note that this project is released with a [Contributor Code of Conduct](https://codeberg.org/front-matter/rogue-scholar-api/src/branch/main/CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.
119
+
120
+ License: [MIT](https://codeberg.org/front-matter/rogue-scholar-api/src/branch/main/LICENSE)
@@ -0,0 +1,82 @@
1
+ [![PyPI version](https://img.shields.io/pypi/v/invenio-feeds.svg)](https://pypi.org/project/invenio-feeds/)
2
+ [![docs](https://img.shields.io/badge/docs-passing-blue)](https://docs.rogue-scholar.org)
3
+ ![License](https://img.shields.io/badge/license-MIT-blue?logo=codeberg)
4
+ [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.8433679.svg)](https://doi.org/10.5281/zenodo.8433679)
5
+
6
+ # invenio-feeds
7
+
8
+ Celery-based feed processing extension for [InvenioRDM](https://inveniosoftware.org/products/rdm/), powering the [Rogue Scholar](https://rogue-scholar.org) science blog archive.
9
+
10
+ `invenio-feeds` replaces the former Flask/REST API with Celery workers that periodically fetch blog feeds, normalise posts, and upsert them as InvenioRDM records and communities. It follows the standard `invenio-base` extension pattern and integrates into any InvenioRDM instance.
11
+
12
+ ## Installation
13
+
14
+ Requires Python 3.14. Uses [uv](https://github.com/astral-sh/uv) for dependency management.
15
+
16
+ ```bash
17
+ uv sync
18
+ ```
19
+
20
+ ### Environment variables
21
+
22
+ ```bash
23
+ # InvenioRDM instance to read/write
24
+ FLASK_INVENIORDM_API=https://rogue-scholar.org # default
25
+ FLASK_INVENIORDM_TOKEN=<bearer-token>
26
+ ```
27
+
28
+ ## Running
29
+
30
+ ### Celery worker
31
+
32
+ ```bash
33
+ celery -A invenio_feeds.tasks worker --loglevel=info
34
+ ```
35
+
36
+ ### Celery beat scheduler (periodic tasks)
37
+
38
+ ```bash
39
+ celery -A invenio_feeds.tasks beat --loglevel=info
40
+ ```
41
+
42
+ ### Trigger a feed import manually
43
+
44
+ ```bash
45
+ celery -A invenio_feeds.tasks call invenio_feeds.process_blog_feed --args='["<blog-slug>"]'
46
+ ```
47
+
48
+ ## Scheduled tasks
49
+
50
+ | Task | Schedule | Description |
51
+ |---|---|---|
52
+ | `invenio_feeds.process_all_feeds` | every 30 min | Fan-out: one `process_blog_feed` per active blog |
53
+ | `invenio_feeds.process_blog_feed` | on-demand | Fetch and upsert all new posts for one blog |
54
+ | `invenio_feeds.classify_all_blogs` | daily 03:00 UTC | Fan-out: classify untagged posts per blog |
55
+
56
+ ## Development
57
+
58
+ We use pytest for testing:
59
+
60
+ ```bash
61
+ uv run pytest
62
+ ```
63
+
64
+ Follow along via [Codeberg Issues](https://codeberg.org/front-matter/rogue-scholar-api/issues). Please open an issue if you encounter a bug or have a feature request.
65
+
66
+ ### Note on Patches/Pull Requests
67
+
68
+ - Fork the project
69
+ - Write tests for your new feature or a test that reproduces a bug
70
+ - Implement your feature or make a bug fix
71
+ - Do not mess with Rakefile, version or history
72
+ - Commit, push and make a pull request. Bonus points for topical branches.
73
+
74
+ ## Documentation
75
+
76
+ Documentation (work in progress) for using Rogue Scholar is available at the [Rogue Scholar Documentation](https://docs.rogue-scholar.org/) website.
77
+
78
+ ## Meta
79
+
80
+ Please note that this project is released with a [Contributor Code of Conduct](https://codeberg.org/front-matter/rogue-scholar-api/src/branch/main/CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.
81
+
82
+ License: [MIT](https://codeberg.org/front-matter/rogue-scholar-api/src/branch/main/LICENSE)
@@ -0,0 +1 @@
1
+ """invenio-feeds: Celery-based feed processing for InvenioRDM."""
@@ -0,0 +1,138 @@
1
+ """Blogs module."""
2
+
3
+ import time
4
+ from os import environ
5
+ from urllib.parse import quote
6
+ import requests
7
+ from commonmeta import (
8
+ dig,
9
+ )
10
+ from invenio_feeds.feeds.fetcher import find_feed, parse_generator, parse_feed_format # noqa: F401
11
+ from invenio_feeds.utils import (
12
+ OPENALEX_SUBFIELD_MAPPINGS,
13
+ )
14
+
15
+
16
+ # Reverse map: InvenioRDM feed_format vocab id → MIME type
17
+ _FEED_FORMAT_REVERSE_MAP = {
18
+ "rss": "application/rss+xml",
19
+ "atom": "application/atom+xml",
20
+ "jsonfeed": "application/feed+json",
21
+ }
22
+
23
+
24
+ _opml_cache: tuple[float, str] | None = None
25
+ _OPML_TTL = 3600 # 60 minutes
26
+
27
+
28
+ def _fetch_all_blog_communities(statuses: list[str] | None = None) -> list[dict]:
29
+ """Fetch all InvenioRDM communities matching the given statuses.
30
+
31
+ Paginates through the API and returns a list of minimal blog dicts
32
+ with the fields needed for OPML generation.
33
+ """
34
+ base = environ.get("FLASK_INVENIORDM_API", "https://rogue-scholar.org")
35
+ token = environ.get("FLASK_INVENIORDM_TOKEN")
36
+ if not token:
37
+ return []
38
+ headers = {"Authorization": f"Bearer {token}"}
39
+ # The rs:status field name contains a colon which is special in Lucene query
40
+ # syntax. Backslash-escape it and send the backslash literally (not as %5C)
41
+ # using urllib.parse.quote with safe='\' so requests does not percent-encode it.
42
+ if statuses:
43
+ clauses = " OR ".join(f"custom_fields.rs\\:status.id:{s}" for s in statuses)
44
+ q = quote(f"({clauses})", safe=r"\():. ")
45
+ else:
46
+ q = ""
47
+ results: list[dict] = []
48
+ page, size = 1, 25
49
+ while True:
50
+ try:
51
+ response = requests.get(
52
+ f"{base}/api/communities?q={q}&sort=newest&size={size}&page={page}",
53
+ headers=headers,
54
+ timeout=10,
55
+ )
56
+ response.raise_for_status()
57
+ data = response.json()
58
+ hits = dig(data, "hits.hits") or []
59
+ if not hits:
60
+ break
61
+ for hit in hits:
62
+ cf = hit.get("custom_fields") or {}
63
+ meta = hit.get("metadata") or {}
64
+ subfield_raw = cf.get("rs:subfield")
65
+ subfield_id = None
66
+ if isinstance(subfield_raw, list) and subfield_raw:
67
+ full_id = dig(subfield_raw[0], "id") or ""
68
+ subfield_id = full_id.rsplit("/", 1)[-1] if full_id else None
69
+ results.append(
70
+ {
71
+ "slug": hit.get("slug"),
72
+ "title": meta.get("title"),
73
+ "feed_url": cf.get("rs:feed_url"),
74
+ "home_page_url": meta.get("website"),
75
+ "subfield": subfield_id,
76
+ }
77
+ )
78
+ total = dig(data, "hits.total") or 0
79
+ if page * size >= total:
80
+ break
81
+ page += 1
82
+ except Exception as error:
83
+ print(error)
84
+ break
85
+ return results
86
+
87
+
88
+ def generate_opml(*, force: bool = False) -> str:
89
+ """Generate OPML export for all active blogs, grouped by subfield name.
90
+
91
+ Result is cached for 60 minutes. Pass ``force=True`` to bypass the cache
92
+ and refresh immediately.
93
+ """
94
+ global _opml_cache
95
+ if (
96
+ not force
97
+ and _opml_cache is not None
98
+ and time.monotonic() - _opml_cache[0] < _OPML_TTL
99
+ ):
100
+ return _opml_cache[1]
101
+
102
+ from xml.etree.ElementTree import Element, SubElement, tostring
103
+ from xml.dom.minidom import parseString
104
+
105
+ blogs_data = _fetch_all_blog_communities(statuses=["active"])
106
+
107
+ # Group blogs by subfield name
108
+ groups: dict[str, list[dict]] = {}
109
+ for blog in blogs_data:
110
+ subfield_id = blog.get("subfield") or ""
111
+ subfield_name = OPENALEX_SUBFIELD_MAPPINGS.get(subfield_id, "Uncategorized")
112
+ groups.setdefault(subfield_name, []).append(blog)
113
+
114
+ opml = Element("opml", version="2.0")
115
+ head = SubElement(opml, "head")
116
+ title_el = SubElement(head, "title")
117
+ title_el.text = "Rogue Scholar"
118
+ body = SubElement(opml, "body")
119
+
120
+ for subfield_name in sorted(groups):
121
+ category_el = SubElement(
122
+ body, "outline", text=subfield_name, title=subfield_name
123
+ )
124
+ for blog in sorted(groups[subfield_name], key=lambda b: b.get("title") or ""):
125
+ attrs: dict[str, str] = {
126
+ "type": "rss",
127
+ "text": str(blog.get("title") or blog.get("slug", "")),
128
+ "title": str(blog.get("title") or blog.get("slug", "")),
129
+ "xmlUrl": str(blog.get("feed_url") or ""),
130
+ "htmlUrl": str(blog.get("home_page_url") or ""),
131
+ }
132
+ SubElement(category_el, "outline", attrs)
133
+
134
+ xml_bytes = tostring(opml, encoding="unicode")
135
+ pretty = parseString(xml_bytes).toprettyxml(indent=" ", encoding="UTF-8")
136
+ result = pretty.decode("UTF-8")
137
+ _opml_cache = (time.monotonic(), result)
138
+ return result
@@ -0,0 +1,14 @@
1
+ """Default configuration for invenio-feeds."""
2
+
3
+ from celery.schedules import crontab
4
+
5
+ INVENIO_FEEDS_CELERY_BEAT_SCHEDULE = {
6
+ "invenio-feeds-process-all-feeds": {
7
+ "task": "invenio_feeds.process_all_feeds",
8
+ "schedule": crontab(minute="*/30"),
9
+ },
10
+ "invenio-feeds-classify-all-blogs": {
11
+ "task": "invenio_feeds.classify_all_blogs",
12
+ "schedule": crontab(hour="3", minute="0"),
13
+ },
14
+ }