跳转到内容
下载

将您的视频博客搬上电视

假设您有一个博客,每篇文章都附有一段视频,而您希望在大屏幕上观看。大多数博客都会发布 RSS 订阅源,文章中的视频即订阅源中的 <enclosure>。在本教程中,您将编写一个读取此类订阅源的插件,并将其安装到杨桃播放器中。

本教程会用到插件的所有组成部分:清单、四个必需的函数、由用户填写的设置、缓存、用户能够理解的错误提示,以及无需联网即可运行的测试。完成后的插件约有 80 行代码。您需要 Node.js 20 或更高版本;最后安装时,还需要一台装有杨桃播放器的电视、模拟器或手机。

终端窗口
yonto-plugin init video-blog --name "Video blog"

此命令会创建 video-blog 目录,其中的 video-blog-plugin.js 是一个占位插件,无需修改即可通过 lint 和 doctor。您将在第 1 步中替换其内容。

以下是插件要读取的订阅源。请在 video-blog 目录中新建 site 目录,并将其保存为 site/feed.xml。第三篇文章没有视频,这一点稍后会用到。

<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/">
<channel>
<title>Sourdough Diaries</title>
<link>https://sourdough.example.com/</link>
<description>Bread, on camera.</description>
<item>
<title>My first sourdough loaf</title>
<link>https://sourdough.example.com/first-loaf/</link>
<guid isPermaLink="false">post-3</guid>
<pubDate>Sat, 07 Jun 2025 08:00:00 +0000</pubDate>
<description><![CDATA[Starter, flour, water & a lot of patience.]]></description>
<enclosure url="https://sourdough.example.com/video/first-loaf.mp4" length="48211032" type="video/mp4"/>
<media:thumbnail url="https://sourdough.example.com/img/first-loaf.jpg"/>
</item>
<item>
<title>Feeding the starter</title>
<link>https://sourdough.example.com/feeding/</link>
<guid isPermaLink="false">post-2</guid>
<pubDate>Sat, 24 May 2025 08:00:00 +0000</pubDate>
<description>How often, how much, and what the bubbles mean.</description>
<enclosure url="https://sourdough.example.com/video/feeding.mp4" length="30118222" type="video/mp4"/>
<media:thumbnail url="https://sourdough.example.com/img/feeding.jpg"/>
</item>
<item>
<title>Why I stopped using a Dutch oven (text only)</title>
<link>https://sourdough.example.com/dutch-oven/</link>
<guid isPermaLink="false">post-1</guid>
<pubDate>Sat, 10 May 2025 08:00:00 +0000</pubDate>
<description>No video this week, so this post is not a title.</description>
</item>
</channel>
</rss>

请另开一个终端,在电脑上启动本地服务以提供该文件,并保持此终端处于打开状态:

终端窗口
cd video-blog/site
python3 -m http.server 8765

将 video-blog-plugin.js 的全部内容替换为以下代码。首先是清单,即位于文件开头的注释:

/* yonto-plugin
{
"kind": "content-source",
"id": "video-blog",
"name": "Video blog",
"version": "1.0.0",
"contractVersion": 21,
"description": "A video blog, read from its RSS feed: every post with a video attached becomes a title.",
"probeQuery": "starter",
"provides": "source-type",
"allowedHosts": [],
"configSchema": [
{ "id": "feedUrl", "label": "Feed URL", "type": "url", "required": true }
]
}
*/
  • provides: "source-type" 表示这是一类由用户自行配置的片源,因此会出现在添加片源表单的类型列表中。如果插件本身就是一个固定的片源,请改为 "source"。
  • configSchema 即该表单。其中只有一个字段,即用户必须填写的 url。
  • allowedHosts 列出插件可以访问的网站。此处留空,因为该插件只读取用户在 feedUrl 中填写的网站,而 url 字段中的主机本身就允许访问。
  • probeQuery 是 doctor 测试插件时用于搜索的关键词。
  • contractVersion 是插件所依赖的接口版本,并非由您自行选择。请先编写插件,运行 lint,再将其给出的数字填回此处。目前所有插件均为 21,这是应用仍会运行的最低契约版本。

在清单下方添加一个函数,用于获取订阅源,并将每个条目转换为一篇文章:

const FEED_TTL_SECONDS = 300;
async function readPosts() {
const cacheKey = `feed:${yonto.config.feedUrl}`;
const cached = await yonto.store.get(cacheKey);
if (cached) return cached;
let response;
try {
response = await yonto.fetch(yonto.config.feedUrl);
} catch (error) {
yonto.log(`feed request failed: ${error.code}`);
throw yonto.error.unreachable('the feed did not answer');
}
if (response.status !== 200) throw yonto.error.unavailable(`the feed answered ${response.status}`);
const $ = yonto.xml.load(response.body);
if ($('rss > channel').length === 0) throw yonto.error.unavailable('the address is not an RSS feed');
const posts = $('item')
.toArray()
.map((item) => postFrom($(item)))
.filter((post) => post.videoUrl);
try {
await yonto.store.set(cacheKey, posts, FEED_TTL_SECONDS);
} catch (error) {
yonto.log(`feed not cached: ${error.code}`);
}
return posts;
}
function postFrom(item) {
const enclosure = item.find('enclosure');
const isVideo = (enclosure.attr('type') ?? '').startsWith('video/');
return {
id: item.find('guid').text().trim() || item.find('link').text().trim(),
title: item.find('title').text().trim(),
synopsis: item.find('description').text().trim(),
year: (item.find('pubDate').text().match(/\d{4}/) ?? [])[0],
posterUrl: item.find('media\\:thumbnail').attr('url'),
videoUrl: isVideo ? enclosure.attr('url') : undefined,
mimeType: isVideo ? enclosure.attr('type') : undefined,
};
}

这里用到的都是宿主提供的接口,今后还会经常用到:

  • yonto.config.feedUrl 是用户输入的内容。每项设置都是字符串,留空的字段根本不存在。
  • 无论状态码如何,yonto.fetch 都会返回响应;仅在完全没有响应时才会拒绝,并附带一个说明原因的 code。插件将前一种情况转换为 yonto.error.unreachable(…),将错误的状态码转换为 unavailable(…)。您传入的文字会原样显示在应用的错误界面中,用户看到的正是这段文字,因此请用一句简短的话说明出错的环节。
  • yonto.log 会向日志写入一行内容。请勿将网址、密钥或用户的搜索内容写入日志,因为电视会保留这份日志。
  • yonto.xml.load 返回 cheerio 的 $,用于解析 XML 文档。yonto.html.load 以相同方式解析网页。选择带命名空间的标签时,需要转义冒号,写为 media\\:thumbnail。
  • yonto.store 是该片源专属的缓存。订阅源会缓存五分钟,因此打开标题时无需再次获取。set 也可能被拒绝,因此请仅将其用作缓存,切勿依赖它。
  • .filter 仅保留带有视频的文章,因此 Dutch oven 那篇文章不会出现在您的片库中。

最后,导出杨桃播放器会调用的函数:

const summaryOf = ({ id, title, posterUrl, year }) => ({ id, title, posterUrl, year, type: 'movie' });
export default {
async getCategories() {
return [{ id: 'latest', name: 'Latest' }];
},
async getMediaList(categoryId, { page }) {
if (page > 1) return [];
return (await readPosts()).map(summaryOf);
},
async getMediaDetail(id) {
const post = (await readPosts()).find((candidate) => candidate.id === id);
if (!post) throw yonto.error.notFound(`no post ${id}`);
return {
...summaryOf(post),
synopsis: post.synopsis,
playbackOptions: [{ label: 'Watch', stream: { url: post.videoUrl, mimeType: post.mimeType } }],
};
},
async search(query) {
const needle = query.toLowerCase();
const posts = await readPosts();
return posts
.filter((post) => `${post.title} ${post.synopsis}`.toLowerCase().includes(needle))
.map(summaryOf);
},
};
  • getCategories 对应首页上方的标签。一个博客只有一个列表,因此只有一个分类。
  • getMediaList 接收分类的 id 和 { page },页码从 1 开始计数。订阅源没有分页,因此第 2 页返回空列表,杨桃播放器据此判断列表已经结束。
  • getMediaDetail 接收的是该插件之前返回过的 id。playbackOptions 是用户可以播放的内容,stream 是播放器要打开的网址。请求的文章不存在时,抛出 notFound。
  • search 是必需的,不支持搜索的片源同样需要导出它,并抛出 yonto.error.noSearch()。返回 [] 则表示已经搜索,但未找到任何结果。

在另一个终端中,进入 video-blog 目录:

终端窗口
yonto-plugin lint
✓ manifest id=video-blog version=1.0.0 contract=21 provides=source-type hosts=[]
✓ bundle /…/video-blog/video-blog-plugin.js builds
✓ contract 21

lint 只读取清单和代码,并不运行它们。如果您声明的是 20,它会拒绝:任何应用都不会运行低于 21 的插件。

接下来,使用真实的订阅源进行测试。需要设置的插件会从插件旁边的 doctor.json 读取设置,因此请新建该文件:

{ "feedUrl": "http://localhost:8765/feed.xml" }

插件访问您电脑本机上的地址会被拒绝,唯有用户在 url 字段中输入的地址例外,而此处的 doctor.json 就相当于这位用户。

终端窗口
yonto-plugin doctor

doctor 会像应用一样完整运行插件,每一步都以上一步的结果作为输入,并为每一步输出一行结果。如果您选择的 probeQuery 在文章中搜索不到,search 会以 EMPTY_RESULT 失败。这是有意为之:结果为空是插件最常见的故障形式,网站发生变化后,插件看似仍在正常工作,却不返回任何内容,因此 doctor 将其视为失败。

您也可以只调用一个函数,查看其返回结果:

终端窗口
yonto-plugin run . getMediaDetail '"post-3"'

参数为 JSON 格式,因此字符串需要加两层引号。

再次运行 doctor,录制订阅源的响应:

终端窗口
yonto-plugin doctor --record
yonto-plugin doctor --replay

--record 会将每个响应写入 fixtures/,--replay 则在断网状态下使用这些数据运行全部检查。将这些数据提交到仓库后,即使明年再修改插件,也能在一秒内完成验证,无需该博客在线。

在插件所在的目录中启动服务:

终端窗口
python3 -m http.server 8000

在杨桃播放器中,依次选择设置、高级、插件、从网址安装,然后粘贴 video-blog-plugin.js 的地址,例如在 Android 模拟器中为 http://10.0.2.2:8000/video-blog-plugin.js。在真实的电视或手机上,请改用电脑在局域网中的地址,因为 10.0.2.2 仅在模拟器中指向您的电脑。杨桃播放器会提示 http:// 链接未加密,在您自己的网络中测试时,这属于正常现象。选择读取插件,确认名称及其可访问的范围后,再选择安装。杨桃播放器会提示“接下来请设置一个片源。”,并带您进入已选好 Video blog 的添加片源。输入您博客的订阅源地址,选择测试连接,然后选择保存。

订阅源地址必须是电视能够访问的地址,请勿使用 localhost,因为它指向电视本身。示例订阅源中的视频是虚构的;如需实际观看内容,请将片源指向一个文章附有视频 enclosure 的真实博客。

  • 通过 getCategories 返回文章的分类,并在 getMediaList 中按所选分类进行筛选。
  • 如需读取分页的博客订阅源,让 getMediaList 返回 nextCursor 即可。
  • 改为读取 WordPress 博客的 JSON API,以代替 RSS 订阅源。只需使用 JSON.parse(response.body) 即可。

完成后的插件连同录制好的订阅源,就是一个现成的模板:yonto-plugin init my-blog --template video-blog 会生成一份副本供您作为起点。本教程未涉及的内容,请参阅插件参考。

杨桃播放器支持 Android 电视、Android 手机和平板、Windows、Mac 以及 Linux,iPhone、iPad 和 Apple TV 版即将推出,Android 版也即将登陆 Google Play。