Skip to content

Instantly share code, notes, and snippets.

@bpot
Created June 10, 2010 16:30
Show Gist options
  • Save bpot/433250 to your computer and use it in GitHub Desktop.
Save bpot/433250 to your computer and use it in GitHub Desktop.
class ImapConnection < EM::Connection
include EM::Protocols::LineText2
def post_init
@state = :unconnected
@tag_count = 0
@need_bytes = 0
end
def connection_completed
start_tls
end
def ssl_handshake_completed
@state = :connected
end
def unbind
@on_disconnect.call
end
def on_ready(&block)
@on_ready = block.to_proc
end
def on_disconnect(&block)
@on_disconnect = block.to_proc
end
def on_response(&block)
@on_response = block.to_proc
end
def connection_ready
@state = :ready
@on_ready.call
end
def receive_data(line)
super
end
def receive_line(line)
case @state
when :connected
connection_ready if line =~ /OK/
when :ready
line = line + "\r\n"
@buffer ||= ""
@buffer += line if @need_bytes > 0
if @need_bytes > 0 && @buffer.length >= @need_bytes
p = Net::IMAP::ResponseParser.new
response = p.parse(@buffer)
@on_response.call(response)
@buffer = ""
@need_bytes = 0
return
end
if line.match(/\{(\d+)\}\r\n$/)
@buffer = line
@need_bytes = $1.to_i + 3 + line.length
elsif @need_bytes == 0
p = Net::IMAP::ResponseParser.new
response = p.parse(line)
@on_response.call(response) if @on_response
if response.class == Net::IMAP::TaggedResponse
@tagged_response_callback.call(response)
end
@buffer = ""
end
else
raise "Unrecognized state"
end
end
def send_data(d)
super
end
def send_command(command, &block)
raise "Not Ready" unless @state == :ready
@tagged_response_callback = block.to_proc
command = "#{current_tag} #{command}\r\n"
send_data command
end
def current_tag
@tag_count += 1
"EM" + @tag_count.to_s
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment