BasePage.js 10 KB

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