Pack and Unpack Epubs

ePub files are simply small html based websites in a zip container. The structure of an ePub must comply with the IDPF ePub standard and the mimetype must be the first file in the zip archive and must also be uncompressed.

Pack

#!/usr/bin/env ruby

require 'optparse'

options = { :log => $stdout }

opt = OptionParser.new do |opt|
  opt.banner = "Usage: pack epub [options] <expanded epub root directory location>"
  opt.on_tail('-h', '--help') do
    puts opt
    exit
  end
end

opt.parse!(ARGV)
unless ARGV.size == 1
  puts opt
  exit
end

source_path = ARGV.first

begin

  if File.directory?(source_path) then
    Dir.chdir(source_path)

    system("zip -0Xq '#{source_path}.epub' mimetype")
    system("zip -Xr9Dq '#{source_path}.epub' *")

  else
    puts "You must choose a directory for packing"
  end

rescue Exception => e

  puts "Epub packing failed"
  puts e.to_s

end

Unpack

#!/usr/bin/env ruby

require 'optparse'

options = { :log => $stdout }

opt = OptionParser.new do |opt|
  opt.banner = "Usage: unpack epub [options] <epub location>"
  opt.on_tail('-h', '--help') do
    puts opt
    exit
  end
end

opt.parse!(ARGV)
unless ARGV.size == 1
  puts opt
  exit
end

source_epub = ARGV.first
out_dir_name = source_epub.gsub(".epub", "")
out_dir_path = ARGV[1]

begin

  system("mkdir '#{out_dir_path}#{out_dir_name}'")
  system("unzip '#{source_epub}' -d '#{out_dir_name}'")

rescue

  puts "Expand failed"

end