<a id="embedded-content"></a>

# 嵌入内容

Wagtail 支持根据 YouTube、Reddit 等外部内容提供商上的内容 URL 来生成嵌入代码。
默认情况下，Wagtail 会使用 oEmbed 协议直接从相关提供商的站点获取
嵌入代码。

Wagtail 内置了最常见提供商的列表，这个列表可以
[通过设置](#customizing-embed-providers)来更改。Wagtail 也支持通过 [Embedly](#embedly) 和 [自定义嵌入查找器](#custom-embed-finders) 获取嵌入代码。

## 在站点中嵌入内容

对大多数提供商来说，Wagtail 的 embeds 模块开箱即用。
你可以用下列任一方法调用该模块：

### 富文本

Wagtail 默认的富文本编辑器有一个「media」图标，允许把嵌入内容
放入富文本。你无需做任何事来启用它；只要确保
富文本字段的内容在模板中经过了 `|richtext`
过滤器，因为正是它调用 embeds 模块来获取并
嵌套嵌入代码。

### `EmbedBlock` StreamField 区块类型

`EmbedBlock` 区块类型允许把嵌入内容
放入 `StreamField`。

`max_width` 和 `max_height` 参数会在获取嵌入代码时发送给提供商。

例如：

```python
from wagtail.embeds.blocks import EmbedBlock


class MyStreamField(blocks.StreamBlock):
    ...

    embed = EmbedBlock(max_width=800, max_height=400)
```

### `{% embed %}` 标签

语法：`{% embed <url> [max_width=<max width>] %}`

你可以把 URL 和一个可选的 `max_width` 参数传给 `{% embed %}` 标签，
从而在模板中嵌套嵌入内容。

`max_width` 参数会在获取嵌入代码时发送给提供商。

```html+django
{% load wagtailembeds_tags %}

{# Embed a YouTube video #}
{% embed 'https://www.youtube.com/watch?v=Ffu-2jEdLPw' %}

{# This tag can also take the URL from a variable #}
{% embed page.video_url %}
```

### 在 Python 中调用

你也可以调用内部的 `get_embed` 函数，它接收一个 URL 字符串，
返回一个 `Embed` 对象（见下面的模型文档）。它同样
接收 `max_width` 关键字参数，该参数会在获取嵌入代码时发送给提供商。

```python
from wagtail.embeds.embeds import get_embed
from wagtail.embeds.exceptions import EmbedException

try:
    embed = get_embed("https://www.youtube.com/watch?v=Ffu-2jEdLPw")

    print(embed.html)
except EmbedException:
    # Cannot find embed
    pass
```

<a id="configuring-embed-finders"></a>

## 配置嵌入「查找器」

嵌入查找器是 Wagtail 内部负责根据 URL 生成
嵌入代码的模块。

嵌入查找器通过 `WAGTAILEMBEDS_FINDERS` 设置来配置。它
是一个查找器配置列表，会按顺序逐个运行，直到其中一个成功返回嵌入内容：

默认配置是：

```python
WAGTAILEMBEDS_FINDERS = [{"class": "wagtail.embeds.finders.oembed"}]
```

<a id="oembed"></a>

### oEmbed（默认）

默认的嵌入查找器使用 oEmbed 协议直接从内容提供商
获取嵌入代码。Wagtail 内置了一个提供商列表，
这些提供商默认全部启用。你可以通过下面这个链接找到该提供商列表：

[https://github.com/wagtail/wagtail/blob/main/wagtail/embeds/oembed_providers.py](https://github.com/wagtail/wagtail/blob/main/wagtail/embeds/oembed_providers.py)

<a id="customizing-embed-providers"></a>

#### 定制提供商列表

你可以通过在查找器配置中指定提供商列表，
来限制允许使用哪些提供商。

例如，下面这个配置只允许从 Vimeo
和 Youtube 嵌套内容。它还添加了一个自定义提供商：

```python
from wagtail.embeds.oembed_providers import youtube, vimeo

# Add a custom provider
# Your custom provider must support oEmbed for this to work. You should be
# able to find these details in the provider's documentation.
# - 'endpoint' is the URL of the oEmbed endpoint that Wagtail will call
# - 'urls' specifies which patterns
my_custom_provider = {
    "endpoint": "https://customvideosite.com/oembed",
    "urls": [
        "^http(?:s)?://(?:www\\.)?customvideosite\\.com/[^#?/]+/videos/.+$",
    ],
}

WAGTAILEMBEDS_FINDERS = [
    {
        "class": "wagtail.embeds.finders.oembed",
        "providers": [youtube, vimeo, my_custom_provider],
    }
]
```

#### 定制单个提供商

多个查找器可以串联使用。这样可以只定制某一个提供商的
配置，而不影响其它提供商。

例如，下面这样就能要求 YouTube 以 HTTPS 返回视频
（对 YouTube 而言必须显式指定）：

```python
from wagtail.embeds.oembed_providers import youtube


WAGTAILEMBEDS_FINDERS = [
    # Fetches YouTube videos but puts ``?scheme=https`` in the GET parameters
    # when calling YouTube's oEmbed endpoint
    {
        "class": "wagtail.embeds.finders.oembed",
        "providers": [youtube],
        "options": {"scheme": "https"},
    },
    # Handles all other oEmbed providers the default way
    {
        "class": "wagtail.embeds.finders.oembed",
    },
]
```

#### Wagtail 如何使用多个查找器

如果多个提供商都能处理某个 URL（例如上面的配置中
请求了一个 YouTube 视频），会选择最靠前的那个查找器
来执行请求。

Wagtail 不会再去尝试运行其它查找器，即使所选的那个并未
返回嵌入内容。

<a id="facebook-and-instagram-embeds"></a>

### Facebook 与 Instagram

2020 年 10 月起，Meta 弃用了其公开的 oEmbed API。如果你
想在站点中嵌入 Facebook 或 Instagram 的帖子，就需要
使用新的需认证 API。这要求你注册一个 Meta
开发者账号，并创建一个包含 *oEmbed Product* 的 Facebook 应用。
创建所需应用的说明见
[Facebook](https://developers.facebook.com/docs/plugins/oembed)
和 [Instagram](https://developers.facebook.com/docs/instagram/oembed) 文档的要求小节。

2021 年 6 月起，*oEmbed Product* 已被 *oEmbed Read*
功能取代。要嵌入 Facebook 和 Instagram 帖子，你的应用必须激活
*oEmbed Read* 功能。此外，该应用必须经过 Meta 审核并获批准。你可以在
[API 变更日志](https://developers.facebook.com/docs/graph-api/changelog/version11.0/#oembed)中找到相关公告。

在 2021 年 6 月 8 日之前激活了 oEmbed Product 的应用，
需要在 2021 年 9 月 7 日之前激活 oEmbed Read 功能并完成应用审核。

拿到应用的访问令牌（App ID 和 App Secret）之后，把 Facebook 和/或
Instagram 查找器加到你的 `WAGTAILEMBEDS_FINDERS` 设置中，并用
应用中的 App ID 和 App Secret 配置它们：

```python
WAGTAILEMBEDS_FINDERS = [
    {
        "class": "wagtail.embeds.finders.facebook",
        "app_id": "YOUR FACEBOOK APP_ID HERE",
        "app_secret": "YOUR FACEBOOK APP_SECRET HERE",
    },
    {
        "class": "wagtail.embeds.finders.instagram",
        "app_id": "YOUR INSTAGRAM APP_ID HERE",
        "app_secret": "YOUR INSTAGRAM APP_SECRET HERE",
    },
    # Handles all other oEmbed providers the default way
    {
        "class": "wagtail.embeds.finders.oembed",
    },
]
```

默认情况下，Facebook 和 Instagram 嵌入会包含一些完全渲染嵌入内容所必需的
JavaScript。某些情况下这可能不是你想要的 —— 例如，
如果你有多个 Facebook 嵌入，这会导致出现多个 script 标签。
通过在配置中传入 `'omitscript': True`，你可以指明这些 script
标签应从嵌入 HTML 中省略。注意这样你就需要自己负责
加载这段脚本了。

<a id="embedly"></a>

### Embed.ly

[Embed.ly](https://embed.ly) 是一项付费服务，它也能为那些
未实现 oEmbed 协议的站点提供嵌入内容。

它还提供一些有用的功能，例如让嵌入内容外观一致，
以及统一的视频播放 API —— 如果你的站点允许视频托管在不同的
提供商上、而你又需要为它们实现自定义控件，这会很有用。

Wagtail 内置了对从 Embed.ly 获取嵌入内容的支持。要使用它，
先用 pip 安装 `Embedly` [python 包](https://pypi.org/project/Embedly/)。

现在在 `WAGTAILEMBEDS_FINDERS` 设置中添加一个使用
`wagtail.embeds.finders.oembed` 类的嵌入查找器，并传入你的 API 密钥：

```python
WAGTAILEMBEDS_FINDERS = [
    {"class": "wagtail.embeds.finders.embedly", "key": "YOUR EMBED.LY KEY HERE"}
]
```

<a id="custom-embed-finders"></a>

### 自定义嵌入查找器类

如需完全掌控，你可以创建一个自定义查找器类。

下面是一个可作骨架用的查找器类桩；请阅读
docstring 了解各个方法的作用：

```python
from wagtail.embeds.finders.base import EmbedFinder


class ExampleFinder(EmbedFinder):
    def __init__(self, **options):
        pass

    def accept(self, url):
        """
        如果该查找器知道如何为这个 URL 抓取嵌入内容，则返回 True。

        该方法不应有任何副作用（不向外部服务器发请求）
        """
        pass

    def find_embed(self, url, max_width=None):
        """
        接收一个 URL 和最大宽度，返回一个描述该内容的信息字典，
        用于在站点上嵌入该内容。

        这部分代码可能会向外部 API 发请求。
        """
        # TODO: Perform the request to your embed provider's API
        # Parse the response and return the embed information

        return {
            "title": "Title of the content",
            "author_name": "Author name",
            "provider_name": "Provider name (such as YouTube, Vimeo, etc)",
            "type": "Either 'photo', 'video', 'link' or 'rich'",
            "thumbnail_url": "URL to thumbnail image",
            "width": width_in_pixels,
            "height": height_in_pixels,
            "html": "<h2>The Embed HTML</h2>",
        }
```

实现完上述所有方法之后，你只需把它加到
`WAGTAILEMBEDS_FINDERS` 设置中：

```python
WAGTAILEMBEDS_FINDERS = [
    {
        "class": "path.to.your.finder.class.here",
        # Any other options will be passed as kwargs to the __init__ method
    }
]
```

## `Embed` 模型

#### *class* wagtail.embeds.models.Embed

嵌入内容只会被抓取一次并存入数据库，因此后续针对单个嵌入内容的请求
不会再次命中嵌入查找器。

#### url

(text)

该嵌入内容对应的原始内容的 URL。

#### max_width

(integer, nullable)

请求时指定的最大宽度。

#### type

(text)

嵌入内容的类型。可以是 'video'、'photo'、'link' 或 'rich'。

#### html

(text)

应放置到页面上的嵌入 HTML 内容

#### title

(text)

被嵌入内容的标题。

#### author_name

(text)

被嵌入内容的作者名称。

#### provider_name

(text)

被嵌入内容所属的提供商名称。

例如：YouTube、Vimeo

#### thumbnail_url

(text)

被嵌入内容缩略图的 URL。

#### width

(integer, nullable)

嵌入内容的宽度（仅图片和视频）。

#### height

(integer, nullable)

嵌入内容的高度（仅图片和视频）。

#### last_updated

(datetime)

该嵌入内容上次被抓取的日期／时间。

### 删除嵌入内容

只要你的嵌入配置没有损坏，删除
`Embed` 模型中的条目是完全安全的。Wagtail 会自动
重新填充站点上正在使用的记录。

如果你从 oEmbed 换成了 Embedly，或反过来，你可能会想这么做，
因为它们生成的嵌入代码可能略有不同，从而在站点上造成
不一致。

总的来说，每当你更改嵌入相关设置时，都建议用 [`purge_embeds` 命令](../reference/management_commands.html.md#purge-embeds)清空 Embed 对象。
