BasePage.js 9.7 KB

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