-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathparseEpub.ts
302 lines (258 loc) · 8.45 KB
/
parseEpub.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
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
302
import fs from 'node:fs'
import { Buffer } from 'node:buffer'
import _ from 'lodash'
import type { ParserOptions, GeneralObject } from './types'
// @ts-ignore
import nodeZip from 'node-zip'
import parseLink from './parseLink'
import parseSection, { Section } from './parseSection'
import { xmlToJs, determineRoot } from './utils'
type MetaInfo = Partial<{
title: string,
author: string | string[],
description: string,
language: string,
publisher: string,
rights: string,
}>
const parseMetadata = (metadata: GeneralObject[]): MetaInfo => {
const meta = metadata[0];
const info: MetaInfo = {};
(['title', 'author', 'description', 'language', 'publisher', 'rights'] as (keyof MetaInfo)[]).forEach((item: keyof MetaInfo) => {
if (item === 'author') {
info.author = _.get(meta, ['dc:creator', 0])
if (_.isString(info.author)) {
info.author = [info.author] as string[]
} else {
info.author = [_.get(info.author!, ['_'])]
}
}
else if (item === 'description') {
info.description = _.get(meta, ['description', 0, '_'])
}
else {
info[item] = _.get(meta, ['dc:' + item, 0]) as string
}
})
return _.pickBy(info, (v: string | string[]) => {
if (Array.isArray(v)) return v.length !== 0 && !_.isUndefined(v[0])
return !_.isUndefined(v)
})
}
export const defaultOptions = { type: "path", expand: false } as ParserOptions
export interface TOCItem {
name: string
sectionId: string
nodeId: string
path: string
playOrder: number | string
children?: TOCItem[]
}
interface Manifest {
href: string
id: string
[k: string]: string
}
export class Epub {
private _zip: any // nodeZip instance
private _opfPath?: string
private _root?: string
private _content?: GeneralObject
private _manifest?: Manifest[]
private _spine?: Record<string, number> // array of ids defined in manifest
private _toc?: GeneralObject
private _metadata?: GeneralObject[]
private _options: ParserOptions = defaultOptions
structure?: TOCItem[]
info?: MetaInfo
sections?: Section[]
tocFile?: string
constructor(buffer: Buffer, options?: ParserOptions) {
this._zip = new nodeZip(buffer, { binary: true, base64: false, checkCRC32: true })
if (options) this._options = { ...defaultOptions, ...options }
}
/**
* get specific file from epub book.
*/
resolve(path: string): {
asText: () => string
asNodeBuffer: () => Buffer
} {
let _path
if (path[0] === '/') {
// use absolute path, root is zip root
_path = path.substr(1)
} else {
_path = this._root + path
}
const file = this._zip.file(decodeURI(_path))
if (file) {
return file
} else {
throw new Error(`${_path} not found!`)
}
}
async _resolveXMLAsJsObject(path: string): Promise<GeneralObject> {
const xml = this.resolve(path).asText()
return xmlToJs(xml)
}
private async _getOpfPath() {
const container = await this._resolveXMLAsJsObject('/META-INF/container.xml')
const opfPath = container.container.rootfiles[0].rootfile[0]['$']['full-path']
return opfPath as string
}
_resolveIdFromLink(href: string): string {
const { name: tarName } = parseLink(href)
const tarItem = _.find(this._manifest, (item: Manifest) => {
const { name } = parseLink(item.href)
return name === tarName
})
return _.get(tarItem!, 'id')
}
getManifest(content?: GeneralObject): Manifest[] {
return (
this._manifest ||
(_.get(content, ['package', 'manifest', 0, 'item'], []).map((item: any) => item.$))
)
}
getSpine(): Record<string, number> {
const spine: Record<string, number> = {}
this.getManifest()
_.get(this._content, ['package', 'spine', 0, 'itemref'], []).map(
(item: GeneralObject, i: number) => {
return spine[item.$.idref] = i
},
)
return spine
}
/** for toc is toc.html */
private _genStructureForHTML(tocObj: GeneralObject) {
const tocRoot = tocObj.html.body[0].nav[0]['ol'][0].li
let runningIndex = 1
const parseHTMLNavPoints = (navPoint: GeneralObject) => {
const element = navPoint.a[0] || {}
const path = element['$'].href
let name = element['_']
const prefix = element.span
if (prefix) {
name = `${prefix.map((p: GeneralObject) => p['_']).join('')}${name}`
}
const sectionId = this._resolveIdFromLink(path)
const { hash: nodeId } = parseLink(path)
const playOrder = runningIndex
let children = navPoint?.ol?.[0]?.li
if (children) {
children = parseOuterHTML(children)
}
runningIndex++
return {
name,
sectionId,
nodeId,
path,
playOrder,
children,
}
}
const parseOuterHTML = (collection: GeneralObject[]) => {
return collection.map((point) => parseHTMLNavPoints(point))
}
return parseOuterHTML(tocRoot)
}
_genStructure(tocObj: GeneralObject, resolveNodeId = false): TOCItem[] {
if (tocObj.html) {
return this._genStructureForHTML(tocObj)
}
const rootNavPoints = _.get(tocObj, ['ncx', 'navMap', '0', 'navPoint'], [])
const parseNavPoint = (navPoint: GeneralObject) => {
// link to section
const path = _.get(navPoint, ['content', '0', '$', 'src'], '')
const name = _.get(navPoint, ['navLabel', '0', 'text', '0'])
const playOrder = _.get(navPoint, ['$', 'playOrder']) as string
const { hash } = parseLink(path)
let children = navPoint.navPoint
if (children) {
// tslint:disable-next-line:no-use-before-declare
children = parseNavPoints(children)
}
const sectionId = this._resolveIdFromLink(path)
return {
name,
sectionId,
nodeId: hash || _.get(navPoint, ['$', 'id']),
path,
playOrder,
children,
}
}
const parseNavPoints = (navPoints: GeneralObject[]) => {
return navPoints.map((point) => {
return parseNavPoint(point)
})
}
return parseNavPoints(rootNavPoints)
}
/**
*
* @param {String} id
*/
private _resolveSections(id?: string) {
let list: any[] = _.union(Object.keys(this._spine!))
// no chain
if (id) {
list = [id];
}
return list.map((id) => {
const path = _.find(this._manifest, { id })!.href
const html = this.resolve(path).asText()
return parseSection({
id,
htmlString: html,
resourceResolver: this.resolve.bind(this),
idResolver: this._resolveIdFromLink.bind(this),
expand: this._options.expand,
})
})
}
getSection(id: string): Section | null {
let sectionIndex = -1
// console.log(id, this.getManifest())
if (this._spine) sectionIndex = this._spine[id]
// fix other html ont include spine structure
if (sectionIndex === undefined) {
return this._resolveSections(id)[0]
}
return this.sections ? sectionIndex != -1 ? this.sections[sectionIndex] : null : null
}
async parse(): Promise<Epub> {
this._opfPath = await this._getOpfPath()
this._content = await this._resolveXMLAsJsObject('/' + this._opfPath)
this._root = determineRoot(this._opfPath)
this._manifest = this.getManifest(this._content)
this._metadata = _.get(this._content, ['package', 'metadata'], []) as GeneralObject[]
// https://github.com/gaoxiaoliangz/epub-parser/issues/13
// https://www.w3.org/publishing/epub32/epub-packages.html#sec-spine-elem
this.tocFile = (_.find(this._manifest, { id: 'ncx' }) || {}).href
if (this.tocFile) {
const toc = await this._resolveXMLAsJsObject(this.tocFile)
this._toc = toc
this.structure = this._genStructure(toc)
}
this._spine = this.getSpine()
this.info = parseMetadata(this._metadata)
this.sections = this._resolveSections()
return this
}
}
export default function parserWrapper(target: string | Buffer, opts?: ParserOptions): Promise<Epub> {
// seems 260 is the length limit of old windows standard
// so path length is not used to determine whether it's path or binary string
// the downside here is that if the filepath is incorrect, it will be treated as binary string by default
// but it can use options to define the target type
const options = { ...defaultOptions, ...opts }
let _target = target
if (options.type === 'path' || (typeof target === 'string' && fs.existsSync(target))) {
_target = fs.readFileSync(target as string, 'binary')
}
return new Epub(_target as Buffer, options).parse()
}