index.js 15 KB

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