Retrieve metadata when adding book to library. Show progress while scanning folders...
[dorian] / model / book.cpp
1 #include <QDir>
2 #include <QString>
3 #include <QDebug>
4 #include <QtXml>
5 #include <qtextdocument.h>  // Qt::escape is currently defined here...
6 #include <QDirIterator>
7 #include <QFileInfo>
8 #include <QtAlgorithms>
9 #include <QCryptographicHash>
10
11 #include "book.h"
12 #include "opshandler.h"
13 #include "xmlerrorhandler.h"
14 #include "extractzip.h"
15 #include "library.h"
16 #include "containerhandler.h"
17 #include "ncxhandler.h"
18 #include "trace.h"
19
20 const int COVER_WIDTH = 53;
21 const int COVER_HEIGHT = 59;
22
23 static QImage makeCover(const QString &path)
24 {
25     return QImage(path).scaled(COVER_WIDTH, COVER_HEIGHT,
26         Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation).
27         scaled(COVER_WIDTH, COVER_HEIGHT, Qt::KeepAspectRatio);
28 }
29
30 Book::Book(const QString &p, QObject *parent): QObject(parent)
31 {
32     mPath = "";
33     if (p.size()) {
34         QFileInfo info(p);
35         mPath = info.absoluteFilePath();
36         title = info.baseName();
37         cover = makeCover(":/icons/book.png");
38         mTempFile.open();
39     }
40 }
41
42 QString Book::path() const
43 {
44     return mPath;
45 }
46
47 bool Book::open()
48 {
49     Trace t("Book::open");
50     t.trace(path());
51     close();
52     clear();
53     if (path().isEmpty()) {
54         title = "No book";
55         return false;
56     }
57     if (!extract()) {
58         return false;
59     }
60     if (!parse()) {
61         return false;
62     }
63     save();
64     emit opened(path());
65     return true;
66 }
67
68 void Book::peek()
69 {
70     Trace t("Book::peek");
71     t.trace(path());
72     close();
73     clear();
74     if (path().isEmpty()) {
75         title = "No book";
76         return;
77     }
78     if (!extractMetaData()) {
79         return;
80     }
81     if (!parse()) {
82         return;
83     }
84     save();
85     close();
86 }
87
88 void Book::close()
89 {
90     Trace t("Book::close");
91     content.clear();
92     parts.clear();
93     QDir::setCurrent(QDir::rootPath());
94     clearDir(tmpDir());
95 }
96
97 QString Book::tmpDir() const
98 {
99     QString tmpName = QFileInfo(mTempFile.fileName()).fileName();
100     return QDir::tempPath() + "/dorian/" + tmpName;
101 }
102
103 bool Book::extract()
104 {
105     Trace t("Book::extract");
106     bool ret = false;
107     QString tmp = tmpDir();
108     t.trace("Extracting " + mPath + " to " + tmp);
109
110     QDir::setCurrent(QDir::rootPath());
111     if (!clearDir(tmp)) {
112         qCritical() << "Book::extract: Failed to remove" << tmp;
113         return false;
114     }
115     QDir d;
116     if (!d.mkpath(tmp)) {
117         qCritical() << "Book::extract: Could not create" << tmp;
118         return false;
119     }
120
121     // If book comes from resource, copy it to the temporary directory first
122     QString bookPath = path();
123     if (bookPath.startsWith(":/books/")) {
124         QFile src(bookPath);
125         QString dst(tmp + "/book.epub");
126         if (!src.copy(dst)) {
127             qCritical() << "Book::extract: Failed to copy built-in book to"
128                     << dst;
129             return false;
130         }
131         bookPath = dst;
132     }
133
134     QString oldDir = QDir::currentPath();
135     if (!QDir::setCurrent(tmp)) {
136         qCritical() << "Book::extract: Could not change to" << tmp;
137         return false;
138     }
139     ret = extractZip(bookPath);
140     if (!ret) {
141         qCritical() << "Book::extract: Extracting ZIP failed";
142     }
143     QDir::setCurrent(oldDir);
144     return ret;
145 }
146
147 bool Book::parse()
148 {
149     Trace t("Book::parse");
150
151     // Parse OPS file
152     bool ret = false;
153     QString opsFileName = opsPath();
154     t.trace("Parsing OPS file" + opsFileName);
155     QFile opsFile(opsFileName);
156     QXmlSimpleReader reader;
157     QXmlInputSource *source = new QXmlInputSource(&opsFile);
158     OpsHandler *opsHandler = new OpsHandler(*this);
159     XmlErrorHandler *errorHandler = new XmlErrorHandler();
160     reader.setContentHandler(opsHandler);
161     reader.setErrorHandler(errorHandler);
162     ret = reader.parse(source);
163     delete errorHandler;
164     delete opsHandler;
165     delete source;
166
167     // Initially, put all content items in the chapter list.
168     // This will be refined by parsing the NCX file later
169     chapters = parts;
170
171     // Load cover image
172     QStringList coverKeys;
173     coverKeys << "cover-image" << "img-cover-jpeg" << "cover";
174     foreach (QString key, coverKeys) {
175         if (content.contains(key)) {
176             t.trace("Loading cover image from " + content[key].href);
177             cover = makeCover(content[key].href);
178             break;
179         }
180     }
181
182     // If there is an "ncx" item in content, parse it: That's the real table of
183     // contents
184     if (content.contains("ncx")) {
185         QString ncxFileName = content["ncx"].href;
186         t.trace("Parsing NCX file " + ncxFileName);
187         QFile ncxFile(ncxFileName);
188         source = new QXmlInputSource(&ncxFile);
189         NcxHandler *ncxHandler = new NcxHandler(*this);
190         errorHandler = new XmlErrorHandler();
191         reader.setContentHandler(ncxHandler);
192         reader.setErrorHandler(errorHandler);
193         ret = reader.parse(source);
194         delete ncxHandler;
195         delete errorHandler;
196         delete source;
197     }
198
199     // Calculate book part sizes
200     size = 0;
201     foreach (QString part, parts) {
202         QFileInfo info(content[part].href);
203         content[part].size = info.size();
204         size += content[part].size;
205         t.trace(QString("Size of part %1: %2").arg(part).arg(content[part].size));
206     }
207
208     return ret;
209 }
210
211 bool Book::clearDir(const QString &dir)
212 {
213     QDir d(dir);
214     if (!d.exists()) {
215         return true;
216     }
217     QDirIterator i(dir, QDirIterator::Subdirectories);
218     while (i.hasNext()) {
219         QString entry = i.next();
220         if (entry.endsWith("/.") || entry.endsWith("/..")) {
221             continue;
222         }
223         QFileInfo info(entry);
224         if (info.isDir()) {
225             if (!clearDir(entry)) {
226                 return false;
227             }
228         }
229         else {
230             if (!QFile::remove(entry)) {
231                 qCritical() << "Book::clearDir: Could not remove" << entry;
232                 // FIXME: To be investigated: This is happening too often
233                 // return false;
234             }
235         }
236     }
237     (void)d.rmpath(dir);
238     return true;
239 }
240
241 void Book::clear()
242 {
243     close();
244     title = "";
245     creators.clear();
246     date = "";
247     publisher = "";
248     datePublished = "";
249     subject = "";
250     source = "";
251     rights = "";
252 }
253
254 void Book::load()
255 {
256     Trace t("Book::load");
257     t.trace("path: " + path());
258     QSettings settings;
259     QString key = "book/" + path() + "/";
260     t.trace("key: " + key);
261
262     // Load book info
263     title = settings.value(key + "title").toString();
264     t.trace(title);
265     creators = settings.value(key + "creators").toStringList();
266     date = settings.value(key + "date").toString();
267     publisher = settings.value(key + "publisher").toString();
268     datePublished = settings.value(key + "datepublished").toString();
269     subject = settings.value(key + "subject").toString();
270     source = settings.value(key + "source").toString();
271     rights = settings.value(key + "rights").toString();
272     mLastBookmark.part = settings.value(key + "lastpart").toInt();
273     mLastBookmark.pos = settings.value(key + "lastpos").toReal();
274     cover = settings.value(key + "cover").value<QImage>().scaled(COVER_WIDTH,
275         COVER_HEIGHT, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
276     if (cover.isNull()) {
277         cover = makeCover(":/icons/book.png");
278     }
279
280     // Load bookmarks
281     int size = settings.value(key + "bookmarks").toInt();
282     for (int i = 0; i < size; i++) {
283         int part = settings.value(key + "bookmark" + QString::number(i) +
284                                      "/part").toInt();
285         qreal pos = settings.value(key + "bookmark" + QString::number(i) +
286                                    "/pos").toReal();
287         t.trace(QString("Bookmark %1 at part %2, %3").
288                 arg(i).arg(part).arg(pos));
289         mBookmarks.append(Bookmark(part, pos));
290     }
291 }
292
293 void Book::save()
294 {
295     Trace t("Book::save");
296     QSettings settings;
297     QString key = "book/" + path() + "/";
298     t.trace("key: " + key);
299
300     // Save book info
301     settings.setValue(key + "title", title);
302     t.trace("title: " + title);
303     settings.setValue(key + "creators", creators);
304     settings.setValue(key + "date", date);
305     settings.setValue(key + "publisher", publisher);
306     settings.setValue(key + "datepublished", datePublished);
307     settings.setValue(key + "subject", subject);
308     settings.setValue(key + "source", source);
309     settings.setValue(key + "rights", rights);
310     settings.setValue(key + "lastpart", mLastBookmark.part);
311     settings.setValue(key + "lastpos", mLastBookmark.pos);
312     settings.setValue(key + "cover", cover);
313
314     // Save bookmarks
315     settings.setValue(key + "bookmarks", mBookmarks.size());
316     for (int i = 0; i < mBookmarks.size(); i++) {
317         t.trace(QString("Bookmark %1 at %2, %3").
318                 arg(i).arg(mBookmarks[i].part).arg(mBookmarks[i].pos));
319         settings.setValue(key + "bookmark" + QString::number(i) + "/part",
320                           mBookmarks[i].part);
321         settings.setValue(key + "bookmark" + QString::number(i) + "/pos",
322                           mBookmarks[i].pos);
323     }
324 }
325
326 void Book::setLastBookmark(int part, qreal position)
327 {
328     mLastBookmark.part = part;
329     mLastBookmark.pos = position;
330     save();
331 }
332
333 Book::Bookmark Book::lastBookmark() const
334 {
335     return Book::Bookmark(mLastBookmark);
336 }
337
338 void Book::addBookmark(int part, qreal position)
339 {
340     mBookmarks.append(Bookmark(part, position));
341     qSort(mBookmarks.begin(), mBookmarks.end());
342     save();
343 }
344
345 void Book::deleteBookmark(int index)
346 {
347     mBookmarks.removeAt(index);
348     save();
349 }
350
351 QList<Book::Bookmark> Book::bookmarks() const
352 {
353     return mBookmarks;
354 }
355
356 QString Book::opsPath()
357 {
358     Trace t("Book::opsPath");
359     QString ret;
360
361     QFile container(tmpDir() + "/META-INF/container.xml");
362     t.trace(container.fileName());
363     QXmlSimpleReader reader;
364     QXmlInputSource *source = new QXmlInputSource(&container);
365     ContainerHandler *containerHandler = new ContainerHandler();
366     XmlErrorHandler *errorHandler = new XmlErrorHandler();
367     reader.setContentHandler(containerHandler);
368     reader.setErrorHandler(errorHandler);
369     if (reader.parse(source)) {
370         ret = tmpDir() + "/" + containerHandler->rootFile;
371         mRootPath = QFileInfo(ret).absoluteDir().absolutePath();
372         t.trace("OSP path: " + ret);
373         t.trace("Root dir: " + mRootPath);
374     }
375     delete errorHandler;
376     delete containerHandler;
377     delete source;
378     return ret;
379 }
380
381 QString Book::rootPath() const
382 {
383     return mRootPath;
384 }
385
386 QString Book::name() const
387 {
388     if (title.size()) {
389         QString ret = title;
390         if (creators.length()) {
391             ret += "\nBy " + creators[0];
392             for (int i = 1; i < creators.length(); i++) {
393                 ret += ", " + creators[i];
394             }
395         }
396         return ret;
397     } else {
398         return path();
399     }
400 }
401
402 QString Book::shortName() const
403 {
404     return (title.isEmpty())? QFileInfo(path()).baseName(): title;
405 }
406
407 int Book::chapterFromPart(int index)
408 {
409     // FIXME
410     Q_UNUSED(index);
411     int ret = -1;
412     return ret;
413 }
414
415 int Book::partFromChapter(int index)
416 {
417     Trace t("Book::partFromChapter");
418     QString id = chapters[index];
419     QString href = content[id].href;
420     QString baseRef(href);
421     QUrl url(QString("file://") + href);
422     if (url.hasFragment()) {
423         QString fragment = url.fragment();
424         baseRef.chop(fragment.length() + 1);
425     }
426
427     // Swipe through all content items to find the one matching the chapter href
428     // FIXME: Do we need to index content items by href, too?
429     QString contentKey;
430     bool found = false;
431     foreach (contentKey, content.keys()) {
432         if (contentKey == id) {
433             continue;
434         }
435         if (content[contentKey].href == baseRef) {
436             found = true;
437             t.trace(QString("Key for %1 is %2").arg(baseRef).arg(contentKey));
438             break;
439         }
440     }
441     if (!found) {
442         t.trace("Could not find key for " + baseRef);
443         return -1;
444     }
445     int partIndex = parts.indexOf(contentKey);
446     if (partIndex == -1) {
447         qCritical()
448             << "Book::partFromChapter: Could not find part index of chapter"
449             << id;
450     }
451     return partIndex;
452 }
453
454 qreal Book::getProgress(int part, qreal position)
455 {
456     Q_ASSERT(part < parts.size());
457     QString key;
458     qreal partSize = 0;
459     for (int i = 0; i < part; i++) {
460         key = parts[i];
461         partSize += content[key].size;
462     }
463     key = parts[part];
464     partSize += content[key].size * position;
465     return partSize / (qreal)size;
466 }
467
468 bool Book::extractMetaData()
469 {
470     // FIXME
471     return extract();
472 }