Created
April 6, 2015 14:51
-
-
Save AndorChen/8ebfc5821ceac8884416 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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