BasePage.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. bookCount: row.bookCount,
  116. };
  117. result.push(rec);
  118. }
  119. return result;
  120. }
  121. async opdsQuery(from, query, otherTitle = '[Другие]', prevLen = 0) {
  122. const queryRes = await this.webWorker.opdsQuery(from, query);
  123. let count = 0;
  124. for (const row of queryRes.found)
  125. count += row.count;
  126. const others = [];
  127. let result = [];
  128. if (count <= 50) {
  129. //конец навигации
  130. return await this.search(from, query);
  131. } else {
  132. let len = 0;
  133. for (const row of queryRes.found) {
  134. const value = row.value;
  135. len += value.length;
  136. let rec;
  137. if (row.count == 1) {
  138. rec = {
  139. id: row.id,
  140. title: row.name,
  141. q: `=${encodeURIComponent(row.name)}`,
  142. bookCount: row.bookCount,
  143. };
  144. } else {
  145. rec = {
  146. id: row.id,
  147. title: `${value.toUpperCase().replace(/ /g, spaceChar)}~`,
  148. q: encodeURIComponent(value),
  149. count: row.count,
  150. };
  151. }
  152. if (query.depth > 1 || enru.has(value[0])) {
  153. result.push(rec);
  154. } else {
  155. others.push(rec);
  156. }
  157. }
  158. if (query[from] && query.depth > 1 && result.length < 10 && len > prevLen) {
  159. //рекурсия, с увеличением глубины, для облегчения навигации
  160. const newQuery = _.cloneDeep(query);
  161. newQuery.depth++;
  162. return await this.opdsQuery(from, newQuery, otherTitle, len);
  163. }
  164. }
  165. if (!query.others && others.length)
  166. result.unshift({id: 'other', title: otherTitle, q: '___others', count: others.length});
  167. return (!query.others ? result : others);
  168. }
  169. //скопировано из BaseList.js, часть функционала не используется
  170. filterBooks(books, query) {
  171. const s = query;
  172. const splitAuthor = (author) => {
  173. if (!author) {
  174. author = emptyFieldValue;
  175. }
  176. const result = author.split(',');
  177. if (result.length > 1)
  178. result.push(author);
  179. return result;
  180. };
  181. const filterBySearch = (bookValue, searchValue) => {
  182. if (!searchValue)
  183. return true;
  184. if (!bookValue)
  185. bookValue = emptyFieldValue;
  186. bookValue = bookValue.toLowerCase();
  187. searchValue = searchValue.toLowerCase();
  188. //особая обработка префиксов
  189. if (searchValue[0] == '=') {
  190. searchValue = searchValue.substring(1);
  191. return bookValue.localeCompare(searchValue) == 0;
  192. } else if (searchValue[0] == '*') {
  193. searchValue = searchValue.substring(1);
  194. return bookValue !== emptyFieldValue && bookValue.indexOf(searchValue) >= 0;
  195. } else if (searchValue[0] == '#') {
  196. searchValue = searchValue.substring(1);
  197. return !bookValue || (bookValue !== emptyFieldValue && !enru.has(bookValue[0]) && bookValue.indexOf(searchValue) >= 0);
  198. } else {
  199. //where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
  200. return bookValue.localeCompare(searchValue) >= 0 && bookValue.localeCompare(searchValue + maxUtf8Char) <= 0;
  201. }
  202. };
  203. return books.filter((book) => {
  204. //author
  205. let authorFound = false;
  206. const authors = splitAuthor(book.author);
  207. for (const a of authors) {
  208. if (filterBySearch(a, s.author)) {
  209. authorFound = true;
  210. break;
  211. }
  212. }
  213. //genre
  214. let genreFound = !s.genre;
  215. if (!genreFound) {
  216. const searchGenres = new Set(s.genre.split(','));
  217. const bookGenres = book.genre.split(',');
  218. for (let g of bookGenres) {
  219. if (!g)
  220. g = emptyFieldValue;
  221. if (searchGenres.has(g)) {
  222. genreFound = true;
  223. break;
  224. }
  225. }
  226. }
  227. //lang
  228. let langFound = !s.lang;
  229. if (!langFound) {
  230. const searchLang = new Set(s.lang.split(','));
  231. langFound = searchLang.has(book.lang || emptyFieldValue);
  232. }
  233. //date
  234. let dateFound = !s.date;
  235. if (!dateFound) {
  236. const date = this.queryDate(s.date).split(',');
  237. let [from = '0000-00-00', to = '9999-99-99'] = date;
  238. dateFound = (book.date >= from && book.date <= to);
  239. }
  240. //librate
  241. let librateFound = !s.librate;
  242. if (!librateFound) {
  243. const searchLibrate = new Set(s.librate.split(',').map(n => parseInt(n, 10)).filter(n => !isNaN(n)));
  244. librateFound = searchLibrate.has(book.librate);
  245. }
  246. return (this.showDeleted || !book.del)
  247. && authorFound
  248. && filterBySearch(book.series, s.series)
  249. && filterBySearch(book.title, s.title)
  250. && genreFound
  251. && langFound
  252. && dateFound
  253. && librateFound
  254. ;
  255. });
  256. }
  257. bookAuthor(author) {
  258. if (author) {
  259. let a = author.split(',');
  260. return a.slice(0, 3).join(', ') + (a.length > 3 ? ' и др.' : '');
  261. }
  262. return '';
  263. }
  264. async getGenres() {
  265. let result;
  266. if (!this.genres) {
  267. const res = await this.webWorker.getGenreTree();
  268. result = {
  269. genreTree: res.genreTree,
  270. genreMap: new Map(),
  271. genreSection: new Map(),
  272. };
  273. for (const section of result.genreTree) {
  274. result.genreSection.set(section.name, section.value);
  275. for (const g of section.value)
  276. result.genreMap.set(g.value, g.name);
  277. }
  278. this.genres = result;
  279. } else {
  280. result = this.genres;
  281. }
  282. return result;
  283. }
  284. }
  285. module.exports = BasePage;