index.js 13 KB

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