Class: RocketChat

Inherits:
Object
  • Object
show all
Defined in:
lib/xify/output/rocket_chat.rb

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ RocketChat

Returns a new instance of RocketChat.



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/xify/output/rocket_chat.rb', line 6

def initialize(config)
  @channel = config['channel']
  uri = URI.parse config['uri']
  @http = Net::HTTP.new uri.host, uri.port
  @http.use_ssl = true

  @user = config['user']
  @pass = config['pass']

  working_dir = "#{ENV['HOME']}/.xify/RocketChat"
  Dir.mkdir working_dir rescue Errno::EEXIST
  @auth_file = "#{working_dir}/#{@user}.json"
end

Instance Method Details

#authenticated_request {|req| ... } ⇒ Object

Yields:

  • (req)


46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/xify/output/rocket_chat.rb', line 46

def authenticated_request
   unless @auth_data

  req = Net::HTTP::Post.new '/api/v1/chat.postMessage',
    'Content-Type' => 'application/json',
    'X-User-Id' => @auth_data['userId'],
    'X-Auth-Token' => @auth_data['authToken']

  yield req

  req
end

#loginObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/xify/output/rocket_chat.rb', line 20

def 
  if File.exists? @auth_file
    @auth_data = JSON.parse File.read @auth_file
    return
  end

  req = Net::HTTP::Post.new '/api/v1/login',
    'Content-Type' => 'application/json'
  req.body = {
    username: @user,
    password: @pass
  }.to_json

  res = @http.request req

  raise "Error: #{res.code} #{res.message}\n#{res.body}" unless res.is_a? Net::HTTPSuccess

  @auth_data = JSON.parse(res.body)['data']
  File.write @auth_file, @auth_data.to_json
end

#process(event) ⇒ Object



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
# File 'lib/xify/output/rocket_chat.rb', line 59

def process(event)
  res = @http.request(authenticated_request do |req|
    req.body = {
      channel: @channel,
      alias: event.author,
      attachments: [
        {
          title: event.args[:parent],
          title_link: event.args[:parent_link],
          text: event.args[:link] ? "#{event.message.chomp} ([more](#{event.args[:link]}))" : event.message.chomp
        }
      ]
    }.to_json
  end)

  case res
  when Net::HTTPUnauthorized
    reset_auth
    process event
  when Net::HTTPSuccess
    # nothing
  else
    $stderr.puts "Error: #{res.code} #{res.message}\n#{res.body}"
  end
end

#reset_authObject



41
42
43
44
# File 'lib/xify/output/rocket_chat.rb', line 41

def reset_auth
  @auth_data = nil
  File.delete @auth_file
end