46 lines
1.2 KiB
Ruby
46 lines
1.2 KiB
Ruby
require "stringio"
|
|
require "zlib"
|
|
|
|
class BackupsController < ApplicationController
|
|
def show
|
|
end
|
|
|
|
def download
|
|
send_data gzip(BackupExport.call),
|
|
filename: "car-tracker-backup-#{Time.current.strftime('%Y%m%d%H%M%S')}.yml.gz",
|
|
type: "application/gzip",
|
|
disposition: "attachment"
|
|
end
|
|
|
|
def restore
|
|
BackupImport.call(gunzip(uploaded_backup.read), mode: params[:mode])
|
|
redirect_to backup_path, notice: "Backup restored."
|
|
rescue BackupImport::Error, Zlib::GzipFile::Error => error
|
|
redirect_to backup_path, alert: "Backup could not be restored: #{restore_error_message(error)}"
|
|
end
|
|
|
|
private
|
|
|
|
def uploaded_backup
|
|
params.fetch(:backup_file)
|
|
rescue KeyError
|
|
raise BackupImport::Error, "Choose a backup file to restore."
|
|
end
|
|
|
|
def gzip(content)
|
|
buffer = StringIO.new
|
|
Zlib::GzipWriter.wrap(buffer) { |gzip| gzip.write(content) }
|
|
buffer.string
|
|
end
|
|
|
|
def gunzip(content)
|
|
Zlib::GzipReader.wrap(StringIO.new(content), &:read)
|
|
rescue Zlib::GzipFile::Error
|
|
raise BackupImport::Error, "Backup file must be a gzip-compressed YAML file."
|
|
end
|
|
|
|
def restore_error_message(error)
|
|
error.message.presence || "unknown error"
|
|
end
|
|
end
|