index.js 14 KB

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