summaryrefslogtreecommitdiffstats
path: root/lib/mattermost_helper.rb
blob: b012dfc9d5f100b0c99c355f1bdcf6ec7fc49809 (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
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# frozen_string_literal: true

# This module contains methods to interact with a mattermost instance
module MattermostHelper # rubocop:disable Metrics/ModuleLength
  def format_mattermost_status(status, aliases = {})
    state = status['status']
    word = aliases[state] || state
    return word + ' :white_check_mark:' if state == 'present'
    # Status is absent
    line = [word, ':no_entry_sign:']
    eta = key_value_unless_blank(status, 'eta')
    line.insert(1, "for #{eta}") if eta
    line.join(' ')
  end

  def mattermost_answer_message
    state = format_mattermost_status(@current_status, 'present' => 'back')
    ['@' + @current_status['handle'], 'is', state].join(' ')
  end

  def mattermost_build_curl_cmd(endpoint, meth = 'GET', data = nil)
    api_token = @config.dig('mattermost', 'api_token')
    api_url = @config.dig('mattermost', 'api_url')
    return nil unless api_token && api_url
    curl_cmd = ['curl', '-s', '-X', meth, '-H',
                "Authorization: Bearer #{api_token}"]
    if ['POST', 'PUT'].include?(meth)
      curl_cmd += ['-H', 'Content-Type: application/json']
    end
    curl_cmd += ['-d', JSON.dump(data)] if data
    curl_cmd << api_url + endpoint
    curl_cmd
  end

  def mattermost_run_curl(curl_cmd)
    warn curl_cmd.join(' ') if ENV['RACK_ENV'] == 'development'
    data = nil
    IO.popen(curl_cmd, unsetenv_others: true, err: '/dev/null') do |p|
      data = p.read
    end
    warn data if ENV['RACK_ENV'] == 'development'
    data
  end

  def mattermost_fetch_user_data(req)
    curl_cmd = mattermost_build_curl_cmd(req)
    return nil unless curl_cmd
    raw = mattermost_run_curl(curl_cmd)
    begin
      data = JSON.parse(raw)
    rescue JSON::ParserError
      warn "Wrong data received: #{data.inspect}"
    end
    data
  end

  def mattermost_user_id
    return @details['mattermost_uid'] if @details['mattermost_uid']
    if key_value_unless_blank(@current_status, 'handle')
      req = '/users/username/' + @current_status['handle']
    else
      req = '/users/email/' + @current_status['email']
    end
    data = mattermost_fetch_user_data(req)
    return nil unless data
    update_status({ 'mattermost_uid' => data.dig('id'),
                    'handle' => data.dig('username') },
                  @current_status['email'])
    data['mattermost_uid']
  end

  def send_mattermost_notification
    return unless @current_status['handle']
    if ENV['RACK_ENV'] == 'development'
      channel = @config.dig('mattermost', 'test_channel')
    else
      channel = @config.dig('mattermost', 'public_channel')
    end
    return unless channel
    msg = { 'channel_id' => channel,
            'message' => mattermost_answer_message }
    curl_cmd = mattermost_build_curl_cmd('/posts', 'POST', msg)
    return unless curl_cmd
    mattermost_run_curl(curl_cmd)
  end

  def change_mattermost_status(new_status)
    return unless @current_status['handle']
    uid = mattermost_user_id
    return unless uid
    if new_status == 'present'
      mat_state = 'online'
    else
      mat_state = 'dnd'
    end
    data = { 'user_id' => uid, 'status' => mat_state }
    curl_cmd = mattermost_build_curl_cmd("/users/#{uid}/status", 'PUT', data)
    return unless curl_cmd
    mattermost_run_curl(curl_cmd)
  end

  def create_or_update_status_for_mattermost(username)
    data = mattermost_fetch_user_data('/users/username/' + username)
    return nil unless data
    email = data.dig('email')
    return nil unless email
    row = fetch_status('email' => email)
    unless row
      generate_and_send_new_token(email)
      row = fetch_status('email' => email)
    end
    @details = row['details']
    @current_status = row
    update_status({ 'mattermost_uid' => data.dig('id'),
                    'handle' => username },
                  email)
    @current_status
  end

  def find_status_for_mattermost(username)
    row = fetch_status('handle' => username)
    if row
      @details = row['details']
      @current_status = row
      return @current_status
    end
    create_or_update_status_for_mattermost(username)
  end

  def parse_mattermost_text(text)
    data = text.split(' ')
    command = data[0]&.strip&.downcase || 'help'
    tail = data[1..]&.join(' ') || ''
    if ['on', 'present', 'back'].include?(command)
      return ['status', 'present', tail]
    end
    if ['off', 'absent', 'away'].include?(command)
      return ['status', 'absent', tail]
    end
    return ['current'] if ['current', 'me'].include?(command)
    return ['list', tail] if ['list', 'all'].include?(command)
    ['help']
  end

  def mattermost_command_current(username)
    unless find_status_for_mattermost(username)
      return { 'text' => 'Not authorized' }
    end
    message = ['Your current status is',
               format_mattermost_status(@current_status)]
    { 'text' => message.join(' ') }
  end

  def mattermost_command_status(username, status, eta)
    unless find_status_for_mattermost(username)
      return { 'response_type' => 'in_channel',
               'text' => "#{status} #{eta}" }
    end
    if status == 'present' && status == @current_status['status']
      return { 'text' => 'You are already present.' }
    end
    eta = '' if status == 'present'
    update_status({ 'status' => status, 'eta' => eta },
                  @current_status['email'])
    change_mattermost_status(status)
    { 'response_type' => 'in_channel',
      'text' => mattermost_answer_message }
  end

  def mattermost_command_help(username)
    help_body = IO.read('./views/mattermost_help.md')
                  .gsub('{{status_uri}}', @config['base_url'])
                  .gsub('{{username}}', username)
    { 'text' => help_body }
  end

  def mattermost_table_format_line_value(value, key)
    return '' if value == ''
    return "[#{value}](tel:#{value.delete(' ')})" if key == 'phone'
    return "[#{key}](#{value})" if value =~ /^https?:\/\//
    value
  end

  def mattermost_custom_values_table_line(status, custom_fields)
    if status['status'] == 'present'
      return custom_fields.map do |f|
        mattermost_table_format_line_value(
          status.dig('details', f) || '', f
        )
      end
    end
    Array.new(custom_fields.length, ' ')
  end

  def mattermost_table_line(status, custom_fields)
    custom_values = mattermost_custom_values_table_line(status, custom_fields)
    name = key_value_unless_blank(status, 'name') \
           || key_value_unless_blank(status, 'handle') \
           || ''
    line = [
      name, format_mattermost_status(status), status['email']
    ] + custom_values
    "| #{line.join(' | ')} |"
  end

  def mattermost_build_table_list(filter)
    custom_fields = (@config['custom_fields'] || []).map { |c| c['name'] }
    cols = ['Name', 'Status', 'Email'] + custom_fields.map(&:capitalize)
    table = ["| #{cols.join(' | ')} |", "|-|-|-|#{'-|' * cols.length}"]
    fetch_all_statuses(filter).each do |status|
      table << mattermost_table_line(status, custom_fields)
    end
    table
  end

  def mattermost_command_list(username, filter)
    output = mattermost_command_current(username)
    if @current_status
      text = ["## #{output['text']}", '---']
    else
      text = []
    end
    filter&.strip!
    filter = nil if filter == ''
    text += mattermost_build_table_list(filter)
    output['text'] = text.join("\n")
    output
  end

  def respond_to_mattermost_request(text, username)
    data = parse_mattermost_text(text&.strip || '')
    meth = "mattermost_command_#{data[0]}".to_sym
    return { 'text' => text } unless respond_to?(meth)
    tail = data[1..] || []
    tail.insert(0, username)
    send(meth, *tail)
  end
end