Skip to content

Instantly share code, notes, and snippets.

@KitaitiMakoto
Last active August 29, 2015 14:23
Show Gist options
  • Save KitaitiMakoto/1d34e514bae47213c527 to your computer and use it in GitHub Desktop.
Save KitaitiMakoto/1d34e514bae47213c527 to your computer and use it in GitHub Desktop.
require 'pathname'
def main(middlewares, files)
files.each do |filename|
pathname = Pathname.new(filename).expand_path
raise "No such file: #{filename}" unless pathname.file?
content_type = middlewares.inject(nil) {|ct, mw|
mw.call(pathname) || ct
}
$stderr.puts [pathname.to_path, content_type].join(': ')
end
end
require 'rack/mime'
class Extension
def initialize(map={})
@mime_types = Rack::Mime::MIME_TYPES.merge(map)
end
def call(pathname)
@mime_types.fetch(pathname.extname, 'application/octet-stream')
end
end
require 'epub/parser'
EPUB::OCF::PhysicalContainer.adapter = :File
class EPUBContent
def initialize(dirs)
@media_types = dirs.each_with_object({}) {|dir, map|
dir = Pathname.new(dir).expand_path
raise "No such directory: #{dir}" unless dir.directory?
epub = EPUB::Parser.parse(dir)
epub_file = Pathname.new(epub.epub_file).expand_path
Pathname.glob("#{epub_file}/META-INF/*.xml").each do |path|
map[path] = 'application/xml'
end
epub.ocf.container.rootfiles.each do |rootfile|
map[epub_file.join(rootfile.full_path)] = rootfile.media_type
end
epub.resources.each do |resource|
map[epub_file.join(resource.entry_name)] = resource.media_type
end
}
end
def call(pathname)
@media_types[pathname]
end
end
epub_base_dir = "#{ENV['HOME']}/ruby/projects/epub-parser/test"
epub_dirs = Pathname.glob("#{epub_base_dir}/**/META-INF/container.xml").map {|path| path.dirname.dirname}
determiners = [
Extension.new({'.epub' => 'application/epub+zip'}),
EPUBContent.new(epub_dirs)
]
main(determiners, ARGV)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment