summaryrefslogtreecommitdiffstats
path: root/lib/mattermost_helper.rb
blob: 42a150af7fd1561f6db1ca23dfcb1b086e6e827a (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
# 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_hook_message
    state = format_mattermost_status(@current_status, 'present' => 'back')
    ['@' + @current_status['handle'], 'is', state].join(' ')
  end

  def send_mattermost_notification
    hook_url = @config.dig('mattermost', 'hook_url')
    return unless hook_url && @current_status['handle']
    if ENV['RACK_ENV'] == 'development'
      warn mattermost_hook_message
    else
      system('curl', '-s', '-X', 'POST', '--data-urlencode',
             "payload={\"text\": \"#{mattermost_hook_message}\"}",
             hook_url)
    end
  end

  def find_status_for_mattermost(username)
    row = fetch_status('handle' => username)
    return nil unless row
    @details = row['details']
    @current_status = row
  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'])
    { 'response_type' => 'in_channel',
      'text' => mattermost_hook_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 update_details_from_mattermost(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