HTML2FB2Lib

This is a library for converting HTML to FB2.

当前为 2023-07-25 提交的版本,查看 最新版本

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

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