HTML2FB2Lib

This is a library for converting HTML to FB2.

当前为 2023-08-28 提交的版本,查看 最新版本

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

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