Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: c93f3bcf18
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 46 lines (37 sloc) 1.088 kb
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
require "em-eventsource"
class Flower::Stream
  attr_accessor :flower, :api_token, :stream

  def initialize(flower)
    self.api_token = Flower::Config.api_token
    self.flower = flower
  end

  def start
    source = EventMachine::EventSource.new(stream_url, nil, request_headers)
    source.message do |message|
      parser << message
    end

    source.open do
      puts "** Stream open"
    end

    source.error do |error|
      puts "** error #{error}"
    end

    source.start
  end

  private

  def parser
    return @parser unless @parser.nil?
    @parser = Yajl::Parser.new(:symbolize_keys => true)
    @parser.on_parse_complete = proc do |data|
      flower.respond_to data if data[:event] == 'message' && data[:flow] == "#{Flower::Config.company}:#{Flower::Config.flow}"
    end
    @parser
  end

  def request_headers
    auth = Base64.encode64(api_token).strip << '='
    {:accept => 'text/event-stream', 'Authorization' => "Basic #{auth}"}
  end

  def stream_url
    "https://stream.flowdock.com/flows/#{Flower::Config.company}/#{Flower::Config.flow}"
  end
end
Something went wrong with that request. Please try again.