sermonindex 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.
- sermonindex-0.1.0/LICENSE +21 -0
- sermonindex-0.1.0/PKG-INFO +127 -0
- sermonindex-0.1.0/README.md +112 -0
- sermonindex-0.1.0/pyproject.toml +28 -0
- sermonindex-0.1.0/sermonindex/__init__.py +29 -0
- sermonindex-0.1.0/sermonindex/_books.py +183 -0
- sermonindex-0.1.0/sermonindex/client.py +336 -0
- sermonindex-0.1.0/sermonindex/py.typed +0 -0
- sermonindex-0.1.0/sermonindex.egg-info/PKG-INFO +127 -0
- sermonindex-0.1.0/sermonindex.egg-info/SOURCES.txt +13 -0
- sermonindex-0.1.0/sermonindex.egg-info/dependency_links.txt +1 -0
- sermonindex-0.1.0/sermonindex.egg-info/top_level.txt +1 -0
- sermonindex-0.1.0/setup.cfg +4 -0
- sermonindex-0.1.0/tests/test_live.py +90 -0
- sermonindex-0.1.0/tests/test_unit.py +171 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) SermonIndex.net
|
|
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,127 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sermonindex
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Client for the SermonIndex.net API: sermons, speakers, topics and scripture. Standard library only.
|
|
5
|
+
Author: SermonIndex.net
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://www.sermonindex.net/api/
|
|
8
|
+
Keywords: sermonindex,sermons,bible,api,audio
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Typing :: Typed
|
|
11
|
+
Requires-Python: >=3.9
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Dynamic: license-file
|
|
15
|
+
|
|
16
|
+
# sermonindex
|
|
17
|
+
|
|
18
|
+
A small Python client for the [SermonIndex.net API](https://www.sermonindex.net/api/): sermons, speakers, topics and scripture, over 70,000 sermons that are free to listen to. It uses only the standard library and needs Python 3.9 or later.
|
|
19
|
+
|
|
20
|
+
The API is a set of pre-generated static files. This library only ever makes GET requests, and never adds a query string.
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
pip install sermonindex
|
|
25
|
+
|
|
26
|
+
## Examples
|
|
27
|
+
|
|
28
|
+
Sermons on a verse (the file for a famous verse such as John 3:16 is several megabytes, so ask for a smaller one when you can):
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from sermonindex import SermonIndex
|
|
32
|
+
|
|
33
|
+
si = SermonIndex()
|
|
34
|
+
verse = si.scripture("Romans", 8, 28) # names, abbreviations and codes all work
|
|
35
|
+
print(verse["reference"], verse["sermonCount"])
|
|
36
|
+
for s in verse["sermons"][:5]:
|
|
37
|
+
print(s["title"], "-", s["speaker"])
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
A small summary of what is preached on a whole chapter, light enough for a hover card:
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
cards = si.cards("John", 3) # short keys: v, b, n, c, k, u, w, h, s, t, e, m
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Walk a preacher's sermons, one page of fifty at a time:
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
for sermon in si.speaker_sermons("zac-poonen"):
|
|
50
|
+
print(sermon["title"])
|
|
51
|
+
if "Prayer" in sermon["title"]:
|
|
52
|
+
break # no further pages are fetched
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Play audio, with a fallback:
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
import urllib.request
|
|
59
|
+
|
|
60
|
+
sermon = si.sermon("OTh0VCDnIG3i6wOj")
|
|
61
|
+
for url in si.audio_sources(sermon): # the archive.org copy, then the CDN copy; empty if hasAudio is false
|
|
62
|
+
try:
|
|
63
|
+
urllib.request.urlretrieve(url, "sermon.mp3")
|
|
64
|
+
break
|
|
65
|
+
except OSError:
|
|
66
|
+
continue
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
One random sermon that is certain to have audio:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
r = si.random()
|
|
73
|
+
print(r["title"], r["speaker"], r["mp3Url"])
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Speakers and topics:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
speakers = si.speakers()["speakers"] # about 1.8 MB
|
|
80
|
+
prayer = si.topic("prayer") # several megabytes for the large topics
|
|
81
|
+
stats = si.stats()
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Search the whole library by title, speaker and topic:
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
for hit in si.search("revival", speaker="ravenhill", limit=10):
|
|
88
|
+
print(hit["title"], hit["url"], hit["hasAudio"])
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Things that surprise people
|
|
92
|
+
|
|
93
|
+
- There are no query parameters. A CDN cannot read them, so every page size is a set of real files. Pages hold 500 sermons for the whole library and 50 for a speaker.
|
|
94
|
+
- Follow `next`. `sermons()` and `speaker_sermons()` do this for you. A guessed page path is a bare 404.
|
|
95
|
+
- Only speakers with more than 50 sermons have pages. For the others `speaker_sermons()` falls back to the full record, which for them is small. The full record of a large speaker can be 8 MB, which is why pages are preferred.
|
|
96
|
+
- Audio is Archive first, CDN second. `mp3Url` points at the Archive.org mirror when there is one; `cdnMp3Url` is our own copy. `audio_sources()` returns them in that order.
|
|
97
|
+
- Check `hasAudio`. Text-only sermons carry empty strings in every media field.
|
|
98
|
+
- The book codes are OSIS-style, with `SNG` for Song of Songs and `NAM` for Nahum. `scripture()` and `cards()` accept names such as "Song of Songs", abbreviations such as "SOS" or "Nah", and the codes themselves.
|
|
99
|
+
- A 404 comes back with an HTML page labelled as JSON. The library checks the status first and raises `NotFoundError`.
|
|
100
|
+
- Some speaker slugs contain accents or `&`. Pass the slug as the API gives it; the library percent-encodes it, and if the file is stored under the other Unicode form (composed or decomposed) it tries that too.
|
|
101
|
+
- `topics()` is about 38 MB, and some chapter and verse files are very large. Prefer `topic(slug)`, `sermons()` and `cards()`.
|
|
102
|
+
|
|
103
|
+
## Search
|
|
104
|
+
|
|
105
|
+
`search(query, speaker=None, limit=20)` reads a compact file, `/v2/search-index.json`, once per client and matches in memory. All words must match somewhere in the title, the speaker name or the topic names; a title match ranks above the others. The file is about 3 MB to download and is fetched only when you first search. If it cannot be found, `search()` raises `SearchUnavailableError`; everything else works without it. You can point at another copy with `SermonIndex(search_index_url=...)`.
|
|
106
|
+
|
|
107
|
+
## Options
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
SermonIndex(
|
|
111
|
+
base_url="https://api.sermonindex.net/v2",
|
|
112
|
+
timeout=30.0, # seconds per request
|
|
113
|
+
user_agent="my-app/1.0",
|
|
114
|
+
)
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
A network error is retried once. Errors are `SermonIndexError`, with `NotFoundError` and `SearchUnavailableError` as subclasses. The package carries type hints. Records are returned as plain dictionaries with the API's own field names.
|
|
118
|
+
|
|
119
|
+
## Tests
|
|
120
|
+
|
|
121
|
+
python3 -m unittest
|
|
122
|
+
|
|
123
|
+
The live tests make light read-only requests to the real API; a few pull a file of one to two megabytes.
|
|
124
|
+
|
|
125
|
+
## Terms
|
|
126
|
+
|
|
127
|
+
The sermons are free for personal and ministry use, and not for commercial sale; see [the copying permissions](https://www.sermonindex.net/md/copying-permissions/). The code is MIT licensed.
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# sermonindex
|
|
2
|
+
|
|
3
|
+
A small Python client for the [SermonIndex.net API](https://www.sermonindex.net/api/): sermons, speakers, topics and scripture, over 70,000 sermons that are free to listen to. It uses only the standard library and needs Python 3.9 or later.
|
|
4
|
+
|
|
5
|
+
The API is a set of pre-generated static files. This library only ever makes GET requests, and never adds a query string.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
pip install sermonindex
|
|
10
|
+
|
|
11
|
+
## Examples
|
|
12
|
+
|
|
13
|
+
Sermons on a verse (the file for a famous verse such as John 3:16 is several megabytes, so ask for a smaller one when you can):
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from sermonindex import SermonIndex
|
|
17
|
+
|
|
18
|
+
si = SermonIndex()
|
|
19
|
+
verse = si.scripture("Romans", 8, 28) # names, abbreviations and codes all work
|
|
20
|
+
print(verse["reference"], verse["sermonCount"])
|
|
21
|
+
for s in verse["sermons"][:5]:
|
|
22
|
+
print(s["title"], "-", s["speaker"])
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
A small summary of what is preached on a whole chapter, light enough for a hover card:
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
cards = si.cards("John", 3) # short keys: v, b, n, c, k, u, w, h, s, t, e, m
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Walk a preacher's sermons, one page of fifty at a time:
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
for sermon in si.speaker_sermons("zac-poonen"):
|
|
35
|
+
print(sermon["title"])
|
|
36
|
+
if "Prayer" in sermon["title"]:
|
|
37
|
+
break # no further pages are fetched
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Play audio, with a fallback:
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
import urllib.request
|
|
44
|
+
|
|
45
|
+
sermon = si.sermon("OTh0VCDnIG3i6wOj")
|
|
46
|
+
for url in si.audio_sources(sermon): # the archive.org copy, then the CDN copy; empty if hasAudio is false
|
|
47
|
+
try:
|
|
48
|
+
urllib.request.urlretrieve(url, "sermon.mp3")
|
|
49
|
+
break
|
|
50
|
+
except OSError:
|
|
51
|
+
continue
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
One random sermon that is certain to have audio:
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
r = si.random()
|
|
58
|
+
print(r["title"], r["speaker"], r["mp3Url"])
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Speakers and topics:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
speakers = si.speakers()["speakers"] # about 1.8 MB
|
|
65
|
+
prayer = si.topic("prayer") # several megabytes for the large topics
|
|
66
|
+
stats = si.stats()
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Search the whole library by title, speaker and topic:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
for hit in si.search("revival", speaker="ravenhill", limit=10):
|
|
73
|
+
print(hit["title"], hit["url"], hit["hasAudio"])
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Things that surprise people
|
|
77
|
+
|
|
78
|
+
- There are no query parameters. A CDN cannot read them, so every page size is a set of real files. Pages hold 500 sermons for the whole library and 50 for a speaker.
|
|
79
|
+
- Follow `next`. `sermons()` and `speaker_sermons()` do this for you. A guessed page path is a bare 404.
|
|
80
|
+
- Only speakers with more than 50 sermons have pages. For the others `speaker_sermons()` falls back to the full record, which for them is small. The full record of a large speaker can be 8 MB, which is why pages are preferred.
|
|
81
|
+
- Audio is Archive first, CDN second. `mp3Url` points at the Archive.org mirror when there is one; `cdnMp3Url` is our own copy. `audio_sources()` returns them in that order.
|
|
82
|
+
- Check `hasAudio`. Text-only sermons carry empty strings in every media field.
|
|
83
|
+
- The book codes are OSIS-style, with `SNG` for Song of Songs and `NAM` for Nahum. `scripture()` and `cards()` accept names such as "Song of Songs", abbreviations such as "SOS" or "Nah", and the codes themselves.
|
|
84
|
+
- A 404 comes back with an HTML page labelled as JSON. The library checks the status first and raises `NotFoundError`.
|
|
85
|
+
- Some speaker slugs contain accents or `&`. Pass the slug as the API gives it; the library percent-encodes it, and if the file is stored under the other Unicode form (composed or decomposed) it tries that too.
|
|
86
|
+
- `topics()` is about 38 MB, and some chapter and verse files are very large. Prefer `topic(slug)`, `sermons()` and `cards()`.
|
|
87
|
+
|
|
88
|
+
## Search
|
|
89
|
+
|
|
90
|
+
`search(query, speaker=None, limit=20)` reads a compact file, `/v2/search-index.json`, once per client and matches in memory. All words must match somewhere in the title, the speaker name or the topic names; a title match ranks above the others. The file is about 3 MB to download and is fetched only when you first search. If it cannot be found, `search()` raises `SearchUnavailableError`; everything else works without it. You can point at another copy with `SermonIndex(search_index_url=...)`.
|
|
91
|
+
|
|
92
|
+
## Options
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
SermonIndex(
|
|
96
|
+
base_url="https://api.sermonindex.net/v2",
|
|
97
|
+
timeout=30.0, # seconds per request
|
|
98
|
+
user_agent="my-app/1.0",
|
|
99
|
+
)
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
A network error is retried once. Errors are `SermonIndexError`, with `NotFoundError` and `SearchUnavailableError` as subclasses. The package carries type hints. Records are returned as plain dictionaries with the API's own field names.
|
|
103
|
+
|
|
104
|
+
## Tests
|
|
105
|
+
|
|
106
|
+
python3 -m unittest
|
|
107
|
+
|
|
108
|
+
The live tests make light read-only requests to the real API; a few pull a file of one to two megabytes.
|
|
109
|
+
|
|
110
|
+
## Terms
|
|
111
|
+
|
|
112
|
+
The sermons are free for personal and ministry use, and not for commercial sale; see [the copying permissions](https://www.sermonindex.net/md/copying-permissions/). The code is MIT licensed.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "sermonindex"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Client for the SermonIndex.net API: sermons, speakers, topics and scripture. Standard library only."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "SermonIndex.net" }]
|
|
14
|
+
keywords = ["sermonindex", "sermons", "bible", "api", "audio"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Typing :: Typed",
|
|
18
|
+
]
|
|
19
|
+
dependencies = []
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://www.sermonindex.net/api/"
|
|
23
|
+
|
|
24
|
+
[tool.setuptools]
|
|
25
|
+
packages = ["sermonindex"]
|
|
26
|
+
|
|
27
|
+
[tool.setuptools.package-data]
|
|
28
|
+
sermonindex = ["py.typed"]
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Client for the SermonIndex.net API: sermons, speakers, topics and scripture.
|
|
2
|
+
|
|
3
|
+
Standard library only. The API is a set of static JSON files, so every call is a
|
|
4
|
+
plain GET with no query string.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from ._books import BOOKS, book_name, resolve_book
|
|
8
|
+
from .client import (
|
|
9
|
+
DEFAULT_BASE_URL,
|
|
10
|
+
NotFoundError,
|
|
11
|
+
SearchUnavailableError,
|
|
12
|
+
SermonIndex,
|
|
13
|
+
SermonIndexError,
|
|
14
|
+
audio_sources,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
__version__ = "0.1.0"
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"BOOKS",
|
|
21
|
+
"DEFAULT_BASE_URL",
|
|
22
|
+
"NotFoundError",
|
|
23
|
+
"SearchUnavailableError",
|
|
24
|
+
"SermonIndex",
|
|
25
|
+
"SermonIndexError",
|
|
26
|
+
"audio_sources",
|
|
27
|
+
"book_name",
|
|
28
|
+
"resolve_book",
|
|
29
|
+
]
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Book names and codes as the SermonIndex API spells them (SNG for Song of Solomon, NAM for Nahum)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import unicodedata
|
|
7
|
+
from typing import Dict, List, Optional, Tuple
|
|
8
|
+
|
|
9
|
+
BOOKS: List[Tuple[str, str]] = [
|
|
10
|
+
("GEN", "Genesis"),
|
|
11
|
+
("EXO", "Exodus"),
|
|
12
|
+
("LEV", "Leviticus"),
|
|
13
|
+
("NUM", "Numbers"),
|
|
14
|
+
("DEU", "Deuteronomy"),
|
|
15
|
+
("JOS", "Joshua"),
|
|
16
|
+
("JDG", "Judges"),
|
|
17
|
+
("RUT", "Ruth"),
|
|
18
|
+
("1SA", "1 Samuel"),
|
|
19
|
+
("2SA", "2 Samuel"),
|
|
20
|
+
("1KI", "1 Kings"),
|
|
21
|
+
("2KI", "2 Kings"),
|
|
22
|
+
("1CH", "1 Chronicles"),
|
|
23
|
+
("2CH", "2 Chronicles"),
|
|
24
|
+
("EZR", "Ezra"),
|
|
25
|
+
("NEH", "Nehemiah"),
|
|
26
|
+
("EST", "Esther"),
|
|
27
|
+
("JOB", "Job"),
|
|
28
|
+
("PSA", "Psalms"),
|
|
29
|
+
("PRO", "Proverbs"),
|
|
30
|
+
("ECC", "Ecclesiastes"),
|
|
31
|
+
("SNG", "Song of Solomon"),
|
|
32
|
+
("ISA", "Isaiah"),
|
|
33
|
+
("JER", "Jeremiah"),
|
|
34
|
+
("LAM", "Lamentations"),
|
|
35
|
+
("EZK", "Ezekiel"),
|
|
36
|
+
("DAN", "Daniel"),
|
|
37
|
+
("HOS", "Hosea"),
|
|
38
|
+
("JOL", "Joel"),
|
|
39
|
+
("AMO", "Amos"),
|
|
40
|
+
("OBA", "Obadiah"),
|
|
41
|
+
("JON", "Jonah"),
|
|
42
|
+
("MIC", "Micah"),
|
|
43
|
+
("NAM", "Nahum"),
|
|
44
|
+
("HAB", "Habakkuk"),
|
|
45
|
+
("ZEP", "Zephaniah"),
|
|
46
|
+
("HAG", "Haggai"),
|
|
47
|
+
("ZEC", "Zechariah"),
|
|
48
|
+
("MAL", "Malachi"),
|
|
49
|
+
("MAT", "Matthew"),
|
|
50
|
+
("MRK", "Mark"),
|
|
51
|
+
("LUK", "Luke"),
|
|
52
|
+
("JHN", "John"),
|
|
53
|
+
("ACT", "Acts"),
|
|
54
|
+
("ROM", "Romans"),
|
|
55
|
+
("1CO", "1 Corinthians"),
|
|
56
|
+
("2CO", "2 Corinthians"),
|
|
57
|
+
("GAL", "Galatians"),
|
|
58
|
+
("EPH", "Ephesians"),
|
|
59
|
+
("PHP", "Philippians"),
|
|
60
|
+
("COL", "Colossians"),
|
|
61
|
+
("1TH", "1 Thessalonians"),
|
|
62
|
+
("2TH", "2 Thessalonians"),
|
|
63
|
+
("1TI", "1 Timothy"),
|
|
64
|
+
("2TI", "2 Timothy"),
|
|
65
|
+
("TIT", "Titus"),
|
|
66
|
+
("PHM", "Philemon"),
|
|
67
|
+
("HEB", "Hebrews"),
|
|
68
|
+
("JAS", "James"),
|
|
69
|
+
("1PE", "1 Peter"),
|
|
70
|
+
("2PE", "2 Peter"),
|
|
71
|
+
("1JN", "1 John"),
|
|
72
|
+
("2JN", "2 John"),
|
|
73
|
+
("3JN", "3 John"),
|
|
74
|
+
("JUD", "Jude"),
|
|
75
|
+
("REV", "Revelation"),
|
|
76
|
+
]
|
|
77
|
+
|
|
78
|
+
_ALIASES: Dict[str, List[str]] = {
|
|
79
|
+
"GEN": ["gn","ge"],
|
|
80
|
+
"EXO": ["ex","exod"],
|
|
81
|
+
"LEV": ["lv","le"],
|
|
82
|
+
"NUM": ["nm","nu","numb"],
|
|
83
|
+
"DEU": ["dt","deut","de"],
|
|
84
|
+
"JOS": ["josh"],
|
|
85
|
+
"JDG": ["judg","jg"],
|
|
86
|
+
"RUT": ["ru","rth"],
|
|
87
|
+
"1SA": ["1sam","1sm"],
|
|
88
|
+
"2SA": ["2sam","2sm"],
|
|
89
|
+
"1KI": ["1kgs","1kin"],
|
|
90
|
+
"2KI": ["2kgs","2kin"],
|
|
91
|
+
"1CH": ["1chron","1chr"],
|
|
92
|
+
"2CH": ["2chron","2chr"],
|
|
93
|
+
"NEH": ["ne"],
|
|
94
|
+
"EST": ["esth","es"],
|
|
95
|
+
"JOB": ["jb"],
|
|
96
|
+
"PSA": ["psalm","ps","pslm"],
|
|
97
|
+
"PRO": ["prov","pr","prv"],
|
|
98
|
+
"ECC": ["eccl","eccles","ec","qoh"],
|
|
99
|
+
"SNG": ["song","sos","sg","songofsongs","canticles","cant"],
|
|
100
|
+
"ISA": ["is"],
|
|
101
|
+
"JER": ["je"],
|
|
102
|
+
"LAM": ["la"],
|
|
103
|
+
"EZK": ["ezek","eze"],
|
|
104
|
+
"DAN": ["dn","da"],
|
|
105
|
+
"HOS": ["ho"],
|
|
106
|
+
"JOL": ["jl","joe"],
|
|
107
|
+
"AMO": ["am"],
|
|
108
|
+
"OBA": ["ob","obad"],
|
|
109
|
+
"JON": ["jnh"],
|
|
110
|
+
"MIC": ["mc"],
|
|
111
|
+
"NAM": ["na","nah"],
|
|
112
|
+
"HAB": ["hb"],
|
|
113
|
+
"ZEP": ["zeph","zp"],
|
|
114
|
+
"HAG": ["hg"],
|
|
115
|
+
"ZEC": ["zech","zc"],
|
|
116
|
+
"MAL": ["ml"],
|
|
117
|
+
"MAT": ["mt","matt"],
|
|
118
|
+
"MRK": ["mk","mr"],
|
|
119
|
+
"LUK": ["lk","lu"],
|
|
120
|
+
"JHN": ["jn","joh"],
|
|
121
|
+
"ACT": ["ac"],
|
|
122
|
+
"ROM": ["ro","rm"],
|
|
123
|
+
"1CO": ["1cor"],
|
|
124
|
+
"2CO": ["2cor"],
|
|
125
|
+
"GAL": ["ga"],
|
|
126
|
+
"EPH": ["ep"],
|
|
127
|
+
"PHP": ["phil","pp","philip"],
|
|
128
|
+
"COL": ["co"],
|
|
129
|
+
"1TH": ["1thess","1thes"],
|
|
130
|
+
"2TH": ["2thess","2thes"],
|
|
131
|
+
"1TI": ["1tim"],
|
|
132
|
+
"2TI": ["2tim"],
|
|
133
|
+
"TIT": ["ti"],
|
|
134
|
+
"PHM": ["philem","phlm"],
|
|
135
|
+
"HEB": ["hebrew"],
|
|
136
|
+
"JAS": ["jm","jam"],
|
|
137
|
+
"1PE": ["1pet","1pt"],
|
|
138
|
+
"2PE": ["2pet","2pt"],
|
|
139
|
+
"1JN": ["1jo","1joh"],
|
|
140
|
+
"2JN": ["2jo","2joh"],
|
|
141
|
+
"3JN": ["3jo","3joh"],
|
|
142
|
+
"JUD": ["jude"],
|
|
143
|
+
"REV": ["re","revelations","apocalypse","rv"],
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
_WORDS = (("first", "1"), ("second", "2"), ("third", "3"))
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _norm(s: str) -> str:
|
|
151
|
+
s = unicodedata.normalize("NFD", str(s).lower())
|
|
152
|
+
s = "".join(ch for ch in s if not unicodedata.combining(ch))
|
|
153
|
+
for word, digit in _WORDS:
|
|
154
|
+
s = re.sub(r"\b%s\b" % word, digit, s)
|
|
155
|
+
s = re.sub(r"^iii\b", "3", s)
|
|
156
|
+
s = re.sub(r"^ii\b", "2", s)
|
|
157
|
+
s = re.sub(r"^i\b", "1", s)
|
|
158
|
+
return re.sub(r"[^a-z0-9]", "", s)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
_LOOKUP: Dict[str, str] = {}
|
|
162
|
+
for _code, _list in _ALIASES.items():
|
|
163
|
+
for _a in _list:
|
|
164
|
+
_LOOKUP[_norm(_a)] = _code
|
|
165
|
+
# Full names and codes win over aliases when they collide ("jud" is Jude).
|
|
166
|
+
for _code, _name in BOOKS:
|
|
167
|
+
_LOOKUP[_norm(_name)] = _code
|
|
168
|
+
_LOOKUP[_norm(_code)] = _code
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def book_name(code: str) -> Optional[str]:
|
|
172
|
+
"""The English name for an API book code, or None."""
|
|
173
|
+
for c, n in BOOKS:
|
|
174
|
+
if c == code:
|
|
175
|
+
return n
|
|
176
|
+
return None
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def resolve_book(value: object) -> Optional[str]:
|
|
180
|
+
"""Map a book name, abbreviation or code to the API's code, or None."""
|
|
181
|
+
if value is None:
|
|
182
|
+
return None
|
|
183
|
+
return _LOOKUP.get(_norm(str(value)))
|
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
"""The SermonIndex client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import random as _random
|
|
7
|
+
import socket
|
|
8
|
+
import unicodedata
|
|
9
|
+
import urllib.error
|
|
10
|
+
import urllib.parse
|
|
11
|
+
import urllib.request
|
|
12
|
+
import re
|
|
13
|
+
from typing import Any, Dict, Iterator, List, Mapping, Optional
|
|
14
|
+
|
|
15
|
+
from ._books import resolve_book
|
|
16
|
+
|
|
17
|
+
__version__ = "0.1.0"
|
|
18
|
+
|
|
19
|
+
DEFAULT_BASE_URL = "https://api.sermonindex.net/v2"
|
|
20
|
+
RANDOM_SHARDS = 80
|
|
21
|
+
|
|
22
|
+
JSON = Dict[str, Any]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SermonIndexError(Exception):
|
|
26
|
+
"""Anything that goes wrong talking to the API."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, message: str, url: Optional[str] = None, status: Optional[int] = None) -> None:
|
|
29
|
+
super().__init__(message)
|
|
30
|
+
self.url = url
|
|
31
|
+
self.status = status
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class NotFoundError(SermonIndexError):
|
|
35
|
+
"""The path does not exist. On a static API this is the only "no" you will get."""
|
|
36
|
+
|
|
37
|
+
def __init__(self, url: str) -> None:
|
|
38
|
+
super().__init__("Not found: %s" % url, url=url, status=404)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class SearchUnavailableError(SermonIndexError):
|
|
42
|
+
"""/v2/search-index.json has not been published."""
|
|
43
|
+
|
|
44
|
+
def __init__(self, url: str) -> None:
|
|
45
|
+
super().__init__(
|
|
46
|
+
"Search is not available yet: the search index (%s) has not been published. "
|
|
47
|
+
"Everything else in this library works without it." % url,
|
|
48
|
+
url=url,
|
|
49
|
+
status=404,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _norm_text(value: object) -> str:
|
|
54
|
+
s = unicodedata.normalize("NFD", str(value or "").lower())
|
|
55
|
+
s = "".join(ch for ch in s if not unicodedata.combining(ch))
|
|
56
|
+
return re.sub(r"[\W_]+", " ", s).strip()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def audio_sources(sermon: Optional[Mapping[str, Any]]) -> List[str]:
|
|
60
|
+
"""URLs to try for a sermon's audio, in order: ``mp3Url`` (the Archive.org
|
|
61
|
+
mirror when there is one), then ``cdnMp3Url`` if it is a different address.
|
|
62
|
+
Empty for a text-only sermon."""
|
|
63
|
+
if not sermon or sermon.get("hasAudio") in (False, "false"):
|
|
64
|
+
return []
|
|
65
|
+
out: List[str] = []
|
|
66
|
+
for key in ("mp3Url", "cdnMp3Url"):
|
|
67
|
+
u = sermon.get(key)
|
|
68
|
+
if isinstance(u, str) and u and u not in out:
|
|
69
|
+
out.append(u)
|
|
70
|
+
return out
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class SermonIndex:
|
|
74
|
+
"""A client. Create one and reuse it; the search index is kept per instance."""
|
|
75
|
+
|
|
76
|
+
def __init__(
|
|
77
|
+
self,
|
|
78
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
79
|
+
timeout: float = 30.0,
|
|
80
|
+
user_agent: Optional[str] = None,
|
|
81
|
+
search_index_url: Optional[str] = None,
|
|
82
|
+
) -> None:
|
|
83
|
+
self.base_url = base_url.rstrip("/")
|
|
84
|
+
self.timeout = timeout
|
|
85
|
+
self.user_agent = user_agent or "sermonindex-python/%s (+https://www.sermonindex.net/api/)" % __version__
|
|
86
|
+
self.search_index_url = search_index_url or self.base_url + "/search-index.json"
|
|
87
|
+
self._index: Optional[JSON] = None
|
|
88
|
+
self._index_norm: Optional[JSON] = None
|
|
89
|
+
|
|
90
|
+
# ---- transport --------------------------------------------------------
|
|
91
|
+
|
|
92
|
+
def _get(self, path_or_url: str) -> Any:
|
|
93
|
+
if re.match(r"^https?://", path_or_url, re.I):
|
|
94
|
+
url = path_or_url
|
|
95
|
+
else:
|
|
96
|
+
url = "%s/%s" % (self.base_url, path_or_url.lstrip("/"))
|
|
97
|
+
req = urllib.request.Request(url, headers={"User-Agent": self.user_agent, "Accept": "application/json"})
|
|
98
|
+
last: object = None
|
|
99
|
+
for attempt in range(2):
|
|
100
|
+
try:
|
|
101
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as res:
|
|
102
|
+
body = res.read()
|
|
103
|
+
except urllib.error.HTTPError as err:
|
|
104
|
+
# Check the status before parsing: a 404 body is HTML labelled as JSON.
|
|
105
|
+
if err.code == 404:
|
|
106
|
+
raise NotFoundError(url) from None
|
|
107
|
+
if err.code in (502, 503, 504) and attempt == 0:
|
|
108
|
+
last = err
|
|
109
|
+
continue
|
|
110
|
+
raise SermonIndexError("HTTP %d from %s" % (err.code, url), url=url, status=err.code) from None
|
|
111
|
+
except (urllib.error.URLError, socket.timeout, ConnectionError, TimeoutError) as err:
|
|
112
|
+
last = err
|
|
113
|
+
continue # a transient network error: one more try
|
|
114
|
+
try:
|
|
115
|
+
return json.loads(body.decode("utf-8"))
|
|
116
|
+
except ValueError as err:
|
|
117
|
+
raise SermonIndexError("Response from %s was not JSON" % url, url=url) from err
|
|
118
|
+
raise SermonIndexError("Could not reach %s: %s" % (url, last), url=url)
|
|
119
|
+
|
|
120
|
+
def _get_by_slug(self, prefix: str, slug: str, suffix: str = "") -> Any:
|
|
121
|
+
# The files are named in whichever Unicode form the build wrote: try ours, then both.
|
|
122
|
+
tries = [str(slug)]
|
|
123
|
+
for form in ("NFD", "NFC"):
|
|
124
|
+
t = unicodedata.normalize(form, str(slug))
|
|
125
|
+
if t not in tries:
|
|
126
|
+
tries.append(t)
|
|
127
|
+
err: Optional[NotFoundError] = None
|
|
128
|
+
for t in tries:
|
|
129
|
+
try:
|
|
130
|
+
return self._get("%s/%s%s" % (prefix, urllib.parse.quote(t, safe=""), suffix))
|
|
131
|
+
except NotFoundError as e:
|
|
132
|
+
err = e
|
|
133
|
+
assert err is not None
|
|
134
|
+
raise err
|
|
135
|
+
|
|
136
|
+
# ---- the API ----------------------------------------------------------
|
|
137
|
+
|
|
138
|
+
def stats(self) -> JSON:
|
|
139
|
+
return self._get("stats")
|
|
140
|
+
|
|
141
|
+
def speakers(self) -> JSON:
|
|
142
|
+
"""All speakers as ``{"count": n, "speakers": [...]}``. About 1.8 MB."""
|
|
143
|
+
return self._get("speakers")
|
|
144
|
+
|
|
145
|
+
def speaker(self, slug: str) -> JSON:
|
|
146
|
+
"""One speaker with every sermon. Zac Poonen's record is about 8 MB; prefer speaker_sermons()."""
|
|
147
|
+
return self._get_by_slug("speakers", slug)
|
|
148
|
+
|
|
149
|
+
def speaker_sermons(self, slug: str) -> Iterator[JSON]:
|
|
150
|
+
"""Iterate a speaker's sermons, following each page's ``next`` link.
|
|
151
|
+
|
|
152
|
+
Only speakers with more than 50 sermons have pages; for the rest the
|
|
153
|
+
full record (which is small for them) is used."""
|
|
154
|
+
try:
|
|
155
|
+
page: Optional[JSON] = self._get_by_slug("speakers", slug, "/page/1")
|
|
156
|
+
except NotFoundError:
|
|
157
|
+
record = self.speaker(slug) # raises NotFoundError if there is no such speaker
|
|
158
|
+
for s in record.get("sermons") or []:
|
|
159
|
+
yield s
|
|
160
|
+
return
|
|
161
|
+
while page:
|
|
162
|
+
for s in page.get("sermons") or []:
|
|
163
|
+
yield s
|
|
164
|
+
page = self._get(page["next"]) if page.get("next") else None
|
|
165
|
+
|
|
166
|
+
def sermon(self, sermon_id: str) -> JSON:
|
|
167
|
+
"""One sermon, full record (the transcript is included, so it can be large)."""
|
|
168
|
+
return self._get("sermons/%s" % urllib.parse.quote(str(sermon_id), safe=""))
|
|
169
|
+
|
|
170
|
+
def sermons(self) -> Iterator[JSON]:
|
|
171
|
+
"""Iterate the whole library, 500 a page, following ``next``."""
|
|
172
|
+
page: Optional[JSON] = self._get("sermons/page/1")
|
|
173
|
+
while page:
|
|
174
|
+
for s in page.get("sermons") or []:
|
|
175
|
+
yield s
|
|
176
|
+
page = self._get(page["next"]) if page.get("next") else None
|
|
177
|
+
|
|
178
|
+
def topics(self) -> JSON:
|
|
179
|
+
"""All topics. This file is about 38 MB; most callers want topic()."""
|
|
180
|
+
return self._get("topics")
|
|
181
|
+
|
|
182
|
+
def topic(self, slug: str) -> JSON:
|
|
183
|
+
return self._get_by_slug("topics", slug)
|
|
184
|
+
|
|
185
|
+
def scripture(self, book: Optional[str] = None, chapter: Optional[int] = None, verse: Optional[int] = None) -> JSON:
|
|
186
|
+
"""The scripture index, or sermons on a book, chapter or verse.
|
|
187
|
+
|
|
188
|
+
``book`` may be a name, an abbreviation or the API's own code ("John",
|
|
189
|
+
"Jn", "JHN", "Song of Songs", "SNG"). Chapter and verse files can be
|
|
190
|
+
several megabytes for well-loved passages."""
|
|
191
|
+
if book is None:
|
|
192
|
+
return self._get("scripture")
|
|
193
|
+
code = self._book(book)
|
|
194
|
+
if chapter is None:
|
|
195
|
+
if verse is not None:
|
|
196
|
+
raise TypeError("A verse needs a chapter.")
|
|
197
|
+
return self._get("scripture/%s" % code)
|
|
198
|
+
ch = self._num(chapter, "chapter")
|
|
199
|
+
if verse is None:
|
|
200
|
+
return self._get("scripture/%s/%d" % (code, ch))
|
|
201
|
+
return self._get("scripture/%s/%d/%d" % (code, ch, self._num(verse, "verse")))
|
|
202
|
+
|
|
203
|
+
def cards(self, book: str, chapter: int) -> JSON:
|
|
204
|
+
"""The slim per-chapter summary; keys v, b, n, c, k, u, w, h, s, t, e, m."""
|
|
205
|
+
return self._get("cards/%s/%d" % (self._book(book), self._num(chapter, "chapter")))
|
|
206
|
+
|
|
207
|
+
def random(self) -> JSON:
|
|
208
|
+
"""One playable sermon from the random pool, with readable key names."""
|
|
209
|
+
try:
|
|
210
|
+
data = self._get("random/%d" % _random.randint(1, RANDOM_SHARDS))
|
|
211
|
+
except NotFoundError:
|
|
212
|
+
data = self._get("random/1") # the pool may be smaller than 80 shards
|
|
213
|
+
pool = data.get("sermons") or []
|
|
214
|
+
if not pool:
|
|
215
|
+
raise SermonIndexError("The random pool was empty.")
|
|
216
|
+
r = _random.choice(pool)
|
|
217
|
+
audio = r.get("a") or r.get("c") or ""
|
|
218
|
+
archive = audio if re.match(r"^https?://(www\.)?archive\.org/", audio) else ""
|
|
219
|
+
p, v = r.get("p"), r.get("v")
|
|
220
|
+
return {
|
|
221
|
+
"id": r.get("i"),
|
|
222
|
+
"title": r.get("t"),
|
|
223
|
+
"url": r.get("u"),
|
|
224
|
+
"speaker": r.get("s"),
|
|
225
|
+
"speakerSlug": r.get("g"),
|
|
226
|
+
"speakerImage": r.get("m"),
|
|
227
|
+
"duration": r.get("d"),
|
|
228
|
+
"summary": r.get("y"),
|
|
229
|
+
"hasAudio": bool(audio),
|
|
230
|
+
"mp3Url": audio,
|
|
231
|
+
"archiveAudioUrl": archive,
|
|
232
|
+
"cdnMp3Url": r.get("c") or ("" if archive else audio),
|
|
233
|
+
"topic": {"name": p[0], "slug": p[1]} if isinstance(p, list) and len(p) >= 2 else None,
|
|
234
|
+
"scripture": {"text": v[0], "path": v[1]} if isinstance(v, list) and len(v) >= 2 else None,
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
def audio_sources(self, sermon: Optional[Mapping[str, Any]]) -> List[str]:
|
|
238
|
+
return audio_sources(sermon)
|
|
239
|
+
|
|
240
|
+
# ---- search -----------------------------------------------------------
|
|
241
|
+
|
|
242
|
+
def load_search_index(self) -> JSON:
|
|
243
|
+
"""Download the search index once per client and keep it in memory."""
|
|
244
|
+
if self._index is None:
|
|
245
|
+
try:
|
|
246
|
+
raw = self._get(self.search_index_url)
|
|
247
|
+
except NotFoundError:
|
|
248
|
+
raise SearchUnavailableError(self.search_index_url) from None
|
|
249
|
+
if not (isinstance(raw, dict) and all(isinstance(raw.get(k), list) for k in ("sermons", "speakers", "topics"))):
|
|
250
|
+
raise SermonIndexError(
|
|
251
|
+
"The search index at %s has an unexpected shape." % self.search_index_url, url=self.search_index_url
|
|
252
|
+
)
|
|
253
|
+
self._index = raw
|
|
254
|
+
self._index_norm = {
|
|
255
|
+
"speakers": [_norm_text(s[1]) for s in raw["speakers"]],
|
|
256
|
+
"topics": [_norm_text(t[1]) for t in raw["topics"]],
|
|
257
|
+
"titles": [_norm_text(s[1]) for s in raw["sermons"]],
|
|
258
|
+
}
|
|
259
|
+
return self._index
|
|
260
|
+
|
|
261
|
+
def search(self, query: str, speaker: Optional[str] = None, limit: int = 20) -> List[JSON]:
|
|
262
|
+
"""Sermons whose title, speaker or topics contain every word of the query.
|
|
263
|
+
|
|
264
|
+
A title match ranks above a speaker or topic match. Raises
|
|
265
|
+
SearchUnavailableError while the search index is not published."""
|
|
266
|
+
raw = self.load_search_index()
|
|
267
|
+
norm = self._index_norm or {}
|
|
268
|
+
q = _norm_text(query)
|
|
269
|
+
words = q.split(" ") if q else []
|
|
270
|
+
if not words:
|
|
271
|
+
return []
|
|
272
|
+
spk = _norm_text(speaker) if speaker else ""
|
|
273
|
+
hits = []
|
|
274
|
+
for i, row in enumerate(raw["sermons"]):
|
|
275
|
+
sp_idx, flags, topic_idx = row[2], row[4], row[5] or []
|
|
276
|
+
sp_slug = raw["speakers"][sp_idx][0] if sp_idx < len(raw["speakers"]) else ""
|
|
277
|
+
sn = norm["speakers"][sp_idx] if sp_idx < len(raw["speakers"]) else ""
|
|
278
|
+
if spk and not (_norm_text(sp_slug) == spk or spk in sn):
|
|
279
|
+
continue
|
|
280
|
+
t = norm["titles"][i]
|
|
281
|
+
tn = [norm["topics"][k] if k < len(norm["topics"]) else "" for k in topic_idx]
|
|
282
|
+
score = 0
|
|
283
|
+
for w in words:
|
|
284
|
+
in_t, in_s, in_p = w in t, w in sn, any(w in x for x in tn)
|
|
285
|
+
if not (in_t or in_s or in_p):
|
|
286
|
+
break
|
|
287
|
+
if in_t:
|
|
288
|
+
score += 3 + (1 if (" %s " % w) in (" %s " % t) else 0)
|
|
289
|
+
if in_s:
|
|
290
|
+
score += 1
|
|
291
|
+
if in_p:
|
|
292
|
+
score += 1
|
|
293
|
+
else:
|
|
294
|
+
if len(words) > 1 and q in t:
|
|
295
|
+
score += 2
|
|
296
|
+
hits.append((score, flags & 1, i))
|
|
297
|
+
hits.sort(key=lambda h: (-h[0], -h[1], h[2]))
|
|
298
|
+
site = (raw.get("site") or "https://www.sermonindex.net").rstrip("/")
|
|
299
|
+
out: List[JSON] = []
|
|
300
|
+
for score, _, i in hits[: max(0, limit)]:
|
|
301
|
+
sid, title, sp_idx, slug, flags, topic_idx = raw["sermons"][i]
|
|
302
|
+
sp_slug, sp_name = raw["speakers"][sp_idx] if sp_idx < len(raw["speakers"]) else ("", "")
|
|
303
|
+
path = slug if "/" in str(slug) else "%s/%s" % (sp_slug, slug)
|
|
304
|
+
out.append(
|
|
305
|
+
{
|
|
306
|
+
"id": sid,
|
|
307
|
+
"title": title,
|
|
308
|
+
"speaker": sp_name,
|
|
309
|
+
"speakerSlug": sp_slug,
|
|
310
|
+
"url": "%s/speakers/%s/" % (site, path),
|
|
311
|
+
"hasAudio": bool(flags & 1),
|
|
312
|
+
"hasVideo": bool(flags & 2),
|
|
313
|
+
"topics": [{"slug": raw["topics"][k][0], "name": raw["topics"][k][1]} for k in (topic_idx or []) if k < len(raw["topics"])],
|
|
314
|
+
"score": score,
|
|
315
|
+
}
|
|
316
|
+
)
|
|
317
|
+
return out
|
|
318
|
+
|
|
319
|
+
# ---- helpers ----------------------------------------------------------
|
|
320
|
+
|
|
321
|
+
@staticmethod
|
|
322
|
+
def _book(book: object) -> str:
|
|
323
|
+
code = resolve_book(book)
|
|
324
|
+
if not code:
|
|
325
|
+
raise ValueError('Unknown book: %r. Use a name such as "John" or a code such as "JHN".' % (book,))
|
|
326
|
+
return code
|
|
327
|
+
|
|
328
|
+
@staticmethod
|
|
329
|
+
def _num(n: object, what: str) -> int:
|
|
330
|
+
try:
|
|
331
|
+
v = int(n) # type: ignore[call-overload]
|
|
332
|
+
except (TypeError, ValueError):
|
|
333
|
+
v = 0
|
|
334
|
+
if v < 1 or isinstance(n, bool):
|
|
335
|
+
raise ValueError("The %s must be a positive whole number, not %r." % (what, n))
|
|
336
|
+
return v
|
|
File without changes
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sermonindex
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Client for the SermonIndex.net API: sermons, speakers, topics and scripture. Standard library only.
|
|
5
|
+
Author: SermonIndex.net
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://www.sermonindex.net/api/
|
|
8
|
+
Keywords: sermonindex,sermons,bible,api,audio
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Typing :: Typed
|
|
11
|
+
Requires-Python: >=3.9
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Dynamic: license-file
|
|
15
|
+
|
|
16
|
+
# sermonindex
|
|
17
|
+
|
|
18
|
+
A small Python client for the [SermonIndex.net API](https://www.sermonindex.net/api/): sermons, speakers, topics and scripture, over 70,000 sermons that are free to listen to. It uses only the standard library and needs Python 3.9 or later.
|
|
19
|
+
|
|
20
|
+
The API is a set of pre-generated static files. This library only ever makes GET requests, and never adds a query string.
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
pip install sermonindex
|
|
25
|
+
|
|
26
|
+
## Examples
|
|
27
|
+
|
|
28
|
+
Sermons on a verse (the file for a famous verse such as John 3:16 is several megabytes, so ask for a smaller one when you can):
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from sermonindex import SermonIndex
|
|
32
|
+
|
|
33
|
+
si = SermonIndex()
|
|
34
|
+
verse = si.scripture("Romans", 8, 28) # names, abbreviations and codes all work
|
|
35
|
+
print(verse["reference"], verse["sermonCount"])
|
|
36
|
+
for s in verse["sermons"][:5]:
|
|
37
|
+
print(s["title"], "-", s["speaker"])
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
A small summary of what is preached on a whole chapter, light enough for a hover card:
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
cards = si.cards("John", 3) # short keys: v, b, n, c, k, u, w, h, s, t, e, m
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Walk a preacher's sermons, one page of fifty at a time:
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
for sermon in si.speaker_sermons("zac-poonen"):
|
|
50
|
+
print(sermon["title"])
|
|
51
|
+
if "Prayer" in sermon["title"]:
|
|
52
|
+
break # no further pages are fetched
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Play audio, with a fallback:
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
import urllib.request
|
|
59
|
+
|
|
60
|
+
sermon = si.sermon("OTh0VCDnIG3i6wOj")
|
|
61
|
+
for url in si.audio_sources(sermon): # the archive.org copy, then the CDN copy; empty if hasAudio is false
|
|
62
|
+
try:
|
|
63
|
+
urllib.request.urlretrieve(url, "sermon.mp3")
|
|
64
|
+
break
|
|
65
|
+
except OSError:
|
|
66
|
+
continue
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
One random sermon that is certain to have audio:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
r = si.random()
|
|
73
|
+
print(r["title"], r["speaker"], r["mp3Url"])
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Speakers and topics:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
speakers = si.speakers()["speakers"] # about 1.8 MB
|
|
80
|
+
prayer = si.topic("prayer") # several megabytes for the large topics
|
|
81
|
+
stats = si.stats()
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Search the whole library by title, speaker and topic:
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
for hit in si.search("revival", speaker="ravenhill", limit=10):
|
|
88
|
+
print(hit["title"], hit["url"], hit["hasAudio"])
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Things that surprise people
|
|
92
|
+
|
|
93
|
+
- There are no query parameters. A CDN cannot read them, so every page size is a set of real files. Pages hold 500 sermons for the whole library and 50 for a speaker.
|
|
94
|
+
- Follow `next`. `sermons()` and `speaker_sermons()` do this for you. A guessed page path is a bare 404.
|
|
95
|
+
- Only speakers with more than 50 sermons have pages. For the others `speaker_sermons()` falls back to the full record, which for them is small. The full record of a large speaker can be 8 MB, which is why pages are preferred.
|
|
96
|
+
- Audio is Archive first, CDN second. `mp3Url` points at the Archive.org mirror when there is one; `cdnMp3Url` is our own copy. `audio_sources()` returns them in that order.
|
|
97
|
+
- Check `hasAudio`. Text-only sermons carry empty strings in every media field.
|
|
98
|
+
- The book codes are OSIS-style, with `SNG` for Song of Songs and `NAM` for Nahum. `scripture()` and `cards()` accept names such as "Song of Songs", abbreviations such as "SOS" or "Nah", and the codes themselves.
|
|
99
|
+
- A 404 comes back with an HTML page labelled as JSON. The library checks the status first and raises `NotFoundError`.
|
|
100
|
+
- Some speaker slugs contain accents or `&`. Pass the slug as the API gives it; the library percent-encodes it, and if the file is stored under the other Unicode form (composed or decomposed) it tries that too.
|
|
101
|
+
- `topics()` is about 38 MB, and some chapter and verse files are very large. Prefer `topic(slug)`, `sermons()` and `cards()`.
|
|
102
|
+
|
|
103
|
+
## Search
|
|
104
|
+
|
|
105
|
+
`search(query, speaker=None, limit=20)` reads a compact file, `/v2/search-index.json`, once per client and matches in memory. All words must match somewhere in the title, the speaker name or the topic names; a title match ranks above the others. The file is about 3 MB to download and is fetched only when you first search. If it cannot be found, `search()` raises `SearchUnavailableError`; everything else works without it. You can point at another copy with `SermonIndex(search_index_url=...)`.
|
|
106
|
+
|
|
107
|
+
## Options
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
SermonIndex(
|
|
111
|
+
base_url="https://api.sermonindex.net/v2",
|
|
112
|
+
timeout=30.0, # seconds per request
|
|
113
|
+
user_agent="my-app/1.0",
|
|
114
|
+
)
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
A network error is retried once. Errors are `SermonIndexError`, with `NotFoundError` and `SearchUnavailableError` as subclasses. The package carries type hints. Records are returned as plain dictionaries with the API's own field names.
|
|
118
|
+
|
|
119
|
+
## Tests
|
|
120
|
+
|
|
121
|
+
python3 -m unittest
|
|
122
|
+
|
|
123
|
+
The live tests make light read-only requests to the real API; a few pull a file of one to two megabytes.
|
|
124
|
+
|
|
125
|
+
## Terms
|
|
126
|
+
|
|
127
|
+
The sermons are free for personal and ministry use, and not for commercial sale; see [the copying permissions](https://www.sermonindex.net/md/copying-permissions/). The code is MIT licensed.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
sermonindex/__init__.py
|
|
5
|
+
sermonindex/_books.py
|
|
6
|
+
sermonindex/client.py
|
|
7
|
+
sermonindex/py.typed
|
|
8
|
+
sermonindex.egg-info/PKG-INFO
|
|
9
|
+
sermonindex.egg-info/SOURCES.txt
|
|
10
|
+
sermonindex.egg-info/dependency_links.txt
|
|
11
|
+
sermonindex.egg-info/top_level.txt
|
|
12
|
+
tests/test_live.py
|
|
13
|
+
tests/test_unit.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
sermonindex
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Live tests: light read-only GETs against https://api.sermonindex.net/v2."""
|
|
2
|
+
import unittest
|
|
3
|
+
|
|
4
|
+
from sermonindex import NotFoundError, SearchUnavailableError, SermonIndex, audio_sources
|
|
5
|
+
|
|
6
|
+
si = SermonIndex()
|
|
7
|
+
SMALL = "aaron-clark" # one sermon, no pages
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Live(unittest.TestCase):
|
|
11
|
+
def test_stats(self):
|
|
12
|
+
s = si.stats()
|
|
13
|
+
self.assertGreater(s["sermons"], 60000)
|
|
14
|
+
|
|
15
|
+
def test_speakers(self):
|
|
16
|
+
d = si.speakers()
|
|
17
|
+
self.assertEqual(d["count"], len(d["speakers"]))
|
|
18
|
+
self.assertTrue(any(x["slug"] == "zac-poonen" for x in d["speakers"]))
|
|
19
|
+
|
|
20
|
+
def test_speaker_and_sermon(self):
|
|
21
|
+
sp = si.speaker(SMALL)
|
|
22
|
+
self.assertEqual(len(sp["sermons"]), sp["sermonCount"])
|
|
23
|
+
full = si.sermon(sp["sermons"][0]["id"])
|
|
24
|
+
self.assertEqual(full["id"], sp["sermons"][0]["id"])
|
|
25
|
+
|
|
26
|
+
def test_speaker_sermons_without_pages(self):
|
|
27
|
+
self.assertEqual(len(list(si.speaker_sermons(SMALL))), 1)
|
|
28
|
+
|
|
29
|
+
def test_speaker_sermons_follows_next(self):
|
|
30
|
+
seen = []
|
|
31
|
+
client = SermonIndex()
|
|
32
|
+
orig = client._get
|
|
33
|
+
client._get = lambda p: (seen.append(p), orig(p))[1]
|
|
34
|
+
n = 0
|
|
35
|
+
for s in client.speaker_sermons("zac-poonen"):
|
|
36
|
+
self.assertEqual(s["speakerSlug"], "zac-poonen")
|
|
37
|
+
n += 1
|
|
38
|
+
if n == 51:
|
|
39
|
+
break
|
|
40
|
+
pages = [p for p in seen if "/page/" in p]
|
|
41
|
+
self.assertEqual(len(pages), 2)
|
|
42
|
+
first = orig(pages[0])
|
|
43
|
+
self.assertEqual(first["next"], pages[1])
|
|
44
|
+
|
|
45
|
+
def test_sermons_first_page(self):
|
|
46
|
+
it = si.sermons()
|
|
47
|
+
self.assertIn("id", next(it))
|
|
48
|
+
|
|
49
|
+
def test_non_ascii_and_ampersand_slugs(self):
|
|
50
|
+
sp = si.speaker("harald-lindström")
|
|
51
|
+
self.assertEqual(len(sp["sermons"]), sp["sermonCount"])
|
|
52
|
+
self.assertGreater(si.speaker("from-the-pulpit-&-classic-sermons")["sermonCount"], 0)
|
|
53
|
+
|
|
54
|
+
def test_topic(self):
|
|
55
|
+
self.assertEqual(si.topic("evangelization")["slug"], "evangelization")
|
|
56
|
+
|
|
57
|
+
def test_scripture(self):
|
|
58
|
+
a = si.scripture("SNG", 1)
|
|
59
|
+
self.assertEqual(a["bookId"], "SNG")
|
|
60
|
+
self.assertEqual(si.scripture("Song of Songs", 1)["sermonCount"], a["sermonCount"])
|
|
61
|
+
self.assertEqual(si.scripture("Nahum", 1)["bookId"], "NAM")
|
|
62
|
+
self.assertTrue(si.scripture())
|
|
63
|
+
|
|
64
|
+
def test_cards(self):
|
|
65
|
+
c = si.cards("John", 3)
|
|
66
|
+
self.assertEqual((c["b"], c["c"]), ("JHN", 3))
|
|
67
|
+
for k in "v b n c k u w h s t e m".split():
|
|
68
|
+
self.assertIn(k, c)
|
|
69
|
+
|
|
70
|
+
def test_random(self):
|
|
71
|
+
r = si.random()
|
|
72
|
+
self.assertTrue(r["hasAudio"])
|
|
73
|
+
self.assertEqual(audio_sources(r)[0], r["mp3Url"])
|
|
74
|
+
|
|
75
|
+
def test_404(self):
|
|
76
|
+
with self.assertRaises(NotFoundError) as cm:
|
|
77
|
+
si.speaker("no-such-speaker-xyz")
|
|
78
|
+
self.assertEqual(cm.exception.status, 404)
|
|
79
|
+
with self.assertRaises(NotFoundError):
|
|
80
|
+
si.sermon("doesnotexist0000")
|
|
81
|
+
|
|
82
|
+
def test_search_is_clear_while_unpublished(self):
|
|
83
|
+
try:
|
|
84
|
+
si.search("grace")
|
|
85
|
+
except SearchUnavailableError as e:
|
|
86
|
+
self.assertIn("not available yet", str(e))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
if __name__ == "__main__":
|
|
90
|
+
unittest.main()
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""Offline tests against a small local HTTP server."""
|
|
2
|
+
import http.server
|
|
3
|
+
import json
|
|
4
|
+
import threading
|
|
5
|
+
import unittest
|
|
6
|
+
from typing import Dict
|
|
7
|
+
|
|
8
|
+
from sermonindex import (
|
|
9
|
+
NotFoundError,
|
|
10
|
+
SearchUnavailableError,
|
|
11
|
+
SermonIndex,
|
|
12
|
+
SermonIndexError,
|
|
13
|
+
audio_sources,
|
|
14
|
+
resolve_book,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
FIXTURE = {
|
|
18
|
+
"v": 1,
|
|
19
|
+
"generated": "2026-11-26T00:00:00Z",
|
|
20
|
+
"count": 4,
|
|
21
|
+
"site": "https://www.sermonindex.net",
|
|
22
|
+
"speakers": [["leonard-ravenhill", "Leonard Ravenhill"], ["zac-poonen", "Zac Poonen"], ["harald-lindström", "Harald Lindström"]],
|
|
23
|
+
"topics": [["prayer", "Prayer"], ["revival", "Revival"], ["humility", "Humility"]],
|
|
24
|
+
"sermons": [
|
|
25
|
+
["id000000000000a1", "Why Revival Tarries", 0, "why-revival-tarries", 1, [1]],
|
|
26
|
+
["id000000000000a2", "The Life of Prayer", 1, "the-life-of-prayer", 3, [0, 2]],
|
|
27
|
+
["id000000000000a3", "Sodom Had No Bible", 0, "sodom-had-no-bible", 2, [0]],
|
|
28
|
+
["id000000000000a4", "Quiet Hearts", 2, "harald/extra/quiet-hearts", 1, []],
|
|
29
|
+
],
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
ROUTES: Dict[str, object] = {}
|
|
33
|
+
HITS = []
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Handler(http.server.BaseHTTPRequestHandler):
|
|
37
|
+
def do_GET(self):
|
|
38
|
+
HITS.append(self.path)
|
|
39
|
+
if self.path in ROUTES:
|
|
40
|
+
body = json.dumps(ROUTES[self.path]).encode()
|
|
41
|
+
self.send_response(200)
|
|
42
|
+
else:
|
|
43
|
+
body = b"<html><body>404 - File Not Found</body></html>"
|
|
44
|
+
self.send_response(404)
|
|
45
|
+
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
46
|
+
self.send_header("Content-Length", str(len(body)))
|
|
47
|
+
self.end_headers()
|
|
48
|
+
self.wfile.write(body)
|
|
49
|
+
|
|
50
|
+
def log_message(self, *a):
|
|
51
|
+
pass
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Base(unittest.TestCase):
|
|
55
|
+
@classmethod
|
|
56
|
+
def setUpClass(cls):
|
|
57
|
+
cls.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
|
58
|
+
cls.base = "http://127.0.0.1:%d/v2" % cls.server.server_address[1]
|
|
59
|
+
threading.Thread(target=cls.server.serve_forever, daemon=True).start()
|
|
60
|
+
|
|
61
|
+
@classmethod
|
|
62
|
+
def tearDownClass(cls):
|
|
63
|
+
cls.server.shutdown()
|
|
64
|
+
cls.server.server_close()
|
|
65
|
+
|
|
66
|
+
def setUp(self):
|
|
67
|
+
ROUTES.clear()
|
|
68
|
+
HITS.clear()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class SearchTests(Base):
|
|
72
|
+
def client(self):
|
|
73
|
+
ROUTES["/v2/search-index.json"] = FIXTURE
|
|
74
|
+
return SermonIndex(base_url=self.base)
|
|
75
|
+
|
|
76
|
+
def test_ranking_and_and(self):
|
|
77
|
+
si = self.client()
|
|
78
|
+
r = si.search("revival")
|
|
79
|
+
self.assertEqual([x["id"] for x in r], ["id000000000000a1"])
|
|
80
|
+
self.assertEqual(r[0]["url"], "https://www.sermonindex.net/speakers/leonard-ravenhill/why-revival-tarries/")
|
|
81
|
+
self.assertTrue(r[0]["hasAudio"])
|
|
82
|
+
self.assertFalse(r[0]["hasVideo"])
|
|
83
|
+
self.assertEqual(r[0]["topics"], [{"slug": "revival", "name": "Revival"}])
|
|
84
|
+
self.assertEqual([x["id"] for x in si.search("ravenhill prayer")], ["id000000000000a3"])
|
|
85
|
+
|
|
86
|
+
def test_title_beats_speaker(self):
|
|
87
|
+
si = self.client()
|
|
88
|
+
ROUTES["/v2/search-index.json"] = dict(FIXTURE, sermons=FIXTURE["sermons"] + [["id000000000000a5", "Ravenhill on Fire", 1, "ravenhill-on-fire", 1, []]])
|
|
89
|
+
si = SermonIndex(base_url=self.base)
|
|
90
|
+
self.assertEqual(si.search("ravenhill")[0]["id"], "id000000000000a5")
|
|
91
|
+
|
|
92
|
+
def test_filters_limit_accents_slash_slug(self):
|
|
93
|
+
si = self.client()
|
|
94
|
+
self.assertEqual(len(si.search("prayer", speaker="zac")), 1)
|
|
95
|
+
self.assertEqual(len(si.search("prayer", limit=1)), 1)
|
|
96
|
+
self.assertEqual(si.search("lindstrom quiet")[0]["url"], "https://www.sermonindex.net/speakers/harald/extra/quiet-hearts/")
|
|
97
|
+
self.assertTrue(si.search("life")[0]["hasVideo"])
|
|
98
|
+
self.assertEqual(si.search(" "), [])
|
|
99
|
+
self.assertEqual(HITS.count("/v2/search-index.json"), 1)
|
|
100
|
+
|
|
101
|
+
def test_overridable_index_url(self):
|
|
102
|
+
ROUTES["/elsewhere/idx.json"] = FIXTURE
|
|
103
|
+
si = SermonIndex(base_url=self.base, search_index_url=self.base.replace("/v2", "/elsewhere/idx.json"))
|
|
104
|
+
self.assertEqual(len(si.search("quiet")), 1)
|
|
105
|
+
|
|
106
|
+
def test_unavailable(self):
|
|
107
|
+
with self.assertRaises(SearchUnavailableError) as cm:
|
|
108
|
+
SermonIndex(base_url=self.base).search("grace")
|
|
109
|
+
self.assertIn("not available yet", str(cm.exception))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class TransportTests(Base):
|
|
113
|
+
def test_404_html_is_not_found(self):
|
|
114
|
+
with self.assertRaises(NotFoundError):
|
|
115
|
+
SermonIndex(base_url=self.base).sermon("x")
|
|
116
|
+
|
|
117
|
+
def test_paths_and_encoding(self):
|
|
118
|
+
ROUTES["/v2/speakers/a%26b"] = {"sermons": [{"id": 1}]}
|
|
119
|
+
si = SermonIndex(base_url=self.base + "/")
|
|
120
|
+
self.assertEqual(len(list(si.speaker_sermons("a&b"))), 1)
|
|
121
|
+
self.assertEqual(HITS[0], "/v2/speakers/a%26b/page/1")
|
|
122
|
+
self.assertTrue(all("?" not in h and not h.endswith("/") for h in HITS))
|
|
123
|
+
|
|
124
|
+
def test_unicode_slug_tries_other_form(self):
|
|
125
|
+
import unicodedata
|
|
126
|
+
nfd = unicodedata.normalize("NFD", "harald-lindström")
|
|
127
|
+
ROUTES["/v2/speakers/" + __import__("urllib.parse").parse.quote(nfd, safe="")] = {"slug": "x"}
|
|
128
|
+
self.assertEqual(SermonIndex(base_url=self.base).speaker(unicodedata.normalize("NFC", nfd))["slug"], "x")
|
|
129
|
+
|
|
130
|
+
def test_follows_next(self):
|
|
131
|
+
ROUTES["/v2/sermons/page/1"] = {"sermons": [{"id": "a"}], "next": self.base + "/sermons/page/zzz"}
|
|
132
|
+
ROUTES["/v2/sermons/page/zzz"] = {"sermons": [{"id": "b"}], "next": None}
|
|
133
|
+
self.assertEqual([s["id"] for s in SermonIndex(base_url=self.base).sermons()], ["a", "b"])
|
|
134
|
+
|
|
135
|
+
def test_unreachable_is_retried_once(self):
|
|
136
|
+
si = SermonIndex(base_url="http://127.0.0.1:9/v2", timeout=2)
|
|
137
|
+
calls = []
|
|
138
|
+
import urllib.request as ur
|
|
139
|
+
real = ur.urlopen
|
|
140
|
+
|
|
141
|
+
def spy(*a, **k):
|
|
142
|
+
calls.append(1)
|
|
143
|
+
return real(*a, **k)
|
|
144
|
+
|
|
145
|
+
ur.urlopen = spy
|
|
146
|
+
try:
|
|
147
|
+
with self.assertRaises(SermonIndexError):
|
|
148
|
+
si.stats()
|
|
149
|
+
finally:
|
|
150
|
+
ur.urlopen = real
|
|
151
|
+
self.assertEqual(len(calls), 2)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class Pure(unittest.TestCase):
|
|
155
|
+
def test_books(self):
|
|
156
|
+
for name, code in [("Song of Songs", "SNG"), ("SOS", "SNG"), ("Nah", "NAM"), ("1 Cor", "1CO"), ("Jude", "JUD"), ("Jn", "JHN"), ("Revelations", "REV")]:
|
|
157
|
+
self.assertEqual(resolve_book(name), code)
|
|
158
|
+
self.assertIsNone(resolve_book("Bogus"))
|
|
159
|
+
with self.assertRaises(ValueError):
|
|
160
|
+
SermonIndex().scripture("Bogus", 1)
|
|
161
|
+
with self.assertRaises(TypeError):
|
|
162
|
+
SermonIndex().scripture("John", None, 16)
|
|
163
|
+
|
|
164
|
+
def test_audio_sources(self):
|
|
165
|
+
self.assertEqual(audio_sources({"hasAudio": True, "mp3Url": "A", "cdnMp3Url": "C"}), ["A", "C"])
|
|
166
|
+
self.assertEqual(audio_sources({"hasAudio": True, "mp3Url": "C", "cdnMp3Url": "C"}), ["C"])
|
|
167
|
+
self.assertEqual(audio_sources({"hasAudio": False, "mp3Url": "", "cdnMp3Url": ""}), [])
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
if __name__ == "__main__":
|
|
171
|
+
unittest.main()
|