diff options
Diffstat (limited to 'lib/plugins/link/youtube.ex')
-rw-r--r-- | lib/plugins/link/youtube.ex | 53 |
1 files changed, 36 insertions, 17 deletions
diff --git a/lib/plugins/link/youtube.ex b/lib/plugins/link/youtube.ex index 0114940..adf9337 100644 --- a/lib/plugins/link/youtube.ex +++ b/lib/plugins/link/youtube.ex @@ -17,11 +17,12 @@ defmodule Nola.Plugins.Link.YouTube do """ @impl true - def match(uri = %URI{host: yt, path: "/watch", query: "v="<>video_id}, _opts) when yt in ["youtube.com", "www.youtube.com"] do + def match(uri = %URI{host: yt, path: "/watch", query: "v=" <> video_id}, _opts) + when yt in ["youtube.com", "www.youtube.com"] do {true, %{video_id: video_id}} end - def match(%URI{host: "youtu.be", path: "/"<>video_id}, _opts) do + def match(%URI{host: "youtu.be", path: "/" <> video_id}, _opts) do {true, %{video_id: video_id}} end @@ -33,40 +34,58 @@ defmodule Nola.Plugins.Link.YouTube do @impl true def expand(_uri, %{video_id: video_id}, opts) do key = Application.get_env(:nola, :youtube)[:api_key] + params = %{ "part" => "snippet,contentDetails,statistics", "id" => video_id, "key" => key } + headers = [] options = [params: params] + case HTTPoison.get("https://www.googleapis.com/youtube/v3/videos", [], options) do {:ok, %HTTPoison.Response{status_code: 200, body: body}} -> case Jason.decode(body) do {:ok, json} -> item = List.first(json["items"]) + if item do snippet = item["snippet"] - duration = item["contentDetails"]["duration"] |> String.replace("PT", "") |> String.downcase - date = snippet["publishedAt"] - |> DateTime.from_iso8601() - |> elem(1) - |> Timex.format("{relative}", :relative) - |> elem(1) - - line = if host = Keyword.get(opts, :invidious) do - ["-> https://#{host}/watch?v=#{video_id}"] - else + + duration = + item["contentDetails"]["duration"] + |> String.replace("PT", "") + |> String.downcase() + + date = + snippet["publishedAt"] + |> DateTime.from_iso8601() + |> elem(1) + |> Timex.format("{relative}", :relative) + |> elem(1) + + line = + if host = Keyword.get(opts, :invidious) do + ["-> https://#{host}/watch?v=#{video_id}"] + else [] - end - {:ok, line ++ ["#{snippet["title"]}", "— #{duration} — uploaded by #{snippet["channelTitle"]} — #{date}" - <> " — #{item["statistics"]["viewCount"]} views, #{item["statistics"]["likeCount"]} likes"]} + end + + {:ok, + line ++ + [ + "#{snippet["title"]}", + "— #{duration} — uploaded by #{snippet["channelTitle"]} — #{date}" <> + " — #{item["statistics"]["viewCount"]} views, #{item["statistics"]["likeCount"]} likes" + ]} else :error end - _ -> :error + + _ -> + :error end end end - end |