BasePage.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. const ruOnly = new Set(ruAlphabet.split(''));
  13. class BasePage {
  14. constructor(config) {
  15. this.config = config;
  16. this.webWorker = new WebWorker(config);
  17. this.rootTag = 'feed';
  18. this.opdsRoot = config.opdsRoot;
  19. this.showDeleted = false;
  20. }
  21. escape(s) {
  22. //костыль для koreader, не понимает hex-экранирование вида '
  23. return he.escape(s).replace(/'/g, ''').replace(/`/g, '`');
  24. }
  25. makeEntry(entry = {}) {
  26. if (!entry.id)
  27. throw new Error('makeEntry: no id');
  28. if (!entry.title)
  29. throw new Error('makeEntry: no title');
  30. entry.title = this.escape(entry.title);
  31. const result = {
  32. updated: (new Date()).toISOString().substring(0, 19) + 'Z',
  33. };
  34. return Object.assign(result, entry);
  35. }
  36. myEntry() {
  37. return this.makeEntry({
  38. id: this.id,
  39. title: this.title,
  40. link: this.navLink({href: `/${this.id}`}),
  41. });
  42. }
  43. makeLink(attrs) {
  44. attrs.href = this.escape(attrs.href);
  45. return {'*ATTRS': attrs};
  46. }
  47. navLink(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=navigation',
  52. });
  53. }
  54. acqLink(attrs) {
  55. return this.makeLink({
  56. href: (attrs.hrefAsIs ? attrs.href : `${this.opdsRoot}${attrs.href || ''}`),
  57. rel: attrs.rel || 'subsection',
  58. type: 'application/atom+xml;profile=opds-catalog;kind=acquisition',
  59. });
  60. }
  61. downLink(attrs) {
  62. if (!attrs.href)
  63. throw new Error('downLink: no href');
  64. if (!attrs.type)
  65. throw new Error('downLink: no type');
  66. return this.makeLink({
  67. href: attrs.href,
  68. rel: 'http://opds-spec.org/acquisition',
  69. type: attrs.type,
  70. });
  71. }
  72. imgLink(attrs) {
  73. if (!attrs.href)
  74. throw new Error('imgLink: no href');
  75. return this.makeLink({
  76. href: attrs.href,
  77. rel: `http://opds-spec.org/image${attrs.thumb ? '/thumbnail' : ''}`,
  78. type: attrs.type || 'image/jpeg',
  79. });
  80. }
  81. baseLinks(req, selfAcq = false) {
  82. const result = [
  83. this.makeLink({href: `${this.opdsRoot}/opensearch`, rel: 'search', type: 'application/opensearchdescription+xml'}),
  84. this.makeLink({href: `${this.opdsRoot}/search?term={searchTerms}`, rel: 'search', type: 'application/atom+xml'}),
  85. this.navLink({rel: 'start'}),
  86. ];
  87. if (selfAcq) {
  88. result.push(this.acqLink({rel: 'self', href: req.originalUrl, hrefAsIs: true}));
  89. } else {
  90. result.push(this.navLink({rel: 'self', href: req.originalUrl, hrefAsIs: true}));
  91. }
  92. return result;
  93. }
  94. makeBody(content, req) {
  95. const base = this.makeEntry({id: this.id, title: this.title});
  96. base['*ATTRS'] = {
  97. 'xmlns': 'http://www.w3.org/2005/Atom',
  98. 'xmlns:dc': 'http://purl.org/dc/terms/',
  99. 'xmlns:opds': 'http://opds-spec.org/2010/catalog',
  100. };
  101. if (!content.link)
  102. base.link = this.baseLinks(req);
  103. const xml = new XmlParser();
  104. const xmlObject = {};
  105. xmlObject[this.rootTag] = Object.assign(base, content);
  106. xml.fromObject(xmlObject);
  107. return xml.toString({format: true});
  108. }
  109. async body() {
  110. throw new Error('Body not implemented');
  111. }
  112. // -- stuff -------------------------------------------
  113. async search(from, query) {
  114. const result = [];
  115. const queryRes = await this.webWorker.search(from, query);
  116. for (const row of queryRes.found) {
  117. const rec = {
  118. id: row.id,
  119. title: (row[from] || 'Без автора'),
  120. q: `=${encodeURIComponent(row[from])}`,
  121. bookCount: row.bookCount,
  122. };
  123. result.push(rec);
  124. }
  125. return result;
  126. }
  127. async opdsQuery(from, query, otherTitle = '[Другие]', prevLen = 0) {
  128. const queryRes = await this.webWorker.opdsQuery(from, query);
  129. let count = 0;
  130. for (const row of queryRes.found)
  131. count += row.count;
  132. const others = [];
  133. let result = [];
  134. if (count <= 50) {
  135. //конец навигации
  136. return await this.search(from, query);
  137. } else {
  138. let len = 0;
  139. const enResult = [];
  140. for (const row of queryRes.found) {
  141. const value = row.value;
  142. len += value.length;
  143. let rec;
  144. if (row.count == 1) {
  145. rec = {
  146. id: row.id,
  147. title: row.name,
  148. q: `=${encodeURIComponent(row.name)}`,
  149. bookCount: row.bookCount,
  150. };
  151. } else {
  152. rec = {
  153. id: row.id,
  154. title: `${value.toUpperCase().replace(/ /g, spaceChar)}~`,
  155. q: encodeURIComponent(value),
  156. count: row.count,
  157. };
  158. }
  159. if (query.depth > 1 || enru.has(value[0]) ) {
  160. //такой костыль из-за проблем с локалями в pkg
  161. //русский язык всегда идет первым!
  162. if (ruOnly.has(value[0]))
  163. result.push(rec)
  164. else
  165. enResult.push(rec);
  166. } else {
  167. others.push(rec);
  168. }
  169. }
  170. result = result.concat(enResult);
  171. if (query[from] && query.depth > 1 && result.length < 10 && len > prevLen) {
  172. //рекурсия, с увеличением глубины, для облегчения навигации
  173. const newQuery = _.cloneDeep(query);
  174. newQuery.depth++;
  175. return await this.opdsQuery(from, newQuery, otherTitle, len);
  176. }
  177. }
  178. if (!query.others && others.length)
  179. result.unshift({id: 'other', title: otherTitle, q: '___others', count: others.length});
  180. return (!query.others ? result : others);
  181. }
  182. //скопировано из BaseList.js, часть функционала не используется
  183. filterBooks(books, query = {}) {
  184. const s = query;
  185. const splitAuthor = (author) => {
  186. if (!author) {
  187. author = emptyFieldValue;
  188. }
  189. const result = author.split(',');
  190. if (result.length > 1)
  191. result.push(author);
  192. return result;
  193. };
  194. const filterBySearch = (bookValue, searchValue) => {
  195. if (!searchValue)
  196. return true;
  197. if (!bookValue)
  198. bookValue = emptyFieldValue;
  199. bookValue = bookValue.toLowerCase();
  200. if (searchValue[0] !== '~')
  201. searchValue = searchValue.toLowerCase();
  202. //особая обработка префиксов
  203. if (searchValue[0] === '=') {
  204. searchValue = searchValue.substring(1);
  205. return bookValue.localeCompare(searchValue) == 0;
  206. } else if (searchValue[0] === '%') {
  207. searchValue = searchValue.substring(1);
  208. const words = searchValue.split(' ').filter(a => a);
  209. if (!words.length)
  210. words.push('');
  211. for (const w of words)
  212. if (bookValue !== emptyFieldValue && bookValue.indexOf(w) >= 0)
  213. return true;
  214. return false;
  215. } else if (searchValue[0] === '*') {
  216. searchValue = searchValue.substring(1);
  217. return bookValue !== emptyFieldValue && bookValue.indexOf(searchValue) >= 0;
  218. } else if (searchValue[0] === '#') {
  219. searchValue = searchValue.substring(1);
  220. if (!bookValue)
  221. return false;
  222. return bookValue !== emptyFieldValue && !enru.has(bookValue[0]) && bookValue.indexOf(searchValue) >= 0;
  223. } else if (searchValue[0] === '~') {//RegExp
  224. searchValue = searchValue.substring(1);
  225. const re = new RegExp(searchValue, 'i');
  226. return re.test(bookValue);
  227. } else {
  228. //where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
  229. return bookValue.localeCompare(searchValue) >= 0 && bookValue.localeCompare(searchValue + maxUtf8Char) <= 0;
  230. }
  231. };
  232. return books.filter((book) => {
  233. //author
  234. let authorFound = false;
  235. const authors = splitAuthor(book.author);
  236. for (const a of authors) {
  237. if (filterBySearch(a, s.author)) {
  238. authorFound = true;
  239. break;
  240. }
  241. }
  242. //genre
  243. let genreFound = !s.genre;
  244. if (!genreFound) {
  245. const searchGenres = new Set(s.genre.split(','));
  246. const bookGenres = book.genre.split(',');
  247. for (let g of bookGenres) {
  248. if (!g)
  249. g = emptyFieldValue;
  250. if (searchGenres.has(g)) {
  251. genreFound = true;
  252. break;
  253. }
  254. }
  255. }
  256. //lang
  257. let langFound = !s.lang;
  258. if (!langFound) {
  259. const searchLang = new Set(s.lang.split(','));
  260. langFound = searchLang.has(book.lang || emptyFieldValue);
  261. }
  262. //date
  263. let dateFound = !s.date;
  264. if (!dateFound) {
  265. const date = this.queryDate(s.date).split(',');
  266. let [from = '0000-00-00', to = '9999-99-99'] = date;
  267. dateFound = (book.date >= from && book.date <= to);
  268. }
  269. //librate
  270. let librateFound = !s.librate;
  271. if (!librateFound) {
  272. const searchLibrate = new Set(s.librate.split(',').map(n => parseInt(n, 10)).filter(n => !isNaN(n)));
  273. librateFound = searchLibrate.has(book.librate);
  274. }
  275. return (this.showDeleted || !book.del)
  276. && authorFound
  277. && filterBySearch(book.series, s.series)
  278. && filterBySearch(book.title, s.title)
  279. && genreFound
  280. && langFound
  281. && dateFound
  282. && librateFound
  283. ;
  284. });
  285. }
  286. bookAuthor(author) {
  287. if (author) {
  288. let a = author.split(',');
  289. return a.slice(0, 3).join(', ') + (a.length > 3 ? ' и др.' : '');
  290. }
  291. return '';
  292. }
  293. async getGenres() {
  294. let result;
  295. if (!this.genres) {
  296. const res = await this.webWorker.getGenreTree();
  297. result = {
  298. genreTree: res.genreTree,
  299. genreMap: new Map(),
  300. genreSection: new Map(),
  301. };
  302. for (const section of result.genreTree) {
  303. result.genreSection.set(section.name, section.value);
  304. for (const g of section.value)
  305. result.genreMap.set(g.value, g.name);
  306. }
  307. this.genres = result;
  308. } else {
  309. result = this.genres;
  310. }
  311. return result;
  312. }
  313. }
  314. module.exports = BasePage;