Class: EmailGraph::GmailFetcher::Fetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/email_graph/gmail_fetcher.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(email: nil, access_token: nil) ⇒ Fetcher

Returns a new instance of Fetcher.



11
12
13
14
15
# File 'lib/email_graph/gmail_fetcher.rb', line 11

def initialize(email: nil, access_token: nil)
  @email = email
  @access_token = access_token
  @batch_size = 500
end

Instance Attribute Details

#access_tokenObject

Returns the value of attribute access_token.



9
10
11
# File 'lib/email_graph/gmail_fetcher.rb', line 9

def access_token
  @access_token
end

#batch_sizeObject

Returns the value of attribute batch_size.



9
10
11
# File 'lib/email_graph/gmail_fetcher.rb', line 9

def batch_size
  @batch_size
end

#emailObject

Returns the value of attribute email.



9
10
11
# File 'lib/email_graph/gmail_fetcher.rb', line 9

def email
  @email
end

Instance Method Details

#count_messages(mailboxes: ['INBOX']) ⇒ Object



17
18
19
# File 'lib/email_graph/gmail_fetcher.rb', line 17

def count_messages(mailboxes: ['INBOX'])
  mailboxes.inject(0){ |r, m| r + imap.status(m, ['MESSAGES'])['MESSAGES'] }
end

#each_envelope(mailboxes: ['INBOX'], batch_size: nil) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/email_graph/gmail_fetcher.rb', line 28

def each_envelope(mailboxes: ['INBOX'], batch_size: nil)
  mailboxes.each do |mailbox|
    # Needed before fetching
    imap.examine(mailbox)

    batch_size ||= @batch_size
    limit = count_messages(mailboxes: [mailbox])

    (1..limit).each_slice(batch_size) do |range|
      envelope_batch = imap.fetch(range, 'ENVELOPE') || []
      envelope_batch.each{ |e| yield e if block_given? }
      puts "Fetched #{range.last}/#{limit}"
    end
  end
end

#each_message(mailboxes: ['INBOX'], batch_size: nil) ⇒ Object



21
22
23
24
25
26
# File 'lib/email_graph/gmail_fetcher.rb', line 21

def each_message(mailboxes: ['INBOX'], batch_size: nil)
  each_envelope(mailboxes: mailboxes, batch_size: batch_size) do |e|
    m = Message.from_net_imap_envelope(e)
    yield m if block_given?
  end
end

#imapObject



50
51
52
# File 'lib/email_graph/gmail_fetcher.rb', line 50

def imap
  @imap ||= imap_connect
end

#imap_connectObject



44
45
46
47
48
# File 'lib/email_graph/gmail_fetcher.rb', line 44

def imap_connect
  Net::IMAP.new('imap.gmail.com', 993, usessl = true, certs = nil, verify = false).tap do |imap|
    imap.authenticate('XOAUTH2', email, access_token)
  end
end