summaryrefslogtreecommitdiff
path: root/lib/chessh/ssh/client/trongle_chat.ex
blob: 3ea0d6d0242620a64af92c1f115ab66640def0a6 (plain)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
defmodule Chessh.SSH.Client.TrongleChat do
  require Logger
  alias Chessh.{Player, Chat, Utils, Repo, PlayerSession}
  import Ecto.Query

  @colors [
    IO.ANSI.light_blue(),
    IO.ANSI.light_red(),
    IO.ANSI.green(),
    IO.ANSI.light_magenta(),
    IO.ANSI.cyan(),
    IO.ANSI.blue(),
    IO.ANSI.yellow()
  ]

  defmodule State do
    defstruct client_pid: nil,
              message: "",
              player_session: nil,
              width: 0,
              height: 0,
              chats: []
  end

  use Chessh.SSH.Client.Screen

  def handle_info(
        {:new_chat, %Chat{} = chat},
        %State{width: width, height: height, chats: chats} = state
      ) do
    new_state = %State{
      state
      | chats: [chat | chats]
    }

    {:noreply, render(width, height, new_state)}
  end

  def init([
        %State{
          client_pid: client_pid,
          player_session: %PlayerSession{player_id: player_id} = player_session
        } = state
      ]) do
    :syn.add_node_to_scopes([:chat])
    :ok = :syn.join(:chat, {:tronglechat}, self())

    send(client_pid, {:send_to_ssh, Utils.clear_codes()})

    {:ok,
     %State{
       state
       | chats: get_initial_chats(),
         player_session: %PlayerSession{player_session | player: Repo.get!(Player, player_id)}
     }}
  end

  def render(
        width,
        height,
        %State{
          client_pid: client_pid,
          chats: chats,
          message: message,
          player_session: %PlayerSession{player: %Player{username: username}}
        } = state
      ) do
    chat_msgs =
      chats
      |> Enum.slice(0, height - 1)
      |> Enum.map(&format_chat/1)
      |> Enum.join("\r\n")

    {prompt, prompt_len} = format_prompt(username, message)

    send(
      client_pid,
      {:send_to_ssh,
       [
         Utils.clear_codes(),
         prompt <>
           "\r\n" <> chat_msgs <> IO.ANSI.cursor(0, prompt_len + 1)
       ]}
    )

    %State{state | width: width, height: height}
  end

  def input(
        action,
        data,
        %State{
          player_session: %PlayerSession{player: player},
          message: message,
          width: width,
          height: height
        } = state
      ) do
    safe_char_regex = ~r/[ A-Za-z0-9._~()'!*:@,;+?-]/

    appended_message_state =
      case action do
        :backspace ->
          %State{state | message: String.slice(message, 0..-2)}

        :return ->
          if message != "" do
            {:ok, saved_chat} = Repo.insert(%Chat{message: message, chatter: player})
            :syn.publish(:chat, {:tronglechat}, {:new_chat, saved_chat})
            %State{state | message: ""}
          else
            state
          end

        _ ->
          if String.match?(data, safe_char_regex) do
            %State{state | message: message <> data}
          else
            state
          end
      end

    render(width, height, appended_message_state)
  end

  defp get_initial_chats() do
    from(c in Chat,
      order_by: [desc: c.id],
      limit: 100
    )
    |> Repo.all()
    |> Repo.preload([:chatter])
  end

  defp username_color(username, colors \\ @colors) do
    ind =
      String.to_charlist(username)
      |> Enum.sum()
      |> rem(length(colors))

    Enum.at(colors, ind)
  end

  defp format_prompt(username, message) do
    {
      [
        IO.ANSI.format_fragment([username_color(username), username, IO.ANSI.default_color()]),
        "> ",
        message
      ]
      |> Enum.join(""),
      String.length(username) + String.length(message) + 2
    }
  end

  defp format_chat(%Chat{chatter: %Player{username: username}, message: message}) do
    {prompt, _} = format_prompt(username, message)
    prompt
  end
end