summaryrefslogtreecommitdiff
path: root/lib/lsg_irc/outline_plugin.ex
blob: 7bfaac1a08c3fc754f94dbe94b35bf35de77a432 (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
defmodule LSG.IRC.OutlinePlugin do
  @moduledoc """
  # outline auto-link

  Envoie un lien vers Outline quand un lien est envoyé.

  * **+outline `<host>`** active outline pour `<host>`.
  * **-outline `<host>`** désactive outline pour `<host>`.
  """
  def short_irc_doc, do: false
  def irc_doc, do: @moduledoc
  require Logger

  def start_link() do
    GenServer.start_link(__MODULE__, [])
  end

  defstruct [:file, :hosts]

  def init([]) do
    {:ok, _} = Registry.register(IRC.PubSub, "trigger:outline", [])
    {:ok, _} = Registry.register(IRC.PubSub, "message", [])
    file = Path.join(LSG.data_path, "/outline.txt")
    hosts = case File.read(file) do
      {:error, :enoent} ->
        []
      {:ok, lines} ->
        String.split(lines, "\n", trim: true)
    end
    {:ok, %__MODULE__{file: file, hosts: hosts}}
  end

  def handle_info({:irc, :trigger, "outline", message = %IRC.Message{trigger: %IRC.Trigger{type: :plus, args: [host]}}}, state) do
    state = %{state | hosts: [host | state.hosts]}
    save(state)
    message.replyfun.("ok")
    {:noreply, state}
  end

  def handle_info({:irc, :trigger, "outline", message = %IRC.Message{trigger: %IRC.Trigger{type: :minus, args: [host]}}}, state) do
    state = %{state | hosts: List.delete(state.hosts, host)}
    save(state)
    message.replyfun.("ok")
    {:noreply, state}
  end

  def handle_info({:irc, :text, message = %IRC.Message{text: text}}, state) do
    String.split(text)
    |> Enum.map(fn(word) ->
      if String.starts_with?(word, "http://") || String.starts_with?(word, "https://") do
        uri = URI.parse(word)
        if uri.scheme && uri.host do
          if Enum.any?(state.hosts, fn(host) -> String.ends_with?(uri.host, host) end) do
            line = "-> https://outline.com/#{word}"
            message.replyfun.(line)
          end
       end
      end
    end)
    {:noreply, state}
  end

  def handle_info(msg, state) do
    {:noreply, state}
  end

  def save(state = %{file: file, hosts: hosts}) do
    string = Enum.join(hosts, "\n")
    File.write(file, string)
  end

end