Class: Vmail::ImapClient
- Inherits:
-
Object
- Object
- Vmail::ImapClient
- Defined in:
- lib/vmail/imap_client.rb
Constant Summary collapse
- DIVIDER_WIDTH =
46
- MailboxAliases =
{ 'sent' => '[Gmail]/Sent Mail', 'all' => '[Gmail]/All Mail', 'starred' => '[Gmail]/Starred', 'important' => '[Gmail]/Important', 'drafts' => '[Gmail]/Drafts', 'spam' => '[Gmail]/Spam', 'trash' => '[Gmail]/Trash' }
- UNITS =
[:b, :kb, :mb, :gb].freeze
- FLAGMAP =
{:Flagged => '*'}
Instance Attribute Summary collapse
-
#max_seqno ⇒ Object
of current mailbox.
Class Method Summary collapse
Instance Method Summary collapse
- #add_more_message_line(res, start_seqno) ⇒ Object
- #append_to_file(uid_set, file) ⇒ Object
- #clear_cached_message ⇒ Object
- #close ⇒ Object
- #copy_to(uid_set, mailbox) ⇒ Object
- #create_if_necessary(mailbox) ⇒ Object
- #decrement_max_seqno(num) ⇒ Object
- #deliver(text) ⇒ Object
- #divider(str) ⇒ Object
-
#extract_row_data(fetch_data) ⇒ Object
TODO extract this to another class or module and write unit tests.
- #fetch_and_cache(uid) ⇒ Object
- #fetch_envelopes(id_set, are_uids, is_update) ⇒ Object
-
#fetch_row_text(id_set, are_uids = false, is_update = false) ⇒ Object
id_set may be a range, array, or string.
-
#flag(uid_set, action, flg) ⇒ Object
id_set is a string comming from the vim client action is -FLAGS or +FLAGS.
-
#format_flags(flags) ⇒ Object
flags is an array like [:Flagged, :Seen].
- #format_headers(hash) ⇒ Object
- #format_parts_info(parts) ⇒ Object
- #forward_template ⇒ Object
- #get_highest_message_id ⇒ Object
-
#get_mailbox_status ⇒ Object
not used for anything.
- #handle_error(error) ⇒ Object
-
#initialize(config) ⇒ ImapClient
constructor
A new instance of ImapClient.
- #list_mailboxes ⇒ Object
- #log(string) ⇒ Object
-
#mailboxes ⇒ Object
called internally, not by vim client.
-
#message_cache ⇒ Object
holds mail objects keyed by [mailbox, uid].
-
#more_messages(message_id, limit = 100) ⇒ Object
gets 100 messages prior to id.
- #move_to(uid_set, mailbox) ⇒ Object
- #new_mail_from_input(text) ⇒ Object
- #new_message_template(subject = nil, append_signature = true) ⇒ Object
-
#number_to_human_size(number) ⇒ Object
borrowed from ActionView/Helpers.
- #open ⇒ Object
- #open_html_part ⇒ Object
-
#prefetch_adjacent(index) ⇒ Object
deprecated.
- #prime_connection ⇒ Object
- #reconnect_if_necessary(timeout = 60, &block) ⇒ Object
- #reload_mailbox ⇒ Object
- #reply_template(replyall = false) ⇒ Object
- #revive_connection ⇒ Object
- #save_attachments(dir) ⇒ Object
- #search(query) ⇒ Object
- #select_mailbox(mailbox, force = false) ⇒ Object
- #show_message(uid, raw = false) ⇒ Object
- #signature ⇒ Object
- #smtp_settings ⇒ Object
- #spawn_thread_if_tty ⇒ Object
- #update ⇒ Object
- #window_width=(width) ⇒ Object
-
#with_open {|_self| ... } ⇒ Object
expects a block, closes on finish.
Constructor Details
#initialize(config) ⇒ ImapClient
Returns a new instance of ImapClient.
25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/vmail/imap_client.rb', line 25 def initialize(config) @username, @password = config['username'], config['password'] @name = config['name'] @signature = config['signature'] @mailbox = nil @logger = Logger.new(config['logfile'] || STDERR) @logger.level = Logger::DEBUG @imap_server = config['server'] || 'imap.gmail.com' @imap_port = config['port'] || 993 @current_mail = nil @current_message_uid = nil @width = 140 end |
Instance Attribute Details
#max_seqno ⇒ Object
of current mailbox
23 24 25 |
# File 'lib/vmail/imap_client.rb', line 23 def max_seqno @max_seqno end |
Class Method Details
.daemon(config) ⇒ Object
792 793 794 795 796 797 798 799 |
# File 'lib/vmail/imap_client.rb', line 792 def self.daemon(config) $gmail = self.start(config) use_uri = config['drb_uri'] || nil # redundant but explicit DRb.start_service(use_uri, $gmail) uri = DRb.uri puts "starting gmail service at #{uri}" uri end |
.start(config) ⇒ Object
786 787 788 789 790 |
# File 'lib/vmail/imap_client.rb', line 786 def self.start(config) imap_client = Vmail::ImapClient.new config imap_client.open imap_client end |
Instance Method Details
#add_more_message_line(res, start_seqno) ⇒ Object
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 |
# File 'lib/vmail/imap_client.rb', line 384 def (res, start_seqno) log "add_more_message_line for start_seqno #{start_seqno}" if @all_search return res if start_seqno.nil? remaining = start_seqno - 1 else # filter search remaining = (@ids.index(start_seqno) || 1) - 1 end if remaining < 1 log "none remaining" return "showing all matches\n" + res end log "remaining messages: #{remaining}" "> Load #{[100, remaining].min} more messages. #{remaining} remaining.\n" + res end |
#append_to_file(uid_set, file) ⇒ Object
584 585 586 587 588 589 590 591 592 593 594 |
# File 'lib/vmail/imap_client.rb', line 584 def append_to_file(uid_set, file) uid_set = uid_set.split(',').map(&:to_i) log "append to file uid set #{uid_set.inspect} to file: #{file}" uid_set.each do |uid| = (uid) File.open(file, 'a') {|f| f.puts(divider('=') + "\n" + + "\n\n")} subject = ([/^subject:(.*)/,1] || '').strip log "appended message '#{subject}'" end "printed #{uid_set.size} message#{uid_set.size == 1 ? '' : 's'} to #{file.strip}" end |
#clear_cached_message ⇒ Object
98 99 100 101 102 103 104 |
# File 'lib/vmail/imap_client.rb', line 98 def return unless STDIN.tty? log "CLEARING CACHED MESSAGE" @current_mail = nil @current_message_uid = nil @current_message = nil end |
#close ⇒ Object
64 65 66 67 68 69 70 71 |
# File 'lib/vmail/imap_client.rb', line 64 def close log "closing connection" Timeout::timeout(10) do @imap.close rescue Net::IMAP::BadResponseError @imap.disconnect rescue IOError end rescue Timeout::Error end |
#copy_to(uid_set, mailbox) ⇒ Object
550 551 552 553 554 555 556 557 558 559 560 561 |
# File 'lib/vmail/imap_client.rb', line 550 def copy_to(uid_set, mailbox) uid_set = uid_set.split(',').map(&:to_i) if MailboxAliases[mailbox] mailbox = MailboxAliases[mailbox] end create_if_necessary mailbox log "copying #{uid_set.inspect} to #{mailbox}" spawn_thread_if_tty do log @imap.uid_copy(uid_set, mailbox) log "copied uid_set #{uid_set.inspect} to #{mailbox}" end end |
#create_if_necessary(mailbox) ⇒ Object
573 574 575 576 577 578 579 580 581 582 |
# File 'lib/vmail/imap_client.rb', line 573 def create_if_necessary(mailbox) current_mailboxes = mailboxes.map {|m| MailboxAliases[m] || m} if !current_mailboxes.include?(mailbox) log "current mailboxes: #{current_mailboxes.inspect}" log "creating mailbox #{mailbox}" log @imap.create(mailbox) @mailboxes = nil # force reload ... list_mailboxes end end |
#decrement_max_seqno(num) ⇒ Object
331 332 333 334 335 |
# File 'lib/vmail/imap_client.rb', line 331 def decrement_max_seqno(num) return unless STDIN.tty? log "Decremented max seqno from #{self.max_seqno} to #{self.max_seqno - num}" self.max_seqno -= num end |
#deliver(text) ⇒ Object
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 |
# File 'lib/vmail/imap_client.rb', line 650 def deliver(text) # parse the text. The headers are yaml. The rest is text body. require 'net/smtp' # prime_connection mail = new_mail_from_input(text) mail.delivery_method(*smtp_settings) res = mail.deliver! log res.inspect log "\n" msg = if res.is_a?(Mail::Message) "message '#{mail.subject}' sent" else "failed to deliver message '#{mail.subject}'" end log msg msg end |
#divider(str) ⇒ Object
646 647 648 |
# File 'lib/vmail/imap_client.rb', line 646 def divider(str) str * DIVIDER_WIDTH end |
#extract_row_data(fetch_data) ⇒ Object
TODO extract this to another class or module and write unit tests
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 |
# File 'lib/vmail/imap_client.rb', line 202 def extract_row_data(fetch_data) seqno = fetch_data.seqno uid = fetch_data.attr['UID'] # log "fetched seqno #{seqno} uid #{uid}" envelope = fetch_data.attr["ENVELOPE"] size = fetch_data.attr["RFC822.SIZE"] flags = fetch_data.attr["FLAGS"] address_struct = if @mailbox == '[Gmail]/Sent Mail' structs = envelope.to || envelope.cc structs.nil? ? nil : structs.first else envelope.from.first end address = if address_struct.nil? "unknown" elsif address_struct.name "#{Mail::Encodings.unquote_and_convert_to(address_struct.name, 'UTF-8')} <#{[address_struct.mailbox, address_struct.host].join('@')}>" else [Mail::Encodings.unquote_and_convert_to(address_struct.mailbox, 'UTF-8'), Mail::Encodings.unquote_and_convert_to(address_struct.host, 'UTF-8')].join('@') end if @mailbox == '[Gmail]/Sent Mail' && envelope.to && envelope.cc total_recips = (envelope.to + envelope.cc).size address += " + #{total_recips - 1}" end date = begin Time.parse(envelope.date).localtime rescue ArgumentError Time.now end date_formatted = if date.year != Time.now.year date.strftime "%b %d %Y" rescue envelope.date.to_s else date.strftime "%b %d %I:%M%P" rescue envelope.date.to_s end subject = envelope.subject || '' subject = Mail::Encodings.unquote_and_convert_to(subject, 'UTF-8') flags = format_flags(flags) mid_width = @width - 38 address_col_width = (mid_width * 0.3).ceil subject_col_width = (mid_width * 0.7).floor identifier = [seqno.to_i, uid.to_i].join(':') row_text = [ flags.col(2), (date_formatted || '').col(14), address.col(address_col_width), subject.col(subject_col_width), number_to_human_size(size).rcol(7), identifier.to_s ].join(' | ') {:uid => uid, :seqno => seqno, :row_text => row_text} rescue log "error extracting header for uid #{uid} seqno #{seqno}: #$!\n#{$!.backtrace}" row_text = "#{seqno.to_s} : error extracting this header" {:uid => uid, :seqno => seqno, :row_text => row_text} end |
#fetch_and_cache(uid) ⇒ Object
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 |
# File 'lib/vmail/imap_client.rb', line 439 def fetch_and_cache(uid) if data = [[@mailbox, uid]] return data end fetch_data = reconnect_if_necessary do res = @imap.uid_fetch(uid, ["FLAGS", "RFC822", "RFC822.SIZE"]) if res.nil? # retry one more time ( find a more elegant way to do this ) res = @imap.uid_fetch(uid, ["FLAGS", "RFC822", "RFC822.SIZE"]) end res[0] end # USE THIS size = fetch_data.attr["RFC822.SIZE"] flags = fetch_data.attr["FLAGS"] mail = Mail.new(fetch_data.attr['RFC822']) formatter = Vmail::MessageFormatter.new(mail) = <<-EOF #{@mailbox} uid:#{uid} #{number_to_human_size size} #{flags.inspect} #{format_parts_info(formatter.list_parts)} #{divider '-'} #{format_headers(formatter.extract_headers)} #{formatter.process_body} EOF # log "storing message_cache[[#{@mailbox}, #{uid}]]" d = {:mail => mail, :size => size, :message_text => , :seqno => fetch_data.seqno, :flags => flags} [[@mailbox, uid]] = d rescue msg = "Error encountered parsing message uid #{uid}:\n#{$!}\n#{$!.backtrace.join("\n")}" + "\n\nRaw message:\n\n" + mail.to_s log msg log {:message_text => msg} end |
#fetch_envelopes(id_set, are_uids, is_update) ⇒ Object
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
# File 'lib/vmail/imap_client.rb', line 183 def fetch_envelopes(id_set, are_uids, is_update) results = reconnect_if_necessary do if are_uids @imap.uid_fetch(id_set, ["FLAGS", "ENVELOPE", "RFC822.SIZE", "UID" ]) else @imap.fetch(id_set, ["FLAGS", "ENVELOPE", "RFC822.SIZE", "UID" ]) end end if results.nil? error = "expected fetch results but got nil" log(error) && raise(error) end log "- extracting headers" = results.map {|x| extract_row_data(x) } log "- returning #{.size} new rows and caching result" end |
#fetch_row_text(id_set, are_uids = false, is_update = false) ⇒ Object
id_set may be a range, array, or string
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 |
# File 'lib/vmail/imap_client.rb', line 167 def fetch_row_text(id_set, are_uids=false, is_update=false) log "fetch_row_text: #{id_set.inspect}" if id_set.is_a?(String) id_set = id_set.split(',') end if id_set.to_a.empty? log "- empty set" return "" end = fetch_envelopes(id_set, are_uids, is_update) .map {|x| x[:row_text]}.join("\n") rescue # Encoding::CompatibilityError (only in 1.9.2) log "Error in fetch_row_text:\n#{$!}\n#{$!.backtrace}" .map {|x| Iconv.conv('US-ASCII//TRANSLIT//IGNORE', 'UTF-8', x[:row_text])}.join("\n") end |
#flag(uid_set, action, flg) ⇒ Object
id_set is a string comming from the vim client action is -FLAGS or +FLAGS
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 |
# File 'lib/vmail/imap_client.rb', line 492 def flag(uid_set, action, flg) log "flag #{uid_set} #{flg} #{action}" uid_set = uid_set.split(',').map(&:to_i) if flg == 'Deleted' log "Deleting uid_set: #{uid_set.inspect}" decrement_max_seqno(uid_set.size) # for delete, do in a separate thread because deletions are slow spawn_thread_if_tty do unless @mailbox == '[Gmail]/Trash' log "@imap.uid_copy #{uid_set.inspect} to trash" log @imap.uid_copy(uid_set, "[Gmail]/Trash") end log "@imap.uid_store #{uid_set.inspect} #{action} [#{flg.to_sym}]" log @imap.uid_store(uid_set, action, [flg.to_sym]) reload_mailbox end elsif flg == 'spam' || flg == '[Gmail]/Spam' log "Marking as spam uid_set: #{uid_set.inspect}" decrement_max_seqno(uid_set.size) spawn_thread_if_tty do log "@imap.uid_copy #{uid_set.inspect} to spam" log @imap.uid_copy(uid_set, "[Gmail]/Spam") log "@imap.uid_store #{uid_set.inspect} #{action} [:Deleted]" log @imap.uid_store(uid_set, action, [:Deleted]) reload_mailbox end else log "Flagging uid_set: #{uid_set.inspect}" spawn_thread_if_tty do log "@imap.uid_store #{uid_set.inspect} #{action} [#{flg.to_sym}]" log @imap.uid_store(uid_set, action, [flg.to_sym]) end end end |
#format_flags(flags) ⇒ Object
flags is an array like [:Flagged, :Seen]
276 277 278 279 280 281 282 283 284 |
# File 'lib/vmail/imap_client.rb', line 276 def format_flags(flags) # other flags like "Old" should be hidden here flags = flags.map {|flag| FLAGMAP[flag] || flag} flags.delete("Old") if flags.delete(:Seen).nil? flags << '+' # unread end flags.join('') end |
#format_headers(hash) ⇒ Object
604 605 606 607 608 609 610 611 612 613 |
# File 'lib/vmail/imap_client.rb', line 604 def format_headers(hash) lines = [] hash.each_pair do |key, value| if value.is_a?(Array) value = value.join(", ") end lines << "#{key.gsub("_", '-')}: #{value}" end lines.join("\n") end |
#format_parts_info(parts) ⇒ Object
483 484 485 486 487 488 |
# File 'lib/vmail/imap_client.rb', line 483 def format_parts_info(parts) lines = parts.select {|part| part !~ %r{text/plain}} if lines.size > 0 "\n#{lines.join("\n")}" end end |
#forward_template ⇒ Object
632 633 634 635 636 637 638 639 640 641 642 643 644 |
# File 'lib/vmail/imap_client.rb', line 632 def forward_template original_body = @current_message.split(/\n-{20,}\n/, 2)[1] formatter = Vmail::MessageFormatter.new(@current_mail) headers = formatter.extract_headers subject = headers['subject'] if subject !~ /Fwd: / subject = "Fwd: #{subject}" end (subject, false) + "\n---------- Forwarded message ----------\n" + original_body + signature end |
#get_highest_message_id ⇒ Object
106 107 108 109 110 111 112 113 114 115 116 |
# File 'lib/vmail/imap_client.rb', line 106 def # get highest message ID res = @imap.fetch([1,"*"], ["ENVELOPE"]) if res @num_messages = res[-1].seqno log "HIGHEST ID: #@num_messages" else @num_messages = 1 log "NO HIGHEST ID: setting @num_messages to 1" end end |
#get_mailbox_status ⇒ Object
not used for anything
119 120 121 122 123 |
# File 'lib/vmail/imap_client.rb', line 119 def get_mailbox_status return @status = @imap.status(@mailbox, ["MESSAGES", "RECENT", "UNSEEN"]) log "mailbox status: #{@status.inspect}" end |
#handle_error(error) ⇒ Object
762 763 764 |
# File 'lib/vmail/imap_client.rb', line 762 def handle_error(error) log error end |
#list_mailboxes ⇒ Object
146 147 148 149 150 151 152 153 154 155 156 |
# File 'lib/vmail/imap_client.rb', line 146 def list_mailboxes log 'loading mailboxes...' @mailboxes ||= ((@imap.list("[Gmail]/", "%") || []) + (@imap.list("", "*")) || []). select {|struct| struct.attr.none? {|a| a == :Noselect} }. map {|struct| struct.name}. map {|name| MailboxAliases.invert[name] || name} @mailboxes.delete("INBOX") @mailboxes.unshift("INBOX") log "loaded mailboxes: #{@mailboxes.inspect}" @mailboxes.join("\n") end |
#log(string) ⇒ Object
758 759 760 |
# File 'lib/vmail/imap_client.rb', line 758 def log(string) @logger.debug string end |
#mailboxes ⇒ Object
called internally, not by vim client
159 160 161 162 163 164 |
# File 'lib/vmail/imap_client.rb', line 159 def mailboxes if @mailboxes.nil? list_mailboxes end @mailboxes end |
#message_cache ⇒ Object
holds mail objects keyed by [mailbox, uid]
40 41 42 43 44 45 46 47 48 |
# File 'lib/vmail/imap_client.rb', line 40 def @message_cache ||= {} size = @message_cache.values.reduce(0) {|sum, x| sum + x[:size]} if size > 2_000_000 # TODO make this configurable log "PRUNING MESSAGE CACHE; message cache is consuming #{number_to_human_size size}" @message_cache.keys[0, @message_cache.size / 2].each {|k| @message_cache.delete(k)} end @message_cache end |
#more_messages(message_id, limit = 100) ⇒ Object
gets 100 messages prior to id
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 |
# File 'lib/vmail/imap_client.rb', line 365 def (, limit=100) log "more_messages: message_id #{}" = .to_i if @all_search x = [( - limit), 0].max y = [ - 1, 0].max res = fetch_row_text((x..y)) (res, x) else # filter search query log "@start_index #@start_index" x = [(@start_index - limit), 0].max y = [@start_index - 1, 0].max @start_index = x res = fetch_row_text(@ids[x..y]) (res, @ids[x]) end end |
#move_to(uid_set, mailbox) ⇒ Object
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 |
# File 'lib/vmail/imap_client.rb', line 529 def move_to(uid_set, mailbox) uid_set = uid_set.split(',').map(&:to_i) decrement_max_seqno(uid_set.size) log "move #{uid_set.inspect} to #{mailbox}" if mailbox == 'all' log "archiving messages" end if MailboxAliases[mailbox] mailbox = MailboxAliases[mailbox] end create_if_necessary mailbox log "moving uid_set: #{uid_set.inspect} to #{mailbox}" spawn_thread_if_tty do log @imap.uid_copy(uid_set, mailbox) log @imap.uid_store(uid_set, '+FLAGS', [:Deleted]) reload_mailbox log "moved uid_set #{uid_set.inspect} to #{mailbox}" end end |
#new_mail_from_input(text) ⇒ Object
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 |
# File 'lib/vmail/imap_client.rb', line 668 def new_mail_from_input(text) require 'mail' mail = Mail.new raw_headers, raw_body = *text.split(/\n\s*\n/, 2) headers = {} raw_headers.split("\n").each do |line| key, value = *line.split(/:\s*/, 2) headers[key] = value end log "delivering message with headers: #{headers.to_yaml}" mail.from = headers['from'] || @username mail.to = headers['to'] #.split(/,\s+/) mail.cc = headers['cc'] #&& headers['cc'].split(/,\s+/) mail.bcc = headers['bcc'] #&& headers['cc'].split(/,\s+/) mail.subject = headers['subject'] mail.from ||= @username # attachments are added as a snippet of YAML after a blank line # after the headers, and followed by a blank line if ( = raw_body.split(/\n\s*\n/, 2)[0]) =~ /^attach(ment|ments)*:/ files = YAML::load().values.flatten log "attach: #{files}" files.each do |file| if File.directory?(file) Dir.glob("#{file}/*").each {|f| mail.add_file(f) if File.size?(f)} else mail.add_file(file) if File.size?(file) end end mail.text_part do body raw_body.split(/\n\s*\n/, 2)[1] end else mail.text_part do body raw_body end end mail end |
#new_message_template(subject = nil, append_signature = true) ⇒ Object
596 597 598 599 600 601 602 |
# File 'lib/vmail/imap_client.rb', line 596 def (subject = nil, append_signature = true) headers = {'from' => "#{@name} <#{@username}>", 'to' => nil, 'subject' => subject } format_headers(headers) + (append_signature ? ("\n\n" + signature) : "\n\n") end |
#number_to_human_size(number) ⇒ Object
borrowed from ActionView/Helpers
261 262 263 264 265 266 267 268 269 270 271 272 |
# File 'lib/vmail/imap_client.rb', line 261 def number_to_human_size(number) if number.to_i < 1024 "<1kb" # round up to 1kh else max_exp = UNITS.size - 1 exponent = (Math.log(number) / Math.log(1024)).to_i # Convert to base 1024 exponent = max_exp if exponent > max_exp # we need this to avoid overflow for the highest unit number /= 1024 ** exponent unit = UNITS[exponent] "#{number}#{unit}" end end |
#open ⇒ Object
50 51 52 53 54 |
# File 'lib/vmail/imap_client.rb', line 50 def open @imap = Net::IMAP.new(@imap_server, @imap_port, true, nil, false) log @imap.login(@username, @password) list_mailboxes # prefetch mailbox list end |
#open_html_part ⇒ Object
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 |
# File 'lib/vmail/imap_client.rb', line 725 def open_html_part log "open_html_part" log @current_mail.parts.inspect multipart = @current_mail.parts.detect {|part| part.multipart?} html_part = if multipart multipart.parts.detect {|part| part.header["Content-Type"].to_s =~ /text\/html/} elsif ! @current_mail.parts.empty? @current_mail.parts.detect {|part| part.header["Content-Type"].to_s =~ /text\/html/} else @current_mail.body end return if html_part.nil? outfile = 'part.html' File.open(outfile, 'w') {|f| f.puts(html_part.decoded)} # client should handle opening the html file return outfile end |
#prefetch_adjacent(index) ⇒ Object
deprecated
475 476 477 478 479 480 481 |
# File 'lib/vmail/imap_client.rb', line 475 def prefetch_adjacent(index) Thread.new do [index + 1, index - 1].each do |idx| fetch_and_cache(idx) end end end |
#prime_connection ⇒ Object
132 133 134 135 136 137 138 139 140 141 142 143 144 |
# File 'lib/vmail/imap_client.rb', line 132 def prime_connection return if @ids.nil? || @ids.empty? reconnect_if_necessary(4) do # this is just to prime the IMAP connection # It's necessary for some reason before update and deliver. log "priming connection" res = @imap.fetch(@ids[-1], ["ENVELOPE"]) if res.nil? # just go ahead, just log log "priming connection didn't work, connection seems broken, but still going ahead..." end end end |
#reconnect_if_necessary(timeout = 60, &block) ⇒ Object
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 |
# File 'lib/vmail/imap_client.rb', line 766 def reconnect_if_necessary(timeout = 60, &block) # if this times out, we know the connection is stale while the user is # trying to update Timeout::timeout(timeout) do block.call end rescue IOError, Errno::EADDRNOTAVAIL, Errno::ECONNRESET, Timeout::Error log "error: #{$!}" log "attempting to reconnect" close log(revive_connection) # hope this isn't an endless loop reconnect_if_necessary do block.call end rescue log "error: #{$!}" raise end |
#reload_mailbox ⇒ Object
93 94 95 96 |
# File 'lib/vmail/imap_client.rb', line 93 def reload_mailbox return unless STDIN.tty? select_mailbox(@mailbox, true) end |
#reply_template(replyall = false) ⇒ Object
615 616 617 618 619 620 621 622 623 624 625 |
# File 'lib/vmail/imap_client.rb', line 615 def reply_template(replyall=false) log "sending reply template" if @current_mail.nil? log "- missing @current mail!" return nil end # user reply_template class reply_headers = Vmail::ReplyTemplate.new(@current_mail, @username, @name, replyall).reply_headers body = reply_headers.delete(:body) format_headers(reply_headers) + "\n\n\n" + body + signature end |
#revive_connection ⇒ Object
125 126 127 128 129 130 |
# File 'lib/vmail/imap_client.rb', line 125 def revive_connection log "reviving connection" open log "reselecting mailbox #@mailbox" @imap.select(@mailbox) end |
#save_attachments(dir) ⇒ Object
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 |
# File 'lib/vmail/imap_client.rb', line 708 def (dir) log "save_attachments #{dir}" if !@current_mail log "missing a current message" end return unless dir && @current_mail = @current_mail. `mkdir -p #{dir}` saved = .map do |x| path = File.join(dir, x.filename) log "saving #{path}" File.open(path, 'wb') {|f| f.puts x.decoded} path end "saved:\n" + saved.map {|x| "- #{x}"}.join("\n") end |
#search(query) ⇒ Object
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 |
# File 'lib/vmail/imap_client.rb', line 286 def search(query) query = Vmail::Query.parse(query) @limit = query.shift.to_i # a limit of zero is effectively no limit if @limit == 0 @limit = @num_messages end if query.size == 1 && query[0].downcase == 'all' # form a sequence range query.unshift [[@num_messages - @limit + 1 , 1].max, @num_messages].join(':') @all_search = true else # this is a special query search # set the target range to the whole set query.unshift "1:#@num_messages" @all_search = false end @query = query.map {|x| x.to_s.downcase} query_string = Vmail::Query.args2string(@query) log "search query: #{@query} > #{query_string.inspect}" log "- @all_search #{@all_search}" @query = query @ids = reconnect_if_necessary(180) do # increase timeout to 3 minutes @imap.search(query_string) end # save ids in @ids, because filtered search relies on it fetch_ids = if @all_search @ids else #filtered search @start_index = [@ids.length - @limit, 0].max @ids[@start_index..-1] end self.max_seqno = @ids[-1] log "- search query got #{@ids.size} results; max seqno: #{self.max_seqno}" res = fetch_row_text(fetch_ids) if STDOUT.tty? (res, fetch_ids[0]) else # non interactive mode puts [@mailbox, res].join("\n") end rescue log "ERROR:\n#{$!.inspect}\n#{$!.backtrace.join("\n")}" end |
#select_mailbox(mailbox, force = false) ⇒ Object
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
# File 'lib/vmail/imap_client.rb', line 73 def select_mailbox(mailbox, force=false) if MailboxAliases[mailbox] mailbox = MailboxAliases[mailbox] end if mailbox == @mailbox && !force return end log "selecting mailbox #{mailbox.inspect}" reconnect_if_necessary(15) do log @imap.select(mailbox) end log "done" @mailbox = mailbox log "getting mailbox status" get_mailbox_status log "getting highest message id" return "OK" end |
#show_message(uid, raw = false) ⇒ Object
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 |
# File 'lib/vmail/imap_client.rb', line 400 def (uid, raw=false) log "show message: #{uid}" return @current_mail.to_s if raw uid = uid.to_i if uid == @current_message_uid return @current_message end #prefetch_adjacent(index) # deprecated # TODO keep state in vim buffers, instead of on Vmail Ruby client # envelope_data[:row_text] = envelope_data[:row_text].gsub(/^\+ /, ' ').gsub(/^\*\+/, '* ') # mark as read in cache #seqno = envelope_data[:seqno] log "showing message uid: #{uid}" data = if x = [[@mailbox, uid]] log "- message cache hit" x else log "- fetching and storing to message_cache[[#{@mailbox}, #{uid}]]" fetch_and_cache(uid) end if data.nil? # retry, though this is a hack! log "- data is nil. retrying..." return (uid, raw) end # make this more DRY later by directly using a ref to the hash mail = data[:mail] size = data[:size] @current_message_uid = uid log "- setting @current_mail" @current_mail = mail # used later to show raw message or extract attachments if any @current_message = data[:message_text] rescue log "parsing error" "Error encountered parsing this message:\n#{$!}\n#{$!.backtrace.join("\n")}" end |
#signature ⇒ Object
627 628 629 630 |
# File 'lib/vmail/imap_client.rb', line 627 def signature return '' unless @signature "\n\n#@signature" end |
#smtp_settings ⇒ Object
748 749 750 751 752 753 754 755 756 |
# File 'lib/vmail/imap_client.rb', line 748 def smtp_settings [:smtp, {:address => "smtp.gmail.com", :port => 587, :domain => 'gmail.com', :user_name => @username, :password => @password, :authentication => 'plain', :enable_starttls_auto => true}] end |
#spawn_thread_if_tty ⇒ Object
563 564 565 566 567 568 569 570 571 |
# File 'lib/vmail/imap_client.rb', line 563 def spawn_thread_if_tty if STDIN.tty? Thread.new do yield end else yield end end |
#update ⇒ Object
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 |
# File 'lib/vmail/imap_client.rb', line 337 def update prime_connection = @num_messages # we need to re-select the mailbox to get the new highest id reload_mailbox update_query = @query.dup # set a new range filter # this may generate a negative rane, e.g., "19893:19992" but that seems harmless update_query[0] = "#{}:#{@num_messages}" ids = reconnect_if_necessary { log "search #update_query" @imap.search(Vmail::Query.args2string(update_query)) } log "- got seqnos: #{ids.inspect}" log "- getting seqnos > #{self.max_seqno}" new_ids = ids.select {|seqno| seqno > self.max_seqno} @ids = @ids + new_ids log "- update: new uids: #{new_ids.inspect}" if !new_ids.empty? self.max_seqno = new_ids[-1] res = fetch_row_text(new_ids, false, true) res else nil end end |
#window_width=(width) ⇒ Object
743 744 745 746 |
# File 'lib/vmail/imap_client.rb', line 743 def window_width=(width) log "setting window width to #{width}" @width = width.to_i end |
#with_open {|_self| ... } ⇒ Object
expects a block, closes on finish
57 58 59 60 61 62 |
# File 'lib/vmail/imap_client.rb', line 57 def with_open @imap = Net::IMAP.new(@imap_server, @imap_port, true, nil, false) log @imap.login(@username, @password) yield self close end |