diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 6ed7fbded..d168d2220 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -29,11 +29,11 @@ jobs: SAFE+='|content/' SAFE+='|themes/jb/layouts/(archive|calendar|community|contact|live|picks|sponsors|tags|taxonomy|people|show|section)/' SAFE+='|themes/jb/layouts/(index|404)\.html$|themes/jb/layouts/partials/(live|community|show)/' - SAFE+='|themes/jb/assets/js/(live|jb-live)\.js$' + SAFE+='|themes/jb/assets/js/live(-indicator)?\.js$' SAFE+='|test/|\.github/)' # carve-outs from SAFE that do feed episode pages UNSAFE='^(content/(show|people|sponsors|membership)/' - UNSAFE+='|test/(conftest\.py|e2e/test_episode\.py|e2e/episode_data\.py|Pipfile|Pipfile\.lock|docker-compose\.yml)$' + UNSAFE+='|test/(conftest\.py|e2e/test_(episode|json|llms)\.py|e2e/episode_data\.py|Pipfile|Pipfile\.lock|docker-compose\.yml)$' UNSAFE+='|\.github/workflows/e2e\.yml$)' changed=$(git diff --name-only ${{ github.event.pull_request.base.sha }} ${{ github.sha }}) # || true: the last grep exits 1 when every changed file matches SAFE (e.g. only content/show/), and bash -e would abort the step diff --git a/Dockerfile b/Dockerfile index c026d5bb3..d2ee233f0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -31,4 +31,6 @@ RUN sed -i 's/#error_page/error_page/' /etc/nginx/conf.d/default.conf # episodes.json need no override: stock mime.types already serve .txt as # text/plain and .json as application/json.) RUN sed -i '/listen /i\ location ~ \\.md$ { root /usr/share/nginx/html; default_type text/markdown; }' /etc/nginx/conf.d/default.conf +# terminal clients get the ANSI home page (/terminal.txt) instead of HTML, like ysap.sh +RUN sed -i '/listen /i\ location = / { root /usr/share/nginx/html; if ($http_user_agent ~* "^(curl|wget|httpie|xh)/") { rewrite ^ /terminal.txt last; } index index.html; }' /etc/nginx/conf.d/default.conf COPY --from=indexer /site/public /usr/share/nginx/html diff --git a/config.toml b/config.toml index 7ae06b428..f596f297f 100644 --- a/config.toml +++ b/config.toml @@ -258,16 +258,33 @@ theme = 'jb' suffixes = ["txt"] [outputFormats] - [outputFormats.webplayer] - mediatype ="application/json" - baseName = "webplayer" + # /show//.json: episode metadata. `ugly` writes .json beside the page directory + # (enabled on episode pages and hosts/guests by the cascades below, and per page via `outputs`: /membership.json, /sponsors.json) + [outputFormats.json] + mediaType = "application/json" + isPlainText = true + ugly = true - # Every page/section also emitted as markdown: /show/x/0650/ -> /show/x/0650/index.md + # Sections and lists emitted as markdown: /community/ -> /community/index.md (list pages ignore `ugly`; + # pages, episodes and shows use pagemd/showmd below instead, named like their JSON) [outputFormats.markdown] mediaType = "text/markdown" isPlainText = true baseName = "index" + # .md markdown beside the page directory, for every regular page (see [outputs]) and hosts/guests terms: + # /show/x/0650/ -> /show/x/0650.md, /membership/ -> /membership.md, /hosts/chris/ -> /hosts/chris.md + [outputFormats.pagemd] + mediaType = "text/markdown" + isPlainText = true + ugly = true + + # show markdown: /show/x/ -> /show/x/show.md (enabled per show via `outputs` in its _index.md) + [outputFormats.showmd] + mediaType = "text/markdown" + isPlainText = true + baseName = "show" + # llmstxt.org spec files (see https://llmstxt.org). Rendered by Hugo from # layouts/index.llms.txt / show/list.llms.txt -- enabled on home below, and # on individual show sections via `outputs` in their _index.md front matter @@ -290,18 +307,132 @@ theme = 'jb' isPlainText = true baseName = "episodes" + # Section twins at the site root: /sponsors.json, /hosts.md, /community.json, ... List pages ignore `ugly`, so the + # home page renders these (layouts/index.
rootjson.json / index.
rootmd.md) and the section's head links them + [outputFormats.sponsorsrootjson] + mediaType = "application/json" + isPlainText = true + baseName = "sponsors" + [outputFormats.sponsorsrootmd] + mediaType = "text/markdown" + isPlainText = true + baseName = "sponsors" + [outputFormats.hostsrootjson] + mediaType = "application/json" + isPlainText = true + baseName = "hosts" + [outputFormats.hostsrootmd] + mediaType = "text/markdown" + isPlainText = true + baseName = "hosts" + [outputFormats.guestsrootjson] + mediaType = "application/json" + isPlainText = true + baseName = "guests" + [outputFormats.guestsrootmd] + mediaType = "text/markdown" + isPlainText = true + baseName = "guests" + [outputFormats.communityrootjson] + mediaType = "application/json" + isPlainText = true + baseName = "community" + [outputFormats.communityrootmd] + mediaType = "text/markdown" + isPlainText = true + baseName = "community" + [outputFormats.liverootjson] + mediaType = "application/json" + isPlainText = true + baseName = "live" + [outputFormats.liverootmd] + mediaType = "text/markdown" + isPlainText = true + baseName = "live" + [outputFormats.archiverootjson] + mediaType = "application/json" + isPlainText = true + baseName = "archive" + [outputFormats.archiverootmd] + mediaType = "text/markdown" + isPlainText = true + baseName = "archive" + [outputFormats.peoplerootjson] + mediaType = "application/json" + isPlainText = true + baseName = "people" + [outputFormats.peoplerootmd] + mediaType = "text/markdown" + isPlainText = true + baseName = "people" + [outputFormats.showrootjson] + mediaType = "application/json" + isPlainText = true + baseName = "show" + [outputFormats.showrootmd] + mediaType = "text/markdown" + isPlainText = true + baseName = "show" + + # /show//show.json: show metadata (enabled per show via `outputs` in its _index.md) + [outputFormats.show] + mediaType = "application/json" + isPlainText = true + baseName = "show" + + # /terminal.txt: ANSI home page for curl/wget, served at / by nginx on User-Agent (see Dockerfile) + [outputFormats.terminal] + mediaType = "text/plain" + isPlainText = true + baseName = "terminal" + +# Without this, `hugo --minify` rewrites 50108000 as 50108e3, which JSON parsers read as a float +[minify.tdewolff.json] + keepNumbers = true + [outputs] - home = ["html", "rss", "llms", "llmsfull"] - page = ["html", "markdown"] - # page = ["json","html","webplayer"] + home = ["html", "rss", "llms", "llmsfull", "sponsorsrootjson", "sponsorsrootmd", "hostsrootjson", "hostsrootmd", "guestsrootjson", "guestsrootmd", "communityrootjson", "communityrootmd", "liverootjson", "liverootmd", "archiverootjson", "archiverootmd", "peoplerootjson", "peoplerootmd", "showrootjson", "showrootmd", "terminal"] + page = ["html", "pagemd", "json"] # section = ["html","rss"] section = ["html", "markdown"] taxonomy = ["html", "markdown"] term = ["html", "markdown"] [[cascade]] + outputs = ["html"] [cascade.build] list = "never" [cascade.target] path = "/search-index" kind = "section" + +# index-only pages, deleted after indexing: no twins +[[cascade]] + outputs = ["html"] + [cascade.target] + path = "/search-index/**" + +[[cascade]] + outputs = ["html", "pagemd", "json"] + [cascade.target] + path = "/show/**" + kind = "page" + +# sections with root twins (/community.json, /community.md, ...; see the output formats above): no index.md +[[cascade]] + outputs = ["html"] + [cascade.target] + path = "{/hosts,/guests}" + kind = "taxonomy" +[[cascade]] + outputs = ["html"] + [cascade.target] + path = "{/community,/live,/archive,/people,/show}" + kind = "section" + +# /hosts/.json, /guests/.json and .md +[[cascade]] + outputs = ["html", "pagemd", "json"] + [cascade.target] + path = "{/hosts/**,/guests/**}" + kind = "term" diff --git a/content/community/picks.md b/content/community/picks.md index bf0076ea0..a24a9de7e 100644 --- a/content/community/picks.md +++ b/content/community/picks.md @@ -5,4 +5,5 @@ date = "2025-02-23T21:23:01-08:00" draft = false layout = "picks" type = "picks" +outputs = ["html", "pagemd", "json"] +++ \ No newline at end of file diff --git a/content/membership/index.md b/content/membership/index.md index 5d4a469dd..d209c91ae 100644 --- a/content/membership/index.md +++ b/content/membership/index.md @@ -4,37 +4,52 @@ description = "Support Jupiter Broadcasting" date = "2022-07-03T03:35:01-05:00" draft = false search_type = "support" -type="" +outputs = ["html", "pagemd", "json"] + +# Plans and perks are rendered by layouts/membership/ into the HTML page, /membership.md and /membership.json + +[[plan_groups]] + title = "Network Membership" + description = "Access special features of every single show on the network, at a discount!" + plans = [ + { name = "Jupiter.party", url = "https://www.jupiter.party/", description = "Join the party!" }, + { name = "Jupiter.party | Annual Membership", url = "https://jupitersignal.memberful.com/checkout?plan=117630", description = "Put your support on automatic with our annual plan." }, + ] + +[[plan_groups]] + title = "A-La-Carte Show Memberships" + description = "Access special features of an individual show only." + plans = [ + { name = "LINUX Unplugged Core Contributor", url = "https://jupitersignal.memberful.com/checkout?plan=52946", show = "linux-unplugged" }, + ] + +[[plan_groups]] + title = "Gift Memberships" + description = "Gift memberships are also available!" + plans = [ + { name = "Gift Memberships", url = "https://jupitersignal.memberful.com/gift?plan=74364" }, + ] + +[[perks]] + show = "linux-unplugged" + items = [ + { name = "The LINUX Unplugged Bootleg Stream", description = "The full live version of the show, which is often packed full of exclusive content. For that raw, no-edits, straight-to-tape, extended-recording feel." }, + { name = "Ad-free version" }, + ] + +[[perks]] + show = "jupiter-extras" + items = [ + { name = "Ad-free version" }, + ] + +[[perks]] + show = "the-launch" + items = [ + { name = "The Launch Bootleg Stream", description = "The full live version of the show, which is often packed full of exclusive content. For that raw, no-edits, straight-to-tape, extended-recording feel." }, + { name = "Ad-free version" }, + ] +++ ## Support Jupiter Broadcasting Your memberships keeps our production going and gives us the ability to run fewer ads and be picky about the ones we do run. - -### Network Membership -Access special features of every single show on the network, at a discount! - -* [Jupiter.party](https://www.jupiter.party/) - Join the party! -* [Jupiter.party | Annual Membership](https://jupitersignal.memberful.com/checkout?plan=117630) - Put your support on automatic with our annual plan. - - -### A-La-Carte Show Memberships -Access special features of an individual show only. -* [LINUX Unplugged Core Contributor](https://jupitersignal.memberful.com/checkout?plan=52946) - -### Gift Memberships -[Gift Memberships](https://jupitersignal.memberful.com/gift?plan=74364) are also available! - -### Special Features Available via Memberships -#### [LINUX Unplugged]({{< ref "/show/linux-unplugged" >}}) -* The LINUX Unplugged Bootleg Stream - * The full live version of the show, which is often packed full of exclusive content. For that raw, no-edits, straight-to-tape, extended-recording feel. -* Ad-free version - - -#### [Jupiter Extras]({{< ref "/show/jupiter-extras" >}}) -* Ad-free version - -#### [The Launch]({{< ref "/show/the-launch" >}}) -* The Launch Bootleg Stream - * The full live version of the show, which is often packed full of exclusive content. For that raw, no-edits, straight-to-tape, extended-recording feel. -* Ad-free version \ No newline at end of file diff --git a/content/show/coder-radio/_index.md b/content/show/coder-radio/_index.md index a06237d9c..a3d403a75 100644 --- a/content/show/coder-radio/_index.md +++ b/content/show/coder-radio/_index.md @@ -1,5 +1,5 @@ +++ -outputs = ["html", "markdown", "llms", "episodes"] +outputs = ["html", "showmd", "llms", "episodes", "show"] title = "Coder Radio" description = "A weekly talk show taking a pragmatic look at the art and business of Software Development and related technologies." date = "2022-05-10T04:10:01-05:00" diff --git a/content/show/coder-radio/subscribe.md b/content/show/coder-radio/subscribe.md index a9a624a6a..8e850f4f9 100644 --- a/content/show/coder-radio/subscribe.md +++ b/content/show/coder-radio/subscribe.md @@ -2,6 +2,7 @@ title: "Subscribe" date: 2022-08-25 draft: false +outputs: [html, pagemd, json] rss: "https://coder.show/rss" direct_links: apple: https://podcasts.apple.com/us/podcast/coder-radio/id534941512 diff --git a/content/show/jupiter-extras/_index.md b/content/show/jupiter-extras/_index.md index 977f8cd59..bf15cb912 100644 --- a/content/show/jupiter-extras/_index.md +++ b/content/show/jupiter-extras/_index.md @@ -1,5 +1,5 @@ +++ -outputs = ["html", "markdown", "llms", "episodes"] +outputs = ["html", "showmd", "llms", "episodes", "show"] title = "Jupiter EXTRAS" description = "New ideas, great interviews, events, and other content you will love. We bring you the Extras." date = "2022-05-10T04:10:01-05:00" diff --git a/content/show/jupiter-extras/subscribe.md b/content/show/jupiter-extras/subscribe.md index 23880748e..b62661bfa 100644 --- a/content/show/jupiter-extras/subscribe.md +++ b/content/show/jupiter-extras/subscribe.md @@ -2,6 +2,7 @@ title: "Subscribe" date: 2022-08-25 draft: false +outputs: [html, pagemd, json] rss: "https://extras.show/rss" direct_links: apple: https://podcasts.apple.com/us/podcast/jupiter-extras/id1476447125 diff --git a/content/show/linux-action-news/_index.md b/content/show/linux-action-news/_index.md index 272cfa87a..30f654570 100644 --- a/content/show/linux-action-news/_index.md +++ b/content/show/linux-action-news/_index.md @@ -1,5 +1,5 @@ +++ -outputs = ["html", "markdown", "llms", "episodes"] +outputs = ["html", "showmd", "llms", "episodes", "show"] title = "Linux Action News" description = "Weekly Linux news and analysis by Chris and Wes. The show every week we hope you'll go to when you want to hear an informed discussion about what’s happening." date = "2022-05-10T04:10:01-05:00" diff --git a/content/show/linux-action-news/subscribe.md b/content/show/linux-action-news/subscribe.md index f66c99013..67d583456 100644 --- a/content/show/linux-action-news/subscribe.md +++ b/content/show/linux-action-news/subscribe.md @@ -2,6 +2,7 @@ title: "Subscribe" date: 2022-08-25 draft: false +outputs: [html, pagemd, json] rss: "https://linuxactionnews.com/rss" direct_links: apple: https://itunes.apple.com/us/podcast/linux-action-news/id1235143849 diff --git a/content/show/linux-unplugged/_index.md b/content/show/linux-unplugged/_index.md index 71fbd61c7..1d9d9a4a9 100644 --- a/content/show/linux-unplugged/_index.md +++ b/content/show/linux-unplugged/_index.md @@ -1,5 +1,5 @@ +++ -outputs = ["html", "markdown", "llms", "episodes"] +outputs = ["html", "showmd", "llms", "episodes", "show"] title = "LINUX Unplugged" description = "An open show powered by community LINUX Unplugged takes the best attributes of open collaboration and turns it into a weekly show about Linux." date = "2022-05-10T04:10:01-05:00" diff --git a/content/show/linux-unplugged/subscribe.md b/content/show/linux-unplugged/subscribe.md index f5566321e..f2bd9710a 100644 --- a/content/show/linux-unplugged/subscribe.md +++ b/content/show/linux-unplugged/subscribe.md @@ -2,6 +2,7 @@ title: "Subscribe" date: 2022-08-16T05:32:19-04:00 draft: false +outputs: [html, pagemd, json] rss: "https://linuxunplugged.com/rss" direct_links: apple: https://itunes.apple.com/us/podcast/linux-unplugged-podcast/id687598126 diff --git a/content/show/office-hours/_index.md b/content/show/office-hours/_index.md index c6f9e256a..e065f1ea6 100644 --- a/content/show/office-hours/_index.md +++ b/content/show/office-hours/_index.md @@ -1,5 +1,5 @@ +++ -outputs = ["html", "markdown", "llms", "episodes"] +outputs = ["html", "showmd", "llms", "episodes", "show"] title = "Office Hours" description = "A podcast for the community of Jupiter Broadcasting, the Open Source media powerhouse of the Internet. Get the inside scope on our projects, the future of independent media, and decentralized community." date = "2022-05-10T04:10:01-05:00" diff --git a/content/show/office-hours/subscribe.md b/content/show/office-hours/subscribe.md index 8c9e19f12..d3da22978 100644 --- a/content/show/office-hours/subscribe.md +++ b/content/show/office-hours/subscribe.md @@ -2,6 +2,7 @@ title: "Subscribe" date: 2022-08-25 draft: false +outputs: [html, pagemd, json] rss: "https://www.officehours.hair/rss" direct_links: google_podcast: https://podcasts.google.com/feed/aHR0cHM6Ly93d3cub2ZmaWNlaG91cnMuaGFpci9yc3M diff --git a/content/show/self-hosted/_index.md b/content/show/self-hosted/_index.md index 506d5a19f..7c5764fdd 100644 --- a/content/show/self-hosted/_index.md +++ b/content/show/self-hosted/_index.md @@ -1,5 +1,5 @@ +++ -outputs = ["html", "markdown", "llms", "episodes"] +outputs = ["html", "showmd", "llms", "episodes", "show"] title = "Self-Hosted" description = "Discover new software and hardware to get the best out of your network, control smart devices, and secure your data on cloud services." date = "2022-05-10T04:10:01-05:00" diff --git a/content/show/self-hosted/subscribe.md b/content/show/self-hosted/subscribe.md index dc4fb87df..4cf91353f 100644 --- a/content/show/self-hosted/subscribe.md +++ b/content/show/self-hosted/subscribe.md @@ -2,6 +2,7 @@ title: "Subscribe" date: 2022-08-25 draft: false +outputs: [html, pagemd, json] rss: "https://selfhosted.show/rss" direct_links: apple: https://podcasts.apple.com/us/podcast/self-hosted/id1477997392 diff --git a/content/show/the-launch/_index.md b/content/show/the-launch/_index.md index 60c74ebb3..38626d2a7 100644 --- a/content/show/the-launch/_index.md +++ b/content/show/the-launch/_index.md @@ -1,5 +1,5 @@ +++ -outputs = ["html", "markdown", "llms", "episodes"] +outputs = ["html", "showmd", "llms", "episodes", "show"] title = "The Launch πŸš€" description = "Let’s warm up for the week together with the best stories and clips that set the stage for the rest of your week." date = "2025-02-10T17:09:11-08:00" diff --git a/content/show/the-launch/subscribe.md b/content/show/the-launch/subscribe.md index a9ab11d10..b031d8c03 100644 --- a/content/show/the-launch/subscribe.md +++ b/content/show/the-launch/subscribe.md @@ -2,6 +2,7 @@ title: "Subscribe" date: 2025-02-10 draft: false +outputs: [html, pagemd, json] rss: "https://serve.podhome.fm/rss/04b078f9-b3e8-4363-a576-98e668231306" direct_links: # TODO: Add more podcasting 2.0? (fountain, podverse, etc?) diff --git a/content/show/this-week-in-bitcoin/_index.md b/content/show/this-week-in-bitcoin/_index.md index 25a79ba96..1ddf630fe 100644 --- a/content/show/this-week-in-bitcoin/_index.md +++ b/content/show/this-week-in-bitcoin/_index.md @@ -1,5 +1,5 @@ +++ -outputs = ["html", "markdown", "llms", "episodes"] +outputs = ["html", "showmd", "llms", "episodes", "show"] title = "This Week in Bitcoin" description = "A high-signal Bitcoin news podcast focused on analysis you'll find valuable." date = "2024-03-22T04:10:01-05:00" diff --git a/content/show/this-week-in-bitcoin/subscribe.md b/content/show/this-week-in-bitcoin/subscribe.md index 7d16863da..3785ed52a 100644 --- a/content/show/this-week-in-bitcoin/subscribe.md +++ b/content/show/this-week-in-bitcoin/subscribe.md @@ -2,6 +2,7 @@ title: "Subscribe" date: 2024-03-24 draft: false +outputs: [html, pagemd, json] rss: "https://serve.podhome.fm/rss/55b53584-4219-4fb0-b916-075ce23f714e" direct_links: apple: https://podcasts.apple.com/us/podcast/this-week-in-bitcoin/id1733733790 diff --git a/content/sponsors/_index.md b/content/sponsors/_index.md index 9ded901bc..7dd4bbb48 100644 --- a/content/sponsors/_index.md +++ b/content/sponsors/_index.md @@ -4,4 +4,6 @@ description = "Our Sponsors" date = "2022-07-03T03:35:01-05:00" draft = false sponsors = ["linode.com-jb"] +# markdown and JSON are /sponsors.md and /sponsors.json, rendered by the home page +outputs = ["html"] +++ \ No newline at end of file diff --git a/docs/json-schema.md b/docs/json-schema.md new file mode 100644 index 000000000..e2b304f39 --- /dev/null +++ b/docs/json-schema.md @@ -0,0 +1,109 @@ +# JSON API + +Static JSON generated at build time for every show and episode. No auth, no server; plain GETs. + +## URLs + +| Level | URL | Content | +|---|---|---| +| Episode list | `/show//episodes.json` | All episodes of a show, newest first | +| Show | `/show//show.json` | One show | +| Episode | `/show//.json` | One episode; the slug is the lowercase episode slug, usually the episode number (`693.json`, or `t-0.json` for special episodes) | +| Episode markdown | `/show//.md` | Markdown version of the episode page (same slug as the JSON) | +| Show markdown | `/show//show.md` | Markdown version of the show page | + +Navigation: `episodes.json` entries carry `json_url` -> episode JSON -> its `show.json_url` -> show JSON. +Show JSON links back to `episodes.json` via `episodes_url` and to its newest episode via `latest_episode.json_url`. + +Discovery from the HTML pages: every episode page has `` to its JSON and `` to its markdown; a show page has the markdown link plus two JSON links, `show.json` and `episodes.json` (title "Episode list"). + +URLs in the payloads follow the site `baseURL` (absolute on production). + +## Versioning + +`schema_version` is an integer present on every episode, show and `episodes.json` record. Additive changes (new fields) keep it at `1`; consumers must ignore unknown fields. Removing or renaming a field, or changing a type, bumps it. + +## Omission rules + +- Array fields are always present, as `[]` when empty. +- Fields that are null or absent in the source are omitted at every depth (including inside chapters and transcripts), never emitted as `null`. +- Dates are RFC 3339 (`2026-11-16T05:29:00Z`). + +## Episode (`.json`) + +Always present unless noted "omitted when absent". + +| Field | Type | Presence | +|---|---|---| +| `schema_version` | integer (`1`) | always | +| `type` | string (`"episode"`) | always | +| `url` | string | always | +| `markdown_url` | string | always | +| `show` | object: `slug`, `name`, `url`, `json_url`, `markdown_url`, `llms_url` | always | +| `episode` | integer, or string for special episodes (e.g. `"T-0"`) | always | +| `title` | string | always | +| `description` | string | omitted when absent | +| `date` | string (RFC 3339) | always | +| `header_image` | string | omitted when absent | +| `tags` | array of string | always | +| `hosts` | array of `{slug, name, url}` | always | +| `guests` | array of `{slug, name, url}` | always | +| `sponsors` | array of `{shortname, name, url, description}` | always | +| `audio` | object: `url`, `bytes` (integer), `duration` (`HH:MM:SS`) | omitted when absent | +| `audio_alt_url` | string | omitted when absent | +| `audio_ogg_url` | string | omitted when absent | +| `video` | object: `url`, `hd_url`, `mobile_url` | omitted when absent | +| `youtube_url` | string | omitted when absent | +| `chapters` | array of chapter objects (`startTime`, `title`, `img`, `url`, ...), passed through as stored | omitted when absent | +| `transcripts` | array of `{type, url}`, passed through as stored | omitted when absent | + +Keys inside `audio` and `video` are omitted individually when absent. Host and guest entries are resolved to names and their people-page URL. Sponsor entries carry the sponsor's name and description and `url`, the sponsor's own link (not a page on this site). An entry whose people or sponsor page does not exist carries only `slug` (or `shortname`). `chapters` items follow the [Podcasting 2.0 chapters format](https://github.com/Podcastindex-org/podcast-namespace/blob/main/chapters/jsonChapters.md). + +## Show (`show.json`) + +| Field | Type | Presence | +|---|---|---| +| `schema_version` | integer (`1`) | always | +| `type` | string (`"show"`) | always | +| `slug` | string | always | +| `name` | string | always | +| `description` | string | omitted when absent | +| `active` | boolean | always | +| `url` | string | always | +| `markdown_url` | string | always | +| `episodes_url` | string (`episodes.json`) | always | +| `llms_url` | string | omitted when the show has none | +| `header_image` | string | omitted when absent | +| `hosts` | array of `{slug, name, url}` | always | +| `links` | object `{name: url}`, `{}` when the show has none | always | +| `podverse_url` | string (`https://podverse.fm/podcast/`) | omitted when absent | +| `episode_count` | integer | always | +| `latest_episode` | object: `episode`, `title`, `date`, `url`, `json_url`, `markdown_url` | omitted when the show has no episodes | + +## `episodes.json` + +Top level: `schema_version` (`1`), `type` (`"episodes"`), `slug`, `title`, `count`, `episodes` (newest first). Each entry is the same small object used for `latest_episode`: `episode`, `title`, `date` (RFC 3339), `url`, `json_url`, `markdown_url`. Hosts, guests, duration and transcripts are in the episode's own JSON. + +## Examples + +List a show's episodes and take the newest episode's JSON URL: + +```sh +curl -s https://jupiterbroadcasting.com/show/linux-unplugged/episodes.json | jq -r '.episodes[0].json_url' +``` + +Show metadata and latest episode: + +```sh +curl -s https://jupiterbroadcasting.com/show/linux-unplugged/show.json | jq '{name, episode_count, latest: .latest_episode.json_url}' +``` + +One episode: title, audio URL and host names: + +```sh +curl -s https://jupiterbroadcasting.com/show/linux-unplugged/693.json | jq '{title, audio: .audio.url, hosts: [.hosts[].name]}' +``` + +## Finding every episode of a show + +Fetch `/show//episodes.json`: it lists every episode (numbered and special) with its `json_url` and `markdown_url`. Numbering does not always start at 1 (Coder Radio, Linux Action News and Self-Hosted start at 0), can have gaps (Jupiter Extras), and some episodes have no number (`T-0` in The Launch, `p01` in Office Hours, `hurricanehelene` in Coder Radio), so use the listed URLs rather than counting up from 1. `show.json`'s `episode_count` matches the list length. diff --git a/test/e2e/episode_data.py b/test/e2e/episode_data.py index 5582cfc8d..6a2822824 100644 --- a/test/e2e/episode_data.py +++ b/test/e2e/episode_data.py @@ -28,13 +28,15 @@ class Episode: number: str url: str data: dict = field(compare=False, hash=False, repr=False) + body: str = field(default="", compare=False, hash=False, repr=False) def load_episode(path: Path) -> Episode: - data, _ = json.JSONDecoder().raw_decode(path.read_text().lstrip()) + text = path.read_text().lstrip() + data, end = json.JSONDecoder().raw_decode(text) show = path.parent.name number = str(data["episode"]) - return Episode(show=show, number=number, url=f"/show/{show}/{str(data['slug']).lower()}/", data=data) + return Episode(show=show, number=number, url=f"/show/{show}/{str(data['slug']).lower()}/", data=data, body=text[end:].strip()) def episodes_by_date(show_dir: Path) -> list[Episode]: @@ -92,3 +94,11 @@ def sponsor_exists(shortname: str) -> bool: def sponsor_link(shortname: str) -> str: return re.search(r"^link: *(\S+)", sponsor_path(shortname).read_text(), re.M).group(1) + + +def yaml_title(path: Path) -> str: + # flat YAML front matter; the test image has no YAML parser, and a few titles are double-quoted with \U escapes + match = re.search(r"""^title: *(?:"(.*)"|'(.*)'|(.*?))\s*$""", path.read_text(), re.M) + if match.group(1) is None: + return match.group(2) or match.group(3) + return re.sub(r"\\U([0-9A-Fa-f]{8})|\\u([0-9A-Fa-f]{4})", lambda m: chr(int(m.group(1) or m.group(2), 16)), match.group(1)) diff --git a/test/e2e/test_episode.py b/test/e2e/test_episode.py index 8aa67b970..e74f19793 100644 --- a/test/e2e/test_episode.py +++ b/test/e2e/test_episode.py @@ -48,6 +48,7 @@ def test_episode_player(page: Page, ep: Episode): expect(player).to_have_attribute("src", re.compile(re.escape(ep.data["episode_guid"]))) else: expect(page.locator("audio source")).not_to_have_count(0) + expect(page.locator("audio")).to_have_css("color-scheme", "dark") @mark.only_browser("chromium") diff --git a/test/e2e/test_home.py b/test/e2e/test_home.py index ce32ea8af..c896aa187 100644 --- a/test/e2e/test_home.py +++ b/test/e2e/test_home.py @@ -135,3 +135,19 @@ def test_show_slider_drag_stops_at_end(page: Page): page.mouse.up() page.wait_for_timeout(800) assert page.locator(".show-slider").evaluate("el => el.swiper.isEnd") + + +def test_terminal_clients_get_ansi_home(page: Page): + for agent in ("curl/8.5.0", "Wget/1.21.4", "HTTPie/3.2.2"): + response = page.request.get("/", headers={"User-Agent": agent}) + assert response.ok + assert response.headers["content-type"].startswith("text/plain"), agent + body = response.text() + assert "B R O A D C A S T I N G" in body + for show in (p for p in CONTENT_SHOW.iterdir() if p.is_dir() and is_active(p)): + assert f"/show/{show.name}/" in body, show.name + + +def test_browsers_get_html_home(page: Page): + response = page.request.get("/", headers={"User-Agent": "Mozilla/5.0"}) + assert response.headers["content-type"].startswith("text/html") diff --git a/test/e2e/test_json.py b/test/e2e/test_json.py new file mode 100644 index 000000000..00dec5858 --- /dev/null +++ b/test/e2e/test_json.py @@ -0,0 +1,672 @@ +""" +JSON twins of shows and episodes: /show//show.json and /show//.json (schema in docs/json-schema.md). + +Expected values come from content/ so the tests hold for any content snapshot. +Links may be absolute (production) or site-relative (CI builds with baseURL "/"). +""" +import json +import re +import tomllib +from dataclasses import dataclass, field +from datetime import datetime +from pathlib import Path +from urllib.parse import urlparse + +from pytest import mark, param +from playwright.sync_api import APIRequestContext, Page, expect + +from episode_data import ( + CONTENT, + CONTENT_SHOW, + Episode, + _published, + episodes_by_date, + load_episode, + person_type, + sample_episodes, + sponsor_exists, + sponsor_link, + sponsor_path, + yaml_title, +) + +HOST = r"(?:https?://[^/)\s]+)?" + + +@dataclass(frozen=True) +class Show: + slug: str + params: dict = field(compare=False, hash=False, repr=False) + episodes: tuple[Episode, ...] = field(compare=False, hash=False, repr=False) # oldest first + + @property + def title(self) -> str: + return self.params["title"] + + +def _toml_front_matter(path: Path) -> dict: + return tomllib.loads(path.read_text().split("+++")[1]) + + +SHOWS: list[Show] = [ + Show( + slug=d.name, + params=_toml_front_matter(d / "_index.md"), + episodes=tuple(e for e in episodes_by_date(d) if e.data.get("type") == "episode"), + ) + for d in sorted(CONTENT_SHOW.iterdir()) + if (d / "_index.md").exists() +] +SHOW_PARAMS = [param(s, id=s.slug) for s in SHOWS] + + +def get_json(api: APIRequestContext, path: str) -> dict: + response = api.get(path) + assert response.status == 200, f"{path}: expected 200, got {response.status}" + assert response.headers["content-type"].startswith("application/json"), ( + f"{path}: expected application/json, got {response.headers['content-type']}" + ) + return response.json() + + +def json_twin(url: str) -> str: + """ + Path of a page's JSON twin: its URL with .json for the trailing slash (only episodes.json entries carry json_url) + """ + return urlparse(url).path.rstrip("/") + ".json" + + +def site_url(path: str) -> str: + """ + Pattern for a site path rendered through absURL/Permalink + """ + return rf"{HOST}{re.escape(path)}" + + +def assert_person_ref(ref: dict, where: str): + if person_type(ref["slug"]) is None: + assert set(ref) == {"slug"}, f"{where} {ref}: no people page, so only the slug" + else: + assert ref["name"] == yaml_title(CONTENT / "people" / f"{ref['slug']}.md"), f"{where} {ref}: name" + assert re.fullmatch(site_url(f"/people/{ref['slug']}/"), ref["url"]), f"{where} {ref}: url" + + +@mark.parametrize("show", SHOW_PARAMS) +def test_show_json(api_request_context: APIRequestContext, show: Show): + """ + show.json carries the show facts from _index.md, counts match content, and links to the other twins + """ + base = f"/show/{show.slug}" + data = get_json(api_request_context, f"{base}/show.json") + p = show.params + newest = show.episodes[-1] + + assert find_nulls(data) == [], "null fields must be omitted at every depth" + assert data["schema_version"] == 1 + assert data["type"] == "show" + assert data["slug"] == show.slug + assert data["name"] == show.title + assert re.fullmatch(site_url(f"{base}/"), data["url"]) + assert data["active"] == p.get("active", False) + assert data.get("description") == (p.get("description") or None) + if p.get("header_image"): + assert re.fullmatch(site_url(p["header_image"]), data["header_image"]) + else: + assert "header_image" not in data + assert data["episode_count"] == len(show.episodes) + assert data["latest_episode"]["episode"] == newest.data["episode"] + assert re.fullmatch(site_url(newest.url), data["latest_episode"]["url"]) + assert re.fullmatch(site_url(f"{newest.url.rstrip('/')}.md"), data["latest_episode"]["markdown_url"]) + assert "json_url" not in data, "a show's own JSON URL is the URL it was fetched from" + assert re.fullmatch(site_url(f"{base}/show.md"), data["markdown_url"]) + assert re.fullmatch(site_url(f"{base}/episodes.json"), data["episodes_url"]) + assert re.fullmatch(site_url(f"{base}/llms.txt"), data["llms_url"]) + + assert [h["slug"] for h in data["hosts"]] == p["hosts"], "hosts keep front matter order" + for host in data["hosts"]: + assert_person_ref(host, "host") + + assert "numbered_episodes" not in data and "special_episodes" not in data, "episodes.json lists every episode" + assert "podverse_podcast_id" not in data + podverse = p.get("podverse_podcast_id") + assert data.get("podverse_url") == (f"https://podverse.fm/podcast/{podverse}" if podverse else None) + + links = {name: link["url"] for name, link in (p.get("links") or {}).items() if link.get("url")} + assert data["links"].keys() == links.keys() + for name, url in links.items(): + expected = site_url(url) if url.startswith("/") else re.escape(url) + assert re.fullmatch(expected, data["links"][name]), f"link {name}: {data['links'][name]}" + + +# the-launch T-0: uppercase slug, non-numeric episode number; coder-radio 3: video, alt and ogg audio +CORE_EPISODES: list[Episode] = list( + { + e.url: e + for e in [ + *sample_episodes(), + load_episode(CONTENT_SHOW / "the-launch" / "T-0.md"), + load_episode(CONTENT_SHOW / "coder-radio" / "0003.md"), + ] + }.values() +) +EPISODE_PARAMS = [param(e, id=e.url, marks=mark.episodes) for e in CORE_EPISODES] + + +def strip_nulls(value): + if isinstance(value, dict): + return {k: strip_nulls(v) for k, v in value.items() if v is not None} + if isinstance(value, list): + return [strip_nulls(v) for v in value] + return value + + +def find_nulls(value, path: str = "") -> list[str]: + if value is None: + return [path] + if isinstance(value, dict): + return [n for k, v in value.items() for n in find_nulls(v, f"{path}.{k}")] + if isinstance(value, list): + return [n for i, v in enumerate(value) for n in find_nulls(v, f"{path}[{i}]")] + return [] + + +def episode_json_path(ep: Episode) -> str: + return f"{ep.url.rstrip('/')}.json" + + +@mark.parametrize("ep", EPISODE_PARAMS) +def test_episode_json_core(api_request_context: APIRequestContext, ep: Episode): + """ + Episode JSON carries the front matter facts, omits what the episode lacks, and links to its twins + """ + d = ep.data + data = get_json(api_request_context, episode_json_path(ep)) + + assert data["schema_version"] == 1 + assert data["type"] == "episode" + assert data["episode"] == d["episode"] + assert data["title"] == d["title"] + assert "guid" not in data + assert data.get("description") == (d.get("description") or None) + assert datetime.fromisoformat(data["date"]) == _published(d["date"]) + assert data["tags"] == (d.get("tags") or []), "tags must round-trip exactly (quotes, emoji, '+', '&')" + assert data.get("youtube_url") == (d.get("youtube_link") or None) + chapters = (d.get("podcast_chapters") or {}).get("chapters") + assert data.get("chapters") == (strip_nulls(chapters) or None), "chapters is the bare list, nulls dropped" + assert data.get("transcripts") == (strip_nulls(d.get("transcripts")) or None) + + if d.get("podcast_file"): + assert data["audio"]["url"] == d["podcast_file"] + assert data["audio"].get("bytes") == (d.get("podcast_bytes") or None) + assert data["audio"].get("duration") == (d.get("podcast_duration") or None) + else: + assert "audio" not in data + assert data.get("audio_alt_url") == (d.get("podcast_alt_file") or None) + assert data.get("audio_ogg_url") == (d.get("podcast_ogg_file") or None) + video = { + out: d[key] + for out, key in (("url", "video_file"), ("hd_url", "video_hd_file"), ("mobile_url", "video_mobile_file")) + if d.get(key) + } + assert data.get("video") == (video or None) + if d.get("header_image"): + assert re.fullmatch(site_url(d["header_image"]), data["header_image"]) + else: + assert "header_image" not in data + + assert re.fullmatch(site_url(ep.url), data["url"]) + assert "json_url" not in data, "an episode's own JSON URL is the URL it was fetched from" + assert re.fullmatch(site_url(f"{ep.url.rstrip('/')}.md"), data["markdown_url"]) + show = f"/show/{ep.show}" + assert data["show"]["slug"] == ep.show + assert data["show"]["name"] == _toml_front_matter(CONTENT_SHOW / ep.show / "_index.md")["title"] + assert re.fullmatch(site_url(f"{show}/"), data["show"]["url"]) + assert re.fullmatch(site_url(f"{show}/show.json"), data["show"]["json_url"]) + assert re.fullmatch(site_url(f"{show}/show.md"), data["show"]["markdown_url"]) + assert re.fullmatch(site_url(f"{show}/llms.txt"), data["show"]["llms_url"]) + assert find_nulls(data) == [], "null fields must be omitted at every depth" + + assert "podverse_url" not in data, "podverse.fm episode pages use Podverse's own id, which the guid cannot give us" + + +def test_core_episodes_cover_every_optional_field(): + """ + Guard: the core sample must exercise each optional episode field, or test_episode_json_core checks it only as absent + """ + keys = ("podcast_alt_file", "podcast_ogg_file", "video_file", "header_image", "podcast_chapters", "transcripts", "youtube_link") + missing = [k for k in keys if not any(e.data.get(k) for e in CORE_EPISODES)] + assert not missing, f"no core episode has {missing}" + + +@mark.parametrize("show", SHOW_PARAMS) +def test_show_json_links_resolve(api_request_context: APIRequestContext, show: Show): + """ + show.json latest_episode and the oldest episodes.json entry lead to that episode's JSON at .json + """ + latest = get_json(api_request_context, f"/show/{show.slug}/show.json")["latest_episode"] + oldest = get_json(api_request_context, f"/show/{show.slug}/episodes.json")["episodes"][-1] + assert "json_url" not in latest, "a ref outside episodes.json carries no json_url" + assert urlparse(oldest["json_url"]).path == json_twin(oldest["url"]), "episodes.json entries link their JSON twin" + for ref in (latest, oldest): + episode = get_json(api_request_context, json_twin(ref["url"])) + assert episode["type"] == "episode" + assert episode["episode"] == ref["episode"] + + +@mark.episodes +@mark.parametrize("show", SHOW_PARAMS) +def test_every_episode_json_is_valid(api_request_context: APIRequestContext, show: Show): + """ + Every episode listed in episodes.json serves parseable JSON with schema_version 1 and type "episode" + """ + entries = get_json(api_request_context, f"/show/{show.slug}/episodes.json")["episodes"] + problems = [] + for entry in entries: + path = urlparse(entry["json_url"]).path + response = api_request_context.get(path) + content_type = response.headers.get("content-type", "") + if response.status != 200 or not content_type.startswith("application/json"): + problems.append(f"{path}: {response.status} {content_type}") + continue + try: + data = json.loads(response.text()) + except ValueError as e: + problems.append(f"{path}: unparseable: {e}") + continue + if not isinstance(data, dict): + problems.append(f"{path}: top level is {type(data).__name__}, not an object") + elif (data.get("schema_version"), data.get("type"), data.get("episode")) != (1, "episode", entry["episode"]): + problems.append(f"{path}: schema_version={data.get('schema_version')!r} type={data.get('type')!r} episode={data.get('episode')!r}") + assert len(entries) == len(show.episodes) + assert not problems, f"{len(problems)} bad file(s):\n" + "\n".join(problems[:20]) + + +@mark.parametrize("ep", EPISODE_PARAMS) +def test_episode_json_refs(api_request_context: APIRequestContext, ep: Episode): + """ + Hosts, guests and sponsors keep front matter order and resolve to names and URLs; refs without a page keep only the id + """ + data = get_json(api_request_context, episode_json_path(ep)) + + for key in ("hosts", "guests"): + assert [r["slug"] for r in data[key]] == (ep.data.get(key) or []) + for ref in data[key]: + assert_person_ref(ref, key) + + assert [s["shortname"] for s in data["sponsors"]] == (ep.data.get("sponsors") or []) + for sponsor in data["sponsors"]: + if sponsor_exists(sponsor["shortname"]): + assert sponsor["name"] == yaml_title(sponsor_path(sponsor["shortname"])), f"sponsor {sponsor}: name" + assert sponsor["url"] == sponsor_link(sponsor["shortname"]), "sponsor url is the sponsor's own link, not the site stub page" + else: + assert set(sponsor) == {"shortname"}, f"sponsor {sponsor}: no sponsors page, so only the shortname" + + people = [r for r in data["hosts"] + data["guests"] if "url" in r] + for ref in people[:1]: + assert api_request_context.get(urlparse(ref["url"]).path).status == 200, f"{ref['url']} does not resolve" + + +@mark.parametrize( + "path, raw, escaped", + [ + param(CONTENT_SHOW / "linux-action-news" / "0129.md", " & ", "\\u0026", id="ampersand"), + param(CONTENT_SHOW / "jupiter-extras" / "0028.md", "<3", "\\u003c", id="less-than"), + param(CONTENT_SHOW / "office-hours" / "0011.md", " > ", "\\u003e", id="greater-than"), + ], +) +def test_json_text_is_not_html_escaped(api_request_context: APIRequestContext, path: Path, raw: str, escaped: str): + """ + '&', '<' and '>' appear as themselves in the raw text, not as \\u0026 and friends, so grep and agents can read it + """ + ep = load_episode(path) + assert raw in json.dumps(ep.data, ensure_ascii=False), f"fixture episode must contain {raw!r}" + response = api_request_context.get(episode_json_path(ep)) + assert response.status == 200 + text = response.text() + assert raw in text + assert escaped not in text + + +@mark.only_browser("chromium") +@mark.parametrize("ep", EPISODE_PARAMS) +def test_episode_page_links_to_its_json(page: Page, ep: Episode): + """ + The episode HTML head advertises its JSON twin, so a crawler or agent can find it from the page + """ + page.goto(ep.url) + links = page.locator('link[rel="alternate"][type="application/json"]') + expect(links).to_have_count(1) + expect(links).to_have_attribute("href", re.compile(rf"^{site_url(episode_json_path(ep))}$")) + + +@mark.only_browser("chromium") +@mark.parametrize("show", SHOW_PARAMS) +def test_show_page_links_to_show_and_episode_list_json(page: Page, show: Show): + """ + The show HTML head advertises show.json and the full episodes.json + """ + page.goto(f"/show/{show.slug}/") + hrefs = page.locator('link[rel="alternate"][type="application/json"]').evaluate_all("els => els.map(e => e.href)") + assert sorted(urlparse(h).path for h in hrefs) == [f"/show/{show.slug}/episodes.json", f"/show/{show.slug}/show.json"] + + +def test_membership_json(api_request_context: APIRequestContext): + """ + /membership.json carries the plans and perks from content/membership/index.md front matter + """ + params = _toml_front_matter(CONTENT / "membership" / "index.md") + data = get_json(api_request_context, "/membership.json") + assert data["schema_version"] == 1 and data["type"] == "membership" + assert re.fullmatch(site_url("/membership/"), data["url"]) + assert re.fullmatch(site_url("/membership.md"), data["markdown_url"]) + assert [g["title"] for g in data["plan_groups"]] == [g["title"] for g in params["plan_groups"]] + for group, source in zip(data["plan_groups"], params["plan_groups"]): + assert [(p["name"], p["url"]) for p in group["plans"]] == [(p["name"], p["url"]) for p in source["plans"]] + for plan, src in zip(group["plans"], source["plans"]): + assert plan.get("description") == src.get("description"), plan["name"] + if "show" in src: + assert plan["show"]["slug"] == src["show"] + assert re.fullmatch(site_url(f"/show/{src['show']}/"), plan["show"]["url"]) + assert [p["show"]["slug"] for p in data["perks"]] == [p["show"] for p in params["perks"]] + for perk, source in zip(data["perks"], params["perks"]): + show = next(s for s in SHOWS if s.slug == source["show"]) + assert perk["show"]["name"] == show.title + assert perk["items"] == source["items"] + assert not find_nulls(data) + + +@mark.only_browser("chromium") +def test_sponsors_json_matches_page(page: Page, api_request_context: APIRequestContext): + """ + /sponsors.json lists the same sections and sponsor links as the /sponsors/ page, with data/sponsors fields + """ + data = get_json(api_request_context, "/sponsors.json") + assert data["schema_version"] == 1 and data["type"] == "sponsors" + assert data["lookback_days"] > 0 + page.goto("/sponsors/") + rendered = page.evaluate( + """() => { + const sections = []; + for (const el of document.querySelectorAll('.spnosor-list .content > *')) { + if (el.tagName === 'H2') sections.push([el.textContent.trim(), []]); + else if (sections.length) el.querySelectorAll('a[href]').forEach(a => sections.at(-1)[1].push(a.getAttribute('href'))); + } + return sections; + }""" + ) + assert [[s["title"], [sp["url"] for sp in s["sponsors"]]] for s in data["sections"]] == rendered + for section in data["sections"]: + if "show" in section: + assert section["show"]["name"] == section["title"] + assert re.fullmatch(site_url(f"/show/{section['show']['slug']}/"), section["show"]["url"]) + for sponsor in section["sponsors"]: + assert sponsor["title"] and sponsor["description"], sponsor + assert not find_nulls(data) + + +PEOPLE_DIR = CONTENT / "people" +TERM_PARAMS = [ + param("hosts", "chris", id="host-many-shows"), + param("hosts", "brent", id="host"), + param("guests", "brent", id="host-as-guest"), + param("guests", "alessandro", id="guest"), + param("hosts", "allanjude", id="archived"), +] + + +def person_front_matter(slug: str) -> dict[str, str]: + """ + Top-level scalar fields of a people page's flat YAML front matter (the test image has no YAML parser) + """ + text = (PEOPLE_DIR / f"{slug}.md").read_text().split("---")[1] + return {k: v.strip().strip("'\"") for k, v in re.findall(r"^(\w+): *(.*)$", text, re.M) if v.strip() not in ("", "null")} + + +def episode_counts(key: str) -> dict[str, dict[str, int]]: + """ + person slug -> {show slug: number of episodes listing them under key ("hosts"/"guests")} + """ + counts: dict[str, dict[str, int]] = {} + for show in SHOWS: + for ep in show.episodes: + for slug in ep.data.get(key) or []: + per_show = counts.setdefault(slug, {}) + per_show[show.slug] = per_show.get(show.slug, 0) + 1 + return counts + + +EPISODE_COUNTS = {key: episode_counts(key) for key in ("hosts", "guests")} + + +@mark.parametrize("taxonomy, slug", TERM_PARAMS) +def test_person_term_json(api_request_context: APIRequestContext, taxonomy: str, slug: str): + """ + /hosts/.json and /guests/.json carry the people page profile and that role's per-show episode counts + """ + fm = person_front_matter(slug) + data = get_json(api_request_context, f"/{taxonomy}/{slug}.json") + assert data["schema_version"] == 1 and data["type"] == taxonomy.removesuffix("s") + assert data["slug"] == slug and data["role"] == fm["type"] + assert data["name"] == yaml_title(PEOPLE_DIR / f"{slug}.md") + assert re.fullmatch(site_url(f"/{taxonomy}/{slug}/"), data["url"]) + assert re.fullmatch(site_url(f"/{taxonomy}/{slug}.md"), data["markdown_url"]) + assert re.fullmatch(site_url(f"/people/{slug}/"), data["profile_url"]) + assert data.get("archived", False) == (fm.get("is_archived") == "true") + assert data["links"] == {k: fm[k] for k in ("twitter", "mastodon", "linkedin", "instagram", "youtube") if k in fm} + expected = EPISODE_COUNTS[taxonomy][slug] + assert {s["slug"]: s["episode_count"] for s in data["shows"]} == expected + assert data["episode_count"] == sum(expected.values()), "show pages listing hosts are not episodes" + for show in data["shows"]: + assert re.fullmatch(site_url(f"/show/{show['slug']}/"), show["url"]) + episodes = data["episodes"] + assert len(episodes) == data["episode_count"], "every episode is listed, like the markdown twin" + dates = [datetime.fromisoformat(e["date"]) for e in episodes] + assert dates == sorted(dates, reverse=True), "newest first" + assert {e["show"] for e in episodes} == set(expected) + assert "json_url" not in episodes[0], "json_url is the url with .json for the trailing slash" + newest = urlparse(episodes[0]["url"]).path + assert re.fullmatch(rf"/show/{episodes[0]['show']}/[^/]+/", newest) + assert api_request_context.get(newest.rstrip("/") + ".json").status == 200 + assert not find_nulls(data) + + +@mark.parametrize("taxonomy", ["hosts", "guests"]) +def test_people_taxonomy_json(api_request_context: APIRequestContext, taxonomy: str): + """ + /hosts.json and /guests.json list everyone in that role by name, each with episode count; their JSON is the url with .json + """ + data = get_json(api_request_context, f"/{taxonomy}.json") + assert data["schema_version"] == 1 and data["type"] == taxonomy + assert re.fullmatch(site_url(f"/{taxonomy}/"), data["url"]) + counts = EPISODE_COUNTS[taxonomy] + assert {p["slug"]: p["episode_count"] for p in data["people"]} == {k: sum(v.values()) for k, v in counts.items()} + assert data["count"] == len(data["people"]) + for person in data["people"]: + assert person.get("role") == person_type(person["slug"]), person["slug"] + assert "json_url" not in person, person["slug"] + assert re.fullmatch(site_url(f"/{taxonomy}/{person['slug']}/"), person["url"]) + assert api_request_context.get(f"/{taxonomy}/{data['people'][0]['slug']}.json").status == 200 + assert not find_nulls(data) + + +def test_picks_json(api_request_context: APIRequestContext): + """ + /community/picks.json lists every data/picks file with its link, license and the episodes it was picked on + """ + from test_community import PICKS + + data = get_json(api_request_context, "/community/picks.json") + assert data["schema_version"] == 1 and data["type"] == "picks" + assert re.fullmatch(site_url("/community/picks/"), data["url"]) + assert data["count"] == len(PICKS) == len(data["picks"]) + expected = {p.url: (p.title, p.episodes) for p in PICKS} + assert {p["slug"] for p in data["picks"]} == {p.stem for p in (CONTENT.parent / "data" / "picks").glob("*.yaml")} + for pick in data["picks"]: + _, episodes = expected[pick["url"]] + title = yaml_title(CONTENT.parent / "data" / "picks" / f"{pick['slug']}.yaml").lstrip("'\"") + assert pick["title"].startswith(title), "yaml_title keeps only a wrapped title's first line" + assert [urlparse(e["url"]).path.rstrip("/") for e in pick["episodes"]] == list(episodes), pick["slug"] + assert all(e["show_name"] for e in pick["episodes"]), pick["slug"] + licenses = [p for p in data["picks"] if "license" in p] + assert licenses and len(licenses) < len(data["picks"]), "null licenses are omitted, set ones kept" + assert "json_url" not in json.dumps(data) + assert not find_nulls(data) + + +COMMUNITY_DIR = CONTENT / "community" +COMMUNITY_PAGES = sorted( + p.stem + for p in COMMUNITY_DIR.glob("*.md") + if p.name != "_index.md" and not re.search(r"^draft\s*=\s*true", p.read_text(), re.M) +) + + +@mark.parametrize("slug", [s for s in COMMUNITY_PAGES if s != "picks"]) +def test_community_page_json(api_request_context: APIRequestContext, slug: str): + """ + /community/.json carries the link and kind the community card shows + """ + params = _toml_front_matter(COMMUNITY_DIR / f"{slug}.md") + data = get_json(api_request_context, f"/community/{slug}.json") + assert data["schema_version"] == 1 and data["type"] == "community" + assert data["title"] == params["title"].strip() + assert data.get("link") == params.get("direct_link") + assert data.get("kind") == params.get("comms_type") + assert re.fullmatch(site_url(f"/community/{slug}/"), data["url"]) + assert re.fullmatch(site_url(f"/community/{slug}.md"), data["markdown_url"]) + assert not find_nulls(data) + + +def test_community_json(api_request_context: APIRequestContext): + data = get_json(api_request_context, "/community.json") + assert data["type"] == "community" and re.fullmatch(site_url("/community/"), data["url"]) + assert sorted(urlparse(p["url"]).path for p in data["pages"]) == sorted(f"/community/{s}/" for s in COMMUNITY_PAGES) + assert not find_nulls(data) + + +@mark.parametrize("show", SHOW_PARAMS) +def test_subscribe_json(api_request_context: APIRequestContext, show: Show): + """ + /show//subscribe.json carries the RSS feed and the podcast app links from subscribe.md + """ + text = (CONTENT_SHOW / show.slug / "subscribe.md").read_text() + data = get_json(api_request_context, f"/show/{show.slug}/subscribe.json") + assert data["type"] == "subscribe" + assert data["rss"] == re.search(r'^rss: *"?([^"\n]+)"?', text, re.M).group(1) + assert data["show"]["slug"] == show.slug and data["show"]["name"] == show.title + assert data.get("apps") and all(v.startswith("http") for v in data["apps"].values()) + assert not find_nulls(data) + + +@mark.parametrize("taxonomy, slug", [param("hosts", "chris", id="host"), param("guests", "alessandro", id="guest")]) +def test_person_page_json(api_request_context: APIRequestContext, taxonomy: str, slug: str): + """ + /people/.json is the profile, pointing at the hosts/guests page that lists their episodes + """ + fm = person_front_matter(slug) + data = get_json(api_request_context, f"/people/{slug}.json") + assert data["type"] == "person" and data["slug"] == slug and data["role"] == fm["type"] + assert data["name"] == yaml_title(PEOPLE_DIR / f"{slug}.md") + assert re.fullmatch(site_url(f"/{taxonomy}/{slug}/"), data[f"{taxonomy}_url"]) + assert "profile_url" not in data, "the profile is this page" + assert data["links"] == {k: fm[k] for k in ("twitter", "mastodon", "linkedin", "instagram", "youtube") if k in fm} + assert not find_nulls(data) + + +def test_people_json(api_request_context: APIRequestContext): + data = get_json(api_request_context, "/people.json") + assert data["type"] == "people" + assert sorted(p["slug"] for p in data["people"]) == sorted(p.stem for p in PEOPLE_DIR.glob("*.md")) + assert data["count"] == len(data["people"]) + for person in data["people"]: + slug = person["slug"] + assert person["role"] == person_type(slug), slug + assert re.fullmatch(site_url(f"/people/{slug}/"), person["url"]), slug + assert re.fullmatch(site_url(f"/people/{slug}.json"), person["json_url"]), slug + assert re.fullmatch(site_url(f"/people/{slug}.md"), person["markdown_url"]), slug + for person in data["people"][:3]: + assert get_json(api_request_context, urlparse(person["json_url"]).path)["slug"] == person["slug"] + assert api_request_context.get(urlparse(person["markdown_url"]).path).status == 200 + assert not find_nulls(data) + + +@mark.parametrize("path, active", [param("/show.json", None, id="shows"), param("/archive.json", False, id="archive")]) +def test_shows_json(api_request_context: APIRequestContext, path: str, active: bool | None): + """ + /show.json lists every show; /archive.json only the inactive ones + """ + data = get_json(api_request_context, path) + expected = [s for s in SHOWS if active is None or bool(s.params.get("active")) == active] + assert sorted(s["slug"] for s in data["shows"]) == sorted(s.slug for s in expected) + for show in data["shows"]: + source = next(s for s in SHOWS if s.slug == show["slug"]) + assert show["name"] == source.title + assert show["active"] == bool(source.params.get("active")) + assert show["episode_count"] == len(source.episodes) + assert re.fullmatch(site_url(f"/show/{show['slug']}/show.md"), show["markdown_url"]) + assert not find_nulls(data) + + +def test_live_json(api_request_context: APIRequestContext): + data = get_json(api_request_context, "/live.json") + assert data["type"] == "live" + assert data["audio_url"].startswith("http") and data["video_url"].startswith("http") + assert len(data["latest_episodes"]) == 3 + for ref in data["latest_episodes"]: + assert "json_url" not in ref + assert api_request_context.get(json_twin(data["latest_episodes"][0]["url"])).status == 200 + + +@mark.parametrize("path, field", [param("/calendar.json", "ical_url", id="calendar"), param("/boost.json", "content", id="boost")]) +def test_page_json(api_request_context: APIRequestContext, path: str, field: str): + """ + Plain pages carry their markdown body as content, plus what the page shows from site params + """ + data = get_json(api_request_context, path) + assert data["schema_version"] == 1 and data[field] + assert re.fullmatch(site_url(path.removesuffix(".json") + ".md"), data["markdown_url"]) + assert "{{" not in json.dumps(data) + + +@mark.only_browser("chromium") +@mark.parametrize( + "path, json_path", + [ + ("/membership/", "/membership.json"), + ("/sponsors/", "/sponsors.json"), + ("/hosts/", "/hosts.json"), + ("/guests/", "/guests.json"), + ("/hosts/chris/", "/hosts/chris.json"), + ("/guests/alessandro/", "/guests/alessandro.json"), + ("/community/picks/", "/community/picks.json"), + ("/community/", "/community.json"), + ("/community/github/", "/community/github.json"), + ("/live/", "/live.json"), + ("/archive/", "/archive.json"), + ("/people/", "/people.json"), + ("/people/chris/", "/people/chris.json"), + ("/show/", "/show.json"), + ("/contact/", "/contact.json"), + ("/calendar/", "/calendar.json"), + ("/boost/", "/boost.json"), + ("/show/linux-unplugged/subscribe/", "/show/linux-unplugged/subscribe.json"), + ], +) +def test_site_page_links_to_its_json(page: Page, path: str, json_path: str): + """ + Site pages with a JSON twin advertise .json, named like the episode twins + """ + page.goto(path) + links = page.locator('link[rel="alternate"][type="application/json"]') + expect(links).to_have_count(1) + expect(links).to_have_attribute("href", re.compile(rf"^{site_url(json_path)}$")) + + +@mark.only_browser("chromium") +@mark.parametrize("path", ["/", "/tags/zfs/", "/search/"]) +def test_pages_without_json_advertise_none(page: Page, path: str): + """ + The home page (llms.txt covers it), tags and search have no JSON twin and must not advertise one + """ + page.goto(path) + expect(page.locator('link[rel="alternate"][type="application/json"]')).to_have_count(0) diff --git a/test/e2e/test_live.py b/test/e2e/test_live.py index 61674b722..5b80af082 100644 --- a/test/e2e/test_live.py +++ b/test/e2e/test_live.py @@ -110,3 +110,27 @@ def test_live_fallback_clears_footer(page: Page, stream: StreamStub): footer = page.locator("footer").bounding_box() gap = footer["y"] - (card["y"] + card["height"]) assert gap >= 24, f"episode cards end {gap}px above the footer" + + +def test_nav_live_indicator(page: Page, stream: StreamStub): + """ + Every page's navbar turns red (is-live) while the HLS playlist is live, and stays plain when it is off air + """ + nav = page.locator("#mainnavigation") + page.goto("/") + expect(nav).not_to_have_class(re.compile(r"\bis-live\b")) + + stream.live = True + page.goto("/") + expect(nav).to_have_class(re.compile(r"\bis-live\b")) + expect(page.locator("#livebutton")).to_have_css("background-color", "rgb(255, 0, 0)") + + +def test_live_endlist_is_not_live(page: Page, stream: StreamStub): + """ + A finished (VOD) playlist carries #EXT-X-ENDLIST and must not light the indicator + """ + page.route(f"{VIDEO_URL}*", lambda route: route.fulfill(status=200, body=LIVE_PLAYLIST + "#EXT-X-ENDLIST\n")) + page.goto("/") + page.wait_for_load_state("networkidle") + expect(page.locator("#mainnavigation")).not_to_have_class(re.compile(r"\bis-live\b")) diff --git a/test/e2e/test_llms.py b/test/e2e/test_llms.py index fd37cbd86..d6baf7dc4 100644 --- a/test/e2e/test_llms.py +++ b/test/e2e/test_llms.py @@ -1,6 +1,6 @@ """ llms.txt machinery (llmstxt.org v2): /llms.txt, /llms-full.txt, per-show llms.txt + episodes.json, -markdown twins at index.md, and discovery links in HTML heads. +markdown twins (.md, sections at the root), and discovery links in HTML heads. Expected values come from content/ so the tests hold for any content snapshot. Links may be absolute (production) or site-relative (CI builds with baseURL "/"). @@ -12,11 +12,31 @@ from pytest import mark, param from playwright.sync_api import APIRequestContext, APIResponse, Page, expect -from episode_data import CONTENT, CONTENT_SHOW, Episode, episodes_by_date, is_active, sample_episodes, sponsor_exists, sponsor_link +from episode_data import ( + CONTENT, + CONTENT_SHOW, + Episode, + episodes_by_date, + is_active, + load_episode, + person_type, + sample_episodes, + sponsor_exists, + sponsor_link, +) HOST = r"(?:https?://[^/)\s]+)?" LLMS_SECTIONS = ["/show/", "/hosts/", "/guests/"] SITE_PAGES = ["/membership/", "/live/", "/community/", "/hosts/", "/sponsors/", "/contact/"] +# every page's markdown is .md like its .json; sections' are rendered by the home page at the root +SITE_MARKDOWN = { + "/membership/": "/membership.md", + "/live/": "/live.md", + "/community/": "/community.md", + "/hosts/": "/hosts.md", + "/sponsors/": "/sponsors.md", + "/contact/": "/contact.md", +} def _yaml_field(path: Path, key: str) -> str | None: @@ -99,12 +119,12 @@ def _slug(ep: Episode) -> str: def test_root_llms_txt(api_request_context: APIRequestContext): """ - /llms.txt follows the spec layout: H1, summary blockquote, then Shows / Site / Optional sections in order + /llms.txt follows the spec layout: H1, summary blockquote, then Shows / Site / Data / Optional sections in order """ text = _get(api_request_context, "/llms.txt", "text/plain").text() assert text.startswith("# Jupiter Broadcasting\n"), "H1 must be the first line" assert "\n> " in text, "missing summary blockquote" - positions = [text.find(h) for h in ("## Shows", "## Site", "## Optional")] + positions = [text.find(h) for h in ("## Shows", "## Site", "## Data (JSON)", "## Optional")] assert -1 not in positions and positions == sorted(positions), "sections missing or out of order" assert re.search(rf"\]\({HOST}/llms-full\.txt\)", text), "Optional must link llms-full.txt" @@ -130,7 +150,7 @@ def test_root_show_entry(api_request_context: APIRequestContext, show: Show): if show.active: section, target = _section(text, "## Shows", "## Site"), "llms.txt" else: - section, target = _section(text, "## Optional"), "index.md" + section, target = _section(text, "## Optional"), "show.md" entry = re.search( rf"^- \[{re.escape(show.title.strip())}\]\({HOST}/show/{show.slug}/{re.escape(target)}\): " @@ -150,8 +170,100 @@ def test_root_site_links(api_request_context: APIRequestContext): """ site = _section(_get(api_request_context, "/llms.txt", "text/plain").text(), "## Site", "## Optional") for path in SITE_PAGES: - assert re.search(rf"\]\({HOST}{re.escape(path)}index\.md\)", site), f"{path} not linked" - _get(api_request_context, f"{path}index.md", "text/markdown") + assert re.search(rf"\]\({HOST}{re.escape(SITE_MARKDOWN[path])}\)", site), f"{path} not linked" + _get(api_request_context, SITE_MARKDOWN[path], "text/markdown") + + +@mark.parametrize("path", SITE_PAGES) +def test_site_page_markdown_has_no_shortcodes(api_request_context: APIRequestContext, path: str): + """ + {{< ref >}} shortcodes in page bodies become absolute links in the markdown twin + """ + text = _get(api_request_context, SITE_MARKDOWN[path], "text/markdown").text() + assert "{{" not in text, "unrendered shortcode" + + +def test_boost_markdown_ref_resolves(api_request_context: APIRequestContext): + text = _get(api_request_context, "/boost.md", "text/markdown").text() + assert re.search(rf"\[Member\]\({HOST}/membership/\)", text), "ref shortcode not converted to a link" + + +def test_sponsors_markdown_lists_sponsors(api_request_context: APIRequestContext): + """ + /sponsors.md lists sponsors from data/sponsors under section headings, linking to each sponsor's site + """ + text = _get(api_request_context, "/sponsors.md", "text/markdown").text() + assert "\n## Jupiter Broadcasting\n" in text + links = re.findall(r"^- \[.+\]\((\S+)\)", text, re.M) + assert links and all(not re.match(rf"{HOST}/sponsors/", link) for link in links), "links go to sponsors' own sites" + + +def test_root_data_links_are_json(api_request_context: APIRequestContext): + """ + ## Data (JSON) links resolve to JSON, and every ## Site entry's (JSON: ...) twin does too + """ + text = _get(api_request_context, "/llms.txt", "text/plain").text() + data = _section(text, "## Data (JSON)", "## Optional") + links = re.findall(rf"\]\({HOST}(/[^)]+\.json)\)", data) + assert len(links) >= 10, f"Data section lists too few JSON links: {links}" + site_json = re.findall(rf"\(JSON: {HOST}(/\S+\.json)\)", _section(text, "## Site", "## Data (JSON)")) + assert len(site_json) == len(SITE_PAGES) + 5, site_json + for path in links + site_json: + _get(api_request_context, path, "application/json") + assert "'" not in text and "&" not in text, "plain text must not be HTML-escaped" + + +@mark.parametrize("show", SHOW_PARAMS) +def test_show_llms_txt_links_twins_and_hosts(api_request_context: APIRequestContext, show: Show): + """ + Per-show llms.txt points at show.json, the subscribe twins and each host's markdown/JSON, all resolving + """ + text = _get(api_request_context, f"/show/{show.slug}/llms.txt", "text/plain").text() + the_show = _section(text, "## The show") + assert re.search(rf"\]\({HOST}/show/{show.slug}/show\.json\)", the_show), "missing show.json" + assert re.search(rf"\]\({HOST}/show/{show.slug}/subscribe\.md\)", the_show), "missing subscribe twin" + assert ".json` for the JSON twin" in text, "episode JSON pattern not explained" + hosts = re.findall(rf"^- \[[^\]]+\]\({HOST}(/hosts/[^)]+)\.md\).*\(JSON: {HOST}(/hosts/[^)]+)\.json\)$", text, re.M) + assert hosts, "no hosts listed" + for md, js in hosts[:2]: + assert md == js + _get(api_request_context, f"{md}.md", "text/markdown") + _get(api_request_context, f"{js}.json", "application/json") + assert "'" not in text and "&" not in text, "plain text must not be HTML-escaped" + + +def test_picks_markdown(api_request_context: APIRequestContext): + """ + /community/picks.md lists every pick with its link, and every "Picked on" episode twin resolves + """ + from test_community import PICKS + + text = _get(api_request_context, "/community/picks.md", "text/markdown").text() + for pick in PICKS: + assert f"]({pick.url})" in text, pick.title + episodes = set(re.findall(rf"\]\({HOST}(/show/[^/]+/[^/)]+\.md)\)", text)) + assert episodes == {f"{e}.md" for p in PICKS for e in p.episodes} + broken = [e for e in sorted(episodes) if api_request_context.get(e).status != 200] + assert not broken, f"picked-on episode twins that 404: {broken}" + + +@mark.parametrize( + "path, expected", + [ + param("/community.md", "/community/github.md) (https://github.com/", id="community"), + param("/people.md", "/people/chris.md) (host)", id="people"), + param("/show.md", "/show/linux-unplugged/show.md)", id="shows"), + param("/archive.md", "/show/coder-radio/show.md)", id="archive"), + param("/live.md", "- Audio stream: http", id="live"), + param("/calendar.md", "iCalendar: http", id="calendar"), + param("/community/github.md", "Link: https://github.com/", id="community-page"), + param("/show/linux-unplugged/subscribe.md", "RSS: http", id="subscribe"), + ], +) +def test_page_markdown_lists_what_the_page_shows(api_request_context: APIRequestContext, path: str, expected: str): + text = _get(api_request_context, path, "text/markdown").text() + assert expected in text, f"{path} missing {expected!r}" + assert "{{" not in text def test_llms_full_txt(api_request_context: APIRequestContext): @@ -160,6 +272,7 @@ def test_llms_full_txt(api_request_context: APIRequestContext): """ text = _get(api_request_context, "/llms-full.txt", "text/plain").text() assert "Membership" in text + assert "jupitersignal.memberful.com/checkout" in text, "membership plans from front matter missing" assert "Brent Gervais" in text assert "+++" not in text, "TOML front matter leaked" assert "avatar_small" not in text, "YAML front matter leaked" @@ -184,10 +297,10 @@ def test_show_llms_txt(api_request_context: APIRequestContext, show: Show): assert text.startswith(f"# {show.title}\n"), "H1 must be the show title" assert len(text) < 20_000, "per-show llms.txt should be curated, not a full index" assert re.search(rf"\]\({HOST}/show/{show.slug}/episodes\.json\)", text), "missing episodes.json link" - assert re.search(rf"\]\({HOST}/show/{show.slug}/index\.md\)", text), "missing show twin link" + assert re.search(rf"\]\({HOST}/show/{show.slug}/show\.md\)", text), "missing show twin link" recent = _section(text, f"## Most recent episodes (of {len(show.episodes)})", "## Episode archive") - entries = re.findall(rf"^- \[(\d{{4}}-\d{{2}}-\d{{2}}) Β· .*\]\({HOST}(/show/{show.slug}/[^/]+/)index\.md\)", recent, re.M) + entries = re.findall(rf"^- \[(\d{{4}}-\d{{2}}-\d{{2}}) Β· .*\]\({HOST}(/show/{show.slug}/[^/]+)\.md\)", recent, re.M) assert [d for d, _ in entries] == [_episode_date(e) for e in show.newest_first[:10]], ( "recent episodes must be the 10 newest, newest first" ) @@ -206,21 +319,25 @@ def test_show_episodes_json(api_request_context: APIRequestContext, show: Show): episodes.json enumerates every episode in content (incl. prefixed specials like the-launch T-0), newest first """ data = _get(api_request_context, f"/show/{show.slug}/episodes.json", "application/json").json() - assert data["show"] == show.slug + assert data["schema_version"] == 1 + assert data["type"] == "episodes" + assert data["slug"] == show.slug + assert "show" not in data assert data["title"] == show.title assert data["count"] == len(show.episodes), "count differs from content" assert len(data["episodes"]) == data["count"] - assert {e["slug"] for e in data["episodes"]} == {_slug(e) for e in show.episodes} + assert {e["url"].rstrip("/").rsplit("/", 1)[-1] for e in data["episodes"]} == {_slug(e).lower() for e in show.episodes} dates = [e["date"] for e in data["episodes"]] assert dates == sorted(dates, reverse=True), "episodes must be newest first" for ep in data["episodes"]: - assert ep["title"], f"{ep['slug']}: empty title" - assert re.fullmatch(rf"{HOST}/show/{show.slug}/{re.escape(ep['slug'].lower())}/", ep["url"]), ep["url"] - assert isinstance(ep["hosts"], (list, type(None))), f"{ep['slug']}: hosts" - assert isinstance(ep["guests"], (list, type(None))), f"{ep['slug']}: guests" - assert all(t["url"] for t in ep["transcripts"] or []), f"{ep['slug']}: transcript without url" + slug = ep["url"].rstrip("/").rsplit("/", 1)[-1] + assert set(ep) == {"episode", "title", "date", "url", "json_url", "markdown_url"}, f"{slug}: {sorted(ep)}" + assert re.fullmatch(rf"{HOST}/show/{show.slug}/{re.escape(slug)}\.json", ep["json_url"]), ep["json_url"] + assert ep["title"], f"{slug}: empty title" + assert re.fullmatch(rf"{HOST}/show/{show.slug}/{re.escape(slug)}/", ep["url"]), ep["url"] + assert re.fullmatch(rf"{HOST}/show/{show.slug}/{re.escape(slug)}\.md", ep["markdown_url"]), ep["markdown_url"] @mark.parametrize("show", SHOW_PARAMS) @@ -231,7 +348,8 @@ def test_show_llms_newest_oldest_match_json(api_request_context: APIRequestConte text = _get(api_request_context, f"/show/{show.slug}/llms.txt", "text/plain").text() episodes = _get(api_request_context, f"/show/{show.slug}/episodes.json", "application/json").json()["episodes"] for label, ep in (("Newest", episodes[0]), ("Oldest", episodes[-1])): - assert re.search(rf"{label}: `{HOST}/show/{show.slug}/{re.escape(ep['slug'].lower())}/index\.md`", text), label + slug = ep["url"].rstrip("/").rsplit("/", 1)[-1] + assert re.search(rf"{label}: `{HOST}/show/{show.slug}/{re.escape(slug)}\.md`", text), label @mark.parametrize("show", SHOW_PARAMS) @@ -239,7 +357,7 @@ def test_show_markdown_twin(api_request_context: APIRequestContext, show: Show): """ Show twin has the title, its URL, links to the show llms.txt and the RSS feed """ - text = _get(api_request_context, f"/show/{show.slug}/index.md", "text/markdown").text() + text = _get(api_request_context, f"/show/{show.slug}/show.md", "text/markdown").text() assert text.startswith(f"# {show.title}\n"), "H1 must be the show title" assert re.search(rf"^URL: {HOST}/show/{show.slug}/$", text, re.M), "missing URL line" assert re.search(rf"\[llms\.txt\]\({HOST}/show/{show.slug}/llms\.txt\)", text), "missing llms.txt link" @@ -248,34 +366,182 @@ def test_show_markdown_twin(api_request_context: APIRequestContext, show: Show): assert "{{" not in text and "+++" not in text, "template or front matter leaked" +@mark.parametrize( + "path, first_note", + [ + param(CONTENT_SHOW / "coder-radio" / "0000.md", None, id="episode-links-heading-only"), + param(CONTENT_SHOW / "coder-radio" / "0001.md", "#### What is Coder Radio?", id="episode-links-heading-then-notes"), + param(CONTENT_SHOW / "coder-radio" / "0055.md", None, id="empty-body"), + ], +) +def test_episode_markdown_show_notes(api_request_context: APIRequestContext, path: Path, first_note: str | None): + """ + The body's leading Episode Links heading is replaced by ## Show Notes; a body that is only that heading, or empty, gets no section + """ + ep = load_episode(path) + text = _get(api_request_context, f"{ep.url.rstrip('/')}.md", "text/markdown").text() + assert "Episode Links" not in text + if first_note is None: + assert "## Show Notes" not in text + else: + assert re.search(rf"^## Show Notes\n+{re.escape(first_note)}$", text, re.M), "notes must follow the heading directly" + + @mark.parametrize("ep", [param(e, id=e.url, marks=mark.episodes) for e in SAMPLE_EPISODES]) def test_episode_markdown_twin(api_request_context: APIRequestContext, ep: Episode): """ Episode twin resolves at the lowercase permalink and carries the front matter facts """ - text = _get(api_request_context, f"{ep.url}index.md", "text/markdown").text() + text = _get(api_request_context, f"{ep.url.rstrip('/')}.md", "text/markdown").text() assert text.splitlines()[0].strip() == f"# {ep.data['title']}".strip(), "H1 must be the episode title" assert re.search(rf"^URL: {HOST}{re.escape(ep.url)}$", text, re.M), "missing URL line" assert f"- Episode: {ep.number}\n" in text assert f"- Date: {_episode_date(ep)}\n" in text - if ep.data.get("hosts"): - assert f"- Hosts: {', '.join(ep.data['hosts'])}\n" in text - if ep.data.get("guests"): - assert f"- Guests: {', '.join(ep.data['guests'])}\n" in text - for transcript in ep.data.get("transcripts") or []: - assert f"]({transcript['url']})" in text, f"missing transcript {transcript['url']}" + for label, key in (("Hosts", "hosts"), ("Guests", "guests")): + slugs = ep.data.get(key) or [] + line = re.search(rf"^- {label}: (.*)$", text, re.M) + assert bool(line) == bool(slugs), f"{label} line presence" + for slug in slugs: + link = rf"\[[^\]]+\]\({HOST}/people/{re.escape(slug)}\.md\)" + if person_type(slug): + assert re.search(link, line.group(1)), f"{slug} should link to its people page" + else: + assert slug in line.group(1) and not re.search(link, line.group(1)), f"{slug} has no people page" + transcripts = ep.data.get("transcripts") or [] + assert ("\n## Transcripts\n" in text) == bool(transcripts) + for transcript in transcripts: + assert f"- [{transcript.get('type') or 'transcript'}]({transcript['url']})\n" in text, f"missing transcript {transcript['url']}" + if not ep.body: + assert "\n## Show Notes\n" not in text, "no body, no Show Notes" + assert "Episode Links" not in text, "the Show Notes heading replaces the body's own Episode Links heading" sponsors = [s for s in ep.data.get("sponsors") or [] if sponsor_exists(s)] + assert ("\n## Sponsors\n" in text) == bool(sponsors) if sponsors: - assert "\nSponsors:\n" in text for shortname in sponsors: assert re.search(rf"^- \[.+\]\({re.escape(sponsor_link(shortname))}\)", text, re.M), f"{shortname}: links to the sponsor's own site" assert "{{" not in text and "+++" not in text, "template or front matter leaked" +def _notes(ep: Episode) -> str: + return re.sub(r"\A(?:\s*(?:#{1,6}\s*|\*\*)Episode Links(?:\*\*)?:?[ \t]*(?:\n|\Z))+", "", ep.body).lstrip("\r\n") + + +def _spread(episodes: list[Episode], n: int = 8) -> list[Episode]: + step = max(1, len(episodes) // n) + return episodes[::step][:n] + + +ALL_EPISODES: list[Episode] = [e for show in SHOWS for e in show.episodes] +INDENTED_NOTES = _spread([e for e in ALL_EPISODES if re.match(r"[ \t]+[*-] ", _notes(e))]) +MULTILINE_DESCRIPTIONS = _spread([e for e in ALL_EPISODES if "\n" in (e.data.get("description") or "").strip()]) +ESCAPED_ENTITIES = _spread([e for e in ALL_EPISODES if re.search(r"&(?:#x27|#39|quot|amp);", e.body)]) +ENTITY = re.compile(r"&(?:#x27|#39|quot|amp);") + + +@mark.parametrize("ep", [param(e, id=e.url) for e in INDENTED_NOTES]) +def test_episode_markdown_show_notes_keep_list_indent(api_request_context: APIRequestContext, ep: Episode): + """ + A Show Notes list indented in the source keeps every item at the same depth, the first included + """ + text = _get(api_request_context, f"{ep.url.rstrip('/')}.md", "text/markdown").text() + first = _section(text, "\n## Show Notes\n").lstrip("\r\n").splitlines()[0] + indent = lambda line: len(line) - len(line.lstrip()) + assert indent(first) == indent(_notes(ep).splitlines()[0]), f"first Show Notes line {first!r} lost its indent" + + +@mark.parametrize("ep", [param(e, id=e.url) for e in MULTILINE_DESCRIPTIONS]) +def test_episode_markdown_multiparagraph_description_stays_quoted(api_request_context: APIRequestContext, ep: Episode): + """ + Every line of a multi-line description sits inside the blockquote, with no stray carriage returns + """ + text = _get(api_request_context, f"{ep.url.rstrip('/')}.md", "text/markdown").text() + quoted = [line[1:].strip() for line in text.splitlines() if line.startswith(">")] + for line in ep.data["description"].replace("\r\n", "\n").splitlines(): + if line.strip(): + assert line.strip() in quoted, f"description line {line.strip()!r} is outside the blockquote" + assert "\r" not in text + + +@mark.parametrize("ep", [param(e, id=e.url) for e in ESCAPED_ENTITIES]) +def test_episode_markdown_has_no_escaped_entities(api_request_context: APIRequestContext, ep: Episode): + """ + ' ' " and & in the source body appear as the characters themselves in the markdown twin + """ + text = _get(api_request_context, f"{ep.url.rstrip('/')}.md", "text/markdown").text() + assert not ENTITY.findall(text), ENTITY.findall(text)[:5] + + +@mark.parametrize("show", SHOW_PARAMS) +def test_show_llms_txt_recent_entries_are_single_lines(api_request_context: APIRequestContext, show: Show): + """ + A multi-line episode description never breaks an llms.txt list item + """ + text = _get(api_request_context, f"/show/{show.slug}/llms.txt", "text/plain").text() + recent = _section(text, "## Most recent episodes", "## Episode archive") + stray = [line for line in recent.splitlines()[1:] if line.strip() and not line.startswith("- [")] + assert not stray, stray[:3] + + +SPREAD_EPISODES = _spread(ALL_EPISODES, 40) + + +@mark.parametrize("ep", SPREAD_EPISODES, ids=lambda e: f"{e.show}-{e.url.rstrip('/').rsplit('/', 1)[-1]}") +def test_episode_markdown_twin_has_every_episode_json_fact(api_request_context: APIRequestContext, ep: Episode): + """ + An LLM reading .md instead of .json still gets tags, image, every audio and video URL, and chapters + """ + base = ep.url.rstrip("/") + data = _get(api_request_context, f"{base}.json", "application/json").json() + text = _get(api_request_context, f"{base}.md", "text/markdown").text() + + for key, label in ( + ("audio_alt_url", "Audio (alternate)"), + ("audio_ogg_url", "Audio (OGG)"), + ("youtube_url", "YouTube"), + ("header_image", "Image"), + ): + if key in data: + assert f"- {label}: {data[key]}\n" in text, f"{key} missing" + for key, label in (("url", "Video"), ("hd_url", "Video (HD)"), ("mobile_url", "Video (mobile)")): + if key in data.get("video", {}): + assert f"- {label}: {data['video'][key]}\n" in text, f"video.{key} missing" + if data["tags"]: + assert f"- Tags: {', '.join(data['tags'])}\n" in text + else: + assert "- Tags:" not in text + chapters = data.get("chapters", []) + assert ("## Chapters" in text) == bool(chapters) + for chapter in chapters: + t = int(chapter["startTime"]) + stamp = f"{t // 3600:02d}:{t // 60 % 60:02d}:{t % 60:02d}" + assert re.search(rf"^- {stamp} .*{re.escape(chapter['title'])}", text, re.M), f"chapter {stamp} missing" + + +def test_show_root_markdown_lists_every_show_grouped_by_status(api_request_context: APIRequestContext): + """ + /show.md is the show directory: active shows first, then archived + """ + text = _get(api_request_context, "/show.md", "text/markdown").text() + assert "- Status:" not in text + for active, heading, until in ((True, "## Active shows", "## Archived shows"), (False, "## Archived shows", None)): + block = _section(text, heading, until) + for show in SHOWS: + line = rf"^- \[.*\]\({HOST}/show/{show.slug}/show\.md\): {len(show.episodes)} episodes" + assert bool(re.search(line, block, re.M)) == (show.active == active), f"{show.slug} in wrong group" + + +@mark.parametrize("show", SHOW_PARAMS) +def test_show_markdown_about_has_no_html_or_repeated_description(api_request_context: APIRequestContext, show: Show): + text = _get(api_request_context, f"/show/{show.slug}/show.md", "text/markdown").text() + assert ".md, like episodes" def test_guests_twin(api_request_context: APIRequestContext): - text = _get(api_request_context, "/guests/index.md", "text/markdown").text() - assert re.search(rf"\]\({HOST}/guests/[^/]+/index\.md\)", text), "guests twin lists no guests" + text = _get(api_request_context, "/guests.md", "text/markdown").text() + assert re.search(rf"\]\({HOST}/guests/[^/)]+\.md\)", text), "guests twin lists no guests" assert "{{" not in text, "template error" @@ -320,17 +588,107 @@ def test_home_discovery_link(page: Page): @mark.only_browser("chromium") @mark.parametrize( - "path, llms", - [param("/community/", "/llms.txt", id="community")] - + [param(f"/show/{s.slug}/", f"/show/{s.slug}/llms.txt", id=s.slug) for s in SHOWS] - + [param(SAMPLE_EPISODES[0].url, f"/show/{SAMPLE_EPISODES[0].show}/llms.txt", id="episode")], + "path, llms, markdown", + [param("/community/", "/llms.txt", "/community.md", id="community")] + + [param("/membership/", "/llms.txt", "/membership.md", id="page")] + + [param("/sponsors/", "/llms.txt", "/sponsors.md", id="root-list")] + + [param("/show/linux-unplugged/subscribe/", "/show/linux-unplugged/llms.txt", "/show/linux-unplugged/subscribe.md", id="subscribe")] + + [param(f"/show/{s.slug}/", f"/show/{s.slug}/llms.txt", f"/show/{s.slug}/show.md", id=s.slug) for s in SHOWS] + + [ + param( + SAMPLE_EPISODES[0].url, + f"/show/{SAMPLE_EPISODES[0].show}/llms.txt", + f"{SAMPLE_EPISODES[0].url.rstrip('/')}.md", + id="episode", + ) + ], ) -def test_discovery_links(page: Page, path: str, llms: str): +def test_discovery_links(page: Page, path: str, llms: str, markdown: str): """ Every page points at its nearest llms.txt (describedby) and its markdown twin (alternate) """ page.goto(path) expect(page.locator('link[rel="describedby"]')).to_have_attribute("href", re.compile(rf"^{HOST}{re.escape(llms)}$")) expect(page.locator('link[rel="alternate"][type="text/markdown"]')).to_have_attribute( - "href", re.compile(rf"^{HOST}{re.escape(path)}index\.md$") + "href", re.compile(rf"^{HOST}{re.escape(markdown)}$") ) + + +@mark.parametrize( + "path", + [ + "/membership/index.md", + "/contact/index.md", + "/boost/index.md", + "/community/picks/index.md", + "/sponsors/index.md", + "/hosts/index.md", + "/guests/index.md", + "/show/linux-unplugged/subscribe/index.md", + "/community/index.md", + "/community/github/index.md", + "/live/index.md", + "/archive/index.md", + "/people/index.md", + "/show/index.md", + "/search-index/index.md", + ], +) +def test_old_page_twin_urls_are_gone(api_request_context: APIRequestContext, path: str): + """ + Page markdown twins are .md like their .json; the old index.md must not linger + """ + assert api_request_context.get(path).status == 404, f"{path} should no longer exist" + + +@mark.parametrize("show", SHOW_PARAMS) +def test_old_show_and_episode_twin_urls_are_gone(api_request_context: APIRequestContext, show: Show): + """ + Show and episode markdown twins moved from index.md to show.md and .md; the old URLs must not linger + """ + newest = show.newest_first[0] + for path in (f"/show/{show.slug}/index.md", f"{newest.url}index.md"): + assert api_request_context.get(path).status == 404, f"{path} should no longer exist" + + +@mark.parametrize("show", SHOW_PARAMS) +def test_show_markdown_twin_has_every_show_json_fact(api_request_context: APIRequestContext, show: Show): + """ + An LLM reading show.md instead of show.json gets the main facts: status, hosts, links, feeds, and which episodes exist + """ + data = _get(api_request_context, f"/show/{show.slug}/show.json", "application/json").json() + text = _get(api_request_context, f"/show/{show.slug}/show.md", "text/markdown").text() + + assert f"- Status: {'active' if data['active'] else 'archived'}\n" in text + assert f"- Episodes: {data['episode_count']}\n" in text + if data.get("description"): + assert f"> {data['description']}\n" in text + for key in ("episodes_url", "llms_url"): + assert data[key] in text, f"{key} missing" + if "podverse_url" in data: + assert data["podverse_url"] in text, "podverse_url missing" + assert data["markdown_url"] not in text.replace(f"URL: {data['url']}", ""), "no self link to show.md" + for host in data["hosts"]: + assert host.get("name", host["slug"]) in text, f"host {host['slug']} missing" + if "url" in host: + assert f"{host['url'].rstrip('/')}.md)" in text, f"host {host['slug']} should link its markdown twin" + for name, url in data["links"].items(): + assert f"- {name}: {url}\n" in text, f"link {name} missing" + + listed = _get(api_request_context, f"/show/{show.slug}/episodes.json", "application/json").json()["episodes"] + numbers = sorted(e["episode"] for e in listed if isinstance(e["episode"], int)) + special = [e for e in reversed(listed) if not isinstance(e["episode"], int)] + if numbers: + assert f"- Numbered episodes: {numbers[0]} to {numbers[-1]}" in text + missing = ", ".join(str(n) for n in sorted(set(range(numbers[0], numbers[-1] + 1)) - set(numbers))) + assert (f"- Missing numbers: {missing}\n" in text) == bool(missing) + for episode in special: + line = re.search(rf"^ - {re.escape(str(episode['episode']))} Β· (\d{{4}}-\d{{2}}-\d{{2}}) Β· \[(.*)\]\((.*)\)$", text, re.M) + assert line, f"special episode {episode['episode']} missing" + assert line.group(1) == episode["date"][:10] + assert line.group(2) == episode["title"].strip() + assert line.group(3) == episode["url"].rstrip("/") + ".md" + latest = data["latest_episode"] + assert f"- Latest episode: {latest['episode']} Β· {latest['date'][:10]} Β· [{latest['title'].strip()}]({latest['url'].rstrip('/')}.md)\n" in text + if not special: + assert "Special episodes" not in text diff --git a/test/e2e/test_membership.py b/test/e2e/test_membership.py index 9d9d4e28a..14ae02e6b 100644 --- a/test/e2e/test_membership.py +++ b/test/e2e/test_membership.py @@ -1,37 +1,61 @@ -import re +import tomllib from pathlib import Path -from pytest import fixture, mark -from playwright.sync_api import Page, expect +from pytest import fixture, param, mark +from playwright.sync_api import APIRequestContext, Page, expect MEMBERSHIP_MD = Path(__file__).parents[2] / "content/membership/index.md" -MEMBERSHIP_LINK = re.compile( - r"\[([^\]]+)\]\((https://(?:jupitersignal\.memberful\.com|www\.jupiter\.party)/[^)]*)\)" -) -MEMBERSHIP_LINKS = MEMBERSHIP_LINK.findall(MEMBERSHIP_MD.read_text(encoding="utf-8")) +MEMBERSHIP = tomllib.loads(MEMBERSHIP_MD.read_text(encoding="utf-8").split("+++")[1]) +PLANS = [plan for group in MEMBERSHIP["plan_groups"] for plan in group["plans"]] +PLAN_PARAMS = [param(p["name"], p["url"], id=p["url"]) for p in PLANS] -@fixture(autouse=True) -def setup(page: Page): - """ - Code here will run for every test in this file - """ +@fixture +def membership(page: Page) -> Page: page.goto("/membership/") + return page -def test_membership_links_found(): +def test_membership_plans_found(): """ - Guard against the regex silently matching nothing + Guard against the front matter silently losing its plans """ - assert MEMBERSHIP_LINKS + assert PLANS and MEMBERSHIP["perks"] -@mark.parametrize("text,href", MEMBERSHIP_LINKS, ids=[href for _, href in MEMBERSHIP_LINKS]) -def test_membership_links(page: Page, text: str, href: str): +@mark.parametrize("text,href", PLAN_PARAMS) +def test_membership_links(membership: Page, text: str, href: str): """ - Ensure every membership link in content/membership/index.md renders with the same href and text + Ensure every plan in content/membership/index.md front matter renders with the same href and text """ - link = page.locator(f'a[href="{href}"]') + link = membership.locator(f'a[href="{href}"]') expect(link).to_have_count(1) expect(link).to_be_visible() expect(link).to_have_text(text) + + +@mark.parametrize("perk", [param(p, id=p["show"]) for p in MEMBERSHIP["perks"]]) +def test_membership_perks(membership: Page, perk: dict): + """ + Each show's perks are listed under a heading linking to the show + """ + heading = membership.locator("h4", has=membership.locator(f'a[href="/show/{perk["show"]}/"]')) + expect(heading).to_have_count(1) + items = heading.locator("xpath=following-sibling::ul[1]/li") + expect(items).to_have_count(len(perk["items"])) + for item, li in zip(perk["items"], items.all()): + expect(li).to_contain_text(item["name"]) + + +def test_membership_markdown(api_request_context: APIRequestContext): + """ + /membership.md carries every plan and perk from the front matter, not raw shortcodes + """ + text = api_request_context.get("/membership.md").text() + for plan in PLANS: + assert f"- [{plan['name']}]({plan['url']})" in text, plan["name"] + for perk in MEMBERSHIP["perks"]: + assert f"/show/{perk['show']}/)" in text, perk["show"] + for item in perk["items"]: + assert f"- {item['name']}" in text, item["name"] + assert "{{" not in text and "+++" not in text, "template or front matter leaked" diff --git a/test/unit/test_public_json.py b/test/unit/test_public_json.py new file mode 100644 index 000000000..38468ae1b --- /dev/null +++ b/test/unit/test_public_json.py @@ -0,0 +1,24 @@ +import os +import re +from pathlib import Path + +import pytest + +PUBLIC_DIR = Path(os.environ.get("PUBLIC_DIR", "public")) + +if not (PUBLIC_DIR / "show").is_dir(): + pytest.skip(f"{PUBLIC_DIR}/show not found; build the site first", allow_module_level=True) + +JSON_FILES = sorted((PUBLIC_DIR / "show").glob("**/*.json")) + + +def test_bytes_are_written_as_plain_integers(): + """ + hugo --minify rewrites 50108000 as 50108e3, which JSON parsers read as a float + """ + bad = [] + for path in JSON_FILES: + for value in re.findall(r'"bytes":\s*([^,}\s]+)', path.read_text(encoding="utf-8")): + if not value.isdigit(): + bad.append(f"{path}: bytes {value}") + assert not bad, f"{len(bad)} non-integer bytes value(s):\n" + "\n".join(bad[:20]) diff --git a/themes/jb/assets/css/components/audioplayer.sass b/themes/jb/assets/css/components/audioplayer.sass index d24a870bf..cb7e3cf12 100644 --- a/themes/jb/assets/css/components/audioplayer.sass +++ b/themes/jb/assets/css/components/audioplayer.sass @@ -1,7 +1,22 @@ +@use "../variables" as v + #pv-embed-player margin: 24px auto padding: 0 border: none height: 170px width: 100% - display: flex \ No newline at end of file + display: flex + +audio + border-radius: 30px + color-scheme: dark + + // Chrome ignores color-scheme for the panel fill; Firefox has no pseudo-elements, so it stays on its dark default + &::-webkit-media-controls-panel + background-color: v.$jb-darker + +// The timeline fill is painted natively, so tint it with a luma-to-colour matrix: white maps to +// v.$jb-blue-light (#6ecff5, the is-info button colour) and the grey buffered track to a darker blue +audio::-webkit-media-controls-timeline, video::-webkit-media-controls-timeline + filter: url("data:image/svg+xml,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%3E%3Cfilter%20id%3D%27t%27%20color-interpolation-filters%3D%27sRGB%27%3E%3CfeColorMatrix%20type%3D%27matrix%27%20values%3D%270.0917%200.3085%200.0311%200%200%20%200.1726%200.5806%200.0586%200%200%20%200.2043%200.6872%200.0694%200%200%20%200%200%200%201%200%27%2F%3E%3C%2Ffilter%3E%3C%2Fsvg%3E#t") diff --git a/themes/jb/assets/css/components/live.sass b/themes/jb/assets/css/components/live.sass index 92bea7d7f..c3ddbc198 100644 --- a/themes/jb/assets/css/components/live.sass +++ b/themes/jb/assets/css/components/live.sass @@ -11,6 +11,9 @@ display: flex justify-content: center + audio + width: 75% + .video-wrapper position: relative display: grid diff --git a/themes/jb/assets/js/jb-live.js b/themes/jb/assets/js/jb-live.js deleted file mode 100644 index 15e87e551..000000000 --- a/themes/jb/assets/js/jb-live.js +++ /dev/null @@ -1,74 +0,0 @@ -/* Query URLs */ -const JoopTubeURL = new URL("https://jupiter.tube/api/v1/"); -const JoopTubeQuery = - ({ isLive }) => new URL("video-channels/live/videos?" + - `isLive=${isLive ? true : false}` + // Normally redundant, avoids injection - `&skipCount=false` + - `&count=1` + - `&sort=-createdAt`, - JoopTubeURL); -const liveRequestOptions = { - method: 'GET', - headers: new Headers({ "Accept": "application/json" }), - redirect: 'follow' -} - -/** - * Gets the embedable link from a PeerTube Video object passed via Promise - * - * This assumes the result of the promise of is an API repsonse - * with at least one result. If no shows are live the API response - * will be undefined at `promiseResult.value`, don't poke it. - * - * @param {PromiseSettledResult} show The final result of either fetch call above - * @returns {URL | undefined} The URL object referencing the embedable video - */ -const getEmbedLink = show => { - if (!show || show.status === 'rejected') { - return undefined - } - - const promiseResult = show.value - /** - * @const - * @type {string | undefined} - */ - const embedPath = promiseResult.data?.[0]?.embedPath; - return !embedPath ? undefined : new URL(embedPath, JoopTubeURL); -}; - -/** - * Queries the 'live' channel at jupiter.tube for either - * a) the embed link of the currently live show - * OR - * b) the embed link of the most recently aired show - * @returns {string} The embedable URL - */ -async function jbLive() { - const liveShowQuery = fetch(JoopTubeQuery({ isLive: true }), liveRequestOptions) - .then(response => response.text()) - .then(result => JSON.parse(result)) - .catch(error => console.error('Error while fetching live URL!', error)); - - const archivedShowQuery = fetch(JoopTubeQuery({ isLive: false }), liveRequestOptions) - .then(response => response.text()) - .then(result => JSON.parse(result)) - .catch(error => console.error(('Error while fetching live URL!', error))); - - const [liveShow, archivedShow] = await Promise.allSettled([liveShowQuery, archivedShowQuery]) - - return getEmbedLink(liveShow)?.toString() ?? getEmbedLink(archivedShow)?.toString(); -} -/** - * Queries the 'live' channel at jupiter.tube for live - * show status and sets the CSS style background-color red for #livebutton - */ -async function doLiveHighlight() { - fetch(JoopTubeQuery({ isLive: true }), liveRequestOptions) - .then(response => response.text()) - .then(result => JSON.parse(result)) - .then(data => {if(data.total > 0) - document.getElementById("mainnavigation").classList.add("is-live") - }) - .catch(error => console.error('Error while fetching live URL!', error)); -} diff --git a/themes/jb/assets/js/live-indicator.js b/themes/jb/assets/js/live-indicator.js new file mode 100644 index 000000000..74646e9ac --- /dev/null +++ b/themes/jb/assets/js/live-indicator.js @@ -0,0 +1,15 @@ +document.addEventListener("DOMContentLoaded", async () => { + const nav = document.getElementById("mainnavigation"); + if (!nav || !nav.dataset.liveUrl) return; + try { + const response = await fetch(nav.dataset.liveUrl); + if (!response.ok) return; + const text = await response.text(); + // A live HLS playlist has no #EXT-X-ENDLIST + if (text.includes("#EXTM3U") && !text.includes("#EXT-X-ENDLIST")) { + nav.classList.add("is-live"); + } + } catch (err) { + // offline or CORS-blocked: leave the navbar unhighlighted + } +}); diff --git a/themes/jb/layouts/_default/list.md b/themes/jb/layouts/_default/list.md index 46cb6567d..670155c74 100644 --- a/themes/jb/layouts/_default/list.md +++ b/themes/jb/layouts/_default/list.md @@ -1,6 +1 @@ -# {{ .Title }} - -URL: {{ .Permalink }} -{{ with .Description }}> {{ . }} -{{ end }} -{{ partial "llms-body.md" . }} +{{ partial "md/list.md" . }} diff --git a/themes/jb/layouts/_default/single.json b/themes/jb/layouts/_default/single.json new file mode 100644 index 000000000..3289322e7 --- /dev/null +++ b/themes/jb/layouts/_default/single.json @@ -0,0 +1 @@ +{{ partial "json/page.html" . | partial "json-strip-null.html" | jsonify (dict "indent" " " "noHTMLEscape" true) }} diff --git a/themes/jb/layouts/_default/term.md b/themes/jb/layouts/_default/term.md index 1e238527b..adf7196f6 100644 --- a/themes/jb/layouts/_default/term.md +++ b/themes/jb/layouts/_default/term.md @@ -5,5 +5,5 @@ URL: {{ .Permalink }} {{ end }} {{ if $person }}{{ partial "person-details.md" $person }} {{ end }} -{{ range .Pages }}- [{{ .Title }}]({{ .Permalink }}index.md) +{{ range .Pages }}- [{{ .Title }}]({{ partial "markdown-url.html" . }}) {{ end }} diff --git a/themes/jb/layouts/episode/single.html b/themes/jb/layouts/episode/single.html index 8587334d6..d049a154f 100644 --- a/themes/jb/layouts/episode/single.html +++ b/themes/jb/layouts/episode/single.html @@ -52,7 +52,7 @@
-