class Redwood::IMAP

Constants

RECOVERABLE_ERRORS

upon these errors we'll try to rereconnect a few times

SCAN_INTERVAL

Attributes

password[RW]
username[RW]

Public Class Methods

new(uri, username, password, last_idate=nil, usual=true, archived=false, id=nil, labels=[]) click to toggle source
Calls superclass method
# File lib/sup/imap.rb, line 61
def initialize uri, username, password, last_idate=nil, usual=true, archived=false, id=nil, labels=[]
  raise ArgumentError, "username and password must be specified" unless username && password
  raise ArgumentError, "not an imap uri" unless uri =~ %rimaps?://!

  super uri, last_idate, usual, archived, id

  @parsed_uri = URI(uri)
  @username = username
  @password = password
  @imap = nil
  @imap_state = {}
  @ids = []
  @last_scan = nil
  @labels = Set.new((labels || []) - LabelManager::RESERVED_LABELS)
  @say_id = nil
  @mutex = Mutex.new
end
suggest_labels_for(path) click to toggle source
# File lib/sup/imap.rb, line 79
def self.suggest_labels_for path
  path =~ /([^\/]*inbox[^\/]*)/i ? [$1.downcase.intern] : []
end

Public Instance Methods

==(o;) click to toggle source

is this necessary? TODO: remove maybe

# File lib/sup/imap.rb, line 95
def == o; o.is_a?(IMAP) && o.uri == self.uri && o.username == self.username; end
check() click to toggle source
# File lib/sup/imap.rb, line 91
def check; end
connect() click to toggle source
# File lib/sup/imap.rb, line 146
def connect
  return if @imap
  safely { } # do nothing!
end
each() { |id, labels| ... } click to toggle source
# File lib/sup/imap.rb, line 174
def each
  return unless start_offset

  ids = 
    @mutex.synchronize do
      unsynchronized_scan_mailbox
      @ids
    end

  start = ids.index(cur_offset || start_offset) or raise OutOfSyncSourceError, "Unknown message id #{cur_offset || start_offset}."

  start.upto(ids.length - 1) do |i|
    id = ids[i]
    state = @mutex.synchronize { @imap_state[id] } or next
    self.cur_offset = id 
    labels = { :Flagged => :starred,
               :Deleted => :deleted
             }.inject(@labels) do |cur, (imap, sup)|
      cur + (state[:flags].include?(imap) ? [sup] : [])
    end

    labels += [:unread] unless state[:flags].include?(:Seen)

    yield id, labels
  end
end
each_raw_message_line(id) { |l| ... } click to toggle source
# File lib/sup/imap.rb, line 105
def each_raw_message_line id
  StringIO.new(raw_message(id)).each { |l| yield l }
end
end_offset() click to toggle source
# File lib/sup/imap.rb, line 207
def end_offset
  unsynchronized_scan_mailbox
  @ids.last + 1
end
expunge() click to toggle source
# File lib/sup/imap.rb, line 139
def expunge
  @imap.expunge
  unsynchronized_scan_mailbox true
  true
end
host() click to toggle source
# File lib/sup/imap.rb, line 83
def host; @parsed_uri.host; end
load_header(id) click to toggle source
# File lib/sup/imap.rb, line 97
def load_header id
  parse_raw_email_header StringIO.new(raw_header(id))
end
load_message(id) click to toggle source
# File lib/sup/imap.rb, line 101
def load_message id
  RMail::Parser.read raw_message(id)
end
mailbox() click to toggle source
# File lib/sup/imap.rb, line 85
def mailbox
  x = @parsed_uri.path[1..-1]
  (x.nil? || x.empty?) ? 'INBOX' : CGI.unescape(x)
end
mark_as_deleted(ids) click to toggle source
# File lib/sup/imap.rb, line 130
def mark_as_deleted ids
  ids = [ids].flatten # accept single arguments
  unsynchronized_scan_mailbox
  imap_ids = ids.map { |i| @imap_state[i] && @imap_state[i][:id] }.compact
  return if imap_ids.empty?
  @imap.store imap_ids, "+FLAGS", [:Deleted]
end
pct_done() click to toggle source
# File lib/sup/imap.rb, line 213
def pct_done; 100.0 * (@ids.index(cur_offset) || 0).to_f / (@ids.length - 1).to_f; end
port() click to toggle source
# File lib/sup/imap.rb, line 84
def port; @parsed_uri.port || (ssl? ? 993 : 143); end
raw_header(id) click to toggle source
# File lib/sup/imap.rb, line 109
def raw_header id
  unsynchronized_scan_mailbox
  header, flags = get_imap_fields id, 'RFC822.HEADER'
  header.gsub(/\r\n/, "\n")
end
raw_message(id) click to toggle source
# File lib/sup/imap.rb, line 124
def raw_message id
  unsynchronized_scan_mailbox
  get_imap_fields(id, 'RFC822').first.gsub(/\r\n/, "\n")
end
scan_mailbox(force=false) click to toggle source
# File lib/sup/imap.rb, line 152
def scan_mailbox force=false
  return if !force && @last_scan && (Time.now - @last_scan) < SCAN_INTERVAL
  last_id = safely do
    @imap.examine mailbox
    @imap.responses["EXISTS"].last
  end
  @last_scan = Time.now

  @ids = [] if force
  return if last_id == @ids.length

  range = (@ids.length + 1) .. last_id
  debug "fetching IMAP headers #{range}"
  fetch(range, ['RFC822.SIZE', 'INTERNALDATE', 'FLAGS']).each do |v|
    id = make_id v
    @ids << id
    @imap_state[id] = { :id => v.seqno, :flags => v.attr["FLAGS"] }
  end
  debug "done fetching IMAP headers"
end
ssl?() click to toggle source
# File lib/sup/imap.rb, line 89
def ssl?; @parsed_uri.scheme == 'imaps' end
start_offset() click to toggle source
# File lib/sup/imap.rb, line 201
def start_offset
  unsynchronized_scan_mailbox
  @ids.first
end
store_message(date, from_email) { |message| ... } click to toggle source
# File lib/sup/imap.rb, line 116
def store_message date, from_email, &block
  message = StringIO.new
  yield message
  message.string.gsub! /\n/, "\r\n"

  safely { @imap.append mailbox, message.string, [:Seen], Time.now }
end

Private Instance Methods

fetch(ids, fields) click to toggle source
# File lib/sup/imap.rb, line 217
def fetch ids, fields
  results = safely { @imap.fetch ids, fields }
  good_results = 
    if ids.respond_to? :member?
      results.find_all { |r| ids.member?(r.seqno) && fields.all? { |f| r.attr.member?(f) } }
    else
      results.find_all { |r| ids == r.seqno && fields.all? { |f| r.attr.member?(f) } }
    end

  if good_results.empty?
    raise FatalSourceError, "no IMAP response for #{ids} containing all fields #{fields.join(', ')} (got #{results.size} results)"
  elsif good_results.size < results.size
    warn "Your IMAP server sucks. It sent #{results.size} results for a request for #{good_results.size} messages. What are you using, Binc?"
  end

  good_results
end
get_imap_fields(id, *fields) click to toggle source
# File lib/sup/imap.rb, line 297
def get_imap_fields id, *fields
  raise OutOfSyncSourceError, "Unknown message id #{id}" unless @imap_state[id]

  imap_id = @imap_state[id][:id]
  result = fetch(imap_id, (fields + ['RFC822.SIZE', 'INTERNALDATE']).uniq).first
  got_id = make_id result

  ## I've turned off the following sanity check because Microsoft
  ## Exchange fails it.  Exchange actually reports two different
  ## INTERNALDATEs for the exact same message when queried at different
  ## points in time.
  ##
  ## RFC2060 defines the semantics of INTERNALDATE for messages that
  ## arrive via SMTP for via various IMAP commands, but states that
  ## "All other cases are implementation defined.". Great, thanks guys,
  ## yet another useless field.
  ## 
  ## Of course no OTHER imap server I've encountered returns DIFFERENT
  ## values for the SAME message. But it's Microsoft; what do you
  ## expect? If their programmers were any good they'd be working at
  ## Google.

  # raise OutOfSyncSourceError, "IMAP message mismatch: requested #{id}, got #{got_id}." unless got_id == id

  fields.map { |f| result.attr[f] or raise FatalSourceError, "empty response from IMAP server: #{f}" }
end
make_id(imap_stuff) click to toggle source
# File lib/sup/imap.rb, line 287
def make_id imap_stuff
  # use 7 digits for the size. why 7? seems nice.
  %w(RFC822.SIZE INTERNALDATE).each do |w|
    raise FatalSourceError, "requested data not in IMAP response: #{w}" unless imap_stuff.attr[w]
  end

  msize, mdate = imap_stuff.attr['RFC822.SIZE'] % 10000000, Time.parse(imap_stuff.attr["INTERNALDATE"])
  sprintf("%d%07d", mdate.to_i, msize).to_i
end
safely() { || ... } click to toggle source

execute a block, connected if unconnected, re-connected up to 3 times if a recoverable error occurs, and properly dying if an unrecoverable error occurs.

# File lib/sup/imap.rb, line 327
def safely
  retries = 0
  begin
    begin
      unsafe_connect unless @imap
      yield
    rescue *RECOVERABLE_ERRORS => e
      if (retries += 1) <= 3
        @imap = nil
        warn "got #{e.class.name}: #{e.message.inspect}"
        sleep 2
        retry
      end
      raise
    end
  rescue SocketError, Net::IMAP::Error, SystemCallError, IOError, OpenSSL::SSL::SSLError => e
    raise FatalSourceError, "While communicating with IMAP server (type #{e.class.name}): #{e.message.inspect}"
  end
end
say(s) click to toggle source
# File lib/sup/imap.rb, line 277
def say s
  @say_id = BufferManager.say s, @say_id if BufferManager.instantiated?
  info s
end
shutup() click to toggle source
# File lib/sup/imap.rb, line 282
def shutup
  BufferManager.clear @say_id if BufferManager.instantiated?
  @say_id = nil
end
unsafe_connect() click to toggle source
# File lib/sup/imap.rb, line 235
def unsafe_connect
  say "Connecting to IMAP server #{host}:#{port}..."

  ## apparently imap.rb does a lot of threaded stuff internally and if
  ## an exception occurs, it will catch it and re-raise it on the
  ## calling thread. but i can't seem to catch that exception, so i've
  ## resorted to initializing it in its own thread. surely there's a
  ## better way.
  exception = nil
  ::Thread.new do
    begin
      #raise Net::IMAP::ByeResponseError, "simulated imap failure"
      @imap = Net::IMAP.new host, port, ssl?
      say "Logging in..."

      ## although RFC1730 claims that "If an AUTHENTICATE command fails
      ## with a NO response, the client may try another", in practice
      ## it seems like they can also send a BAD response.
      begin
        raise Net::IMAP::NoResponseError unless @imap.capability().member? "AUTH=CRAM-MD5"
        @imap.authenticate 'CRAM-MD5', @username, @password
      rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
        debug "CRAM-MD5 authentication failed: #{e.class}. Trying LOGIN auth..."
        begin
          raise Net::IMAP::NoResponseError unless @imap.capability().member? "AUTH=LOGIN"
          @imap.authenticate 'LOGIN', @username, @password
        rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
          debug "LOGIN authentication failed: #{e.class}. Trying plain-text LOGIN..."
          @imap.login @username, @password
        end
      end
      say "Successfully connected to #{@parsed_uri}."
    rescue Exception => e
      exception = e
    ensure
      shutup
    end
  end.join

  raise exception if exception
end