summaryrefslogtreecommitdiff
path: root/lib/lsg_web/controllers/irc_controller.ex
blob: 022807dd05700fe86f1c48cb5aa4c3a5c1e5ad9d (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
defmodule LSGWeb.IrcController do
  use LSGWeb, :controller

  def index(conn, _) do
    commands = for mod <- (Application.get_env(:lsg, :irc)[:plugins] ++ Application.get_env(:lsg, :irc)[:handlers]) do
      identifier = Module.split(mod) |> List.last |> String.replace("Plugin", "") |> Macro.underscore
      {identifier, mod.irc_doc()}
    end
    |> Enum.reject(fn({_, i}) -> i == nil end)
    render conn, "index.html", commands: commands
  end

  def txt(conn, %{"name" => name}) do
    case String.split(name, ".", parts: 2) do
      [name, "txt"] ->
        data = data()
        if Map.has_key?(data, name) do
          lines = Enum.join(data[name], "\n")
          text(conn, lines)
        else
          conn
          |> put_status(404)
          |> text("Not found")
        end
      _ ->
        do_txt(conn, name)
    end
  end
  def txt(conn, _), do: do_txt(conn, nil)


  defp do_txt(conn, nil) do
    doc = LSG.IRC.TxtPlugin.irc_doc()
    data = data()
    lines = Enum.reduce(data, 0, fn({_, lines}, acc) -> acc + Enum.count(lines) end)
    render conn, "txts.html", data: data, doc: doc, files: Enum.count(data), lines: lines
  end

  defp do_txt(conn, txt) do
    data = data()
    if Map.has_key?(data, txt) do
      render(conn, "txt.html", name: txt, data: data[txt], doc: nil)
    else
      conn
      |> put_status(404)
      |> text("Not found")
    end
  end

  defp data() do
    dir = Application.get_env(:lsg, :data_path) <> "/irc.txt/"
    Path.wildcard(dir <> "/*.txt")
    |> Enum.reduce(%{}, fn(path, m) ->
      path = String.split(path, "/")
      file = List.last(path)
      [key, "txt"] = String.split(file, ".", parts: 2)
      data = dir <> file
      |> File.read!
      |> String.split("\n")
      |> Enum.reject(fn(line) ->
        cond do
          line == "" -> true
          !line -> true
          true -> false
        end
      end)
      Map.put(m, key, data)
    end)
    |> Enum.sort
    |> Enum.into(Map.new)
  end

end