BasePage.js 12 KB

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