BasePage.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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: 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. if (count <= query.limit)
  118. return await this.search(from, query);
  119. const result = [];
  120. const others = [];
  121. const names = new Set();
  122. for (const row of queryRes.found) {
  123. const name = row.name.toUpperCase();
  124. if (!names.has(name)) {
  125. const rec = {
  126. id: row.id,
  127. title: name.replace(/ /g, spaceChar),
  128. q: encodeURIComponent(row.name.toLowerCase()),
  129. count: row.count,
  130. };
  131. if (query.depth > 1 || enru.has(row.name[0].toLowerCase())) {
  132. result.push(rec);
  133. } else {
  134. others.push(rec);
  135. }
  136. names.add(name);
  137. }
  138. }
  139. if (query.depth > 1 && result.length == 1 && query[from]) {
  140. const newQuery = _.cloneDeep(query);
  141. newQuery[from] = decodeURIComponent(result[0].q);
  142. if (newQuery[from].length >= query.depth) {
  143. newQuery.depth = newQuery[from].length + 1;
  144. return await this.opdsQuery(from, newQuery);
  145. }
  146. }
  147. if (!query.others && query.depth == 1)
  148. result.push({id: 'other', title: 'Все остальные', q: '___others'});
  149. return (!query.others ? result : others);
  150. }
  151. //скопировано из BaseList.js, часть функционала не используется
  152. filterBooks(books, query) {
  153. const s = query;
  154. const splitAuthor = (author) => {
  155. if (!author) {
  156. author = emptyFieldValue;
  157. }
  158. const result = author.split(',');
  159. if (result.length > 1)
  160. result.push(author);
  161. return result;
  162. };
  163. const filterBySearch = (bookValue, searchValue) => {
  164. if (!searchValue)
  165. return true;
  166. if (!bookValue)
  167. bookValue = emptyFieldValue;
  168. bookValue = bookValue.toLowerCase();
  169. searchValue = searchValue.toLowerCase();
  170. //особая обработка префиксов
  171. if (searchValue[0] == '=') {
  172. searchValue = searchValue.substring(1);
  173. return bookValue.localeCompare(searchValue) == 0;
  174. } else if (searchValue[0] == '*') {
  175. searchValue = searchValue.substring(1);
  176. return bookValue !== emptyFieldValue && bookValue.indexOf(searchValue) >= 0;
  177. } else if (searchValue[0] == '#') {
  178. searchValue = searchValue.substring(1);
  179. return !bookValue || (bookValue !== emptyFieldValue && !enru.has(bookValue[0]) && bookValue.indexOf(searchValue) >= 0);
  180. } else {
  181. //where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
  182. return bookValue.localeCompare(searchValue) >= 0 && bookValue.localeCompare(searchValue + maxUtf8Char) <= 0;
  183. }
  184. };
  185. return books.filter((book) => {
  186. //author
  187. let authorFound = false;
  188. const authors = splitAuthor(book.author);
  189. for (const a of authors) {
  190. if (filterBySearch(a, s.author)) {
  191. authorFound = true;
  192. break;
  193. }
  194. }
  195. //genre
  196. let genreFound = !s.genre;
  197. if (!genreFound) {
  198. const searchGenres = new Set(s.genre.split(','));
  199. const bookGenres = book.genre.split(',');
  200. for (let g of bookGenres) {
  201. if (!g)
  202. g = emptyFieldValue;
  203. if (searchGenres.has(g)) {
  204. genreFound = true;
  205. break;
  206. }
  207. }
  208. }
  209. //lang
  210. let langFound = !s.lang;
  211. if (!langFound) {
  212. const searchLang = new Set(s.lang.split(','));
  213. langFound = searchLang.has(book.lang || emptyFieldValue);
  214. }
  215. //date
  216. let dateFound = !s.date;
  217. if (!dateFound) {
  218. const date = this.queryDate(s.date).split(',');
  219. let [from = '0000-00-00', to = '9999-99-99'] = date;
  220. dateFound = (book.date >= from && book.date <= to);
  221. }
  222. //librate
  223. let librateFound = !s.librate;
  224. if (!librateFound) {
  225. const searchLibrate = new Set(s.librate.split(',').map(n => parseInt(n, 10)).filter(n => !isNaN(n)));
  226. librateFound = searchLibrate.has(book.librate);
  227. }
  228. return (this.showDeleted || !book.del)
  229. && authorFound
  230. && filterBySearch(book.series, s.series)
  231. && filterBySearch(book.title, s.title)
  232. && genreFound
  233. && langFound
  234. && dateFound
  235. && librateFound
  236. ;
  237. });
  238. }
  239. }
  240. module.exports = BasePage;