File: epub_packer.rb

package info (click to toggle)
rails 2%3A7.2.2.1%2Bdfsg-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 43,352 kB
  • sloc: ruby: 349,799; javascript: 30,703; yacc: 46; sql: 43; sh: 29; makefile: 27
file content (59 lines) | stat: -rw-r--r-- 1,520 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/env ruby
# frozen_string_literal: true

require "nokogiri"
require "fileutils"
require "yaml"
require "date"
require "zip"

module EpubPacker # :nodoc:
  extend self

  def pack(output_dir, epub_file_name)
    @output_dir = output_dir

    FileUtils.rm_f(epub_file_name)

    Zip::OutputStream.open(epub_file_name) {
      |epub|
      create_epub(epub, epub_file_name)
    }

    entries = Dir.entries(output_dir) - %w[. ..]

    entries.reject! { |item| File.extname(item) == ".epub" }

    Zip::File.open(epub_file_name, create: true) do |epub|
      write_entries(entries, "", epub)
    end
  end

  def create_epub(epub, epub_file_name)
    epub.put_next_entry("mimetype", nil, nil, Zip::Entry::STORED, Zlib::NO_COMPRESSION)
    epub.write "application/epub+zip"
  end

  def write_entries(entries, path, zipfile)
    entries.each do |e|
      zipfile_path = path == "" ? e : File.join(path, e)
      disk_file_path = File.join(@output_dir, zipfile_path)

      if File.directory? disk_file_path
        recursively_deflate_directory(disk_file_path, zipfile, zipfile_path)
      else
        put_into_archive(disk_file_path, zipfile, zipfile_path)
      end
    end
  end

  def recursively_deflate_directory(disk_file_path, zipfile, zipfile_path)
    zipfile.mkdir zipfile_path
    subdir = Dir.entries(disk_file_path) - %w[. ..]
    write_entries subdir, zipfile_path, zipfile
  end

  def put_into_archive(disk_file_path, zipfile, zipfile_path)
    zipfile.add(zipfile_path, disk_file_path)
  end
end