Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'fileutils'
# Usage: rake duokanify file=path/to/sample.epub
desc 'Adds dtb:depth to ncx file in an ePub'
task :duokanify do
unless ENV['file']
abort("ERROR: Please provide the ePub file path!\nexit")
end
unless ENV['file'].end_with?('.epub')
abort("ERROR: The file you provided is not an ePub!\nexit")
end
path = File.expand_path(ENV['file'])
unless File.exist?(path)
abort("ERROR: The file you provided is not exists!\nexit")
end
puts 'Unzipping....'
dest_dir = File.basename(path, '.epub')
system "unzip #{ENV['file']} -d #{dest_dir}"
puts
puts 'Normalize....'
ncx_file = File.join(dest_dir, 'OEBPS', 'toc.ncx')
unless File.exist?(ncx_file)
abort("Info: The ePub has no ncx file, needless to normalize.\nexit")
end
ncx = File.open(ncx_file, 'r+') do |f|
content = f.read
# puts content.inspect
if content =~ /meta="dtb:depth"/i
abort("Info: The ePub already set dtb:depth, needless to normalize.\nexit")
else
parts = content.split('</head>')
parts.first << '<meta name="dtb:depth" content="1"/>'
f.rewind
f.write parts.join('</head>')
end
end
puts
puts 'Rezipping....'
normalized_file = "#{File.basename(dest_dir)}-normalized.epub"
FileUtils.cd(dest_dir) do
system "zip -0 -X #{normalized_file} mimetype"
system "zip -9 -r #{normalized_file} META-INF OEBPS"
end
FileUtils.cp File.join(dest_dir, normalized_file), Dir.pwd
puts
puts 'Cleanning....'
FileUtils.rm_rf(dest_dir, :secure => true)
puts
puts 'Done'
puts "Normalized ePub path: ./#{normalized_file}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment