Class: ReVIEW::EPUBMaker::EPUBCommon

Inherits:
Object
  • Object
show all
Defined in:
lib/review/epubmaker/epubcommon.rb

Overview

EPUBCommon is the common class for EPUB producer. Some methods of this class are overridden by subclasses

Direct Known Subclasses

EPUBv2, EPUBv3

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(producer) ⇒ EPUBCommon

Construct object with parameter hash config and message resource hash res.



25
26
27
28
29
30
# File 'lib/review/epubmaker/epubcommon.rb', line 25

def initialize(producer)
  @config = producer.config
  @contents = producer.contents
  @body_ext = nil
  @logger = ReVIEW.logger
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



32
33
34
# File 'lib/review/epubmaker/epubcommon.rb', line 32

def config
  @config
end

#contentsObject (readonly)

Returns the value of attribute contents.



33
34
35
# File 'lib/review/epubmaker/epubcommon.rb', line 33

def contents
  @contents
end

Instance Method Details

#call_hook(filename, *params) ⇒ Object



349
350
351
352
353
354
355
356
357
# File 'lib/review/epubmaker/epubcommon.rb', line 349

def call_hook(filename, *params)
  return if !filename.present? || !File.exist?(filename) || !FileTest.executable?(filename)

  if ENV['REVIEW_SAFE_MODE'].to_i & 1 > 0
    warn 'hook is prohibited in safe mode. ignored.'
  else
    system(filename, *params)
  end
end

#colophonObject

Return colophon content.



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/review/epubmaker/epubcommon.rb', line 154

def colophon
  @title = h(ReVIEW::I18n.t('colophontitle'))
  @isbn_hyphen = isbn_hyphen

  @body = ReVIEW::Template.generate(path: './html/_colophon.html.erb', binding: binding)

  @language = config['language']
  @stylesheets = config['stylesheet']
  template_path = if config['htmlversion'].to_i == 5
                    './html/layout-html5.html.erb'
                  else
                    './html/layout-xhtml1.html.erb'
                  end
  ReVIEW::Template.generate(path: template_path, binding: binding)
end

#colophon_historyObject



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/review/epubmaker/epubcommon.rb', line 180

def colophon_history
  @col_history = []
  if config['history']
    config['history'].each_with_index do |items, edit|
      items.each_with_index do |item, rev|
        editstr = edit == 0 ? ReVIEW::I18n.t('first_edition') : ReVIEW::I18n.t('nth_edition', (edit + 1).to_s)
        revstr = ReVIEW::I18n.t('nth_impression', (rev + 1).to_s)
        if item =~ /\A\d+-\d+-\d+\Z/
          @col_history << ReVIEW::I18n.t('published_by1', [date_to_s(item), editstr + revstr])
        elsif item =~ /\A(\d+-\d+-\d+)[\s ](.+)/
          # custom date with string
          item.match(/\A(\d+-\d+-\d+)[\s ](.+)/) do |m|
            @col_history << ReVIEW::I18n.t('published_by3', [date_to_s(m[1]), m[2]])
          end
        else
          # free format
          @col_history << item
        end
      end
    end
  end

  ReVIEW::Template.generate(path: './html/_colophon_history.html.erb', binding: binding)
end

#containerObject

Return container content.



87
88
89
90
# File 'lib/review/epubmaker/epubcommon.rb', line 87

def container
  @opf_path = opf_path
  ReVIEW::Template.generate(path: './xml/container.xml.erb', binding: binding)
end

#coverObject

Return cover content. If Producer#config is defined, it will be used for the cover image.



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/review/epubmaker/epubcommon.rb', line 105

def cover
  @body_ext = config['epubversion'] >= 3 ? %Q( epub:type="cover") : ''

  if config['coverimage']
    @coverimage_src = coverimage
    raise ApplicationError, "coverimage #{config['coverimage']} not found. Abort." unless @coverimage_src
  end
  @body = ReVIEW::Template.generate(path: './html/_cover.html.erb', binding: binding)

  @title = h(config.name_of('title'))
  @language = config['language']
  @stylesheets = config['stylesheet']
  template_path = if config['htmlversion'].to_i == 5
                    './html/layout-html5.html.erb'
                  else
                    './html/layout-xhtml1.html.erb'
                  end
  ReVIEW::Template.generate(path: template_path, binding: binding)
end

#coverimageObject



92
93
94
95
96
97
98
99
100
# File 'lib/review/epubmaker/epubcommon.rb', line 92

def coverimage
  return nil unless config['coverimage']

  item = contents.find { |content| content.coverimage?(config['coverimage']) }

  if item
    item.file
  end
end

#date_to_s(date) ⇒ Object



205
206
207
208
209
# File 'lib/review/epubmaker/epubcommon.rb', line 205

def date_to_s(date)
  require 'date'
  d = Date.parse(date)
  d.strftime(ReVIEW::I18n.t('date_format'))
end

#flat_ncx(type, indent = nil) ⇒ Object



303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/review/epubmaker/epubcommon.rb', line 303

def flat_ncx(type, indent = nil)
  s = %Q(<#{type} class="toc-h1">\n)
  contents.each do |item|
    next if !item.notoc.nil? || item.level.nil? || item.file.nil? || item.title.nil? || item.level > config['toclevel'].to_i

    is = indent == true ? ' ' * item.level : ''
    s << %Q(<li><a href="#{item.file}">#{is}#{h(item.title)}</a></li>\n)
  end
  s << %Q(</#{type}>\n)

  s
end

#h(str) ⇒ Object



35
36
37
# File 'lib/review/epubmaker/epubcommon.rb', line 35

def h(str)
  CGI.escapeHTML(str)
end

#hierarchy_ncx(type) ⇒ Object



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'lib/review/epubmaker/epubcommon.rb', line 232

def hierarchy_ncx(type)
  require 'rexml/document'
  level = 1
  find_jump = nil
  has_part = nil
  toclevel = config['toclevel'].to_i

  # check part existance
  contents.each do |item|
    next if item.notoc || item.chaptype != 'part'

    has_part = true
    break
  end

  if has_part
    contents.each do |item|
      if item.chaptype == 'part' && item.level > 0
        # sections in part
        item.level -= 1
      end
      # down level for part and chaps. pre, appendix, post are preserved
      if item.chaptype == 'part' || item.chaptype == 'body'
        item.level += 1
      end
    end
    toclevel += 1
  end

  doc = REXML::Document.new(%Q(<#{type} class="toc-h#{level}"><li /></#{type}>))
  doc.context[:attribute_quote] = :quote

  e = doc.root.elements[1] # first <li/>
  contents.each do |item|
    next if !item.notoc.nil? || item.level.nil? || item.file.nil? || item.title.nil? || item.level > toclevel

    if item.level == level
      e2 = e.parent.add_element('li')
      e = e2
    elsif item.level > level
      find_jump = true if (item.level - level) > 1
      # deeper
      (level + 1).upto(item.level) do |n|
        if e.size == 0
          # empty span for epubcheck
          e.attributes['style'] = 'list-style-type: none;'
          es = e.add_element('span', 'style' => 'display:none;')
          es.add_text(REXML::Text.new('&#xa0;', false, nil, true))
        end

        e2 = e.add_element(type, 'class' => "toc-h#{n}")
        e3 = e2.add_element('li')
        e = e3
      end
      level = item.level
    elsif item.level < level
      # shallower
      (level - 1).downto(item.level) { e = e.parent.parent }
      e2 = e.parent.add_element('li')
      e = e2
      level = item.level
    end
    e2 = e.add_element('a', 'href' => item.file)
    e2.add_text(REXML::Text.new(item.title, true))
  end

  warn %Q(found level jumping in table of contents. consider to use 'epubmaker:flattoc: true' for strict ePUB validator.) unless find_jump.nil?

  doc.to_s.gsub('<li/>', '').gsub('</li>', "</li>\n").gsub("<#{type} ", "\n" + '\&') # ugly
end

#isbn_hyphenObject



170
171
172
173
174
175
176
177
178
# File 'lib/review/epubmaker/epubcommon.rb', line 170

def isbn_hyphen
  str = config['isbn'].to_s

  if str =~ /\A\d{10}\Z/
    "#{str[0..0]}-#{str[1..5]}-#{str[6..8]}-#{str[9..9]}"
  elsif str =~ /\A\d{13}\Z/
    "#{str[0..2]}-#{str[3..3]}-#{str[4..8]}-#{str[9..11]}-#{str[12..12]}"
  end
end

#join_with_separator(value, sep) ⇒ Object



363
364
365
366
367
368
369
# File 'lib/review/epubmaker/epubcommon.rb', line 363

def join_with_separator(value, sep)
  if value.is_a?(Array)
    value.join(sep)
  else
    value
  end
end

#legacy_cover_and_title_file(loadfile, writefile) ⇒ Object



359
360
361
# File 'lib/review/epubmaker/epubcommon.rb', line 359

def legacy_cover_and_title_file(loadfile, writefile)
  FileUtils.cp(loadfile, writefile)
end

#mimetypeObject

Return mimetype content.



44
45
46
# File 'lib/review/epubmaker/epubcommon.rb', line 44

def mimetype
  'application/epub+zip'
end

#mytocObject

Return own toc content.



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/review/epubmaker/epubcommon.rb', line 212

def mytoc
  @title = h(ReVIEW::I18n.t('toctitle'))

  @body = %Q(  <h1 class="toc-title">#{h(ReVIEW::I18n.t('toctitle'))}</h1>\n)
  if config['epubmaker']['flattoc'].nil?
    @body << hierarchy_ncx('ul')
  else
    @body << flat_ncx('ul', config['epubmaker']['flattocindent'])
  end

  @language = config['language']
  @stylesheets = config['stylesheet']
  template_path = if config['htmlversion'].to_i == 5
                    './html/layout-html5.html.erb'
                  else
                    './html/layout-xhtml1.html.erb'
                  end
  ReVIEW::Template.generate(path: template_path, binding: binding)
end

#ncx(indentarray) ⇒ Object

Raises:

  • (NotImplementedError)


82
83
84
# File 'lib/review/epubmaker/epubcommon.rb', line 82

def ncx(indentarray)
  raise NotImplementedError # should be overridden
end

#opfObject

Raises:

  • (NotImplementedError)


48
49
50
# File 'lib/review/epubmaker/epubcommon.rb', line 48

def opf
  raise NotImplementedError # should be overridden
end

#opf_coverimageObject



68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/review/epubmaker/epubcommon.rb', line 68

def opf_coverimage
  if config['coverimage']
    item = contents.find { |content| content.coverimage?(config['coverimage']) }

    unless item
      raise ApplicationError, "coverimage #{config['coverimage']} not found. Abort."
    end

    %Q(    <meta name="cover" content="#{item.id}"/>\n)
  else
    ''
  end
end

#opf_manifestObject

Raises:

  • (NotImplementedError)


52
53
54
# File 'lib/review/epubmaker/epubcommon.rb', line 52

def opf_manifest
  raise NotImplementedError # should be overridden
end

#opf_metainfoObject

Raises:

  • (NotImplementedError)


56
57
58
# File 'lib/review/epubmaker/epubcommon.rb', line 56

def opf_metainfo
  raise NotImplementedError # should be overridden
end

#opf_pathObject



64
65
66
# File 'lib/review/epubmaker/epubcommon.rb', line 64

def opf_path
  "OEBPS/#{config['bookname']}.opf"
end

#opf_tocxObject

Raises:

  • (NotImplementedError)


60
61
62
# File 'lib/review/epubmaker/epubcommon.rb', line 60

def opf_tocx
  raise NotImplementedError # should be overridden
end

#produce(epubfile, basedir, tmpdir) ⇒ Object

Raises:

  • (NotImplementedError)


39
40
41
# File 'lib/review/epubmaker/epubcommon.rb', line 39

def produce(epubfile, basedir, tmpdir)
  raise NotImplementedError # should be overridden
end

#produce_write_common(basedir, tmpdir) ⇒ Object



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/review/epubmaker/epubcommon.rb', line 316

def produce_write_common(basedir, tmpdir)
  File.write("#{tmpdir}/mimetype", mimetype)

  FileUtils.mkdir_p("#{tmpdir}/META-INF")
  File.write("#{tmpdir}/META-INF/container.xml", container)

  FileUtils.mkdir_p("#{tmpdir}/OEBPS")
  File.write(File.join(tmpdir, opf_path), opf)

  if File.exist?("#{basedir}/#{config['cover']}")
    FileUtils.cp("#{basedir}/#{config['cover']}", "#{tmpdir}/OEBPS")
  else
    File.write("#{tmpdir}/OEBPS/#{config['cover']}", cover)
  end

  if config['colophon'] && !config['colophon'].is_a?(String)
    filename = File.join(basedir, "colophon.#{config['htmlext']}")
    File.write(filename, colophon)
  end

  contents.each do |item|
    next if item.file =~ /#/ # skip subgroup

    fname = "#{basedir}/#{item.file}"
    unless File.exist?(fname)
      raise ApplicationError, "#{fname} is not found."
    end

    FileUtils.mkdir_p(File.dirname("#{tmpdir}/OEBPS/#{item.file}"))
    FileUtils.cp(fname, "#{tmpdir}/OEBPS/#{item.file}")
  end
end

#titlepageObject

Return title (copying) content. NOTE: this method is not used yet.

see lib/review/epubmaker.rb#build_titlepage


128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/review/epubmaker/epubcommon.rb', line 128

def titlepage
  @title = h(config.name_of('title'))

  @title_str = config.name_of('title')
  if config['subtitle']
    @subtitle_str = config.name_of('subtitle')
  end
  if config['aut']
    @author_str = join_with_separator(config.names_of('aut'), ReVIEW::I18n.t('names_splitter'))
  end
  if config.names_of('pbl')
    @publisher_str = join_with_separator(config.names_of('pbl'), ReVIEW::I18n.t('names_splitter'))
  end
  @body = ReVIEW::Template.generate(path: './html/_titlepage.html.erb', binding: binding)

  @language = config['language']
  @stylesheets = config['stylesheet']
  template_path = if config['htmlversion'].to_i == 5
                    './html/layout-html5.html.erb'
                  else
                    './html/layout-xhtml1.html.erb'
                  end
  ReVIEW::Template.generate(path: template_path, binding: binding)
end