1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | var Writable = require('stream').Writable;
|
8 | var EpubHelpers = require('../epub/helpers');
|
9 | var utils = require('util');
|
10 | var path = require('path');
|
11 | var stripTags = require('striptags');
|
12 | var js2xml = require('js2xmlparser');
|
13 | var fs = require('fs-extra');
|
14 | var pretty = require('pretty-data').pd;
|
15 |
|
16 | function Editor(options) {
|
17 | if (!(this instanceof Editor)) {
|
18 | return new Editor(options);
|
19 | }
|
20 |
|
21 | this.options = options || {};
|
22 | this._$$count = 0;
|
23 | this._$$Spines = {total: 0, '_struct': {spine: []}};
|
24 | this.opf = {
|
25 | root: '',
|
26 | path: ''
|
27 | };
|
28 |
|
29 | Writable.call(this, options);
|
30 | }
|
31 |
|
32 | utils.inherits(Editor, Writable);
|
33 |
|
34 | var proto = Editor.prototype;
|
35 |
|
36 | proto._write = function(chunk, enc, next) {
|
37 | var data = JSON.parse(chunk.toString()), epub = EpubHelpers(), self = this;
|
38 |
|
39 | if (data.spineLength) {self._$$Spines.total = data.spineLength;}
|
40 |
|
41 | if (data.type === 'EPUB#spine') {
|
42 | self._$$Spines._struct.spine.push({
|
43 | '@': {
|
44 | id: data.idref,
|
45 | href: data.href
|
46 | },
|
47 | "#": stripTags(data.file)
|
48 | });
|
49 |
|
50 | }
|
51 |
|
52 | if (self._$$count === self._$$Spines.total - 1) {
|
53 | fs.outputFile(path.resolve(data.base, 'META-INF/search.xml'),
|
54 | pretty.xml(js2xml('search', self._$$Spines._struct)),
|
55 | function(err) {
|
56 | if (err) {
|
57 | return self._destroy(err);
|
58 | }
|
59 | });
|
60 |
|
61 | self._autoDrain();
|
62 | } else if (data.type === 'EPUB#spine') {
|
63 | self._$$count++;
|
64 | }
|
65 |
|
66 | next();
|
67 | };
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 | proto._autoDrain = function() {
|
76 | var self = this;
|
77 | self._$$Spines = {total: 0, '_struct': {spine: []}};
|
78 | self._$$count = 0;
|
79 | };
|
80 |
|
81 | proto._destroy = function(err) {
|
82 |
|
83 | this.writeable = false;
|
84 | this._$$destroyed = true;
|
85 | this.emit('close', err);
|
86 | };
|
87 |
|
88 | module.exports = Editor;
|