BasePage.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. const _ = require('lodash');
  2. const he = require('he');
  3. const WebWorker = require('../WebWorker');//singleton
  4. const XmlParser = require('../xml/XmlParser');
  5. const spaceChar = String.fromCodePoint(0x00B7);
  6. const emptyFieldValue = '?';
  7. const maxUtf8Char = String.fromCodePoint(0xFFFFF);
  8. const ruAlphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';
  9. const enAlphabet = 'abcdefghijklmnopqrstuvwxyz';
  10. const enruArr = (ruAlphabet + enAlphabet).split('');
  11. const enru = new Set(enruArr);
  12. class BasePage {
  13. constructor(config) {
  14. this.config = config;
  15. this.webWorker = new WebWorker(config);
  16. this.rootTag = 'feed';
  17. this.opdsRoot = config.opdsRoot;
  18. }
  19. makeEntry(entry = {}) {
  20. if (!entry.id)
  21. throw new Error('makeEntry: no id');
  22. if (!entry.title)
  23. throw new Error('makeEntry: no title');
  24. entry.title = he.escape(entry.title);
  25. const result = {
  26. updated: (new Date()).toISOString().substring(0, 19) + 'Z',
  27. };
  28. return Object.assign(result, entry);
  29. }
  30. myEntry() {
  31. return this.makeEntry({
  32. id: this.id,
  33. title: this.title,
  34. link: this.navLink({href: `/${this.id}`}),
  35. });
  36. }
  37. makeLink(attrs) {
  38. attrs.href = he.escape(attrs.href);
  39. return {'*ATTRS': attrs};
  40. }
  41. navLink(attrs) {
  42. return this.makeLink({
  43. href: (attrs.hrefAsIs ? attrs.href : `${this.opdsRoot}${attrs.href || ''}`),
  44. rel: attrs.rel || 'subsection',
  45. type: 'application/atom+xml;profile=opds-catalog;kind=navigation',
  46. });
  47. }
  48. acqLink(attrs) {
  49. return this.makeLink({
  50. href: (attrs.hrefAsIs ? attrs.href : `${this.opdsRoot}${attrs.href || ''}`),
  51. rel: attrs.rel || 'subsection',
  52. type: 'application/atom+xml;profile=opds-catalog;kind=acquisition',
  53. });
  54. }
  55. downLink(attrs) {
  56. if (!attrs.href)
  57. throw new Error('downLink: no href');
  58. if (!attrs.type)
  59. throw new Error('downLink: no type');
  60. return this.makeLink({
  61. href: attrs.href,
  62. rel: 'http://opds-spec.org/acquisition',
  63. type: attrs.type,
  64. });
  65. }
  66. imgLink(attrs) {
  67. if (!attrs.href)
  68. throw new Error('imgLink: no href');
  69. return this.makeLink({
  70. href: attrs.href,
  71. rel: `http://opds-spec.org/image${attrs.thumb ? '/thumbnail' : ''}`,
  72. type: attrs.type || 'image/jpeg',
  73. });
  74. }
  75. baseLinks(req, selfAcq = false) {
  76. const result = [
  77. this.makeLink({href: `${this.opdsRoot}/opensearch`, rel: 'search', type: 'application/opensearchdescription+xml'}),
  78. this.makeLink({href: `${this.opdsRoot}/search?term={searchTerms}`, rel: 'search', type: 'application/atom+xml'}),
  79. this.navLink({rel: 'start'}),
  80. ];
  81. if (selfAcq) {
  82. result.push(this.acqLink({rel: 'self', href: req.originalUrl, hrefAsIs: true}));
  83. } else {
  84. result.push(this.navLink({rel: 'self', href: req.originalUrl, hrefAsIs: true}));
  85. }
  86. return result;
  87. }
  88. makeBody(content, req) {
  89. const base = this.makeEntry({id: this.id, title: this.title});
  90. base['*ATTRS'] = {
  91. 'xmlns': 'http://www.w3.org/2005/Atom',
  92. 'xmlns:dc': 'http://purl.org/dc/terms/',
  93. 'xmlns:opds': 'http://opds-spec.org/2010/catalog',
  94. };
  95. if (!content.link)
  96. base.link = this.baseLinks(req);
  97. const xml = new XmlParser();
  98. const xmlObject = {};
  99. xmlObject[this.rootTag] = Object.assign(base, content);
  100. xml.fromObject(xmlObject);
  101. return xml.toString({format: true});
  102. }
  103. async body() {
  104. throw new Error('Body not implemented');
  105. }
  106. // -- stuff -------------------------------------------
  107. async search(from, query) {
  108. const result = [];
  109. const queryRes = await this.webWorker.search(from, query);
  110. for (const row of queryRes.found) {
  111. const rec = {
  112. id: row.id,
  113. title: (row[from] || 'Без автора'),
  114. q: `=${encodeURIComponent(row[from])}`,
  115. };
  116. result.push(rec);
  117. }
  118. return result;
  119. }
  120. async opdsQuery(from, query, otherTitle = '[Другие]', prevLen = 0) {
  121. const queryRes = await this.webWorker.opdsQuery(from, query);
  122. let count = 0;
  123. for (const row of queryRes.found)
  124. count += row.count;
  125. const others = [];
  126. let result = [];
  127. if (count <= 50) {
  128. //конец навигации
  129. return await this.search(from, query);
  130. } else {
  131. let len = 0;
  132. for (const row of queryRes.found) {
  133. const value = row.value;
  134. len += value.length;
  135. let rec;
  136. if (row.count == 1) {
  137. rec = {
  138. id: row.id,
  139. title: row.name,
  140. q: `=${encodeURIComponent(row.name)}`,
  141. };
  142. } else {
  143. rec = {
  144. id: row.id,
  145. title: `${value.toUpperCase().replace(/ /g, spaceChar)}~`,
  146. q: encodeURIComponent(value),
  147. };
  148. }
  149. if (query.depth > 1 || enru.has(value[0])) {
  150. result.push(rec);
  151. } else {
  152. others.push(rec);
  153. }
  154. }
  155. if (query[from] && query.depth > 1 && result.length < 10 && len > prevLen) {
  156. //рекурсия, с увеличением глубины, для облегчения навигации
  157. const newQuery = _.cloneDeep(query);
  158. newQuery.depth++;
  159. return await this.opdsQuery(from, newQuery, otherTitle, len);
  160. }
  161. }
  162. if (!query.others && others.length)
  163. result.unshift({id: 'other', title: otherTitle, q: '___others'});
  164. return (!query.others ? result : others);
  165. }
  166. //скопировано из BaseList.js, часть функционала не используется
  167. filterBooks(books, query) {
  168. const s = query;
  169. const splitAuthor = (author) => {
  170. if (!author) {
  171. author = emptyFieldValue;
  172. }
  173. const result = author.split(',');
  174. if (result.length > 1)
  175. result.push(author);
  176. return result;
  177. };
  178. const filterBySearch = (bookValue, searchValue) => {
  179. if (!searchValue)
  180. return true;
  181. if (!bookValue)
  182. bookValue = emptyFieldValue;
  183. bookValue = bookValue.toLowerCase();
  184. searchValue = searchValue.toLowerCase();
  185. //особая обработка префиксов
  186. if (searchValue[0] == '=') {
  187. searchValue = searchValue.substring(1);
  188. return bookValue.localeCompare(searchValue) == 0;
  189. } else if (searchValue[0] == '*') {
  190. searchValue = searchValue.substring(1);
  191. return bookValue !== emptyFieldValue && bookValue.indexOf(searchValue) >= 0;
  192. } else if (searchValue[0] == '#') {
  193. searchValue = searchValue.substring(1);
  194. return !bookValue || (bookValue !== emptyFieldValue && !enru.has(bookValue[0]) && bookValue.indexOf(searchValue) >= 0);
  195. } else {
  196. //where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
  197. return bookValue.localeCompare(searchValue) >= 0 && bookValue.localeCompare(searchValue + maxUtf8Char) <= 0;
  198. }
  199. };
  200. return books.filter((book) => {
  201. //author
  202. let authorFound = false;
  203. const authors = splitAuthor(book.author);
  204. for (const a of authors) {
  205. if (filterBySearch(a, s.author)) {
  206. authorFound = true;
  207. break;
  208. }
  209. }
  210. //genre
  211. let genreFound = !s.genre;
  212. if (!genreFound) {
  213. const searchGenres = new Set(s.genre.split(','));
  214. const bookGenres = book.genre.split(',');
  215. for (let g of bookGenres) {
  216. if (!g)
  217. g = emptyFieldValue;
  218. if (searchGenres.has(g)) {
  219. genreFound = true;
  220. break;
  221. }
  222. }
  223. }
  224. //lang
  225. let langFound = !s.lang;
  226. if (!langFound) {
  227. const searchLang = new Set(s.lang.split(','));
  228. langFound = searchLang.has(book.lang || emptyFieldValue);
  229. }
  230. //date
  231. let dateFound = !s.date;
  232. if (!dateFound) {
  233. const date = this.queryDate(s.date).split(',');
  234. let [from = '0000-00-00', to = '9999-99-99'] = date;
  235. dateFound = (book.date >= from && book.date <= to);
  236. }
  237. //librate
  238. let librateFound = !s.librate;
  239. if (!librateFound) {
  240. const searchLibrate = new Set(s.librate.split(',').map(n => parseInt(n, 10)).filter(n => !isNaN(n)));
  241. librateFound = searchLibrate.has(book.librate);
  242. }
  243. return (this.showDeleted || !book.del)
  244. && authorFound
  245. && filterBySearch(book.series, s.series)
  246. && filterBySearch(book.title, s.title)
  247. && genreFound
  248. && langFound
  249. && dateFound
  250. && librateFound
  251. ;
  252. });
  253. }
  254. bookAuthor(author) {
  255. if (author) {
  256. let a = author.split(',');
  257. return a.slice(0, 3).join(', ') + (a.length > 3 ? ' и др.' : '');
  258. }
  259. return '';
  260. }
  261. async getGenres() {
  262. let result;
  263. if (!this.genres) {
  264. const res = await this.webWorker.getGenreTree();
  265. result = {
  266. genreTree: res.genreTree,
  267. genreMap: new Map(),
  268. genreSection: new Map(),
  269. };
  270. for (const section of result.genreTree) {
  271. result.genreSection.set(section.name, section.value);
  272. for (const g of section.value)
  273. result.genreMap.set(g.value, g.name);
  274. }
  275. this.genres = result;
  276. } else {
  277. result = this.genres;
  278. }
  279. return result;
  280. }
  281. }
  282. module.exports = BasePage;