HTML2FB2Lib

This library is designed to convert HTML to FB2.

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

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

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