Improve traces. Simplify folder management.
[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     qDebug() << 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     qDebug() << 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     qDebug() << "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     qDebug() << "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             qDebug() << "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         qDebug() << "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     }
206
207     return ret;
208 }
209
210 bool Book::clearDir(const QString &dir)
211 {
212     QDir d(dir);
213     if (!d.exists()) {
214         return true;
215     }
216     QDirIterator i(dir, QDirIterator::Subdirectories);
217     while (i.hasNext()) {
218         QString entry = i.next();
219         if (entry.endsWith("/.") || entry.endsWith("/..")) {
220             continue;
221         }
222         QFileInfo info(entry);
223         if (info.isDir()) {
224             if (!clearDir(entry)) {
225                 return false;
226             }
227         }
228         else {
229             if (!QFile::remove(entry)) {
230                 qCritical() << "Book::clearDir: Could not remove" << entry;
231                 // FIXME: To be investigated: This is happening too often
232                 // return false;
233             }
234         }
235     }
236     (void)d.rmpath(dir);
237     return true;
238 }
239
240 void Book::clear()
241 {
242     close();
243     title = "";
244     creators.clear();
245     date = "";
246     publisher = "";
247     datePublished = "";
248     subject = "";
249     source = "";
250     rights = "";
251 }
252
253 void Book::load()
254 {
255     Trace t("Book::load");
256     qDebug() << "path" << path();
257     QSettings settings;
258     QString key = "book/" + path() + "/";
259     qDebug() << "key" << key;
260
261     // Load book info
262     title = settings.value(key + "title").toString();
263     qDebug() << title;
264     creators = settings.value(key + "creators").toStringList();
265     date = settings.value(key + "date").toString();
266     publisher = settings.value(key + "publisher").toString();
267     datePublished = settings.value(key + "datepublished").toString();
268     subject = settings.value(key + "subject").toString();
269     source = settings.value(key + "source").toString();
270     rights = settings.value(key + "rights").toString();
271     mLastBookmark.part = settings.value(key + "lastpart").toInt();
272     mLastBookmark.pos = settings.value(key + "lastpos").toReal();
273     cover = settings.value(key + "cover").value<QImage>().scaled(COVER_WIDTH,
274         COVER_HEIGHT, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
275     if (cover.isNull()) {
276         cover = makeCover(":/icons/book.png");
277     }
278
279     // Load bookmarks
280     int size = settings.value(key + "bookmarks").toInt();
281     for (int i = 0; i < size; i++) {
282         int part = settings.value(key + "bookmark" + QString::number(i) +
283                                      "/part").toInt();
284         qreal pos = settings.value(key + "bookmark" + QString::number(i) +
285                                    "/pos").toReal();
286         qDebug() << QString("Bookmark %1 at part %2, %3").
287                 arg(i).arg(part).arg(pos);
288         mBookmarks.append(Bookmark(part, pos));
289     }
290 }
291
292 void Book::save()
293 {
294     Trace t("Book::save");
295     QSettings settings;
296     QString key = "book/" + path() + "/";
297     qDebug() << "key" << key;
298
299     // Save book info
300     settings.setValue(key + "title", title);
301     qDebug() << "title" << title;
302     settings.setValue(key + "creators", creators);
303     settings.setValue(key + "date", date);
304     settings.setValue(key + "publisher", publisher);
305     settings.setValue(key + "datepublished", datePublished);
306     settings.setValue(key + "subject", subject);
307     settings.setValue(key + "source", source);
308     settings.setValue(key + "rights", rights);
309     settings.setValue(key + "lastpart", mLastBookmark.part);
310     settings.setValue(key + "lastpos", mLastBookmark.pos);
311     settings.setValue(key + "cover", cover);
312
313     // Save bookmarks
314     settings.setValue(key + "bookmarks", mBookmarks.size());
315     for (int i = 0; i < mBookmarks.size(); i++) {
316         qDebug() << QString("Bookmark %1 at %2, %3").
317                 arg(i).arg(mBookmarks[i].part).arg(mBookmarks[i].pos);
318         settings.setValue(key + "bookmark" + QString::number(i) + "/part",
319                           mBookmarks[i].part);
320         settings.setValue(key + "bookmark" + QString::number(i) + "/pos",
321                           mBookmarks[i].pos);
322     }
323 }
324
325 void Book::setLastBookmark(int part, qreal position)
326 {
327     mLastBookmark.part = part;
328     mLastBookmark.pos = position;
329     save();
330 }
331
332 Book::Bookmark Book::lastBookmark() const
333 {
334     return Book::Bookmark(mLastBookmark);
335 }
336
337 void Book::addBookmark(int part, qreal position)
338 {
339     mBookmarks.append(Bookmark(part, position));
340     qSort(mBookmarks.begin(), mBookmarks.end());
341     save();
342 }
343
344 void Book::deleteBookmark(int index)
345 {
346     mBookmarks.removeAt(index);
347     save();
348 }
349
350 QList<Book::Bookmark> Book::bookmarks() const
351 {
352     return mBookmarks;
353 }
354
355 QString Book::opsPath()
356 {
357     Trace t("Book::opsPath");
358     QString ret;
359
360     QFile container(tmpDir() + "/META-INF/container.xml");
361     qDebug() << container.fileName();
362     QXmlSimpleReader reader;
363     QXmlInputSource *source = new QXmlInputSource(&container);
364     ContainerHandler *containerHandler = new ContainerHandler();
365     XmlErrorHandler *errorHandler = new XmlErrorHandler();
366     reader.setContentHandler(containerHandler);
367     reader.setErrorHandler(errorHandler);
368     if (reader.parse(source)) {
369         ret = tmpDir() + "/" + containerHandler->rootFile;
370         mRootPath = QFileInfo(ret).absoluteDir().absolutePath();
371         qDebug() << "OSP path" << ret << "\nRoot dir" << mRootPath;
372     }
373     delete errorHandler;
374     delete containerHandler;
375     delete source;
376     return ret;
377 }
378
379 QString Book::rootPath() const
380 {
381     return mRootPath;
382 }
383
384 QString Book::name() const
385 {
386     if (title.size()) {
387         QString ret = title;
388         if (creators.length()) {
389             ret += "\nBy " + creators[0];
390             for (int i = 1; i < creators.length(); i++) {
391                 ret += ", " + creators[i];
392             }
393         }
394         return ret;
395     } else {
396         return path();
397     }
398 }
399
400 QString Book::shortName() const
401 {
402     return (title.isEmpty())? QFileInfo(path()).baseName(): title;
403 }
404
405 int Book::chapterFromPart(int index)
406 {
407     int ret = -1;
408
409     QString partId = parts[index];
410     QString partHref = content[partId].href;
411
412     for (int i = 0; i < chapters.size(); i++) {
413         QString id = chapters[i];
414         QString href = content[id].href;
415         QString baseRef(href);
416         QUrl url(QString("file://") + href);
417         if (url.hasFragment()) {
418             QString fragment = url.fragment();
419             baseRef.chop(fragment.length() + 1);
420         }
421         if (baseRef == partHref) {
422             ret = i;
423             // Don't break, keep looking
424         }
425     }
426
427     return ret;
428 }
429
430 int Book::partFromChapter(int index)
431 {
432     Trace t("Book::partFromChapter");
433     QString id = chapters[index];
434     QString href = content[id].href;
435     QString baseRef(href);
436     QUrl url(QString("file://") + href);
437     if (url.hasFragment()) {
438         QString fragment = url.fragment();
439         baseRef.chop(fragment.length() + 1);
440     }
441
442     // Swipe through all content items to find the one matching the chapter href
443     // FIXME: Do we need to index content items by href, too?
444     QString contentKey;
445     bool found = false;
446     foreach (contentKey, content.keys()) {
447         if (contentKey == id) {
448             continue;
449         }
450         if (content[contentKey].href == baseRef) {
451             found = true;
452             qDebug() << QString("Key for %1 is %2").arg(baseRef).arg(contentKey);
453             break;
454         }
455     }
456     if (!found) {
457         qDebug() << "Could not find key for" << baseRef;
458         return -1;
459     }
460     int partIndex = parts.indexOf(contentKey);
461     if (partIndex == -1) {
462         qCritical()
463             << "Book::partFromChapter: Could not find part index of chapter"
464             << id;
465     }
466     return partIndex;
467 }
468
469 qreal Book::getProgress(int part, qreal position)
470 {
471     Q_ASSERT(part < parts.size());
472     QString key;
473     qreal partSize = 0;
474     for (int i = 0; i < part; i++) {
475         key = parts[i];
476         partSize += content[key].size;
477     }
478     key = parts[part];
479     partSize += content[key].size * position;
480     return partSize / (qreal)size;
481 }
482
483 bool Book::extractMetaData()
484 {
485     // FIXME
486     return extract();
487 }