123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414 |
- const fs = require('fs-extra');
- const URL = require('url').URL;
- const iconv = require('iconv-lite');
- const chardet = require('chardet');
- const _ = require('lodash');
- const FileDetector = require('../FileDetector');
- const EasySAXParser = require('./easysaxmod');
- class BookConverter {
- constructor() {
- this.detector = new FileDetector();
- }
- async convertToFb2(inputFile, outputFile, url, callback) {
- const fileType = await this.detector.detectFile(inputFile);
-
- if (fileType && (fileType.ext == 'html' || fileType.ext == 'xml')) {
- const data = await fs.readFile(inputFile);
- if (data.toString().indexOf('<FictionBook') >= 0) {
- await fs.writeFile(outputFile, data);
- return;
- }
- const parsedUrl = new URL(url);
- if (parsedUrl.hostname == 'samlib.ru' ||
- parsedUrl.hostname == 'budclub.ru') {
- await fs.writeFile(outputFile, await this.convertSamlib(data));
- return;
- }
- //Заглушка
- await fs.writeFile(outputFile, await this.convertHtml(data));
- callback(100);
- } else {
- if (fileType)
- throw new Error(`unknown file format: ${fileType.mime}`);
- else
- throw new Error(`unsupported file format: ${url}`);
- }
- }
- decode(data) {
- const charsetAll = chardet.detectAll(data.slice(0, 10000));
- let selected = 'ISO-8859-1';
- for (const charset of charsetAll) {
- if (charset.name.indexOf('ISO-8859') < 0) {
- selected = charset.name;
- break;
- }
- }
- return iconv.decode(data, selected);
- }
- async convertHtml(data, isText) {
- let titleInfo = {};
- let desc = {_n: 'description', 'title-info': titleInfo};
- let pars = [];
- let body = {_n: 'body', section: {_a: []}};
- let fb2 = [desc, body];
- let title = '';
- let inTitle = false;
- let spaceCounter = [];
- const newParagraph = () => {
- pars.push({_n: 'p', _t: ''});
- };
- const growParagraph = (text) => {
- const l = pars.length;
- if (l) {
- if (pars[l - 1]._t == '')
- text = text.trimLeft();
- pars[l - 1]._t += text;
- }
- //посчитаем отступы у текста, чтобы выделить потом параграфы
- const lines = text.split('\n');
- for (const line of lines) {
- const sp = line.split(' ');
- let l = 0;
- while (l < sp.length && sp[l].trim() == '') {
- l++;
- }
- if (!spaceCounter[l])
- spaceCounter[l] = 0;
- spaceCounter[l]++;
- }
- };
- newParagraph();
- const newPara = new Set(['TR', 'BR', 'BR/', 'DD', 'P', 'TITLE', '/TITLE', 'H1', 'H2', 'H3', '/H1', '/H2', '/H3']);
- const onText = (text) => {
- if (inTitle && !title)
- title = text;
- };
- const onNode = (elem) => {
- if (elem == 'TITLE')
- inTitle = true;
- else if (elem == '/TITLE')
- inTitle = false;
- };
- const innerCut = new Set(['HEAD', 'SCRIPT', 'STYLE']);
- let buf = this.decode(data).toString();
- let i = 0;
- const len = buf.length;
- let cutCounter = 0;
- let cutTag = '';
- while (i < len) {
- let left = buf.indexOf('<', i);
- if (left < 0)
- break;
- let right = buf.indexOf('>', left + 1);
- if (right < 0)
- break;
- let tag = buf.substr(left + 1, right - left - 1).trim().toUpperCase();
- const firstSpace = tag.indexOf(' ');
- if (firstSpace >= 0)
- tag = tag.substr(0, firstSpace);
- const text = buf.substr(i, left - i);
- if (!cutCounter) {
- growParagraph(text);
- if (newPara.has(tag))
- newParagraph();
- }
- onText(text);
- onNode(tag);
- if (innerCut.has(tag) && (!cutCounter || cutTag == tag)) {
- if (!cutCounter)
- cutTag = tag;
- cutCounter++;
- }
- if (tag != '' && tag.charAt(0) == '/' && cutTag == tag.substr(1)) {
- cutCounter = (cutCounter > 0 ? cutCounter - 1 : 0);
- if (!cutCounter)
- cutTag = '';
- }
- i = right + 1;
- }
- if (i < len && !cutCounter)
- growParagraph(buf.substr(i, len - i));
- titleInfo['book-title'] = title;
- //подозрение на чистый текст, надо разбить на параграфы
- if ((isText || pars.length < buf.length/2000) && spaceCounter.length) {
- let total = 0;
- for (let i = 0; i < spaceCounter.length; i++) {
- total += (spaceCounter[i] ? spaceCounter[i] : 0);
- }
- total /= 10;
- let i = spaceCounter.length - 1;
- while (i > 0 && (!spaceCounter[i] || spaceCounter[i] < total)) i--;
- const parIndent = i;
- if (parIndent > 0) {//нашли отступ параграфа
- let newPars = [];
- const newPar = () => {
- newPars.push({_n: 'p', _t: ''});
- };
- const growPar = (text) => {
- const l = newPars.length;
- if (l) {
- if (newPars[l - 1]._t == '')
- text = text.trimLeft();
- newPars[l - 1]._t += text;
- }
- }
- for (const par of pars) {
- newPar();
- const lines = par._t.split('\n');
- for (const line of lines) {
- const sp = line.split(' ');
- let l = 0;
- while (l < sp.length && sp[l].trim() == '') {
- l++;
- }
- if (l >= parIndent)
- newPar();
- growPar(line + ' ');
- }
- }
- body.section._a[0] = newPars;
- } else {
- body.section._a[0] = pars;
- }
- } else {
- body.section._a[0] = pars;
- }
- return this.formatFb2(fb2);
- }
- async convertSamlib(data) {
- let titleInfo = {};
- let desc = {_n: 'description', 'title-info': titleInfo};
- let pars = [];
- let body = {_n: 'body', section: {_a: [pars]}};
- let fb2 = [desc, body];
- let path = '';
- let tag = '';// eslint-disable-line no-unused-vars
- let inText = false;
- let center = false;
- const newParagraph = () => {
- pars.push({_n: 'p', _t: ''});
- };
- const newSubTitle = () => {
- pars.push({_n: 'subtitle', _t: ''});
- };
- const growParagraph = (text) => {
- const l = pars.length;
- if (l) {
- if (pars[l - 1]._t == '')
- text = text.trimLeft();
- pars[l - 1]._t += text;
- }
- };
- const parser = new EasySAXParser();
- parser.on('error', (msgError) => {// eslint-disable-line no-unused-vars
- });
- parser.on('startNode', (elemName, getAttr, isTagEnd, getStrNode) => {// eslint-disable-line no-unused-vars
- if (!inText) {
- path += '/' + elemName;
- tag = elemName;
- } else {
- if (!center && (elemName == 'p' || elemName == 'dd')) {
- newParagraph();
- }
- switch (elemName) {
- case 'i':
- growParagraph('<emphasis>');
- break;
- case 'b':
- growParagraph('<strong>');
- break;
- case 'div':
- var a = getAttr();
- if (a && a.align == 'center') {
- center = true;
- newSubTitle();
- }
- break;
- }
- }
- });
- parser.on('endNode', (elemName, isTagStart, getStrNode) => {// eslint-disable-line no-unused-vars
- if (!inText) {
- const oldPath = path;
- let t = '';
- do {
- let i = path.lastIndexOf('/');
- t = path.substr(i + 1);
- path = path.substr(0, i);
- } while (t != elemName && path);
- if (t != elemName) {
- path = oldPath;
- }
- let i = path.lastIndexOf('/');
- tag = path.substr(i + 1);
- } else {
- switch (elemName) {
- case 'i':
- growParagraph('</emphasis>');
- break;
- case 'b':
- growParagraph('</strong>');
- break;
- case 'div':
- center = false;
- break;
- }
- }
- });
- parser.on('textNode', (text) => {// eslint-disable-line no-unused-vars
- if (text != ' ' && text.trim() == '')
- text = text.trim();
- if (text == '')
- return;
- switch (path) {
- case '/html/body/center/h2':
- titleInfo['book-title'] = text;
- return;
- case '/html/body/div/h3':
- if (!titleInfo.author)
- titleInfo.author = {};
- text = text.replace(':', '').trim().split(' ');
- if (text[0])
- titleInfo.author['last-name'] = text[0];
- if (text[1])
- titleInfo.author['first-name'] = text[1];
- if (text[2])
- titleInfo.author['middle-name'] = text[2];
- return;
- }
- if (inText)
- growParagraph(text);
- });
- parser.on('cdata', (data) => {// eslint-disable-line no-unused-vars
- });
- parser.on('comment', (text) => {// eslint-disable-line no-unused-vars
- if (text == '--------- Собственно произведение -------------')
- inText = true;
- if (text == '-----------------------------------------------')
- inText = false;
- });
- /*
- parser.on('progress', async(progress) => {
- callback(...........);
- });
- */
- await parser.parse(this.decode(data));
- const title = (titleInfo['book-title'] ? titleInfo['book-title'] : '');
- let author = '';
- if (titleInfo.author) {
- author = _.compact([
- (titleInfo.author['last-name'] ? titleInfo.author['last-name'] : ''),
- (titleInfo.author['first-name'] ? titleInfo.author['first-name'] : ''),
- (titleInfo.author['middle-name'] ? titleInfo.author['middle-name'] : ''),
- ]).join(' ');
- }
- pars.unshift({_n: 'title', _a: [
- {_n: 'p', _t: author}, {_n: 'p', _t: ''},
- {_n: 'p', _t: title}, {_n: 'p', _t: ''},
- ]})
- return this.formatFb2(fb2);
- }
- formatFb2(fb2) {
- let out = '<?xml version="1.0" encoding="utf-8"?>';
- out += '<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">';
- out += this.formatFb2Node(fb2);
- out += '</FictionBook>';
- return out;
- }
- formatFb2Node(node, name) {
- let out = '';
- if (Array.isArray(node)) {
- for (const n of node) {
- out += this.formatFb2Node(n);
- }
- } else if (typeof node == 'string') {
- out += `<${name}>${node}</${name}>`;
- } else {
- if (node._n)
- name = node._n;
- if (!name)
- throw new Error(`malformed fb2 object`);
- out += `<${name}>`;
- if (node.hasOwnProperty('_t')) {
- out += node._t;
- } else {
- for (let nodeName in node) {
- if (nodeName == '_n')
- continue;
- const n = node[nodeName];
- out += this.formatFb2Node(n, nodeName);
- }
- }
- out += `</${name}>`;
- }
- return out;
- }
- }
- module.exports = BookConverter;
|