Class: Vmail::InboxPoller

Inherits:
ImapClient show all
Defined in:
lib/vmail/inbox_poller.rb

Constant Summary

Constants included from ShowingHeaders

ShowingHeaders::FLAGMAP

Instance Attribute Summary

Attributes inherited from ImapClient

#max_seqno

Instance Method Summary collapse

Methods inherited from ImapClient

#append_to_file, #check_for_new_messages, #clear_cached_message, #close, #create_if_necessary, daemon, #decrement_max_seqno, #deliver, #format_headers, #format_sent_message, #forward_template, #get_highest_message_id, #get_mailbox_status, #handle_error, #initialize, #list_mailboxes, #mailbox_aliases, #mailboxes, #more_messages, #new_mail_from_input, #new_message_template, #open, #open_html_part, #prime_connection, #reconnect_if_necessary, #reload_mailbox, #revive_connection, #save_attachments, #select_mailbox, #signature, #signature_script, #smtp_settings, #spawn_thread_if_tty, start, #update_message_list, #window_width=, #with_open

Methods included from ReplyTemplating

#reply_cc, #reply_headers, #reply_recipient, #reply_template

Methods included from FlaggingAndMoving

#convert_to_message_ids, #copy_to, #flag, #move_to

Methods included from ShowingMessage

#cached_full_message?, #current_mail, #current_message, #fetch_and_cache, #format_parts_info, #show_message

Methods included from ShowingHeaders

#extract_address, #fetch_and_cache_headers, #format_flags, #format_header_for_list, #get_message_headers, #with_more_message_line

Methods included from Searching

#search, #search_query?

Methods included from AddressQuoter

#quote_addresses

Methods included from Helpers

#divider, #number_to_human_size, #retry_if_needed

Constructor Details

This class inherits a constructor from Vmail::ImapClient

Instance Method Details

#log(string) ⇒ Object



147
148
149
150
151
152
# File 'lib/vmail/inbox_poller.rb', line 147

def log(string)
  if string.is_a?(::Net::IMAP::TaggedResponse)
    string = string.raw_data
  end
  @logger.debug "[INBOX POLLER]: #{ string }"
end

#start_pollingObject

This is a second IMAP client operating in a separate process



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
# File 'lib/vmail/inbox_poller.rb', line 8

def start_polling
  n = [`which notify-send`.chomp, `which growlnotify`.chomp].detect {|c| c != ''}
  if n
    log "Using notify tool: #{ n }"
    @notifier = case n
      when /notify-send/
        Proc.new {|t, m| `#{ n } -t 6000000 '#{ t }' '#{ m }'` }
      when /growlnotify/
        Proc.new {|t, m| `#{ n } -t '#{ t }' -m '#{ m }'` }
      end
  else
    log "No notification tool detected. INBOX polling aborted."
    return
  end

  sleep 30
  log "INBOX POLLER: started polling"
  @mailboxes.unshift "INBOX"
  select_mailbox "INBOX"
  search "ALL"
  loop do
    log "INBOX POLLER: checking inbox"
    update
    sleep 30
  end
end

#uncached_headers(id_set) ⇒ Object

doesn’t try to access Sequel / sqlite3



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/vmail/inbox_poller.rb', line 124

def uncached_headers(id_set)
  log "Fetching headers for #{ id_set.size } messages"
  results = reconnect_if_necessary do
    @imap.fetch(id_set, ["FLAGS", "ENVELOPE", "RFC822.SIZE", "UID"])
  end
  results.reverse.map do |x|
    envelope = x.attr["ENVELOPE"]
    message_id = envelope.message_id
    subject = Mail::Encodings.unquote_and_convert_to((envelope.subject || ''), 'UTF-8')
    recipients = ((envelope.to || []) + (envelope.cc || [])).map {|a| extract_address(a)}.join(', ')
    sender = extract_address envelope.from.first
    uid = x.attr["UID"]
    params = {
      subject: (subject || ''),
      flags: x.attr['FLAGS'].join(','),
      date: Time.parse(envelope.date).localtime.to_s,
      size: x.attr['RFC822.SIZE'],
      sender: sender,
      recipients: recipients
    }
  end
end

#updateObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/vmail/inbox_poller.rb', line 35

def update
  new_ids = check_for_new_messages
  if !new_ids.empty?
    @ids = @ids + new_ids

    notification_title = "Vmail: "
    notification_body = ""

    if new_ids.size == 1
      # If there is a single email, message is more descriptive about the
      # received email.
      #
      # Example:
      #
      #   (title) Vmail: Colin Sullivan
      #   (body) New Pull request received!
      #
      log "single new message received!"
      new_message = uncached_headers(new_ids)[0]

      # Extract just sender's name from sender field
      notification_title += new_message[:sender].gsub(/\<.*\>/, "").strip()

      # Truncate message subject if necessary
      if new_message[:subject].length > 128
        # Extract first 128 characters from subject of email
        notification_body += new_message[:subject][0..128] + "..."
      else
        notification_body += new_message[:subject]
      end

    else
      # If there are multiple new messages, notification is just a brief
      # listing.
      #
      # Example:
      #
      #   (title)   Vmail: 3 new messages
      #   (body)    Colin Sullivan: New Pull request rec...
      #             Henry Cowell: I am back from the dead!
      #             ...
      #
      log "multiple new messages received!"

      notification_title += new_ids.size.to_s() + " new messages"

      # for each message
      for i in 0...new_ids.size
        new_message = uncached_headers(new_ids)[i]

        # Create message line
        message_line = ""

        # Extract just sender's name from sender field
        message_line += new_message[:sender].gsub(/\<.*\>/, "").strip()

        # Extract subject
        message_line += ": " + new_message[:subject]

        # Concatenate line if necessary
        if message_line.length > 32
          message_line = message_line[0...29] + "..."
        end

        # Add to notification body
        notification_body += message_line + "\n"

      end

      # Concatenate entire notification body if necessary
      if notification_body.length > 128
        notification_body = notification_body[0...125] + "..."
      end

    end

    # Remove any '<>' characters from notification just incase, libnotify
    # can't print '<'
    notification_title = notification_title.tr('<>', '')
    notification_body = notification_body.tr('<>', '')

    @notifier.call notification_title, notification_body

  end
rescue
  log "VMAIL_ERROR: #{[$!.message, $!.backtrace].join("\n")}"
end