index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. const fs = require('fs-extra');
  2. const URL = require('url').URL;
  3. const iconv = require('iconv-lite');
  4. const chardet = require('chardet');
  5. const _ = require('lodash');
  6. const FileDetector = require('../FileDetector');
  7. const EasySAXParser = require('./easysaxmod');
  8. class BookConverter {
  9. constructor() {
  10. this.detector = new FileDetector();
  11. }
  12. async convertToFb2(inputFile, outputFile, url, callback) {
  13. const fileType = await this.detector.detectFile(inputFile);
  14. if (fileType && (fileType.ext == 'html' || fileType.ext == 'xml')) {
  15. const data = await fs.readFile(inputFile);
  16. if (data.toString().indexOf('<FictionBook') >= 0) {
  17. await fs.writeFile(outputFile, data);
  18. return;
  19. }
  20. const parsedUrl = new URL(url);
  21. if (parsedUrl.hostname == 'samlib.ru' ||
  22. parsedUrl.hostname == 'budclub.ru') {
  23. await fs.writeFile(outputFile, await this.convertSamlib(data));
  24. return;
  25. }
  26. //Заглушка
  27. await fs.writeFile(outputFile, await this.convertHtml(data));
  28. callback(100);
  29. } else {
  30. if (fileType)
  31. throw new Error(`unknown file format: ${fileType.mime}`);
  32. else
  33. throw new Error(`unsupported file format: ${url}`);
  34. }
  35. }
  36. decode(data) {
  37. const charsetAll = chardet.detectAll(data.slice(0, 10000));
  38. let selected = 'ISO-8859-1';
  39. for (const charset of charsetAll) {
  40. if (charset.name.indexOf('ISO-8859') < 0) {
  41. selected = charset.name;
  42. break;
  43. }
  44. }
  45. return iconv.decode(data, selected);
  46. }
  47. async convertHtml(data, isText) {
  48. let titleInfo = {};
  49. let desc = {_n: 'description', 'title-info': titleInfo};
  50. let pars = [];
  51. let body = {_n: 'body', section: {_a: []}};
  52. let fb2 = [desc, body];
  53. let title = '';
  54. let inTitle = false;
  55. let spaceCounter = [];
  56. const newParagraph = () => {
  57. pars.push({_n: 'p', _t: ''});
  58. };
  59. const growParagraph = (text) => {
  60. const l = pars.length;
  61. if (l) {
  62. if (pars[l - 1]._t == '')
  63. text = text.trimLeft();
  64. pars[l - 1]._t += text;
  65. }
  66. //посчитаем отступы у текста, чтобы выделить потом параграфы
  67. const lines = text.split('\n');
  68. for (const line of lines) {
  69. const sp = line.split(' ');
  70. let l = 0;
  71. while (l < sp.length && sp[l].trim() == '') {
  72. l++;
  73. }
  74. if (!spaceCounter[l])
  75. spaceCounter[l] = 0;
  76. spaceCounter[l]++;
  77. }
  78. };
  79. newParagraph();
  80. const newPara = new Set(['TR', 'BR', 'BR/', 'DD', 'P', 'TITLE', '/TITLE', 'H1', 'H2', 'H3', '/H1', '/H2', '/H3']);
  81. const onText = (text) => {
  82. if (inTitle && !title)
  83. title = text;
  84. };
  85. const onNode = (elem) => {
  86. if (elem == 'TITLE')
  87. inTitle = true;
  88. else if (elem == '/TITLE')
  89. inTitle = false;
  90. };
  91. const innerCut = new Set(['HEAD', 'SCRIPT', 'STYLE']);
  92. let buf = this.decode(data).toString();
  93. buf = buf.replace(/&nbsp;/g, ' ');
  94. let i = 0;
  95. const len = buf.length;
  96. let cutCounter = 0;
  97. let cutTag = '';
  98. while (i < len) {
  99. let left = buf.indexOf('<', i);
  100. if (left < 0)
  101. break;
  102. let right = buf.indexOf('>', left + 1);
  103. if (right < 0)
  104. break;
  105. let tag = buf.substr(left + 1, right - left - 1).trim().toUpperCase();
  106. const firstSpace = tag.indexOf(' ');
  107. if (firstSpace >= 0)
  108. tag = tag.substr(0, firstSpace);
  109. const text = buf.substr(i, left - i);
  110. if (!cutCounter) {
  111. growParagraph(text);
  112. if (newPara.has(tag))
  113. newParagraph();
  114. }
  115. onText(text);
  116. onNode(tag);
  117. if (innerCut.has(tag) && (!cutCounter || cutTag == tag)) {
  118. if (!cutCounter)
  119. cutTag = tag;
  120. cutCounter++;
  121. }
  122. if (tag != '' && tag.charAt(0) == '/' && cutTag == tag.substr(1)) {
  123. cutCounter = (cutCounter > 0 ? cutCounter - 1 : 0);
  124. if (!cutCounter)
  125. cutTag = '';
  126. }
  127. i = right + 1;
  128. }
  129. if (i < len && !cutCounter)
  130. growParagraph(buf.substr(i, len - i));
  131. titleInfo['book-title'] = title;
  132. //подозрение на чистый текст, надо разбить на параграфы
  133. if ((isText || pars.length < buf.length/2000) && spaceCounter.length) {
  134. let total = 0;
  135. for (let i = 0; i < spaceCounter.length; i++) {
  136. total += (spaceCounter[i] ? spaceCounter[i] : 0);
  137. }
  138. total /= 10;
  139. let i = spaceCounter.length - 1;
  140. while (i > 0 && (!spaceCounter[i] || spaceCounter[i] < total)) i--;
  141. const parIndent = i;
  142. if (parIndent > 0) {//нашли отступ параграфа
  143. let newPars = [];
  144. const newPar = () => {
  145. newPars.push({_n: 'p', _t: ''});
  146. };
  147. const growPar = (text) => {
  148. const l = newPars.length;
  149. if (l) {
  150. newPars[l - 1]._t += text;
  151. }
  152. }
  153. for (const par of pars) {
  154. newPar();
  155. const lines = par._t.split('\n');
  156. for (const line of lines) {
  157. const sp = line.split(' ');
  158. let l = 0;
  159. while (l < sp.length && sp[l].trim() == '') {
  160. l++;
  161. }
  162. if (l >= parIndent)
  163. newPar();
  164. growPar(line.trim() + ' ');
  165. }
  166. }
  167. body.section._a[0] = newPars;
  168. } else {
  169. body.section._a[0] = pars;
  170. }
  171. } else {
  172. body.section._a[0] = pars;
  173. }
  174. //убрать лишнее
  175. for (let p of body.section._a[0]) {
  176. p._t = p._t.replace(/[\t\n\r]/g, ' ');
  177. }
  178. return this.formatFb2(fb2);
  179. }
  180. async convertSamlib(data) {
  181. let titleInfo = {};
  182. let desc = {_n: 'description', 'title-info': titleInfo};
  183. let pars = [];
  184. let body = {_n: 'body', section: {_a: [pars]}};
  185. let fb2 = [desc, body];
  186. let path = '';
  187. let tag = '';// eslint-disable-line no-unused-vars
  188. let inText = false;
  189. let center = false;
  190. const newParagraph = () => {
  191. pars.push({_n: 'p', _t: ''});
  192. };
  193. const newSubTitle = () => {
  194. pars.push({_n: 'subtitle', _t: ''});
  195. };
  196. const growParagraph = (text) => {
  197. const l = pars.length;
  198. if (l) {
  199. if (pars[l - 1]._t == '')
  200. text = text.trimLeft();
  201. pars[l - 1]._t += text;
  202. }
  203. };
  204. const parser = new EasySAXParser();
  205. parser.on('error', (msgError) => {// eslint-disable-line no-unused-vars
  206. });
  207. parser.on('startNode', (elemName, getAttr, isTagEnd, getStrNode) => {// eslint-disable-line no-unused-vars
  208. if (!inText) {
  209. path += '/' + elemName;
  210. tag = elemName;
  211. } else {
  212. if (!center && (elemName == 'p' || elemName == 'dd')) {
  213. newParagraph();
  214. }
  215. switch (elemName) {
  216. case 'i':
  217. growParagraph('<emphasis>');
  218. break;
  219. case 'b':
  220. growParagraph('<strong>');
  221. break;
  222. case 'div':
  223. var a = getAttr();
  224. if (a && a.align == 'center') {
  225. center = true;
  226. newSubTitle();
  227. }
  228. break;
  229. }
  230. }
  231. });
  232. parser.on('endNode', (elemName, isTagStart, getStrNode) => {// eslint-disable-line no-unused-vars
  233. if (!inText) {
  234. const oldPath = path;
  235. let t = '';
  236. do {
  237. let i = path.lastIndexOf('/');
  238. t = path.substr(i + 1);
  239. path = path.substr(0, i);
  240. } while (t != elemName && path);
  241. if (t != elemName) {
  242. path = oldPath;
  243. }
  244. let i = path.lastIndexOf('/');
  245. tag = path.substr(i + 1);
  246. } else {
  247. switch (elemName) {
  248. case 'i':
  249. growParagraph('</emphasis>');
  250. break;
  251. case 'b':
  252. growParagraph('</strong>');
  253. break;
  254. case 'div':
  255. center = false;
  256. break;
  257. }
  258. }
  259. });
  260. parser.on('textNode', (text) => {// eslint-disable-line no-unused-vars
  261. if (text != ' ' && text.trim() == '')
  262. text = text.trim();
  263. if (text == '')
  264. return;
  265. switch (path) {
  266. case '/html/body/center/h2':
  267. titleInfo['book-title'] = text;
  268. return;
  269. case '/html/body/div/h3':
  270. if (!titleInfo.author)
  271. titleInfo.author = {};
  272. text = text.replace(':', '').trim().split(' ');
  273. if (text[0])
  274. titleInfo.author['last-name'] = text[0];
  275. if (text[1])
  276. titleInfo.author['first-name'] = text[1];
  277. if (text[2])
  278. titleInfo.author['middle-name'] = text[2];
  279. return;
  280. }
  281. if (inText)
  282. growParagraph(text);
  283. });
  284. parser.on('cdata', (data) => {// eslint-disable-line no-unused-vars
  285. });
  286. parser.on('comment', (text) => {// eslint-disable-line no-unused-vars
  287. if (text == '--------- Собственно произведение -------------')
  288. inText = true;
  289. if (text == '-----------------------------------------------')
  290. inText = false;
  291. });
  292. /*
  293. parser.on('progress', async(progress) => {
  294. callback(...........);
  295. });
  296. */
  297. await parser.parse(this.decode(data));
  298. const title = (titleInfo['book-title'] ? titleInfo['book-title'] : '');
  299. let author = '';
  300. if (titleInfo.author) {
  301. author = _.compact([
  302. (titleInfo.author['last-name'] ? titleInfo.author['last-name'] : ''),
  303. (titleInfo.author['first-name'] ? titleInfo.author['first-name'] : ''),
  304. (titleInfo.author['middle-name'] ? titleInfo.author['middle-name'] : ''),
  305. ]).join(' ');
  306. }
  307. pars.unshift({_n: 'title', _a: [
  308. {_n: 'p', _t: author}, {_n: 'p', _t: ''},
  309. {_n: 'p', _t: title}, {_n: 'p', _t: ''},
  310. ]})
  311. return this.formatFb2(fb2);
  312. }
  313. formatFb2(fb2) {
  314. let out = '<?xml version="1.0" encoding="utf-8"?>';
  315. out += '<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">';
  316. out += this.formatFb2Node(fb2);
  317. out += '</FictionBook>';
  318. return out;
  319. }
  320. formatFb2Node(node, name) {
  321. let out = '';
  322. if (Array.isArray(node)) {
  323. for (const n of node) {
  324. out += this.formatFb2Node(n);
  325. }
  326. } else if (typeof node == 'string') {
  327. out += `<${name}>${node}</${name}>`;
  328. } else {
  329. if (node._n)
  330. name = node._n;
  331. if (!name)
  332. throw new Error(`malformed fb2 object`);
  333. out += `<${name}>`;
  334. if (node.hasOwnProperty('_t')) {
  335. out += node._t;
  336. } else {
  337. for (let nodeName in node) {
  338. if (nodeName == '_n')
  339. continue;
  340. const n = node[nodeName];
  341. out += this.formatFb2Node(n, nodeName);
  342. }
  343. }
  344. out += `</${name}>`;
  345. }
  346. return out;
  347. }
  348. }
  349. module.exports = BookConverter;