Sha256: 6e0701b27e3fdf29f22b1ff9d0ec0c72f7b523c8099591b0167cce25a468255f

Contents?: true

Size: 1.79 KB

Versions: 16

Compression:

Stored size: 1.79 KB

Contents

module Imap::Backup
  class Uploader
    attr_reader :folder
    attr_reader :serializer

    def initialize(folder, serializer)
      @folder = folder
      @serializer = serializer
    end

    def run
      if folder.uids.any?
        rename_serialized_folder
      else
        folder.create
        serializer.force_uid_validity(folder.uid_validity)
      end

      return if count.zero?

      Logger.logger.debug "[#{folder.name}] #{count} to restore"
      serializer.each_message(missing_uids).with_index do |message, i|
        upload_message message, i + 1
      end
    end

    private

    def upload_message(message, index)
      return if message.nil?

      log_prefix = "[#{folder.name}] uid: #{message.uid} (#{index}/#{count}) -"
      Logger.logger.debug(
        "#{log_prefix} #{message.body.size} bytes"
      )

      begin
        new_uid = folder.append(message)
        serializer.update_uid(message.uid, new_uid)
      rescue StandardError => e
        Logger.logger.warn "#{log_prefix} append error: #{e}"
      end
    end

    def count
      @count ||= missing_uids.count
    end

    def missing_uids
      serializer.uids - folder.uids
    end

    def rename_serialized_folder
      Logger.logger.debug(
        "There's already a '#{folder.name}' folder with emails"
      )

      # Rename the local folder to a unique name
      new_name = serializer.apply_uid_validity(folder.uid_validity)

      return if !new_name

      # Restore the renamed folder
      Logger.logger.debug(
        "Backup '#{serializer.folder}' renamed and restored to '#{new_name}'"
      )
      @folder = Account::Folder.new(folder.connection, new_name)
      folder.create
      @serializer = Serializer.new(serializer.path, new_name)
      serializer.force_uid_validity(@folder.uid_validity)
    end
  end
end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
imap-backup-9.3.2 lib/imap/backup/uploader.rb
imap-backup-9.4.0.pre1 lib/imap/backup/uploader.rb
imap-backup-9.3.1 lib/imap/backup/uploader.rb
imap-backup-9.3.0 lib/imap/backup/uploader.rb
imap-backup-9.2.0 lib/imap/backup/uploader.rb
imap-backup-9.1.1 lib/imap/backup/uploader.rb
imap-backup-9.1.0 lib/imap/backup/uploader.rb
imap-backup-9.0.2 lib/imap/backup/uploader.rb
imap-backup-9.0.1.rc1 lib/imap/backup/uploader.rb
imap-backup-9.0.0 lib/imap/backup/uploader.rb
imap-backup-9.0.0.rc1 lib/imap/backup/uploader.rb
imap-backup-8.0.2 lib/imap/backup/uploader.rb
imap-backup-8.0.1 lib/imap/backup/uploader.rb
imap-backup-8.0.0 lib/imap/backup/uploader.rb
imap-backup-8.0.0.rc1 lib/imap/backup/uploader.rb
imap-backup-7.0.2 lib/imap/backup/uploader.rb