BasePage.js 11 KB

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