Class: Imap::Backup::Downloader

Inherits:
Object
  • Object
show all
Defined in:
lib/imap/backup/downloader.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(folder, serializer, block_size: 1) ⇒ Downloader

Returns a new instance of Downloader.



7
8
9
10
11
# File 'lib/imap/backup/downloader.rb', line 7

def initialize(folder, serializer, block_size: 1)
  @folder = folder
  @serializer = serializer
  @block_size = block_size
end

Instance Attribute Details

#block_size ⇒ Object (readonly)

Returns the value of attribute block_size.



5
6
7
# File 'lib/imap/backup/downloader.rb', line 5

def block_size
  @block_size
end

#folder ⇒ Object (readonly)

Returns the value of attribute folder.



3
4
5
# File 'lib/imap/backup/downloader.rb', line 3

def folder
  @folder
end

#serializer ⇒ Object (readonly)

Returns the value of attribute serializer.



4
5
6
# File 'lib/imap/backup/downloader.rb', line 4

def serializer
  @serializer
end

Instance Method Details

#run ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/imap/backup/downloader.rb', line 13

def run
  uids = folder.uids - serializer.uids
  count = uids.count
  Imap::Backup::Logger.logger.debug "[#{folder.name}] #{count} new messages"
  uids.each_slice(block_size).with_index do |block, i|
    offset = i * block_size + 1
    uids_and_bodies = folder.fetch_multi(block)
    if uids_and_bodies.nil?
      if block_size > 1
        Imap::Backup::Logger.logger.debug("[#{folder.name}] Multi fetch failed for UIDs #{block.join(", ")}, switching to single fetches")
        @block_size = 1
        redo
      else
        Imap::Backup::Logger.logger.debug("[#{folder.name}] Fetch failed for UID #{block[0]} - skipping")
        next
      end
    end

    uids_and_bodies.each.with_index do |uid_and_body, j|
      uid = uid_and_body[:uid]
      body = uid_and_body[:body]
      Imap::Backup::Logger.logger.debug(
        "[#{folder.name}] uid: #{uid} (#{offset +j}/#{count}) - " \
          "#{body.size} bytes"
      )
      serializer.save(uid, body)
    end
  end
end