defmodule LSG.IRC.YouTubeHandler do
require Logger
@moduledoc """
# youtube
* **!yt `<recherche>`**, !youtube `<recherche>`: retourne le premier résultat de la `<recherche>` YouTube
"""
defstruct client: nil
def irc_doc, do: @moduledoc
def start_link(client) do
GenServer.start_link(__MODULE__, [client])
end
def init([client]) do
ExIRC.Client.add_handler(client, self())
{:ok, %__MODULE__{client: client}}
end
def handle_info({:received, "!youtube " <> query, sender, chan}, state) do
irc_search(query, chan, state)
{:noreply, state}
end
def handle_info({:received, "!yt " <> query, sender, chan}, state) do
irc_search(query, chan, state)
{:noreply, state}
end
def handle_info(info, state) do
{:noreply, state}
end
defp irc_search(query, chan, state) do
case search(query) do
{:ok, %{"items" => [item | _]}} ->
title = get_in(item, ["snippet", "title"])
url = "https://youtube.com/watch?v=" <> get_in(item, ["id", "videoId"])
msg = "#{title} — #{url}"
ExIRC.Client.msg(state.client, :privmsg, chan, msg)
{:error, error} ->
ExIRC.Client.msg(state.client, :privmsg, chan, "Erreur YouTube: "<>error)
_ ->
nil
end
end
defp search(query) do
query = query
|> String.strip
key = Application.get_env(:lsg, __MODULE__)[:api_key]
params = %{
"key" => key,
"maxResults" => 1,
"part" => "snippet",
"safeSearch" => "none",
"type" => "video",
"q" => query,
}
url = "https://www.googleapis.com/youtube/v3/search"
case HTTPoison.get(url, [], params: params) do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} -> Jason.decode(body)
{:ok, %HTTPoison.Response{status_code: 400, body: body}} ->
Logger.error "YouTube HTTP 400: #{inspect body}"
{:error, "http 400"}
error ->
Logger.error "YouTube http error: #{inspect error}"
:error
end
end
end