HTML2FB2Lib

This library is designed to convert HTML to FB2.

当前为 2023-09-13 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/468831/1249508/HTML2FB2Lib.js

  1. // ==UserScript==
  2. // @name HTML2FB2Lib
  3. // @name:ru HTML2FB2Lib
  4. // @namespace 90h.yy.zz
  5. // @version 0.7.2
  6. // @author Ox90
  7. // @description This library is designed to convert HTML to FB2.
  8. // @description:ru Эта библиотека предназначена для конвертирования HTML в FB2.
  9. // @license MIT
  10. // ==/UserScript==
  11.  
  12. class FB2Parser {
  13. constructor() {
  14. this._stop = null;
  15. }
  16.  
  17. parse(htmlNode, fromNode) {
  18. const that = this;
  19. function _parse(node, from, fb2el, depth) {
  20. let n = from || node.firstChild;
  21. while (n) {
  22. const nn = that.startNode(n, depth);
  23. if (nn) {
  24. const f = that.processElement(FB2Element.fromHTML(nn, false), depth);
  25. if (f) {
  26. if (fb2el) fb2el.children.push(f);
  27. _parse(nn, null, f, depth + 1);
  28. }
  29. that.endNode(nn, depth);
  30. }
  31. if (that._stop) break;
  32. n = n.nextSibling;
  33. }
  34. }
  35. _parse(htmlNode, fromNode, null, 0);
  36. return this._stop;
  37. }
  38.  
  39. startNode(node, depth) {
  40. return node;
  41. }
  42.  
  43. processElement(fb2el, depth) {
  44. return fb2el;
  45. }
  46.  
  47. endNode(node, depth) {
  48. }
  49. }
  50.  
  51. class FB2AnnotationParser extends FB2Parser {
  52. run(fb2doc, element) {
  53. this._binaries = [];
  54. const res = this.parse(element);
  55. fb2doc.annotation = this._annotation;
  56. if (fb2doc.annotation) {
  57. fb2doc.annotation.normalize();
  58. this._binaries.forEach(bin => fb2doc.binaries.push(bin));
  59. this._binaries = null;
  60. }
  61. return res;
  62. }
  63.  
  64. parse(element) {
  65. this._annotation = new FB2Annotation();
  66. const res = super.parse(element);
  67. if (!this._annotation.children.length) this._annotation = null;
  68. return res;
  69. }
  70.  
  71. processElement(fb2el, depth) {
  72. if (fb2el) {
  73. if (depth === 0) this._annotation.children.push(fb2el);
  74. if (fb2el instanceof FB2Image) this._binaries.push(fb2el);
  75. }
  76. return super.processElement(fb2el, depth);
  77. }
  78. }
  79.  
  80. class FB2ChapterParser extends FB2Parser {
  81. run(fb2doc, element, title) {
  82. this._binaries = [];
  83. const res = this.parse(title, element);
  84. this._chapter.normalize();
  85. fb2doc.chapters.push(this._chapter);
  86. this._binaries.forEach(bin => fb2doc.binaries.push(bin));
  87. this._binaries = null;
  88. return res;
  89. }
  90.  
  91. parse(title, element) {
  92. this._chapter = new FB2Chapter(title);
  93. return super.parse(element);
  94. }
  95.  
  96. processElement(fb2el, depth) {
  97. if (fb2el) {
  98. if (depth === 0) this._chapter.children.push(fb2el);
  99. if (fb2el instanceof FB2Image) this._binaries.push(fb2el);
  100. }
  101. return super.processElement(fb2el, depth);
  102. }
  103. }
  104.  
  105. class FB2Document {
  106. constructor() {
  107. this.binaries = [];
  108. this.bookAuthors = [];
  109. this.annotation = null;
  110. this.genres = [];
  111. this.keywords = [];
  112. this.chapters = [];
  113. this.history = [];
  114. this.xmldoc = null;
  115. this._parsers = new Map();
  116. }
  117.  
  118. toString() {
  119. this._ensureXMLDocument();
  120. const root = this.xmldoc.documentElement;
  121. this._markBinaries();
  122. root.appendChild(this._makeDescriptionElement());
  123. root.appendChild(this._makeBodyElement());
  124. this._makeBinaryElements().forEach(el => root.appendChild(el));
  125. const res = (new XMLSerializer()).serializeToString(this.xmldoc);
  126. this.xmldoc = null;
  127. return res;
  128. }
  129.  
  130. createElement(name) {
  131. this._ensureXMLDocument();
  132. return this.xmldoc.createElementNS(this.xmldoc.documentElement.namespaceURI, name);
  133. }
  134.  
  135. createTextNode(value) {
  136. this._ensureXMLDocument();
  137. return this.xmldoc.createTextNode(value);
  138. }
  139.  
  140. createDocumentFragment() {
  141. this._ensureXMLDocument();
  142. return this.xmldoc.createDocumentFragment();
  143. }
  144.  
  145. bindParser(parser, id) {
  146. if (!parser && !id) {
  147. this._parsers.clear();
  148. return;
  149. }
  150. this._parsers.set(id, parser);
  151. }
  152.  
  153. parse(parser_id, ...args) {
  154. const parser = this._parsers.get(parser_id);
  155. if (!parser) throw new Error(`Unknown parser id: ${parser_id}`);
  156. return parser.run(this, ...args);
  157. }
  158.  
  159. _ensureXMLDocument() {
  160. if (!this.xmldoc) {
  161. this.xmldoc = new DOMParser().parseFromString(
  162. '<?xml version="1.0" encoding="UTF-8"?><FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0"/>',
  163. "application/xml"
  164. );
  165. this.xmldoc.documentElement.setAttribute("xmlns:l", "http://www.w3.org/1999/xlink");
  166. }
  167. }
  168.  
  169. _makeDescriptionElement() {
  170. const desc = this.createElement("description");
  171. // title-info
  172. const t_info = this.createElement("title-info");
  173. desc.appendChild(t_info);
  174. //--
  175. const ch_num = t_info.children.length;
  176. this.genres.forEach(gi => {
  177. if (gi instanceof FB2Genre) {
  178. t_info.appendChild(gi.xml(this));
  179. } else if (typeof(gi) === "string") {
  180. (new FB2GenreList(gi)).forEach(g => t_info.appendChild(g.xml(this)));
  181. }
  182. });
  183. if (t_info.children.length === ch_num) t_info.appendChild((new FB2Genre("network_literature")).xml(this));
  184. //--
  185. (this.bookAuthors.length ? this.bookAuthors : [ new FB2Author("Неизвестный автор") ]).forEach(a => {
  186. t_info.appendChild(a.xml(this));
  187. });
  188. //--
  189. t_info.appendChild((new FB2Element("book-title", this.bookTitle)).xml(this));
  190. //--
  191. if (this.annotation) t_info.appendChild(this.annotation.xml(this));
  192. //--
  193. let keywords = null;
  194. if (Array.isArray(this.keywords) && this.keywords.length) {
  195. keywords = this.keywords.join(", ");
  196. } else if (typeof(this.keywords) === "string" && this.keywords.trim()) {
  197. keywords = this.keywords.trim();
  198. }
  199. if (keywords) t_info.appendChild((new FB2Element("keywords", keywords)).xml(this));
  200. //--
  201. if (this.bookDate) {
  202. const el = this.createElement("date");
  203. el.setAttribute("value", FB2Utils.dateToAtom(this.bookDate));
  204. el.textContent = this.bookDate.getFullYear();
  205. t_info.appendChild(el);
  206. }
  207. //--
  208. if (this.coverpage) {
  209. const el = this.createElement("coverpage");
  210. (Array.isArray(this.coverpage) ? this.coverpage : [ this.coverpage ]).forEach(img => {
  211. el.appendChild(img.xml(this));
  212. });
  213. t_info.appendChild(el);
  214. }
  215. //--
  216. const lang = this.createElement("lang");
  217. lang.textContent = "ru";
  218. t_info.appendChild(lang);
  219. //--
  220. if (this.sequence) {
  221. const el = this.createElement("sequence");
  222. el.setAttribute("name", this.sequence.name);
  223. if (this.sequence.number) el.setAttribute("number", this.sequence.number);
  224. t_info.appendChild(el);
  225. }
  226. // document-info
  227. const d_info = this.createElement("document-info");
  228. desc.appendChild(d_info);
  229. //--
  230. d_info.appendChild((new FB2Author("Ox90")).xml(this));
  231. //--
  232. if (this.programName) d_info.appendChild((new FB2Element("program-used", this.programName)).xml(this));
  233. //--
  234. d_info.appendChild((() => {
  235. const f_time = new Date();
  236. const el = this.createElement("date");
  237. el.setAttribute("value", FB2Utils.dateToAtom(f_time));
  238. el.textContent = f_time.toUTCString();
  239. return el;
  240. })());
  241. //--
  242. if (this.sourceURL) {
  243. d_info.appendChild((new FB2Element("src-url", this.sourceURL)).xml(this));
  244. }
  245. //--
  246. d_info.appendChild((new FB2Element("id", this._genBookId())).xml(this));
  247. //--
  248. d_info.appendChild((new FB2Element("version", "1.0")).xml(this));
  249. //--
  250. if (this.history.length) {
  251. const hs = this.createElement("history");
  252. d_info.appendChild(hs);
  253. this.history.forEach(it => hs.appendChild((new FB2Paragraph(it)).xml(this)));
  254. }
  255. //--
  256. return desc;
  257. }
  258.  
  259. _makeBodyElement() {
  260. const body = this.createElement("body");
  261. if (this.bookTitle || this.bookAuthors.length) {
  262. const title = this.createElement("title");
  263. body.appendChild(title);
  264. if (this.bookAuthors.length) title.appendChild((new FB2Paragraph(this.bookAuthors.join(", "))).xml(this));
  265. if (this.bookTitle) title.appendChild((new FB2Paragraph(this.bookTitle)).xml(this));
  266. }
  267. this.chapters.forEach(ch => body.appendChild(ch.xml(this)));
  268. return body;
  269. }
  270.  
  271. _markBinaries() {
  272. let idx = 0;
  273. this.binaries.forEach(img => {
  274. if (!img.id) img.id = "image" + (++idx) + img.suffix();
  275. });
  276. }
  277.  
  278. _makeBinaryElements() {
  279. return this.binaries.reduce((list, img) => {
  280. if (img.value) list.push(img.xmlBinary(this));
  281. return list;
  282. }, []);
  283. }
  284.  
  285. _genBookId() {
  286. let str = this.sourceURL || this.bookTitle || "";
  287. let hash = 0;
  288. const slen = str.length;
  289. for (let i = 0; i < slen; ++i) {
  290. const ch = str.charCodeAt(i);
  291. hash = ((hash << 5) - hash) + ch;
  292. hash = hash & hash; // Convert to 32bit integer
  293. }
  294. return (this.idPrefix || "h2f2l_") + Math.abs(hash).toString() + (hash > 0 ? "1" : "");
  295. }
  296. }
  297.  
  298. class FB2Element {
  299. constructor(name, value) {
  300. this.name = name;
  301. this.value = value !== undefined ? value : null;
  302. this.children = [];
  303. }
  304.  
  305. static fromHTML(node, recursive) {
  306. let fb2el = null;
  307. const names = new Map([
  308. [ "U", "emphasis" ], [ "EM", "emphasis" ], [ "EMPHASIS", "emphasis" ], [ "I", "emphasis" ],
  309. [ "S", "strikethrough" ], [ "DEL", "strikethrough" ], [ "STRIKE", "strikethrough" ],
  310. [ "STRONG", "strong" ], [ "B", "strong" ], [ "BLOCKQUOTE", "cite" ],
  311. [ "SUB", "sub" ], [ "SUP", "sup" ],
  312. [ "SCRIPT", null ], [ "#comment", null ]
  313. ]);
  314. const node_name = node.nodeName;
  315. if (names.has(node_name)) {
  316. const name = names.get(node_name);
  317. if (!name) return null;
  318. fb2el = new FB2Element(names.get(node_name));
  319. } else {
  320. switch (node_name) {
  321. case "#text":
  322. return new FB2Text(node.textContent);
  323. case "SPAN":
  324. fb2el = new FB2Text();
  325. break;
  326. case "P":
  327. case "LI":
  328. fb2el = new FB2Paragraph();
  329. break;
  330. case "SUBTITLE":
  331. fb2el = new FB2Subtitle();
  332. break;
  333. case "A":
  334. fb2el = new FB2Link(node.href || node.getAttribute("l:href"));
  335. break;
  336. case "OL":
  337. fb2el = new FB2OrderedList();
  338. break;
  339. case "UL":
  340. fb2el = new FB2UnorderedList();
  341. break;
  342. case "BR":
  343. return new FB2EmptyLine();
  344. case "HR":
  345. return new FB2Paragraph("---");
  346. case "IMG":
  347. return new FB2Image(node.src);
  348. default:
  349. return new FB2UnknownNode(node);
  350. }
  351. }
  352. if (recursive) fb2el.appendContentFromHTML(node);
  353. return fb2el;
  354. }
  355.  
  356. hasValue() {
  357. return ((this.value !== undefined && this.value !== null) || !!this.children.length);
  358. }
  359.  
  360. setContentFromHTML(data, fb2doc, log) {
  361. this.children = [];
  362. this.appendContentFromHTML(data, fb2doc, log);
  363. }
  364.  
  365. appendContentFromHTML(data, fb2doc, log) {
  366. for (const node of data.childNodes) {
  367. let fe = FB2Element.fromHTML(node, true);
  368. if (fe) this.children.push(fe);
  369. }
  370. }
  371.  
  372. normalize() {
  373. const _normalize = function(list) {
  374. let done = true;
  375. let res_list = list.reduce((accum, cur_el) => {
  376. accum.push(cur_el);
  377. const tmp_ch = cur_el.children;
  378. cur_el.children = [];
  379. tmp_ch.forEach(el => {
  380. if (
  381. (
  382. (el instanceof FB2Paragraph || el instanceof FB2EmptyLine) &&
  383. (!(el instanceof FB2Chapter || el instanceof FB2Annotation || el.name === "cite" || el.name === "title"))
  384. ) || (
  385. (el.name === "cite") &&
  386. (!(el instanceof FB2Chapter || el instanceof FB2Annotation))
  387. ) || (
  388. (el instanceof FB2Subtitle) &&
  389. (!(el instanceof FB2Chapter || el.name === "cite"))
  390. )
  391. ) {
  392. // Вытолкнуть элемент вверх, разбив текущий элемент на две части
  393. accum.push(el);
  394. const nm = cur_el.name;
  395. cur_el = new cur_el.constructor();
  396. if (!cur_el.name) cur_el.name = nm;
  397. accum.push(cur_el);
  398. done = false;
  399. } else {
  400. let cnt = 0;
  401. el.normalize().forEach(e => {
  402. // Убрать избыточную вложенность: <el><el>value</el></el> --> <el>value</el>
  403. if (!e.value && e.children.length === 1 && e.name === e.children[0].name) {
  404. e = e.children[0];
  405. }
  406. if (e !== el) done = false;
  407. if (e.hasValue()) cur_el.children.push(e);
  408. });
  409. }
  410. });
  411. return accum;
  412. }, []);
  413. return { list: res_list, done: done };
  414. }
  415. //--
  416. let result = _normalize([ this ]);
  417. while (!result.done) {
  418. result = _normalize(result.list);
  419. }
  420. return result.list;
  421. }
  422.  
  423. xml(doc) {
  424. const el = doc.createElement(this.name);
  425. if (this.value !== null) el.textContent = this.value;
  426. this.children.forEach(ch => el.appendChild(ch.xml(doc)));
  427. return el;
  428. }
  429. }
  430.  
  431. class FB2BlockElement extends FB2Element {
  432. normalize() {
  433. // Предварительная нормализация
  434. this.children = this.children.reduce((list, ch) => {
  435. ch.normalize().forEach(cc => list.push(cc));
  436. return list;
  437. }, []);
  438. // Удалить пустоты справа
  439. while (this.children.length) {
  440. const el = this.children[this.children.length - 1];
  441. if (el instanceof FB2Text) el.trimRight();
  442. if (!el.hasValue()) {
  443. this.children.pop();
  444. continue;
  445. }
  446. break;
  447. }
  448. // Удалить пустоты слева
  449. while (this.children.length) {
  450. const el = this.children[0];
  451. if (el instanceof FB2Text) el.trimLeft();
  452. if (!el.hasValue()) {
  453. this.children.shift();
  454. continue;
  455. }
  456. break;
  457. }
  458. // Удалить пустоты в содержимом элемента
  459. if (!this.children.length && typeof(this.value) === "string") {
  460. this.value = this.value.trim();
  461. }
  462. // Окончательная нормализация
  463. return super.normalize();
  464. }
  465. }
  466.  
  467. /**
  468. * FB2 элемент верхнего уровня section
  469. */
  470. class FB2Chapter extends FB2Element {
  471. constructor(title) {
  472. super("section");
  473. this.title = title;
  474. }
  475.  
  476. normalize() {
  477. // Обернуть все запрещенные на этом уровне элементы в параграфы
  478. this.children = this.children.reduce((list, el) => {
  479. if (![ "p", "subtitle", "image", "empty-line", "cite" ].includes(el.name)) {
  480. const pe = new FB2Paragraph();
  481. pe.children.push(el);
  482. el = pe;
  483. }
  484. el.normalize().forEach(el => {
  485. if (el.hasValue()) list.push(el);
  486. });
  487. return list;
  488. }, []);
  489. return [ this ];
  490. }
  491.  
  492. xml(doc) {
  493. const el = super.xml(doc);
  494. if (this.title) {
  495. const t_el = doc.createElement("title");
  496. const p_el = doc.createElement("p");
  497. p_el.textContent = this.title;
  498. t_el.appendChild(p_el);
  499. el.prepend(t_el);
  500. }
  501. return el;
  502. }
  503. }
  504.  
  505. /**
  506. * FB2 элемент верхнего уровня annotation
  507. */
  508. class FB2Annotation extends FB2Element {
  509. constructor() {
  510. super("annotation");
  511. }
  512.  
  513. normalize() {
  514. // Обернуть неформатированный текст, разделенный <br> в параграфы
  515. let lp = null;
  516. const newParagraph = list => {
  517. lp = new FB2Paragraph();
  518. list.push(lp);
  519. };
  520. this.children = this.children.reduce((list, el) => {
  521. if ([ "p", "subtitle", "cite" ].includes(el.name)) {
  522. list.push(el);
  523. lp = null;
  524. } else if (el.name === "empty-line") {
  525. if (!lp) {
  526. // Перенос между блоками
  527. if (list.length) list.push(new FB2EmptyLine);
  528. } else if (!lp.children.length) {
  529. // Более одного переноса подряд между inline элементами
  530. list.pop();
  531. list.push(new FB2EmptyLine());
  532. list.push(lp);
  533. } else {
  534. // Перенос между inline элементами
  535. newParagraph(list);
  536. }
  537. } else {
  538. if (!lp) newParagraph(list);
  539. lp.children.push(el);
  540. }
  541. return list;
  542. }, []);
  543. // Запустить собственную нормализацию дочерних элементов
  544. this.children = this.children.reduce((list, el) => {
  545. el.normalize().forEach(el => {
  546. if (el.hasValue()) list.push(el);
  547. });
  548. return list;
  549. }, []);
  550. // Удалить конечные пустые строки
  551. for (let len = this.children.length; len; ) {
  552. if (this.children[len - 1].name !== "empty-line") break;
  553. this.children.pop();
  554. --len;
  555. }
  556. }
  557. }
  558.  
  559. class FB2Subtitle extends FB2BlockElement {
  560. constructor(value) {
  561. super("subtitle", value);
  562. }
  563. }
  564.  
  565. class FB2Paragraph extends FB2BlockElement {
  566. constructor(value) {
  567. super("p", value);
  568. }
  569. }
  570.  
  571. class FB2EmptyLine extends FB2Element {
  572. constructor() {
  573. super("empty-line");
  574. }
  575.  
  576. hasValue() {
  577. return true;
  578. }
  579. }
  580.  
  581. class FB2Text extends FB2Element {
  582. constructor(value) {
  583. super("text", value);
  584. }
  585.  
  586. trimLeft() {
  587. if (typeof(this.value) === "string") this.value = this.value.trimLeft() || null;
  588. if (!this.value) {
  589. while (this.children.length) {
  590. const first_child = this.children[0];
  591. if (first_child instanceof FB2Text) first_child.trimLeft();
  592. if (first_child.hasValue()) break;
  593. this.children.shift();
  594. }
  595. }
  596. }
  597.  
  598. trimRight() {
  599. while (this.children.length) {
  600. const last_child = this.children[this.children.length - 1];
  601. if (last_child instanceof FB2Text) last_child.trimRight();
  602. if (last_child.hasValue()) break;
  603. this.children.pop();
  604. }
  605. if (!this.children.length && typeof(this.value) === "string") {
  606. this.value = this.value.trimRight() || null;
  607. }
  608. }
  609.  
  610. xml(doc) {
  611. if (!this.value && this.children.length) {
  612. let fr = doc.createDocumentFragment();
  613. for (const ch of this.children) {
  614. fr.appendChild(ch.xml(doc));
  615. }
  616. return fr;
  617. }
  618. return doc.createTextNode(this.value);
  619. }
  620. }
  621.  
  622. class FB2Link extends FB2Element {
  623. constructor(href) {
  624. super("a");
  625. this.href = href;
  626. }
  627.  
  628. xml(doc) {
  629. const el = super.xml(doc);
  630. el.setAttribute("l:href", this.href);
  631. return el;
  632. }
  633. }
  634.  
  635. class FB2List extends FB2Element {
  636. constructor() {
  637. super("list");
  638. }
  639.  
  640. xml(doc) {
  641. const fr = doc.createDocumentFragment();
  642. for (const ch of this.children) {
  643. if (ch.hasValue()) {
  644. let ch_el = null;
  645. if (ch instanceof FB2BlockElement) {
  646. ch_el = ch.xml(doc);
  647. } else {
  648. const par = new FB2Paragraph();
  649. par.children.push(ch);
  650. ch_el = par.xml(doc);
  651. }
  652. if (ch_el.textContent.trim() !== "") fr.appendChild(ch_el);
  653. }
  654. }
  655. return fr;
  656. }
  657. }
  658.  
  659. class FB2OrderedList extends FB2List {
  660. xml(doc) {
  661. let pos = 0;
  662. const fr = super.xml(doc);
  663. for (const el of fr.children) {
  664. ++pos;
  665. el.prepend(`${pos}. `);
  666. }
  667. return fr;
  668. }
  669. }
  670.  
  671. class FB2UnorderedList extends FB2List {
  672. xml(doc) {
  673. const fr = super.xml(doc);
  674. for (const el of fr.children) {
  675. el.prepend("- ");
  676. }
  677. return fr;
  678. }
  679. }
  680.  
  681. class FB2Author extends FB2Element {
  682. constructor(s) {
  683. super("author");
  684. const a = s.split(" ");
  685. switch (a.length) {
  686. case 1:
  687. this.nickName = s;
  688. break;
  689. case 2:
  690. this.firstName = a[0];
  691. this.lastName = a[1];
  692. break;
  693. default:
  694. this.firstName = a[0];
  695. this.middleName = a.slice(1, -1).join(" ");
  696. this.lastName = a[a.length - 1];
  697. break;
  698. }
  699. this.homePage = null;
  700. }
  701.  
  702. hasValue() {
  703. return (!!this.firstName || !!this.lastName || !!this.middleName);
  704. }
  705.  
  706. toString() {
  707. if (!this.firstName) return this.nickName;
  708. return [ this.firstName, this.middleName, this.lastName ].reduce((list, name) => {
  709. if (name) list.push(name);
  710. return list;
  711. }, []).join(" ");
  712. }
  713.  
  714. xml(doc) {
  715. let a_el = super.xml(doc);
  716. [
  717. [ "first-name", this.firstName ], [ "middle-name", this.middleName ],
  718. [ "last-name", this.lastName ], [ "nickname", this.nickName ],
  719. [ "home-page", this.homePage ]
  720. ].forEach(it => {
  721. if (it[1]) {
  722. const e = doc.createElement(it[0]);
  723. e.textContent = it[1];
  724. a_el.appendChild(e);
  725. }
  726. });
  727. return a_el;
  728. }
  729. }
  730.  
  731. class FB2Image extends FB2Element {
  732. constructor(value) {
  733. super("image");
  734. if (typeof(value) === "string") {
  735. this.url = value;
  736. } else {
  737. this.value = value;
  738. }
  739. }
  740.  
  741. async load(onprogress) {
  742. if (this.url) {
  743. const bin = await this._load(this.url, { responseType: "binary", onprogress: onprogress });
  744. this.type = bin.type;
  745. this.size = bin.size;
  746. return new Promise((resolve, reject) => {
  747. const reader = new FileReader();
  748. reader.addEventListener("loadend", (event) => resolve(event.target.result));
  749. reader.readAsDataURL(bin);
  750. }).then(base64str => {
  751. this.value = base64str.substr(base64str.indexOf(",") + 1);
  752. }).catch(err => {
  753. throw new Error("Ошибка загрузки изображения");
  754. });
  755. }
  756. }
  757.  
  758. hasValue() {
  759. return true;
  760. }
  761.  
  762. xml(doc) {
  763. if (this.value) {
  764. const el = doc.createElement(this.name);
  765. el.setAttribute("l:href", "#" + this.id);
  766. return el
  767. }
  768. const id = this.id || "изображение";
  769. return doc.createTextNode(`[ ${id} ]`);
  770. }
  771.  
  772. xmlBinary(doc) {
  773. const el = doc.createElement("binary");
  774. el.setAttribute("id", this.id);
  775. el.setAttribute("content-type", this.type);
  776. el.textContent = this.value
  777. return el;
  778. }
  779.  
  780. suffix() {
  781. switch (this.type) {
  782. case "image/png":
  783. return ".png";
  784. case "image/jpeg":
  785. return ".jpg";
  786. case "image/gif":
  787. return ".gif";
  788. case "image/webp":
  789. return ".webp";
  790. }
  791. return "";
  792. }
  793.  
  794. async _load(...args) {
  795. return FB2Loader.addJob(...args);
  796. }
  797. }
  798.  
  799. class FB2Genre extends FB2Element {
  800. constructor(value) {
  801. super("genre", value);
  802. }
  803. }
  804.  
  805. class FB2UnknownNode extends FB2Element {
  806. constructor(value) {
  807. super("unknown", value);
  808. }
  809.  
  810. xml(doc) {
  811. return doc.createTextNode(this.value && this.value.textContent || "");
  812. }
  813. }
  814.  
  815. class FB2GenreList extends Array {
  816. constructor(...args) {
  817. if (args.length === 1 && typeof(args[0]) === "number") {
  818. super(args[0]);
  819. return;
  820. }
  821. const list = (args.length === 1) ? (Array.isArray(args[0]) ? args[0] : [ args[0] ]) : args;
  822. super();
  823. if (!list.length) return;
  824. const keys = FB2GenreList._keys;
  825. const gmap = new Map();
  826. const addWeight = (name, weight) => gmap.set(name, (gmap.get(name) || 0) + weight);
  827.  
  828. list.forEach(p_str => {
  829. p_str = p_str.toLowerCase();
  830. let words = p_str.split(/[\s,.;]+/);
  831. if (words.length === 1) words = [];
  832. for (const it of keys) {
  833. if (it[0] === p_str || it[1] === p_str) {
  834. addWeight(it[0], 3); // Exact match
  835. break;
  836. }
  837. // Scan each word
  838. let weight = words.includes(it[1]) ? 2 : 0;
  839. it[2] && it[2].forEach(k => {
  840. if (words.includes(k)) ++weight;
  841. });
  842. if (weight >= 2) addWeight(it[0], weight);
  843. }
  844. });
  845.  
  846. const res = [];
  847. gmap.forEach((weight, name) => res.push([ name, weight]));
  848. if (!res.length) return;
  849. res.sort((a, b) => b[1] > a[1]);
  850.  
  851. // Add at least five genres with maximum weight
  852. let cur_w = 0;
  853. for (const it of res) {
  854. if (it[1] !== cur_w && this.length >= 5) break;
  855. cur_w = it[1];
  856. this.push(new FB2Genre(it[0]));
  857. }
  858. }
  859. }
  860.  
  861. FB2GenreList._keys = [
  862. [ "adv_animal", "природа и животные", [ "приключения", "животные", "природа" ] ],
  863. [ "adventure", "приключения" ],
  864. [ "adv_geo", "путешествия и география", [ "приключения", "география", "путешествие" ] ],
  865. [ "adv_history", "исторические приключения", [ "история", "приключения" ] ],
  866. [ "adv_indian", "вестерн, про индейцев", [ "индейцы", "вестерн" ] ],
  867. [ "adv_maritime", "морские приключения", [ "приключения", "море" ] ],
  868. [ "adv_modern", "приключения в современном мире", [ "современный", "мир" ] ],
  869. [ "adv_story", "авантюрный роман" ],
  870. [ "antique", "старинное" ],
  871. [ "antique_ant", "античная литература", [ "старинное", "античность" ] ],
  872. [ "antique_east", "древневосточная литература", [ "старинное", "восток" ] ],
  873. [ "antique_european", "европейская старинная литература", [ "старинное", "европа" ] ],
  874. [ "antique_myths", "мифы. легенды. эпос", [ "мифы", "легенды", "эпос", "фольклор" ] ],
  875. [ "antique_russian", "древнерусская литература", [ "древнерусское", "старинное" ] ],
  876. [ "aphorism_quote", "афоризмы, цитаты", [ "афоризмы", "цитаты", "проза" ] ],
  877. [ "architecture_book", "скульптура и архитектура", [ "дизайн" ] ],
  878. [ "art_criticism", "искусствоведение" ],
  879. [ "art_world_culture", "мировая художественная культура", [ "искусство", "искусствоведение" ] ],
  880. [ "astrology", "астрология и хиромантия", [ "астрология", "хиромантия" ] ],
  881. [ "auto_business", "автодело" ],
  882. [ "auto_regulations", "автомобили и ПДД", [ "дорожного", "движения", "дорожное", "движение" ] ],
  883. [ "banking", "финансы", [ "банки", "деньги" ] ],
  884. [ "child_adv", "приключения для детей и подростков" ],
  885. [ "child_classical", "классическая детская литература" ],
  886. [ "child_det", "детская остросюжетная литература" ],
  887. [ "child_education", "детская образовательная литература" ],
  888. [ "child_folklore", "детский фольклор" ],
  889. [ "child_prose", "проза для детей" ],
  890. [ "children", "детская литература", [ "детское" ] ],
  891. [ "child_sf", "фантастика для детей" ],
  892. [ "child_tale", "сказки народов мира" ],
  893. [ "child_tale_rus", "русские сказки" ],
  894. [ "child_verse", "стихи для детей" ],
  895. [ "cine", "кино" ],
  896. [ "comedy", "комедия" ],
  897. [ "comics", "комиксы" ],
  898. [ "comp_db", "программирование, программы, базы данных", [ "программирование", "базы", "программы" ] ],
  899. [ "comp_hard", "компьютерное железо", [ "аппаратное" ] ],
  900. [ "comp_soft", "программное обеспечение" ],
  901. [ "computers", "компьютеры" ],
  902. [ "comp_www", "ос и сети, интернет", [ "ос", "сети", "интернет" ] ],
  903. [ "design", "дизайн" ],
  904. [ "det_action", "боевики", [ "боевик", "триллер" ] ],
  905. [ "det_classic", "классический детектив" ],
  906. [ "det_crime", "криминальный детектив", [ "криминал" ] ],
  907. [ "det_espionage", "шпионский детектив", [ "шпион", "шпионы", "детектив" ] ],
  908. [ "det_hard", "крутой детектив" ],
  909. [ "det_history", "исторический детектив", [ "история" ] ],
  910. [ "det_irony", "иронический детектив" ],
  911. [ "det_maniac", "про маньяков", [ "маньяки", "детектив" ] ],
  912. [ "det_police", "полицейский детектив", [ "полиция", "детектив" ] ],
  913. [ "det_political", "политический детектив", [ "политика", "детектив" ] ],
  914. [ "det_su", "советский детектив", [ "ссср", "детектив" ] ],
  915. [ "detective", "детектив", [ "детективы" ] ],
  916. [ "drama", "драма" ],
  917. [ "drama_antique", "античная драма" ],
  918. [ "dramaturgy", "драматургия" ],
  919. [ "economics", "экономика" ],
  920. [ "economics_ref", "деловая литература" ],
  921. [ "epic", "былины, эпопея", [ "былины", "эпопея" ] ],
  922. [ "epistolary_fiction", "эпистолярная проза" ],
  923. [ "equ_history", "история техники" ],
  924. [ "fairy_fantasy", "мифологическое фэнтези", [ "мифология", "фантастика" ] ],
  925. [ "family", "семейные отношения", [ "дом", "семья" ] ],
  926. [ "fanfiction", "фанфик" ],
  927. [ "folklore", "фольклор, загадки" ],
  928. [ "folk_songs", "народные песни" ],
  929. [ "folk_tale", "народные сказки" ],
  930. [ "foreign_antique", "средневековая классическая проза" ],
  931. [ "foreign_children", "зарубежная литература для детей" ],
  932. [ "foreign_prose", "зарубежная классическая проза" ],
  933. [ "geo_guides", "путеводители, карты, атласы", [ "география", "атласы", "карты", "путеводители" ] ],
  934. [ "gothic_novel", "готический роман" ],
  935. [ "great_story", "роман", [ "повесть" ] ],
  936. [ "home", "домоводство", [ "дом", "семья" ] ],
  937. [ "home_collecting", "коллекционирование" ],
  938. [ "home_cooking", "кулинария", [ "домашняя", "еда" ] ],
  939. [ "home_crafts", "хобби и ремесла" ],
  940. [ "home_diy", "сделай сам" ],
  941. [ "home_entertain", "развлечения" ],
  942. [ "home_garden", "сад и огород" ],
  943. [ "home_health", "здоровье" ],
  944. [ "home_pets", "домашние животные" ],
  945. [ "home_sex", "семейные отношения, секс" ],
  946. [ "home_sport", "боевые исскусства, спорт" ],
  947. [ "hronoopera", "хроноопера" ],
  948. [ "humor", "юмор" ],
  949. [ "humor_anecdote", "анекдоты" ],
  950. [ "humor_prose", "юмористическая проза" ],
  951. [ "humor_satire", "сатира" ],
  952. [ "humor_verse", "юмористические стихи, басни", [ "юмор", "стихи", "басни" ] ],
  953. [ "limerick", [ "частушки", "прибаутки", "потешки" ] ],
  954. [ "literature_18", "классическая проза XVII-XVIII веков" ],
  955. [ "literature_19", "классическая проза ХIX века" ],
  956. [ "literature_20", "классическая проза ХX века" ],
  957. [ "love", "любовные романы" ],
  958. [ "love_contemporary", "современные любовные романы" ],
  959. [ "love_detective", "остросюжетные любовные романы", [ "детектив", "любовь" ] ],
  960. [ "love_erotica", "эротика", [ "эротическая", "литература" ] ],
  961. [ "love_hard", "порно" ],
  962. [ "love_history", "исторические любовные романы", [ "история", "любовь" ] ],
  963. [ "love_sf", "любовное фэнтези" ],
  964. [ "love_short", "короткие любовные романы" ],
  965. [ "lyrics", "лирика" ],
  966. [ "military_history", "военная история", [ "война", "история" ] ],
  967. [ "military_special", "военное дело" ],
  968. [ "military_weapon", "военная техника и вооружение", [ "военная", "вооружение", "техника" ] ],
  969. [ "modern_tale", "современная сказка" ],
  970. [ "music", "музыка" ],
  971. [ "network_literature", "сетевая литература" ],
  972. [ "nonf_biography", "биографии и мемуары", [ "биография", "биографии", "мемуары" ] ],
  973. [ "nonf_criticism", "критика" ],
  974. [ "nonfiction", "документальная литература" ],
  975. [ "nonf_military", "военная документалистика и аналитика" ],
  976. [ "nonf_publicism", "публицистика" ],
  977. [ "notes:", "партитуры" ],
  978. [ "org_behavior", "маркентиг, pr", [ "организации" ] ],
  979. [ "painting", "живопись", [ "альбомы", "иллюстрированные", "каталоги" ] ],
  980. [ "palindromes", "визуальная и экспериментальная поэзия", [ "верлибры", "палиндромы", "поэзия" ] ],
  981. [ "periodic", "журналы, газеты", [ "журналы", "газеты" ]],
  982. [ "poem", "поэма", [ "эпическая", "поэзия" ] ],
  983. [ "poetry", "поэзия" ],
  984. [ "poetry_classical", "классическая поэзия" ],
  985. [ "poetry_east", "поэзия востока" ],
  986. [ "poetry_for_classical", "классическая зарубежная поэзия" ],
  987. [ "poetry_for_modern", "современная зарубежная поэзия" ],
  988. [ "poetry_modern", "современная поэзия" ],
  989. [ "poetry_rus_classical", "классическая русская поэзия" ],
  990. [ "poetry_rus_modern", "современная русская поэзия", [ "русская", "поэзия" ] ],
  991. [ "popadanec", "попаданцы", [ "попаданец" ] ],
  992. [ "popular_business", "карьера, кадры", [ "карьера", "дело", "бизнес" ] ],
  993. [ "prose", "проза" ],
  994. [ "prose_abs", "фантасмагория, абсурдистская проза" ],
  995. [ "prose_classic", "классическая проза" ],
  996. [ "prose_contemporary", "современная русская и зарубежная проза", [ "современная", "проза" ] ],
  997. [ "prose_counter", "контркультура" ],
  998. [ "prose_game", "игры, упражнения для детей", [ "игры", "упражнения" ] ],
  999. [ "prose_history", "историческая проза", [ "история", "проза" ] ],
  1000. [ "prose_magic", "магический реализм", [ "магия", "проза" ] ],
  1001. [ "prose_military", "проза о войне" ],
  1002. [ "prose_neformatny", "неформатная проза", [ "экспериментальная", "проза" ] ],
  1003. [ "prose_rus_classic", "русская классическая проза" ],
  1004. [ "prose_su_classics", "советская классическая проза" ],
  1005. [ "proverbs", "пословицы", [ "поговорки" ] ],
  1006. [ "ref_dict", "словари", [ "справочник" ] ],
  1007. [ "ref_encyc", "энциклопедии", [ "энциклопедия" ] ],
  1008. [ "ref_guide", "руководства", [ "руководство", "справочник" ] ],
  1009. [ "ref_ref", "справочники", [ "справочник" ] ],
  1010. [ "reference", "справочная литература" ],
  1011. [ "religion", "религия", [ "духовность", "эзотерика" ] ],
  1012. [ "religion_budda", "буддизм" ],
  1013. [ "religion_catholicism", "католицизм" ],
  1014. [ "religion_christianity", "христианство" ],
  1015. [ "religion_esoterics", "эзотерическая литература", [ "эзотерика" ] ],
  1016. [ "religion_hinduism", "индуизм" ],
  1017. [ "religion_islam", "ислам" ],
  1018. [ "religion_judaism", "иудаизм" ],
  1019. [ "religion_orthdoxy", "православие" ],
  1020. [ "religion_paganism", "язычество" ],
  1021. [ "religion_protestantism", "протестантизм" ],
  1022. [ "religion_self", "самосовершенствование" ],
  1023. [ "russian_fantasy", "славянское фэнтези", [ "русское", "фэнтези" ] ],
  1024. [ "sci_biology", "биология", [ "биофизика", "биохимия" ] ],
  1025. [ "sci_botany", "ботаника" ],
  1026. [ "sci_build", "строительство и сопромат", [ "строительтво", "сопромат" ] ],
  1027. [ "sci_chem", "химия" ],
  1028. [ "sci_cosmos", "астрономия и космос", [ "астрономия", "космос" ] ],
  1029. [ "sci_culture", "культурология" ],
  1030. [ "sci_ecology", "экология" ],
  1031. [ "sci_economy", "экономика" ],
  1032. [ "science", "научная литература" ],
  1033. [ "sci_geo", "геология и география" ],
  1034. [ "sci_history", "история" ],
  1035. [ "sci_juris", "юриспруденция" ],
  1036. [ "sci_linguistic", "языкознание", [ "иностранный", "язык" ] ],
  1037. [ "sci_math", "математика" ],
  1038. [ "sci_medicine_alternative", "альтернативная медицина" ],
  1039. [ "sci_medicine", "медицина" ],
  1040. [ "sci_metal", "металлургия" ],
  1041. [ "sci_oriental", "востоковедение" ],
  1042. [ "sci_pedagogy", "педагогика, воспитание детей, литература для родителей", [ "воспитание", "детей" ] ],
  1043. [ "sci_philology", "литературоведение" ],
  1044. [ "sci_philosophy", "философия" ],
  1045. [ "sci_phys", "физика" ],
  1046. [ "sci_politics", "политика" ],
  1047. [ "sci_popular", "зарубежная образовательная литература", [ "зарубежная", "научно-популярная" ] ],
  1048. [ "sci_psychology", "психология и психотерапия" ],
  1049. [ "sci_radio", "радиоэлектроника" ],
  1050. [ "sci_religion", "религиоведение", [ "религия", "духовность" ] ],
  1051. [ "sci_social_studies", "обществознание", [ "социология" ] ],
  1052. [ "sci_state", "государство и право" ],
  1053. [ "sci_tech", "технические науки", [ "техника", "наука" ] ],
  1054. [ "sci_textbook", "учебники и пособия" ],
  1055. [ "sci_theories", "альтернативные науки и научные теории" ],
  1056. [ "sci_transport", "транспорт и авиация" ],
  1057. [ "sci_veterinary", "ветеринария" ],
  1058. [ "sci_zoo", "зоология" ],
  1059. [ "science", "научная литература", [ "образование" ] ],
  1060. [ "screenplays", "сценарии", [ "сценарий" ] ],
  1061. [ "sf", "научная фантастика", [ "наука", "фантастика" ] ],
  1062. [ "sf_action", "боевая фантастика" ],
  1063. [ "sf_cyberpunk", "киберпанк" ],
  1064. [ "sf_detective", "детективная фантастика", [ "детектив", "фантастика" ] ],
  1065. [ "sf_epic", "эпическая фантастика", [ "эпическое", "фэнтези" ] ],
  1066. [ "sf_etc", "фантастика" ],
  1067. [ "sf_fantasy", "фэнтези" ],
  1068. [ "sf_fantasy_city", "городское фэнтези" ],
  1069. [ "sf_heroic", "героическая фантастика", [ "героическое", "герой", "фэнтези" ] ],
  1070. [ "sf_history", "альтернативная история", [ "историческое", "фэнтези" ] ],
  1071. [ "sf_horror", "ужасы", [ "фантастика" ] ],
  1072. [ "sf_humor", "юмористическая фантастика", [ "юмор", "фантастика" ] ],
  1073. [ "sf_litrpg", "гитрпг", [ "litrpg", "рпг" ] ],
  1074. [ "sf_mystic", "мистика", [ "мистическая", "фантастика" ] ],
  1075. [ "sf_postapocalyptic", "постапокалипсис" ],
  1076. [ "sf_realrpg", "реалрпг", [ "realrpg" ] ],
  1077. [ "sf_social", "Социально-психологическая фантастика", [ "социум", "психология", "фантастика" ] ],
  1078. [ "sf_space", "космическая фантастика", [ "космос", "фантастика" ] ],
  1079. [ "sf_stimpank", "стимпанк" ],
  1080. [ "sf_technofantasy", "технофэнтези" ],
  1081. [ "song_poetry", "песенная поэзия" ],
  1082. [ "story", "рассказ", [ "рассказы", "эссе", "новеллы", "новелла", "феерия", "сборник", "рассказов" ] ],
  1083. [ "tale_chivalry", "рыцарский роман", [ "рыцари", "приключения" ] ],
  1084. [ "tbg_computers", "учебные пособия, самоучители", [ "пособия", "самоучители" ] ],
  1085. [ "tbg_higher", "учебники и пособия ВУЗов", [ "учебники", "пособия" ] ],
  1086. [ "tbg_school", "школьные учебники и пособия, рефераты, шпаргалки", [ "школьные", "учебники", "шпаргалки", "рефераты" ] ],
  1087. [ "tbg_secondary", "учебники и пособия для среднего и специального образования", [ "учебники", "пособия", "образование" ] ],
  1088. [ "theatre", "театр" ],
  1089. [ "thriller", "триллер", [ "триллеры", "детектив", "детективы" ] ],
  1090. [ "tragedy", "трагедия", [ "драматургия" ] ],
  1091. [ "travel_notes", " география, путевые заметки", [ "география", "заметки" ] ],
  1092. [ "vaudeville", "мистерия", [ "буффонада", "водевиль" ] ],
  1093. ];
  1094.  
  1095. class FB2Loader {
  1096. static async addJob(url, params) {
  1097. params ||= {};
  1098. const fp = {};
  1099. fp.method = params.method || "GET";
  1100. fp.credentials = "same-origin";
  1101. fp.signal = this._getSignal();
  1102. const resp = await fetch(url, fp);
  1103. if (!resp.ok) throw new Error(`Сервер вернул ошибку (${resp.status})`);
  1104. const reader = resp.body.getReader();
  1105. const type = resp.headers.get("Content-Type");
  1106. const total = +resp.headers.get("Content-Length");
  1107. let loaded = 0;
  1108. const chunks = [];
  1109. const onprogress = (total && typeof(params.onprogress) === "function") ? params.onprogress : null;
  1110. while (true) {
  1111. const { done, value } = await reader.read();
  1112. if (done) break;
  1113. chunks.push(value);
  1114. loaded += value.length;
  1115. if (onprogress) onprogress(loaded, total);
  1116. }
  1117. switch (params.responseType) {
  1118. case "binary":
  1119. return new Blob(chunks, { type: type });
  1120. default:
  1121. {
  1122. let pos = 0;
  1123. const data = new Uint8Array(loaded);
  1124. for (let ch of chunks) {
  1125. data.set(ch, pos);
  1126. pos += ch.length;
  1127. }
  1128. return (new TextDecoder("utf-8")).decode(data);
  1129. }
  1130. }
  1131. }
  1132.  
  1133. static abortAll() {
  1134. if (this._controller) {
  1135. this._controller.abort();
  1136. this._controller = null;
  1137. }
  1138. }
  1139.  
  1140. static _getSignal() {
  1141. let controller = this._controller;
  1142. if (!controller) this._controller = controller = new AbortController();
  1143. return controller.signal;
  1144. }
  1145. }
  1146.  
  1147. class FB2Utils {
  1148. static dateToAtom(date) {
  1149. const m = date.getMonth() + 1;
  1150. const d = date.getDate();
  1151. return "" + date.getFullYear() + '-' + (m < 10 ? "0" : "") + m + "-" + (d < 10 ? "0" : "") + d;
  1152. }
  1153. }