Greasy Fork is available in English.

HTML2FB2Lib

This is a library for converting HTML to FB2.

Този скрипт не може да бъде инсталиран директно. Това е библиотека за други скриптове и може да бъде използвана с мета-директива // @require https://update.greasyfork.org/scripts/468831/1478439/HTML2FB2Lib.js

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