BasePage.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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. class BasePage {
  13. constructor(config) {
  14. this.config = config;
  15. this.webWorker = new WebWorker(config);
  16. this.rootTag = 'feed';
  17. this.opdsRoot = config.opdsRoot;
  18. }
  19. makeEntry(entry = {}) {
  20. if (!entry.id)
  21. throw new Error('makeEntry: no id');
  22. if (!entry.title)
  23. throw new Error('makeEntry: no title');
  24. entry.title = he.escape(entry.title);
  25. const result = {
  26. updated: (new Date()).toISOString().substring(0, 19) + 'Z',
  27. };
  28. return Object.assign(result, entry);
  29. }
  30. myEntry() {
  31. return this.makeEntry({
  32. id: this.id,
  33. title: this.title,
  34. link: this.navLink({href: `/${this.id}`}),
  35. });
  36. }
  37. makeLink(attrs) {
  38. return {'*ATTRS': attrs};
  39. }
  40. navLink(attrs) {
  41. return this.makeLink({
  42. href: this.opdsRoot + (attrs.href || ''),
  43. rel: attrs.rel || 'subsection',
  44. type: 'application/atom+xml; profile=opds-catalog; kind=navigation',
  45. });
  46. }
  47. acqLink(attrs) {
  48. if (!attrs.href)
  49. throw new Error('acqLink: no href');
  50. if (!attrs.type)
  51. throw new Error('acqLink: no type');
  52. return this.makeLink({
  53. href: attrs.href,
  54. rel: 'http://opds-spec.org/acquisition/open-access',
  55. type: attrs.type,
  56. });
  57. }
  58. imgLink(attrs) {
  59. if (!attrs.href)
  60. throw new Error('acqLink: no href');
  61. return this.makeLink({
  62. href: attrs.href,
  63. rel: `http://opds-spec.org/image${attrs.thumb ? '/thumbnail' : ''}`,
  64. type: attrs.type || 'image/jpeg',
  65. });
  66. }
  67. baseLinks() {
  68. return [
  69. this.navLink({rel: 'start'}),
  70. this.navLink({rel: 'self', href: (this.id ? `/${this.id}` : '')}),
  71. ];
  72. }
  73. makeBody(content) {
  74. const base = this.makeEntry({id: this.id, title: this.title});
  75. base['*ATTRS'] = {
  76. 'xmlns': 'http://www.w3.org/2005/Atom',
  77. 'xmlns:dc': 'http://purl.org/dc/terms/',
  78. 'xmlns:opds': 'http://opds-spec.org/2010/catalog',
  79. };
  80. if (!content.link)
  81. base.link = this.baseLinks();
  82. const xml = new XmlParser();
  83. const xmlObject = {};
  84. xmlObject[this.rootTag] = Object.assign(base, content);
  85. xml.fromObject(xmlObject);
  86. return xml.toString({format: true});
  87. }
  88. async body() {
  89. throw new Error('Body not implemented');
  90. }
  91. // -- stuff -------------------------------------------
  92. async search(from, query) {
  93. const result = [];
  94. const queryRes = await this.webWorker.search(from, query);
  95. for (const row of queryRes.found) {
  96. const rec = {
  97. id: row.id,
  98. title: (row[from] || 'Без автора'),
  99. q: `=${encodeURIComponent(row[from])}`,
  100. };
  101. result.push(rec);
  102. }
  103. return result;
  104. }
  105. async opdsQuery(from, query) {
  106. const queryRes = await this.webWorker.opdsQuery(from, query);
  107. let count = 0;
  108. for (const row of queryRes.found)
  109. count += row.count;
  110. if (count <= query.limit)
  111. return await this.search(from, query);
  112. const result = [];
  113. const others = [];
  114. const names = new Set();
  115. for (const row of queryRes.found) {
  116. const name = row.name.toUpperCase();
  117. if (!names.has(name)) {
  118. const rec = {
  119. id: row.id,
  120. title: name.replace(/ /g, spaceChar),
  121. q: encodeURIComponent(row.name.toLowerCase()),
  122. count: row.count,
  123. };
  124. if (query.depth > 1 || enru.has(row.name[0].toLowerCase())) {
  125. result.push(rec);
  126. } else {
  127. others.push(rec);
  128. }
  129. names.add(name);
  130. }
  131. }
  132. if (query.depth > 1 && result.length == 1 && query[from]) {
  133. const newQuery = _.cloneDeep(query);
  134. newQuery[from] = decodeURIComponent(result[0].q);
  135. if (newQuery[from].length >= query.depth) {
  136. newQuery.depth = newQuery[from].length + 1;
  137. return await this.opdsQuery(from, newQuery);
  138. }
  139. }
  140. if (!query.others && query.depth == 1)
  141. result.push({id: 'other', title: 'Все остальные', q: '___others'});
  142. return (!query.others ? result : others);
  143. }
  144. //скопировано из BaseList.js, часть функционала не используется
  145. filterBooks(books, query) {
  146. const s = query;
  147. const splitAuthor = (author) => {
  148. if (!author) {
  149. author = emptyFieldValue;
  150. }
  151. const result = author.split(',');
  152. if (result.length > 1)
  153. result.push(author);
  154. return result;
  155. };
  156. const filterBySearch = (bookValue, searchValue) => {
  157. if (!searchValue)
  158. return true;
  159. if (!bookValue)
  160. bookValue = emptyFieldValue;
  161. bookValue = bookValue.toLowerCase();
  162. searchValue = searchValue.toLowerCase();
  163. //особая обработка префиксов
  164. if (searchValue[0] == '=') {
  165. searchValue = searchValue.substring(1);
  166. return bookValue.localeCompare(searchValue) == 0;
  167. } else if (searchValue[0] == '*') {
  168. searchValue = searchValue.substring(1);
  169. return bookValue !== emptyFieldValue && bookValue.indexOf(searchValue) >= 0;
  170. } else if (searchValue[0] == '#') {
  171. searchValue = searchValue.substring(1);
  172. return !bookValue || (bookValue !== emptyFieldValue && !enru.has(bookValue[0]) && bookValue.indexOf(searchValue) >= 0);
  173. } else {
  174. //where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
  175. return bookValue.localeCompare(searchValue) >= 0 && bookValue.localeCompare(searchValue + maxUtf8Char) <= 0;
  176. }
  177. };
  178. return books.filter((book) => {
  179. //author
  180. let authorFound = false;
  181. const authors = splitAuthor(book.author);
  182. for (const a of authors) {
  183. if (filterBySearch(a, s.author)) {
  184. authorFound = true;
  185. break;
  186. }
  187. }
  188. //genre
  189. let genreFound = !s.genre;
  190. if (!genreFound) {
  191. const searchGenres = new Set(s.genre.split(','));
  192. const bookGenres = book.genre.split(',');
  193. for (let g of bookGenres) {
  194. if (!g)
  195. g = emptyFieldValue;
  196. if (searchGenres.has(g)) {
  197. genreFound = true;
  198. break;
  199. }
  200. }
  201. }
  202. //lang
  203. let langFound = !s.lang;
  204. if (!langFound) {
  205. const searchLang = new Set(s.lang.split(','));
  206. langFound = searchLang.has(book.lang || emptyFieldValue);
  207. }
  208. //date
  209. let dateFound = !s.date;
  210. if (!dateFound) {
  211. const date = this.queryDate(s.date).split(',');
  212. let [from = '0000-00-00', to = '9999-99-99'] = date;
  213. dateFound = (book.date >= from && book.date <= to);
  214. }
  215. //librate
  216. let librateFound = !s.librate;
  217. if (!librateFound) {
  218. const searchLibrate = new Set(s.librate.split(',').map(n => parseInt(n, 10)).filter(n => !isNaN(n)));
  219. librateFound = searchLibrate.has(book.librate);
  220. }
  221. return (this.showDeleted || !book.del)
  222. && authorFound
  223. && filterBySearch(book.series, s.series)
  224. && filterBySearch(book.title, s.title)
  225. && genreFound
  226. && langFound
  227. && dateFound
  228. && librateFound
  229. ;
  230. });
  231. }
  232. }
  233. module.exports = BasePage;