BasePage.js 11 KB

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