BasePage.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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) {
  76. return [
  77. this.navLink({rel: 'start'}),
  78. this.navLink({rel: 'self', href: req.originalUrl, hrefAsIs: true}),
  79. ];
  80. }
  81. makeBody(content, req) {
  82. const base = this.makeEntry({id: this.id, title: this.title});
  83. base['*ATTRS'] = {
  84. 'xmlns': 'http://www.w3.org/2005/Atom',
  85. 'xmlns:dc': 'http://purl.org/dc/terms/',
  86. 'xmlns:opds': 'http://opds-spec.org/2010/catalog',
  87. };
  88. if (!content.link)
  89. base.link = this.baseLinks(req);
  90. const xml = new XmlParser();
  91. const xmlObject = {};
  92. xmlObject[this.rootTag] = Object.assign(base, content);
  93. xml.fromObject(xmlObject);
  94. return xml.toString({format: true});
  95. }
  96. async body() {
  97. throw new Error('Body not implemented');
  98. }
  99. // -- stuff -------------------------------------------
  100. async search(from, query) {
  101. const result = [];
  102. const queryRes = await this.webWorker.search(from, query);
  103. for (const row of queryRes.found) {
  104. const rec = {
  105. id: row.id,
  106. title: (row[from] || 'Без автора'),
  107. q: `=${encodeURIComponent(row[from])}`,
  108. };
  109. result.push(rec);
  110. }
  111. return result;
  112. }
  113. async opdsQuery(from, query) {
  114. const queryRes = await this.webWorker.opdsQuery(from, query);
  115. let count = 0;
  116. for (const row of queryRes.found)
  117. count += row.count;
  118. const others = [];
  119. let result = [];
  120. if (count <= query.limit) {
  121. result = await this.search(from, query);
  122. } else {
  123. const names = new Set();
  124. for (const row of queryRes.found) {
  125. const name = row.name.toUpperCase();
  126. if (!names.has(name)) {
  127. const rec = {
  128. id: row.id,
  129. title: name.replace(/ /g, spaceChar),
  130. q: encodeURIComponent(row.name.toLowerCase()),
  131. count: row.count,
  132. };
  133. if (query.depth > 1 || enru.has(row.name[0].toLowerCase())) {
  134. result.push(rec);
  135. } else {
  136. others.push(rec);
  137. }
  138. names.add(name);
  139. }
  140. }
  141. }
  142. if (query.depth > 1 && result.length == 1 && query[from]) {
  143. const newQuery = _.cloneDeep(query);
  144. newQuery[from] = decodeURIComponent(result[0].q);
  145. if (newQuery[from].length >= query.depth) {
  146. newQuery.depth = newQuery[from].length + 1;
  147. return await this.opdsQuery(from, newQuery);
  148. }
  149. }
  150. if (!query.others && others.length)
  151. result.push({id: 'other', title: 'Все остальные', q: '___others'});
  152. return (!query.others ? result : others);
  153. }
  154. //скопировано из BaseList.js, часть функционала не используется
  155. filterBooks(books, query) {
  156. const s = query;
  157. const splitAuthor = (author) => {
  158. if (!author) {
  159. author = emptyFieldValue;
  160. }
  161. const result = author.split(',');
  162. if (result.length > 1)
  163. result.push(author);
  164. return result;
  165. };
  166. const filterBySearch = (bookValue, searchValue) => {
  167. if (!searchValue)
  168. return true;
  169. if (!bookValue)
  170. bookValue = emptyFieldValue;
  171. bookValue = bookValue.toLowerCase();
  172. searchValue = searchValue.toLowerCase();
  173. //особая обработка префиксов
  174. if (searchValue[0] == '=') {
  175. searchValue = searchValue.substring(1);
  176. return bookValue.localeCompare(searchValue) == 0;
  177. } else if (searchValue[0] == '*') {
  178. searchValue = searchValue.substring(1);
  179. return bookValue !== emptyFieldValue && bookValue.indexOf(searchValue) >= 0;
  180. } else if (searchValue[0] == '#') {
  181. searchValue = searchValue.substring(1);
  182. return !bookValue || (bookValue !== emptyFieldValue && !enru.has(bookValue[0]) && bookValue.indexOf(searchValue) >= 0);
  183. } else {
  184. //where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
  185. return bookValue.localeCompare(searchValue) >= 0 && bookValue.localeCompare(searchValue + maxUtf8Char) <= 0;
  186. }
  187. };
  188. return books.filter((book) => {
  189. //author
  190. let authorFound = false;
  191. const authors = splitAuthor(book.author);
  192. for (const a of authors) {
  193. if (filterBySearch(a, s.author)) {
  194. authorFound = true;
  195. break;
  196. }
  197. }
  198. //genre
  199. let genreFound = !s.genre;
  200. if (!genreFound) {
  201. const searchGenres = new Set(s.genre.split(','));
  202. const bookGenres = book.genre.split(',');
  203. for (let g of bookGenres) {
  204. if (!g)
  205. g = emptyFieldValue;
  206. if (searchGenres.has(g)) {
  207. genreFound = true;
  208. break;
  209. }
  210. }
  211. }
  212. //lang
  213. let langFound = !s.lang;
  214. if (!langFound) {
  215. const searchLang = new Set(s.lang.split(','));
  216. langFound = searchLang.has(book.lang || emptyFieldValue);
  217. }
  218. //date
  219. let dateFound = !s.date;
  220. if (!dateFound) {
  221. const date = this.queryDate(s.date).split(',');
  222. let [from = '0000-00-00', to = '9999-99-99'] = date;
  223. dateFound = (book.date >= from && book.date <= to);
  224. }
  225. //librate
  226. let librateFound = !s.librate;
  227. if (!librateFound) {
  228. const searchLibrate = new Set(s.librate.split(',').map(n => parseInt(n, 10)).filter(n => !isNaN(n)));
  229. librateFound = searchLibrate.has(book.librate);
  230. }
  231. return (this.showDeleted || !book.del)
  232. && authorFound
  233. && filterBySearch(book.series, s.series)
  234. && filterBySearch(book.title, s.title)
  235. && genreFound
  236. && langFound
  237. && dateFound
  238. && librateFound
  239. ;
  240. });
  241. }
  242. async getGenres() {
  243. let result;
  244. if (!this.genres) {
  245. const res = await this.webWorker.getGenreTree();
  246. result = {
  247. genreTree: res.genreTree,
  248. genreMap: new Map(),
  249. };
  250. for (const section of result.genreTree) {
  251. for (const g of section.value)
  252. result.genreMap.set(g.value, g.name);
  253. }
  254. this.genres = result;
  255. } else {
  256. result = this.genres;
  257. }
  258. return result;
  259. }
  260. }
  261. module.exports = BasePage;