index.js 13 KB

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