summaryrefslogtreecommitdiff
path: root/lib/lsg_irc/youtube_handler.ex
blob: e7eadfc0a6ef7065886be3a06a21d9d496ba55e7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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, dets: 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