index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. if (newPars[l - 1]._t == '')
  151. text = text.trimLeft();
  152. newPars[l - 1]._t += text;
  153. }
  154. }
  155. for (const par of pars) {
  156. newPar();
  157. const lines = par._t.split('\n');
  158. for (const line of lines) {
  159. const sp = line.split(' ');
  160. let l = 0;
  161. while (l < sp.length && sp[l].trim() == '') {
  162. l++;
  163. }
  164. if (l >= parIndent)
  165. newPar();
  166. growPar(line.trim() + ' ');
  167. }
  168. }
  169. body.section._a[0] = newPars;
  170. } else {
  171. body.section._a[0] = pars;
  172. }
  173. } else {
  174. body.section._a[0] = pars;
  175. }
  176. return this.formatFb2(fb2);
  177. }
  178. async convertSamlib(data) {
  179. let titleInfo = {};
  180. let desc = {_n: 'description', 'title-info': titleInfo};
  181. let pars = [];
  182. let body = {_n: 'body', section: {_a: [pars]}};
  183. let fb2 = [desc, body];
  184. let path = '';
  185. let tag = '';// eslint-disable-line no-unused-vars
  186. let inText = false;
  187. let center = false;
  188. const newParagraph = () => {
  189. pars.push({_n: 'p', _t: ''});
  190. };
  191. const newSubTitle = () => {
  192. pars.push({_n: 'subtitle', _t: ''});
  193. };
  194. const growParagraph = (text) => {
  195. const l = pars.length;
  196. if (l) {
  197. if (pars[l - 1]._t == '')
  198. text = text.trimLeft();
  199. pars[l - 1]._t += text;
  200. }
  201. };
  202. const parser = new EasySAXParser();
  203. parser.on('error', (msgError) => {// eslint-disable-line no-unused-vars
  204. });
  205. parser.on('startNode', (elemName, getAttr, isTagEnd, getStrNode) => {// eslint-disable-line no-unused-vars
  206. if (!inText) {
  207. path += '/' + elemName;
  208. tag = elemName;
  209. } else {
  210. if (!center && (elemName == 'p' || elemName == 'dd')) {
  211. newParagraph();
  212. }
  213. switch (elemName) {
  214. case 'i':
  215. growParagraph('<emphasis>');
  216. break;
  217. case 'b':
  218. growParagraph('<strong>');
  219. break;
  220. case 'div':
  221. var a = getAttr();
  222. if (a && a.align == 'center') {
  223. center = true;
  224. newSubTitle();
  225. }
  226. break;
  227. }
  228. }
  229. });
  230. parser.on('endNode', (elemName, isTagStart, getStrNode) => {// eslint-disable-line no-unused-vars
  231. if (!inText) {
  232. const oldPath = path;
  233. let t = '';
  234. do {
  235. let i = path.lastIndexOf('/');
  236. t = path.substr(i + 1);
  237. path = path.substr(0, i);
  238. } while (t != elemName && path);
  239. if (t != elemName) {
  240. path = oldPath;
  241. }
  242. let i = path.lastIndexOf('/');
  243. tag = path.substr(i + 1);
  244. } else {
  245. switch (elemName) {
  246. case 'i':
  247. growParagraph('</emphasis>');
  248. break;
  249. case 'b':
  250. growParagraph('</strong>');
  251. break;
  252. case 'div':
  253. center = false;
  254. break;
  255. }
  256. }
  257. });
  258. parser.on('textNode', (text) => {// eslint-disable-line no-unused-vars
  259. if (text != ' ' && text.trim() == '')
  260. text = text.trim();
  261. if (text == '')
  262. return;
  263. switch (path) {
  264. case '/html/body/center/h2':
  265. titleInfo['book-title'] = text;
  266. return;
  267. case '/html/body/div/h3':
  268. if (!titleInfo.author)
  269. titleInfo.author = {};
  270. text = text.replace(':', '').trim().split(' ');
  271. if (text[0])
  272. titleInfo.author['last-name'] = text[0];
  273. if (text[1])
  274. titleInfo.author['first-name'] = text[1];
  275. if (text[2])
  276. titleInfo.author['middle-name'] = text[2];
  277. return;
  278. }
  279. if (inText)
  280. growParagraph(text);
  281. });
  282. parser.on('cdata', (data) => {// eslint-disable-line no-unused-vars
  283. });
  284. parser.on('comment', (text) => {// eslint-disable-line no-unused-vars
  285. if (text == '--------- Собственно произведение -------------')
  286. inText = true;
  287. if (text == '-----------------------------------------------')
  288. inText = false;
  289. });
  290. /*
  291. parser.on('progress', async(progress) => {
  292. callback(...........);
  293. });
  294. */
  295. await parser.parse(this.decode(data));
  296. const title = (titleInfo['book-title'] ? titleInfo['book-title'] : '');
  297. let author = '';
  298. if (titleInfo.author) {
  299. author = _.compact([
  300. (titleInfo.author['last-name'] ? titleInfo.author['last-name'] : ''),
  301. (titleInfo.author['first-name'] ? titleInfo.author['first-name'] : ''),
  302. (titleInfo.author['middle-name'] ? titleInfo.author['middle-name'] : ''),
  303. ]).join(' ');
  304. }
  305. pars.unshift({_n: 'title', _a: [
  306. {_n: 'p', _t: author}, {_n: 'p', _t: ''},
  307. {_n: 'p', _t: title}, {_n: 'p', _t: ''},
  308. ]})
  309. return this.formatFb2(fb2);
  310. }
  311. formatFb2(fb2) {
  312. let out = '<?xml version="1.0" encoding="utf-8"?>';
  313. out += '<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">';
  314. out += this.formatFb2Node(fb2);
  315. out += '</FictionBook>';
  316. return out;
  317. }
  318. formatFb2Node(node, name) {
  319. let out = '';
  320. if (Array.isArray(node)) {
  321. for (const n of node) {
  322. out += this.formatFb2Node(n);
  323. }
  324. } else if (typeof node == 'string') {
  325. out += `<${name}>${node}</${name}>`;
  326. } else {
  327. if (node._n)
  328. name = node._n;
  329. if (!name)
  330. throw new Error(`malformed fb2 object`);
  331. out += `<${name}>`;
  332. if (node.hasOwnProperty('_t')) {
  333. out += node._t;
  334. } else {
  335. for (let nodeName in node) {
  336. if (nodeName == '_n')
  337. continue;
  338. const n = node[nodeName];
  339. out += this.formatFb2Node(n, nodeName);
  340. }
  341. }
  342. out += `</${name}>`;
  343. }
  344. return out;
  345. }
  346. }
  347. module.exports = BookConverter;