Improve HTML formatting. Handle more variants of EPUB.
[quanlib.git] / book.rb
1
2 require 'nokogiri'
3 require 'zip'
4
5 require 'author'
6 require 'cover'
7
8 class Book
9   def initialize(fileName)
10     @author = nil
11     @cover = nil
12     @path = fileName
13     @series = nil
14     @title = nil
15     @volume = nil
16
17     parseFileName!(fileName)
18   end
19
20   def self.canHandle?(fileName)
21     if nil == fileName
22       return false
23     end
24
25     #puts "Filename:  " + fileName.to_s
26     lowerName = fileName.downcase()
27
28     if lowerName.end_with?(".epub")
29       return true
30     end
31
32     return false
33   end
34
35   def cover
36     return @cover
37   end
38
39   def describe
40     result = []
41
42     if nil != @title
43       result.push('<b>' + @title + '</b>')
44     else
45       result.push('<i>(Unknown title)</i>')
46     end
47     if nil != @author
48       result.push(@author.to_s())
49     end
50     
51     seriesInfo = []
52     if nil != @series
53       seriesInfo.push(@series.to_s)
54     end
55     if nil != @volume
56       seriesInfo.push(@volume.to_s)
57     end
58     if seriesInfo.length > 0
59       result.push(seriesInfo.join(' '))
60     end
61
62     return result.join('<br/>')
63   end
64
65   def inspect
66     data = []
67     if nil != @author
68       data.push('author="' + @author.to_s + '"')
69     end
70     if nil != @series
71       data.push('series="' + @series + '"')
72     end
73     if nil != @volume
74       data.push('volume="' + @volume + '"')
75     end
76     if nil != @title
77       data.push('title="' + @title + '"')
78     end
79     if nil != @cover
80       data.push(@cover.inspect())
81     end
82     if nil != @path
83       data.push('path="' + @path + '"')
84     end
85     return '(Book:' + data.join(',') + ')'
86   end
87
88   def path
89     @path
90   end
91
92   def to_s
93     return inspect()
94   end
95
96   protected
97   def isUpper?(c)
98     return /[[:upper:]]/.match(c)
99   end
100
101   protected
102   def massageAuthor(input)
103     if nil == input
104       return nil
105     end
106
107     result = ""
108     input.each_char do |c|
109       if isUpper?(c) and (result.length > 0)
110         result += " "
111       end
112       result += c
113     end
114     
115     return result
116   end
117
118   # Returns (series, volumeNo, titleText)
119   protected
120   def processTitle(input)
121     if nil == input
122       return nil
123     end
124
125     arr = input.split('_')
126
127     series = nil
128     vol = nil
129
130     first = arr[0]
131     matchData = (arr[0]).match(/^([A-Z]+)([0-9]+)$/)
132     if nil != matchData
133       capt = matchData.captures
134       series = capt[0]
135       vol = capt[1]
136       arr.shift
137     end
138
139     pos = arr[-1].rindex('.')
140     if nil != pos
141       arr[-1] = arr[-1].slice(0, pos)
142     end
143
144     title = arr.join(' ')
145
146     return series, vol, title
147   end
148
149   protected
150   def parseFileName!(fileName)
151     parts = fileName.split('/')
152     (@series, @volume, @title) = processTitle(parts[-1])
153     if parts.length > 1
154       @author = massageAuthor(parts[-2])
155     end
156
157     if fileName.downcase.end_with?(".epub")
158       scanEpub!(fileName)
159     end
160   end
161
162   protected 
163   def scanEpub!(fileName)
164     #puts 'Scanning "' + fileName.to_s + '"...'
165     begin
166       Zip::File.open(fileName) do |zipfile|
167         entry = zipfile.find_entry('META-INF/container.xml')
168         if nil == entry
169           return
170         end
171         contXml = zipfile.read('META-INF/container.xml')
172         contDoc = Nokogiri::XML(contXml)
173         opfPath = contDoc.css("container rootfiles rootfile")[0]['full-path']
174
175         scanOpf!(zipfile, opfPath)
176       end
177     rescue Zip::Error => exc
178       puts 'ERROR processing file "' + fileName + '":'
179       puts exc.message
180       puts exc.backtrace
181     end
182   end
183
184   protected
185   def scanOpf!(zipfile, opfPath)
186     coverId = nil
187
188     opfXml = zipfile.read(opfPath)
189     opfDoc = Nokogiri::XML(opfXml)
190
191     #-------
192     # Author
193
194     creator = opfDoc.css('dc|creator', 'dc' => 'http://purl.org/dc/elements/1.1/')
195     if (nil != creator) and (creator.length > 0)
196       roleNode = creator.attr('role')
197       if nil != roleNode
198         role = roleNode.value
199         if ('aut' == role) and (creator.children.length > 0) and (nil != creator.children[0])
200           name = creator.children[0].content
201           parts = name.split(' ')
202           if parts.length > 1
203             surname = parts[-1]
204             givenNames = parts[0..-2].join(' ')
205             @author = Author.new(surname, givenNames)
206           else
207             @author = Author.new(name, '')
208           end
209         end
210       end
211     end
212
213     #---------------------------------------
214     # Other metadata:  series, volume, cover
215
216     metas = opfDoc.css('package metadata meta')
217     for m in metas
218       name = m['name']
219       content = m['content']
220
221       if 'calibre:series' == name
222         @series = content
223       elsif 'calibre:series-index' == name
224         @volume = content
225       elsif 'cover' == name
226         coverId = content
227       end
228     end
229
230     #---------------
231     # Load the cover
232
233     @cover = loadCover(zipfile, opfPath, opfDoc, coverId)
234   end
235
236   protected
237   def loadCover(zipfile, opfPath, opfDoc, coverId)
238     coverFile = nil
239     if nil == coverId
240       coverId = "cover-image"
241     end
242
243     items = opfDoc.css('package manifest item')
244     for i in items
245       href = i['href']
246       id = i['id']
247       mimeType = i['media-type']
248
249       if coverId == id
250         entry = zipfile.find_entry(href)
251
252         if nil == entry
253           # Although the epub standard requires the path to be relative 
254           # to the base of the epub (zip), some books encountered in the
255           # wild have been found to use a bath relative to the location 
256           # of the opf file.
257           parts = opfPath.split('/')
258           opfBasePath = opfPath.split('/')[0..-2].join('/')
259           coverPath = opfBasePath + '/' + href
260           entry = zipfile.find_entry(coverPath)
261         end
262
263         if nil == entry
264           puts 'WARNING!  Cover image "' + href + '" not found in file "' + @path + '".'
265           return nil
266         else
267           entry.get_input_stream() do |is|
268             return Cover.new(is, href, mimeType)
269           end
270         end
271       end
272     end
273     return nil
274   end
275 end
276