Created
March 31, 2019 18:08
-
-
Save cannikin/7db3bdebad31ca1d2038c039c635e383 to your computer and use it in GitHub Desktop.
Fixes cover images for IDW's Transformers Humble Bundle epub: https://www.humblebundle.com/books/transformers-2019-idw-books
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
# Fixes cover images in epub files | |
# Run this file wherever you want, just change the path in the last line to a directory containing all your epub files. | |
class EpubCoverFixer | |
class MetaTagNotFound < StandardError; end | |
attr_reader :starting_dir | |
def initialize(dir) | |
@starting_dir = dir | |
end | |
def run | |
Dir.foreach(starting_dir) do |name| | |
if name.match? /^\./ | |
puts "Skipping #{name}" | |
else | |
puts "#{name}" | |
path = File.expand_path(starting_dir + '/' + name) | |
unzipped_dir = unzip(path) | |
update_cover(unzipped_dir) | |
new_file = zip(unzipped_dir) | |
cleanup(unzipped_dir) | |
end | |
puts "Fixed #{new_file}" | |
end | |
end | |
private def unzip(path) | |
puts " Unzipping..." | |
unzip_to = path.split('.').first | |
`rm -rf #{unzip_to}` | |
`unzip #{path} -d #{unzip_to}` | |
unzip_to | |
end | |
private def update_cover(dir) | |
puts " Updating cover..." | |
path = dir + '/OEBPS/content.opf' | |
opf = File.read(path) | |
if opf.match? /\<meta name="cover" content="cover-image" \/\>/ | |
opf.gsub!(/\<meta name="cover" content="cover-image" \/\>/, '<meta name="cover" content="cover-img" />') | |
write_file(path, opf) | |
puts " Replaced <meta> tag" | |
else | |
raise MetaTagNotFound | |
end | |
end | |
private def zip(dir) | |
puts " Zipping..." | |
filename = "#{dir.split('/').last}-fixed.epub" | |
`cd #{dir} && zip -r ../#{filename} *` | |
"#{starting_dir}/#{filename}" | |
end | |
private def cleanup(dir) | |
`rm -rf #{dir}` | |
end | |
private def write_file(path, contents) | |
File.open(path, 'w') do |file| | |
file.puts contents | |
end | |
end | |
end | |
EpubCoverFixer.new(File.join('/path', 'to', 'downloads')).run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment