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_sizeObject (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

#folderObject (readonly)

Returns the value of attribute folder.



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

def folder
  @folder
end

#serializerObject (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

#runObject



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
42
43
44
45
# File 'lib/imap/backup/downloader.rb', line 13

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

    offset = i * block_size + 1
    uids_and_bodies.each.with_index do |uid_and_body, j|
      uid = uid_and_body[:uid]
      body = uid_and_body[:body]
      case
      when !body
        info("Fetch returned empty body - skipping")
      when !uid
        info("Fetch returned empty UID - skipping")
      else
        debug("uid: #{uid} (#{offset + j}/#{count}) - #{body.size} bytes")
        serializer.save(uid, body)
      end
    end
  end
end