BasePage.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. searchValue = searchValue.toLowerCase();
  201. //особая обработка префиксов
  202. if (searchValue[0] == '=') {
  203. searchValue = searchValue.substring(1);
  204. return bookValue.localeCompare(searchValue) == 0;
  205. } else if (searchValue[0] == '*') {
  206. searchValue = searchValue.substring(1);
  207. return bookValue !== emptyFieldValue && bookValue.indexOf(searchValue) >= 0;
  208. } else if (searchValue[0] == '#') {
  209. searchValue = searchValue.substring(1);
  210. if (!bookValue)
  211. return false;
  212. return bookValue !== emptyFieldValue && !enru.has(bookValue[0]) && bookValue.indexOf(searchValue) >= 0;
  213. } else if (searchValue[0] == '~') {//RegExp
  214. searchValue = searchValue.substring(1);
  215. const re = new RegExp(searchValue, 'i');
  216. return re.test(bookValue);
  217. } else {
  218. //where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
  219. return bookValue.localeCompare(searchValue) >= 0 && bookValue.localeCompare(searchValue + maxUtf8Char) <= 0;
  220. }
  221. };
  222. return books.filter((book) => {
  223. //author
  224. let authorFound = false;
  225. const authors = splitAuthor(book.author);
  226. for (const a of authors) {
  227. if (filterBySearch(a, s.author)) {
  228. authorFound = true;
  229. break;
  230. }
  231. }
  232. //genre
  233. let genreFound = !s.genre;
  234. if (!genreFound) {
  235. const searchGenres = new Set(s.genre.split(','));
  236. const bookGenres = book.genre.split(',');
  237. for (let g of bookGenres) {
  238. if (!g)
  239. g = emptyFieldValue;
  240. if (searchGenres.has(g)) {
  241. genreFound = true;
  242. break;
  243. }
  244. }
  245. }
  246. //lang
  247. let langFound = !s.lang;
  248. if (!langFound) {
  249. const searchLang = new Set(s.lang.split(','));
  250. langFound = searchLang.has(book.lang || emptyFieldValue);
  251. }
  252. //date
  253. let dateFound = !s.date;
  254. if (!dateFound) {
  255. const date = this.queryDate(s.date).split(',');
  256. let [from = '0000-00-00', to = '9999-99-99'] = date;
  257. dateFound = (book.date >= from && book.date <= to);
  258. }
  259. //librate
  260. let librateFound = !s.librate;
  261. if (!librateFound) {
  262. const searchLibrate = new Set(s.librate.split(',').map(n => parseInt(n, 10)).filter(n => !isNaN(n)));
  263. librateFound = searchLibrate.has(book.librate);
  264. }
  265. return (this.showDeleted || !book.del)
  266. && authorFound
  267. && filterBySearch(book.series, s.series)
  268. && filterBySearch(book.title, s.title)
  269. && genreFound
  270. && langFound
  271. && dateFound
  272. && librateFound
  273. ;
  274. });
  275. }
  276. bookAuthor(author) {
  277. if (author) {
  278. let a = author.split(',');
  279. return a.slice(0, 3).join(', ') + (a.length > 3 ? ' и др.' : '');
  280. }
  281. return '';
  282. }
  283. async getGenres() {
  284. let result;
  285. if (!this.genres) {
  286. const res = await this.webWorker.getGenreTree();
  287. result = {
  288. genreTree: res.genreTree,
  289. genreMap: new Map(),
  290. genreSection: new Map(),
  291. };
  292. for (const section of result.genreTree) {
  293. result.genreSection.set(section.name, section.value);
  294. for (const g of section.value)
  295. result.genreMap.set(g.value, g.name);
  296. }
  297. this.genres = result;
  298. } else {
  299. result = this.genres;
  300. }
  301. return result;
  302. }
  303. }
  304. module.exports = BasePage;