class WatchDoge::Notification::Mattermost

Public Class Methods

new(args) click to toggle source
Calls superclass method
# File lib/watchdoge/notification/mattermost.rb, line 10
def initialize args
  super

  @host = args[:host]
  @channel_id = args[:channel_id]
  @auth_token = args[:auth_token]
end

Public Instance Methods

flush() click to toggle source
# File lib/watchdoge/notification/mattermost.rb, line 18
def flush
  @message_queue.each do |message|
    case message
    when String
      post matter_most_meta(message)
    when ChunkyPNG::Image
      post_file matter_most_meta(message)
    when WatchDoge::PixelTest
      post_file matter_most_meta(message.diff)
    end
  end

  @message_queue = []
end

Private Instance Methods

api_uri(path) click to toggle source
# File lib/watchdoge/notification/mattermost.rb, line 67
def api_uri path
  URI("#{@host}/api/v4#{path}")
end
matter_most_meta(message) click to toggle source
# File lib/watchdoge/notification/mattermost.rb, line 71
def matter_most_meta message
  case message
  when String
    {
      channel_id: @channel_id,
      message: message
    }
  when ChunkyPNG::Image
    {
      channel_id: @channel_id,
      files:  UploadIO.new(StringIO.new(message.to_blob), "image/png", "image.png")
    }
  end
end
post(meta) click to toggle source
# File lib/watchdoge/notification/mattermost.rb, line 35
def post meta
  Net::HTTP.post api_uri('/posts'),
                 meta.to_json,
                 "Content-Type" => "application/json",
                 "Authorization" => "Bearer #{@auth_token}"
end
post_file(meta) click to toggle source
# File lib/watchdoge/notification/mattermost.rb, line 42
def post_file meta
  uri = api_uri("/files")

  req = Net::HTTP::Post::Multipart.new uri.path, meta
  req.add_field("Authorization", "Bearer #{@auth_token}")

  res = nil

  Net::HTTP.start(uri.host, uri.port, use_ssl: (uri.scheme == "https")) do |http|
    res = http.request(req).body
  end

  file_id = JSON.parse(res)['file_infos'].first['id']

  post_file_to_channel file_id
end
post_file_to_channel(file_id) click to toggle source
# File lib/watchdoge/notification/mattermost.rb, line 59
def post_file_to_channel file_id
    post({
      channel_id: @channel_id,
      message: 'file uploaded from WatchDoge',
      file_ids: [file_id]
    })
end