Merge OGP parser with TwitterCard
[akkoma] / lib / pleroma / web / rich_media / parsers / oembed_parser.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.RichMedia.Parsers.OEmbed do
6 def parse(html, _data) do
7 with elements = [_ | _] <- get_discovery_data(html),
8 {:ok, oembed_url} <- get_oembed_url(elements),
9 {:ok, oembed_data} <- get_oembed_data(oembed_url) do
10 oembed_data
11 else
12 _e -> %{}
13 end
14 end
15
16 defp get_discovery_data(html) do
17 html |> Floki.find("link[type='application/json+oembed']")
18 end
19
20 defp get_oembed_url(nodes) do
21 {"link", attributes, _children} = nodes |> hd()
22
23 {:ok, Enum.into(attributes, %{})["href"]}
24 end
25
26 defp get_oembed_data(url) do
27 {:ok, %Tesla.Env{body: json}} = Pleroma.HTTP.get(url, [], adapter: [pool: :media])
28
29 {:ok, data} = Jason.decode(json)
30
31 data = data |> Map.new(fn {k, v} -> {String.to_atom(k), v} end)
32
33 {:ok, data}
34 end
35 end