Compare commits
112 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d52a9fd52 | ||
|
|
08287deaa4 | ||
|
|
c43c5520a4 | ||
|
|
4e2b7886a9 | ||
|
|
05744e8472 | ||
|
|
9126973378 | ||
|
|
018e1069d5 | ||
|
|
92617b3263 | ||
|
|
d0172f11c3 | ||
|
|
638126b5f3 | ||
|
|
ef938bff77 | ||
|
|
50597f8d3a | ||
|
|
b84e26fa3b | ||
|
|
d8ac700ee7 | ||
|
|
5519e23e02 | ||
|
|
4d6da6a9b7 | ||
|
|
1385babea5 | ||
|
|
ed916e1b28 | ||
|
|
97c18a290a | ||
|
|
e53bb11566 | ||
|
|
1ecc19b8b5 | ||
|
|
7ef1520756 | ||
|
|
5a5ea147b1 | ||
|
|
5a15241cc1 | ||
|
|
4a8035949c | ||
|
|
ab57dbfbe7 | ||
|
|
302dd8eeb4 | ||
|
|
e983db84ba | ||
|
|
51c026e9d2 | ||
|
|
435b425ab6 | ||
|
|
0981a36fb5 | ||
|
|
3292f35310 | ||
|
|
f85c126d03 | ||
|
|
2cc753f6d0 | ||
|
|
cb26aff4b9 | ||
|
|
ac1be219fb | ||
|
|
b34d915597 | ||
|
|
a2db43bbe1 | ||
|
|
024a5f9b8c | ||
|
|
070c667605 | ||
|
|
6e2ff07a48 | ||
|
|
46f40d29be | ||
|
|
71f2674b38 | ||
|
|
bd2551559b | ||
|
|
85bf7296ef | ||
|
|
64254ccf5f | ||
|
|
48b973d384 | ||
|
|
c17b696d61 | ||
|
|
8837fea654 | ||
|
|
7fe0bcee2f | ||
|
|
b8589ea026 | ||
|
|
de838ebb4d | ||
|
|
74af82f34f | ||
|
|
307b78f60d | ||
|
|
8ed52f62b8 | ||
|
|
93fcbb9084 | ||
|
|
2b017a2ae3 | ||
|
|
d32375d4e4 | ||
|
|
a965032b08 | ||
|
|
3a26a12807 | ||
|
|
0867e4020f | ||
|
|
f132cdfbdf | ||
|
|
4927cdf6ce | ||
|
|
cff6e5aab9 | ||
|
|
85007f3e91 | ||
|
|
5b6ef8202f | ||
|
|
0c07f638f9 | ||
|
|
5faa6a1e8f | ||
|
|
51b325d63c | ||
|
|
a4715be0ed | ||
|
|
c2c88cb397 | ||
|
|
a72a37ddfa | ||
|
|
512d9fc8cb | ||
|
|
6284154a39 | ||
|
|
d78991dc03 | ||
|
|
287edf3d12 | ||
|
|
7b6bd25189 | ||
|
|
b3ed9ea89c | ||
|
|
de9471c2d5 | ||
|
|
4ad5aad64e | ||
|
|
28d68ca569 | ||
|
|
db34b954c5 | ||
|
|
a22ec367a5 | ||
|
|
fd66034ba9 | ||
|
|
c2e1d062e8 | ||
|
|
17e42d7088 | ||
|
|
6858acd0b1 | ||
|
|
ea0845880b | ||
|
|
a9cc87f64f | ||
|
|
7bbe90a968 | ||
|
|
d970863a17 | ||
|
|
10b10f695a | ||
|
|
8272f48cba | ||
|
|
409befce5e | ||
|
|
105680e38a | ||
|
|
0ddf18ec26 | ||
|
|
46b69059e8 | ||
|
|
09a4e70bb0 | ||
|
|
cf5de3ca89 | ||
|
|
8134527a7d | ||
|
|
33aea2a194 | ||
|
|
772ea3ca0c | ||
|
|
5c77b1711b | ||
|
|
602fe39c00 | ||
|
|
6160afa7f0 | ||
|
|
68532e361e | ||
|
|
e0a315f77c | ||
|
|
bcce467bcb | ||
|
|
f5cff52588 | ||
|
|
3472ca7844 | ||
|
|
5372507acd | ||
|
|
01fb6479f3 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,5 +1,4 @@
|
|||||||
/node_modules
|
/node_modules
|
||||||
/server/.inpx-web*
|
/server/.inpx-web*
|
||||||
/server/inpx-web-filter.json
|
|
||||||
/dist
|
/dist
|
||||||
dev*.sh
|
dev*.sh
|
||||||
30
CHANGELOG.md
30
CHANGELOG.md
@@ -1,3 +1,33 @@
|
|||||||
|
1.5.2 / 2023-02-05
|
||||||
|
|
||||||
|
- Исправление проблемы чтения каталога opds для koreader
|
||||||
|
|
||||||
|
1.5.1 / 2023-01-28
|
||||||
|
------------------
|
||||||
|
|
||||||
|
- Настройки веб-интерфейса и опции командной строки "--lib-dir", "--inpx" вынесены в конфиг (#6)
|
||||||
|
- Уменьшена длина имени файла при скачивании (#7)
|
||||||
|
- OPDS: добавлен раздел "Жанры", в поиск добавлен раздел "Поиск книг в жанре" (#9)
|
||||||
|
- Исправление проблем скроллинга панели инструментов (#12)
|
||||||
|
- Улучшено отображение веб-интерфейса на мобильных устройствах
|
||||||
|
|
||||||
|
1.4.1 / 2022-12-21
|
||||||
|
------------------
|
||||||
|
|
||||||
|
- Добавлена возможность поиска по регулярному выражению (префикс "~")
|
||||||
|
- Заплатка для исправления (#10)
|
||||||
|
|
||||||
|
1.4.0 / 2022-12-07
|
||||||
|
------------------
|
||||||
|
|
||||||
|
- Добавлена возможность расширенного поиска (раздел "</>"). Поиск не оптимизирован и может сильно нагружать сервер.
|
||||||
|
Отключить можно в конфиге, параметр extendedSearch
|
||||||
|
- Улучшение поддержки reverse-proxy, в конфиг добавлены параметры server.root и opds.root для встраивания inpx-web в уже существующий веб-сервер
|
||||||
|
- В настройки веб-интерфейса добавлена опция "Скачивать книги в виде zip-архива"
|
||||||
|
- Исправлен баг "Android-читалки не очень хорошо работают с OPDS" (#4)
|
||||||
|
- Добавлена сборка релизов для Linux arm64
|
||||||
|
- В readme добавлена ссылка для донатов: [отблагодарить автора проекта](https://donatty.com/liberama)
|
||||||
|
|
||||||
1.3.3 / 2022-11-28
|
1.3.3 / 2022-11-28
|
||||||
------------------
|
------------------
|
||||||
|
|
||||||
|
|||||||
47
README.md
47
README.md
@@ -19,6 +19,8 @@ OPDS-сервер доступен по адресу [http://127.0.0.1:12380/opd
|
|||||||
Для указания местоположения .inpx-файла или папки с файлами библиотеки, воспользуйтесь [параметрами командной строки](#cli).
|
Для указания местоположения .inpx-файла или папки с файлами библиотеки, воспользуйтесь [параметрами командной строки](#cli).
|
||||||
Дополнительные параметры сервера настраиваются в [конфигурационном файле](#config).
|
Дополнительные параметры сервера настраиваются в [конфигурационном файле](#config).
|
||||||
|
|
||||||
|
[Отблагодарить автора проекта](https://donatty.com/liberama)
|
||||||
|
|
||||||
##
|
##
|
||||||
* [Возможности программы](#capabilities)
|
* [Возможности программы](#capabilities)
|
||||||
* [Использование](#usage)
|
* [Использование](#usage)
|
||||||
@@ -78,6 +80,14 @@ Options:
|
|||||||
При первом запуске в рабочей директории будет создан конфигурационный файл `config.json`:
|
При первом запуске в рабочей директории будет создан конфигурационный файл `config.json`:
|
||||||
```js
|
```js
|
||||||
{
|
{
|
||||||
|
// директория библиотеки (с zip-архивами), аналог параметра командной строки --lib-dir
|
||||||
|
// пустая строка: использовать значение по умолчанию - директорию файла приложения
|
||||||
|
"libDir": "",
|
||||||
|
|
||||||
|
// путь к файлу .inpx, аналог параметра командной строки --inpx
|
||||||
|
// пустая строка: использовать значение по умолчанию - inpx-файл, что найдется в директории библиотеки
|
||||||
|
"inpx": "",
|
||||||
|
|
||||||
// пароль для ограничения доступа к веб-интерфейсу сервера
|
// пароль для ограничения доступа к веб-интерфейсу сервера
|
||||||
// пустое значение - доступ без ограничений
|
// пустое значение - доступ без ограничений
|
||||||
"accessPassword": "",
|
"accessPassword": "",
|
||||||
@@ -87,6 +97,11 @@ Options:
|
|||||||
// 0 - отключить таймаут, время доступа по паролю не ограничено
|
// 0 - отключить таймаут, время доступа по паролю не ограничено
|
||||||
"accessTimeout": 0,
|
"accessTimeout": 0,
|
||||||
|
|
||||||
|
// включить(true)/выключить(false) возможность расширенного поиска (раздел "</>")
|
||||||
|
// расширенный поиск не оптимизирован, поэтому может сильно нагружать сервер
|
||||||
|
// чтобы ускорить поиск, увеличьте параметр dbCacheSize
|
||||||
|
"extendedSearch": true,
|
||||||
|
|
||||||
// содержимое кнопки-ссылки "(читать)", если не задано - кнопка "(читать)" не показывается
|
// содержимое кнопки-ссылки "(читать)", если не задано - кнопка "(читать)" не показывается
|
||||||
// пример: "https://omnireader.ru/#/reader?url=${DOWNLOAD_LINK}"
|
// пример: "https://omnireader.ru/#/reader?url=${DOWNLOAD_LINK}"
|
||||||
// на место ${DOWNLOAD_LINK} будет подставлена ссылка на скачивание файла книги
|
// на место ${DOWNLOAD_LINK} будет подставлена ссылка на скачивание файла книги
|
||||||
@@ -99,7 +114,7 @@ Options:
|
|||||||
// если надо кешировать всю БД, можно поставить значение от 1000 и больше
|
// если надо кешировать всю БД, можно поставить значение от 1000 и больше
|
||||||
"dbCacheSize": 5,
|
"dbCacheSize": 5,
|
||||||
|
|
||||||
// максимальный размер в байтах директории закешированных файлов в <раб.дир>/public/files
|
// максимальный размер в байтах директории закешированных файлов в <раб.дир>/public-files
|
||||||
// чистка каждый час
|
// чистка каждый час
|
||||||
"maxFilesDirSize": 1073741824,
|
"maxFilesDirSize": 1073741824,
|
||||||
|
|
||||||
@@ -140,17 +155,40 @@ Options:
|
|||||||
"remoteLib": false,
|
"remoteLib": false,
|
||||||
|
|
||||||
// настройки веб-сервера
|
// настройки веб-сервера
|
||||||
|
// парамертр root указывает путь для кореневой страницы inpx-web
|
||||||
|
// например для "root": "/library", веб-интерфейс будет доступен по адресу http://127.0.0.1:12380/library
|
||||||
|
// root необходим при настройке reverse-proxy и встраивании inpx-web в уже существующий сервер
|
||||||
"server": {
|
"server": {
|
||||||
"host": "0.0.0.0",
|
"host": "0.0.0.0",
|
||||||
"port": "12380"
|
"port": "12380",
|
||||||
|
"root": ""
|
||||||
},
|
},
|
||||||
|
|
||||||
// настройки opds-сервера
|
// настройки opds-сервера
|
||||||
// user, password используются для Basic HTTP authentication
|
// user, password используются для Basic HTTP authentication
|
||||||
|
// параметр root задает путь для доступа к opds-серверу
|
||||||
"opds": {
|
"opds": {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"user": "",
|
"user": "",
|
||||||
"password": ""
|
"password": "",
|
||||||
|
"root": "/opds"
|
||||||
|
},
|
||||||
|
|
||||||
|
// настройки по умолчанию для веб-интерфейса
|
||||||
|
// устанавливаются при первой загрузке страницы в браузере
|
||||||
|
// дальнейшие изменения настроек с помощью веб-интерфейса уже сохраняются в самом браузере
|
||||||
|
"uiDefaults": {
|
||||||
|
"limit": 20, // результатов на странице
|
||||||
|
"downloadAsZip": false, // скачивать книги в виде zip-архива
|
||||||
|
"showCounts": true, // показывать количество
|
||||||
|
"showRates": true, // показывать оценки
|
||||||
|
"showInfo": true, // показывать кнопку (инфо)
|
||||||
|
"showGenres": true, // показывать жанры
|
||||||
|
"showDates": false, // показывать даты поступления
|
||||||
|
"showDeleted": false, // показывать удаленные
|
||||||
|
"abCacheEnabled": true, // кешировать запросы
|
||||||
|
"langDefault": "", // язык по умолчанию (например "ru,en")
|
||||||
|
"showJson": false // показывать JSON (в расширенном поиске)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -198,7 +236,6 @@ Options:
|
|||||||
{
|
{
|
||||||
"info": {
|
"info": {
|
||||||
"collection": "Новое название коллекции",
|
"collection": "Новое название коллекции",
|
||||||
"structure": "",
|
|
||||||
"version": "1.0.0"
|
"version": "1.0.0"
|
||||||
},
|
},
|
||||||
"filter": "(r) => r.del == 0",
|
"filter": "(r) => r.del == 0",
|
||||||
@@ -280,6 +317,8 @@ sudo service nginx reload
|
|||||||
Сборка только в среде Linux.
|
Сборка только в среде Linux.
|
||||||
Необходима версия node.js не ниже 16.
|
Необходима версия node.js не ниже 16.
|
||||||
|
|
||||||
|
Для сборки linux-arm64 необходимо предварительно установить [QEMU](https://wiki.debian.org/QemuUserEmulation).
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
git clone https://github.com/bookpauk/inpx-web
|
git clone https://github.com/bookpauk/inpx-web
|
||||||
cd inpx-web
|
cd inpx-web
|
||||||
|
|||||||
1
build/appdir.js
Normal file
1
build/appdir.js
Normal file
@@ -0,0 +1 @@
|
|||||||
|
module.exports = 'app0b58f8bd9fbfa95504ba';
|
||||||
@@ -12,8 +12,8 @@ const publicDir = `${tmpDir}/public`;
|
|||||||
const outDir = `${distDir}/${platform}`;
|
const outDir = `${distDir}/${platform}`;
|
||||||
|
|
||||||
async function build() {
|
async function build() {
|
||||||
if (platform != 'linux' && platform != 'win' && platform != 'macos')
|
if (!platform)
|
||||||
throw new Error(`Unknown platform: ${platform}`);
|
throw new Error(`Please set platform`);
|
||||||
|
|
||||||
await fs.emptyDir(outDir);
|
await fs.emptyDir(outDir);
|
||||||
|
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ async function main() {
|
|||||||
await fs.emptyDir(outDir);
|
await fs.emptyDir(outDir);
|
||||||
await makeRelease('win');
|
await makeRelease('win');
|
||||||
await makeRelease('linux');
|
await makeRelease('linux');
|
||||||
|
await makeRelease('linux-arm64');
|
||||||
await makeRelease('macos');
|
await makeRelease('macos');
|
||||||
} catch(e) {
|
} catch(e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ const path = require('path');
|
|||||||
const DefinePlugin = require('webpack').DefinePlugin;
|
const DefinePlugin = require('webpack').DefinePlugin;
|
||||||
const { VueLoaderPlugin } = require('vue-loader');
|
const { VueLoaderPlugin } = require('vue-loader');
|
||||||
|
|
||||||
|
const appdir = require('./appdir');
|
||||||
|
|
||||||
const clientDir = path.resolve(__dirname, '../client');
|
const clientDir = path.resolve(__dirname, '../client');
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
@@ -12,7 +14,7 @@ module.exports = {
|
|||||||
},
|
},
|
||||||
entry: [`${clientDir}/main.js`],
|
entry: [`${clientDir}/main.js`],
|
||||||
output: {
|
output: {
|
||||||
publicPath: '/app/',
|
publicPath: `/${appdir}/`,
|
||||||
clean: true
|
clean: true
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
@@ -16,9 +16,8 @@ module.exports = merge(baseWpConfig, {
|
|||||||
mode: 'development',
|
mode: 'development',
|
||||||
devtool: 'inline-source-map',
|
devtool: 'inline-source-map',
|
||||||
output: {
|
output: {
|
||||||
path: `${publicDir}/app`,
|
path: `${publicDir}${baseWpConfig.output.publicPath}`,
|
||||||
filename: 'bundle.js',
|
filename: 'bundle.js',
|
||||||
clean: true
|
|
||||||
},
|
},
|
||||||
|
|
||||||
module: {
|
module: {
|
||||||
|
|||||||
@@ -18,9 +18,8 @@ fs.emptyDirSync(publicDir);
|
|||||||
module.exports = merge(baseWpConfig, {
|
module.exports = merge(baseWpConfig, {
|
||||||
mode: 'production',
|
mode: 'production',
|
||||||
output: {
|
output: {
|
||||||
path: `${publicDir}/app`,
|
path: `${publicDir}${baseWpConfig.output.publicPath}`,
|
||||||
filename: 'bundle.[contenthash].js',
|
filename: 'bundle.[contenthash].js',
|
||||||
clean: true
|
|
||||||
},
|
},
|
||||||
module: {
|
module: {
|
||||||
rules: [
|
rules: [
|
||||||
|
|||||||
@@ -235,6 +235,10 @@ class Api {
|
|||||||
return await this.request({action: 'search', from, query}, 30);
|
return await this.request({action: 'search', from, query}, 30);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async bookSearch(query) {
|
||||||
|
return await this.request({action: 'bookSearch', query}, 30);
|
||||||
|
}
|
||||||
|
|
||||||
async getAuthorBookList(authorId) {
|
async getAuthorBookList(authorId) {
|
||||||
return await this.request({action: 'get-author-book-list', authorId});
|
return await this.request({action: 'get-author-book-list', authorId});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
import WebSocketConnection from '../../../server/core/WebSocketConnection';
|
import WebSocketConnection from '../../../server/core/WebSocketConnection';
|
||||||
|
|
||||||
export default new WebSocketConnection();
|
const protocol = (window.location.protocol == 'https:' ? 'wss:' : 'ws:');
|
||||||
|
let url = `${protocol}//${window.location.host}${window.location.pathname}`;
|
||||||
|
url += (url[url.length - 1] === '/' ? 'ws' : '/ws');
|
||||||
|
|
||||||
|
export default new WebSocketConnection(url);
|
||||||
@@ -197,8 +197,12 @@ class AuthorList extends BaseList {
|
|||||||
result = `${count}`;
|
result = `${count}`;
|
||||||
if (item.seriesLoaded) {
|
if (item.seriesLoaded) {
|
||||||
const rec = item.seriesLoaded[book.series];
|
const rec = item.seriesLoaded[book.series];
|
||||||
const totalCount = (this.showDeleted ? rec.bookCount + rec.bookDelCount : rec.bookCount);
|
// заплатка для исправления https://github.com/bookpauk/inpx-web/issues/10
|
||||||
result += `/${totalCount}`;
|
// по невыясненным причинам rec иногда равен undefined
|
||||||
|
if (rec) {
|
||||||
|
const totalCount = (this.showDeleted ? rec.bookCount + rec.bookDelCount : rec.bookCount);
|
||||||
|
result += `/${totalCount}`;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return `(${result})`;
|
return `(${result})`;
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import axios from 'axios';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import _ from 'lodash';
|
import _ from 'lodash';
|
||||||
|
|
||||||
@@ -20,13 +21,16 @@ const componentOptions = {
|
|||||||
this.loadSettings();
|
this.loadSettings();
|
||||||
},
|
},
|
||||||
search: {
|
search: {
|
||||||
handler(newValue) {
|
handler() {
|
||||||
this.limit = newValue.limit;
|
if (!this.isExtendedSearch)
|
||||||
|
this.refresh();
|
||||||
if (this.pageCount > 1)
|
},
|
||||||
this.prevPage = this.search.page;
|
deep: true,
|
||||||
|
},
|
||||||
this.refresh();
|
extSearch: {
|
||||||
|
handler() {
|
||||||
|
if (this.isExtendedSearch)
|
||||||
|
this.refresh();
|
||||||
},
|
},
|
||||||
deep: true,
|
deep: true,
|
||||||
},
|
},
|
||||||
@@ -40,6 +44,7 @@ export default class BaseList {
|
|||||||
_props = {
|
_props = {
|
||||||
list: Object,
|
list: Object,
|
||||||
search: Object,
|
search: Object,
|
||||||
|
extSearch: Object,
|
||||||
genreMap: Object,
|
genreMap: Object,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -50,6 +55,7 @@ export default class BaseList {
|
|||||||
expandedAuthor = [];
|
expandedAuthor = [];
|
||||||
expandedSeries = [];
|
expandedSeries = [];
|
||||||
|
|
||||||
|
downloadAsZip = false;
|
||||||
showCounts = true;
|
showCounts = true;
|
||||||
showRates = true;
|
showRates = true;
|
||||||
showGenres = true;
|
showGenres = true;
|
||||||
@@ -66,6 +72,7 @@ export default class BaseList {
|
|||||||
tableData = [];
|
tableData = [];
|
||||||
|
|
||||||
created() {
|
created() {
|
||||||
|
this.isExtendedSearch = false;
|
||||||
this.commit = this.$store.commit;
|
this.commit = this.$store.commit;
|
||||||
this.api = this.$root.api;
|
this.api = this.$root.api;
|
||||||
|
|
||||||
@@ -81,6 +88,7 @@ export default class BaseList {
|
|||||||
|
|
||||||
this.expandedAuthor = _.cloneDeep(settings.expandedAuthor);
|
this.expandedAuthor = _.cloneDeep(settings.expandedAuthor);
|
||||||
this.expandedSeries = _.cloneDeep(settings.expandedSeries);
|
this.expandedSeries = _.cloneDeep(settings.expandedSeries);
|
||||||
|
this.downloadAsZip = settings.downloadAsZip;
|
||||||
this.showCounts = settings.showCounts;
|
this.showCounts = settings.showCounts;
|
||||||
this.showRates = settings.showRates;
|
this.showRates = settings.showRates;
|
||||||
this.showGenres = settings.showGenres;
|
this.showGenres = settings.showGenres;
|
||||||
@@ -105,16 +113,19 @@ export default class BaseList {
|
|||||||
}
|
}
|
||||||
|
|
||||||
selectAuthor(author) {
|
selectAuthor(author) {
|
||||||
this.search.author = `=${author}`;
|
const search = (this.isExtendedSearch ? this.extSearch : this.search);
|
||||||
|
search.author = `=${author}`;
|
||||||
this.scrollToTop();
|
this.scrollToTop();
|
||||||
}
|
}
|
||||||
|
|
||||||
selectSeries(series) {
|
selectSeries(series) {
|
||||||
this.search.series = `=${series}`;
|
const search = (this.isExtendedSearch ? this.extSearch : this.search);
|
||||||
|
search.series = `=${series}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
selectTitle(title) {
|
selectTitle(title) {
|
||||||
this.search.title = `=${title}`;
|
const search = (this.isExtendedSearch ? this.extSearch : this.search);
|
||||||
|
search.title = `=${title}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
async download(book, action) {
|
async download(book, action) {
|
||||||
@@ -133,13 +144,20 @@ export default class BaseList {
|
|||||||
const response = await this.api.getBookLink(book._uid);
|
const response = await this.api.getBookLink(book._uid);
|
||||||
|
|
||||||
const link = response.link;
|
const link = response.link;
|
||||||
const href = `${window.location.origin}${link}`;
|
let href = `${window.location.origin}${link}`;
|
||||||
|
|
||||||
|
//downloadAsZip
|
||||||
|
if (this.downloadAsZip && (action == 'download' || action == 'copyLink')) {
|
||||||
|
href += '/zip';
|
||||||
|
//подожлем формирования zip-файла
|
||||||
|
await axios.head(href);
|
||||||
|
}
|
||||||
|
|
||||||
|
//action
|
||||||
if (action == 'download') {
|
if (action == 'download') {
|
||||||
//скачивание
|
//скачивание
|
||||||
const d = this.$refs.download;
|
const d = this.$refs.download;
|
||||||
d.href = href;
|
d.href = href;
|
||||||
d.download = response.downFileName;
|
|
||||||
|
|
||||||
d.click();
|
d.click();
|
||||||
} else if (action == 'copyLink') {
|
} else if (action == 'copyLink') {
|
||||||
@@ -367,7 +385,14 @@ export default class BaseList {
|
|||||||
} else if (searchValue[0] == '#') {
|
} else if (searchValue[0] == '#') {
|
||||||
|
|
||||||
searchValue = searchValue.substring(1);
|
searchValue = searchValue.substring(1);
|
||||||
return !bookValue || (bookValue !== emptyFieldValue && !enru.has(bookValue[0]) && bookValue.indexOf(searchValue) >= 0);
|
if (!bookValue)
|
||||||
|
return false;
|
||||||
|
return bookValue !== emptyFieldValue && !enru.has(bookValue[0]) && bookValue.indexOf(searchValue) >= 0;
|
||||||
|
} else if (searchValue[0] == '~') {//RegExp
|
||||||
|
|
||||||
|
searchValue = searchValue.substring(1);
|
||||||
|
const re = new RegExp(searchValue, 'i');
|
||||||
|
return re.test(bookValue);
|
||||||
} else {
|
} else {
|
||||||
//where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
|
//where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
|
||||||
return bookValue.localeCompare(searchValue) >= 0 && bookValue.localeCompare(searchValue + maxUtf8Char) <= 0;
|
return bookValue.localeCompare(searchValue) >= 0 && bookValue.localeCompare(searchValue + maxUtf8Char) <= 0;
|
||||||
@@ -506,9 +531,9 @@ export default class BaseList {
|
|||||||
}
|
}
|
||||||
|
|
||||||
getQuery() {
|
getQuery() {
|
||||||
let newQuery = _.cloneDeep(this.search);
|
const search = (this.isExtendedSearch ? this.extSearch : this.search);
|
||||||
newQuery = newQuery.setDefaults(newQuery);
|
const newQuery = {};
|
||||||
delete newQuery.setDefaults;
|
search.setDefaults(newQuery, search);
|
||||||
|
|
||||||
//дата
|
//дата
|
||||||
if (newQuery.date) {
|
if (newQuery.date) {
|
||||||
@@ -519,8 +544,8 @@ export default class BaseList {
|
|||||||
newQuery.offset = (newQuery.page - 1)*newQuery.limit;
|
newQuery.offset = (newQuery.page - 1)*newQuery.limit;
|
||||||
|
|
||||||
//del
|
//del
|
||||||
if (!this.showDeleted)
|
if (!newQuery.del && !this.showDeleted)
|
||||||
newQuery.del = 0;
|
newQuery.del = '0';
|
||||||
|
|
||||||
return newQuery;
|
return newQuery;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,7 @@
|
|||||||
|
|
||||||
<div class="row q-mt-sm no-wrap">
|
<div class="row q-mt-sm no-wrap">
|
||||||
<div class="poster-size">
|
<div class="poster-size">
|
||||||
<div class="poster-size column justify-center items-center" :class="{poster: coverSrc}" @click.stop.prevent="posterClick">
|
<div class="column justify-center items-center" :class="{'poster': coverSrc, 'no-poster': !coverSrc}" @click.stop.prevent="posterClick">
|
||||||
<img v-if="coverSrc" :src="coverSrc" class="fit row justify-center items-center" style="object-fit: contain" @error="coverSrc = ''" />
|
<img v-if="coverSrc" :src="coverSrc" class="fit row justify-center items-center" style="object-fit: contain" @error="coverSrc = ''" />
|
||||||
<div v-if="!coverSrc" class="fit row justify-center items-center text-grey-5" style="border: 1px solid #ccc; font-size: 300%">
|
<div v-if="!coverSrc" class="fit row justify-center items-center text-grey-5" style="border: 1px solid #ccc; font-size: 300%">
|
||||||
<i>{{ book.ext }}</i>
|
<i>{{ book.ext }}</i>
|
||||||
@@ -317,7 +317,7 @@ export default vueComponent(BookInfoDialog);
|
|||||||
min-width: 100px;
|
min-width: 100px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.poster {
|
.poster, .no-poster {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,7 +33,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="q-ml-sm column">
|
<div class="q-ml-sm column">
|
||||||
<div v-if="(mode == 'series' || mode == 'title') && bookAuthor" class="row">
|
<div v-if="(mode == 'series' || mode == 'title' || mode == 'extended') && bookAuthor" class="row">
|
||||||
<div class="clickable2 text-green-10" @click.stop.prevent="emit('authorClick')">
|
<div class="clickable2 text-green-10" @click.stop.prevent="emit('authorClick')">
|
||||||
{{ bookAuthor }}
|
{{ bookAuthor }}
|
||||||
</div>
|
</div>
|
||||||
@@ -46,7 +46,7 @@
|
|||||||
<div class="clickable2" :class="titleColor" @click.stop.prevent="emit('titleClick')">
|
<div class="clickable2" :class="titleColor" @click.stop.prevent="emit('titleClick')">
|
||||||
{{ book.title }}
|
{{ book.title }}
|
||||||
</div>
|
</div>
|
||||||
<div v-if="mode == 'title' && bookSeries" class="q-ml-xs clickable2" @click.stop.prevent="emit('seriesClick')">
|
<div v-if="(mode == 'title' || mode == 'extended') && bookSeries" class="q-ml-xs clickable2" @click.stop.prevent="emit('seriesClick')">
|
||||||
{{ bookSeries }}
|
{{ bookSeries }}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -79,10 +79,10 @@
|
|||||||
{{ bookDate }}
|
{{ bookDate }}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div v-show="false">
|
<div v-show="showJson && mode == 'extended'">
|
||||||
{{ book }}
|
<pre style="font-size: 80%; white-space: pre-wrap;">{{ book }}</pre>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -117,6 +117,7 @@ class BookView {
|
|||||||
showGenres = true;
|
showGenres = true;
|
||||||
showDeleted = false;
|
showDeleted = false;
|
||||||
showDates = false;
|
showDates = false;
|
||||||
|
showJson = false;
|
||||||
|
|
||||||
created() {
|
created() {
|
||||||
this.loadSettings();
|
this.loadSettings();
|
||||||
@@ -130,6 +131,7 @@ class BookView {
|
|||||||
this.showGenres = settings.showGenres;
|
this.showGenres = settings.showGenres;
|
||||||
this.showDates = settings.showDates;
|
this.showDates = settings.showDates;
|
||||||
this.showDeleted = settings.showDeleted;
|
this.showDeleted = settings.showDeleted;
|
||||||
|
this.showJson = settings.showJson;
|
||||||
}
|
}
|
||||||
|
|
||||||
get settings() {
|
get settings() {
|
||||||
|
|||||||
128
client/components/Search/ExtendedList/ExtendedList.vue
Normal file
128
client/components/Search/ExtendedList/ExtendedList.vue
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<a ref="download" style="display: none;"></a>
|
||||||
|
|
||||||
|
<LoadingMessage :message="loadingMessage" z-index="2" />
|
||||||
|
<LoadingMessage :message="loadingMessage2" z-index="1" />
|
||||||
|
|
||||||
|
<!-- Формирование списка ------------------------------------------------------------------------>
|
||||||
|
<div v-for="item in tableData" :key="item.key" class="column" :class="{'odd-item': item.num % 2}" style="font-size: 120%">
|
||||||
|
<BookView
|
||||||
|
class="q-ml-md"
|
||||||
|
:book="item.book" mode="extended" :genre-map="genreMap" :show-read-link="showReadLink" @book-event="bookEvent"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<!-- Формирование списка конец ------------------------------------------------------------------>
|
||||||
|
|
||||||
|
<div v-if="!refreshing && !tableData.length" class="row items-center q-ml-md" style="font-size: 120%">
|
||||||
|
<q-icon class="la la-meh q-mr-xs" size="28px" />
|
||||||
|
Поиск не дал результатов
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
//-----------------------------------------------------------------------------
|
||||||
|
import vueComponent from '../../vueComponent.js';
|
||||||
|
import { reactive } from 'vue';
|
||||||
|
|
||||||
|
import BaseList from '../BaseList';
|
||||||
|
|
||||||
|
import * as utils from '../../../share/utils';
|
||||||
|
|
||||||
|
import _ from 'lodash';
|
||||||
|
|
||||||
|
class ExtendedList extends BaseList {
|
||||||
|
created() {
|
||||||
|
super.created();
|
||||||
|
this.isExtendedSearch = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
get foundCountMessage() {
|
||||||
|
return `${this.list.totalFound} ссыл${utils.wordEnding(this.list.totalFound, 5)} на файл(ы)`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateTableData() {
|
||||||
|
let result = [];
|
||||||
|
|
||||||
|
const books = this.searchResult.found;
|
||||||
|
if (!books)
|
||||||
|
return;
|
||||||
|
|
||||||
|
let num = 0;
|
||||||
|
for (const book of books) {
|
||||||
|
const item = reactive({
|
||||||
|
num: num++,
|
||||||
|
book,
|
||||||
|
});
|
||||||
|
|
||||||
|
result.push(item);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.tableData = result;
|
||||||
|
}
|
||||||
|
|
||||||
|
async refresh() {
|
||||||
|
//параметры запроса
|
||||||
|
const newQuery = this.getQuery();
|
||||||
|
if (_.isEqual(newQuery, this.prevQuery))
|
||||||
|
return;
|
||||||
|
this.prevQuery = newQuery;
|
||||||
|
|
||||||
|
this.queryExecute = newQuery;
|
||||||
|
|
||||||
|
if (this.refreshing)
|
||||||
|
return;
|
||||||
|
|
||||||
|
this.refreshing = true;
|
||||||
|
|
||||||
|
(async() => {
|
||||||
|
await utils.sleep(500);
|
||||||
|
if (this.refreshing)
|
||||||
|
this.loadingMessage = 'Поиск книг...';
|
||||||
|
})();
|
||||||
|
|
||||||
|
try {
|
||||||
|
while (this.queryExecute) {
|
||||||
|
const query = this.queryExecute;
|
||||||
|
this.queryExecute = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await this.api.bookSearch(query);
|
||||||
|
|
||||||
|
this.list.queryFound = response.found.length;
|
||||||
|
this.list.totalFound = response.totalFound;
|
||||||
|
this.list.inpxHash = response.inpxHash;
|
||||||
|
|
||||||
|
this.searchResult = response;
|
||||||
|
|
||||||
|
await utils.sleep(1);
|
||||||
|
if (!this.queryExecute) {
|
||||||
|
await this.updateTableData();
|
||||||
|
this.scrollToTop();
|
||||||
|
this.highlightPageScroller(query);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
this.$root.stdDialog.alert(e.message, 'Ошибка');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
this.refreshing = false;
|
||||||
|
this.loadingMessage = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default vueComponent(ExtendedList);
|
||||||
|
//-----------------------------------------------------------------------------
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.clickable2 {
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.odd-item {
|
||||||
|
background-color: #e8e8e8;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,64 +1,273 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="root column fit" style="position: relative">
|
<div class="root column fit" style="position: relative">
|
||||||
<div ref="scroller" class="col fit column no-wrap" style="overflow: auto; position: relative" @scroll="onScroll">
|
<div ref="scroller" class="col fit column no-wrap" style="overflow: auto; position: relative" @scroll="onScroll">
|
||||||
<div ref="toolPanel" class="tool-panel q-pb-xs column bg-cyan-2" style="position: sticky; top: 0; z-index: 10;">
|
<!-- Tool Panel begin -->
|
||||||
<div class="header q-mx-md q-mb-xs q-mt-sm row items-center">
|
<div ref="toolPanel" class="tool-panel column bg-cyan-2" style="position: sticky; top: 0; z-index: 10;">
|
||||||
<a :href="newSearchLink" style="height: 33px; width: 34px">
|
<!-- 1 -->
|
||||||
<img src="./assets/logo.png" />
|
<div class="row">
|
||||||
<q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
<!-- 1-1 -->
|
||||||
Новый поиск
|
<div class="column col">
|
||||||
</q-tooltip>
|
<div class="header q-mb-xs q-ml-sm q-mt-sm row items-center">
|
||||||
</a>
|
<div class="row no-wrap items-center">
|
||||||
|
<a :href="newSearchLink" style="height: 33px; width: 34px">
|
||||||
|
<img src="./assets/logo.png" />
|
||||||
|
<q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||||
|
Новый поиск
|
||||||
|
</q-tooltip>
|
||||||
|
</a>
|
||||||
|
|
||||||
<q-btn-toggle
|
<q-btn-toggle
|
||||||
v-model="selectedList"
|
v-model="selectedList"
|
||||||
class="q-ml-sm"
|
class="q-ml-sm"
|
||||||
toggle-color="primary"
|
toggle-color="primary"
|
||||||
:options="listOptions"
|
:options="listOptions"
|
||||||
push
|
push
|
||||||
no-caps
|
no-caps
|
||||||
rounded
|
rounded
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="row items-center q-ml-sm" style="font-size: 150%;">
|
<div class="row items-center q-ml-sm" style="font-size: 150%;">
|
||||||
<div class="q-mr-xs">
|
<div class="q-mr-xs">
|
||||||
Коллекция
|
Коллекция
|
||||||
|
</div>
|
||||||
|
<div class="clickable" @click.stop.prevent="showCollectionInfo">
|
||||||
|
{{ collection }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DivBtn class="q-ml-sm text-grey-5 bg-yellow-1" :size="28" :icon-size="24" icon="la la-question" round @click.stop.prevent="showSearchHelp">
|
||||||
|
<template #tooltip>
|
||||||
|
<q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||||
|
Памятка
|
||||||
|
</q-tooltip>
|
||||||
|
</template>
|
||||||
|
</DivBtn>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="clickable" @click.stop.prevent="showCollectionInfo">
|
<div v-show="!isExtendedSearch" class="row q-mx-sm q-mb-xs items-center" style="max-width: 1024px">
|
||||||
{{ collection }}
|
<q-input
|
||||||
|
ref="authorInput" v-model="search.author" :maxlength="5000" :debounce="inputDebounce"
|
||||||
|
class="q-mt-xs col-3" :bg-color="inputBgColor('author')" style="min-width: 140px" label="Автор" stack-label outlined dense clearable
|
||||||
|
>
|
||||||
|
<q-tooltip v-if="search.author" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||||
|
{{ search.author }}
|
||||||
|
</q-tooltip>
|
||||||
|
</q-input>
|
||||||
|
<div class="q-mx-xs" />
|
||||||
|
<q-input
|
||||||
|
v-model="search.series" :maxlength="inputMaxLength" :debounce="inputDebounce"
|
||||||
|
class="q-mt-xs col-3" :bg-color="inputBgColor('series')" style="min-width: 140px" label="Серия" stack-label outlined dense clearable
|
||||||
|
>
|
||||||
|
<q-tooltip v-if="search.series" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||||
|
{{ search.series }}
|
||||||
|
</q-tooltip>
|
||||||
|
</q-input>
|
||||||
|
<div class="q-mx-xs" />
|
||||||
|
<q-input
|
||||||
|
v-model="search.title" :maxlength="inputMaxLength" :debounce="inputDebounce"
|
||||||
|
class="q-mt-xs col-3" :bg-color="inputBgColor('title')" style="min-width: 140px;" label="Название" stack-label outlined dense clearable
|
||||||
|
>
|
||||||
|
<q-tooltip v-if="search.title" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||||
|
{{ search.title }}
|
||||||
|
</q-tooltip>
|
||||||
|
</q-input>
|
||||||
|
<div class="q-mx-xs" />
|
||||||
|
<q-input
|
||||||
|
v-model="search.lang" :maxlength="inputMaxLength" :debounce="inputDebounce"
|
||||||
|
class="q-mt-xs col-1" :bg-color="inputBgColor()" input-style="cursor: pointer" style="min-width: 90px;" label="Язык" stack-label outlined dense clearable readonly
|
||||||
|
@click.stop.prevent="selectLang"
|
||||||
|
>
|
||||||
|
<template v-if="search.lang" #append>
|
||||||
|
<q-icon name="la la-times-circle" class="q-field__focusable-action" @click.stop.prevent="search.lang = ''" />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<q-tooltip v-if="search.lang && showTooltips" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||||
|
{{ search.lang }}
|
||||||
|
</q-tooltip>
|
||||||
|
</q-input>
|
||||||
|
<div class="q-mx-xs" />
|
||||||
|
<DivBtn
|
||||||
|
class="text-grey-8 bg-yellow-1 q-mt-xs" :size="30" :icon-size="24" round
|
||||||
|
icon="la la-level-up-alt"
|
||||||
|
@click.stop.prevent="cloneSearch"
|
||||||
|
>
|
||||||
|
<template #tooltip>
|
||||||
|
<q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||||
|
Клонировать поиск
|
||||||
|
</q-tooltip>
|
||||||
|
</template>
|
||||||
|
</DivBtn>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div v-show="!isExtendedSearch && extendedParams" class="row q-mx-sm q-mb-xs items-center" style="max-width: 1024px">
|
||||||
|
<q-input
|
||||||
|
v-model="genreNames" :maxlength="inputMaxLength" :debounce="inputDebounce"
|
||||||
|
class="q-mt-xs col-3" :bg-color="inputBgColor()" input-style="cursor: pointer" style="min-width: 140px;" label="Жанр" stack-label outlined dense clearable readonly
|
||||||
|
@click.stop.prevent="selectGenre"
|
||||||
|
>
|
||||||
|
<template v-if="genreNames" #append>
|
||||||
|
<q-icon name="la la-times-circle" class="q-field__focusable-action" @click.stop.prevent="search.genre = ''" />
|
||||||
|
</template>
|
||||||
|
|
||||||
<div class="col"></div>
|
<q-tooltip v-if="genreNames && showTooltips" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||||
|
{{ genreNames }}
|
||||||
|
</q-tooltip>
|
||||||
|
</q-input>
|
||||||
|
|
||||||
<DivBtn class="q-ml-md text-white bg-secondary" :size="30" :icon-size="24" icon="la la-question" round @click.stop.prevent="showSearchHelp">
|
<div class="q-mx-xs" />
|
||||||
<template #tooltip>
|
<q-select
|
||||||
<q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
v-model="searchDate"
|
||||||
Памятка
|
class="q-mt-xs col-3"
|
||||||
</q-tooltip>
|
:options="searchDateOptions"
|
||||||
</template>
|
dropdown-icon="la la-angle-down la-sm"
|
||||||
</DivBtn>
|
:bg-color="inputBgColor()"
|
||||||
|
style="min-width: 140px;"
|
||||||
|
label="Дата поступления" stack-label
|
||||||
|
outlined dense emit-value map-options clearable
|
||||||
|
>
|
||||||
|
<template #selected-item="scope">
|
||||||
|
<div v-if="scope.opt.value == 'manual'">
|
||||||
|
<div v-html="formatSearchDate" />
|
||||||
|
</div>
|
||||||
|
<div v-else>
|
||||||
|
{{ scope.opt.label }}
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
<DivBtn class="q-ml-sm text-white bg-secondary" :size="30" :icon-size="24" :imt="1" icon="la la-cog" round @click.stop.prevent="settingsDialogVisible = true">
|
<template #option="scope">
|
||||||
<template #tooltip>
|
<q-item v-bind="scope.itemProps" @click.stop.prevent="dateSelectItemClick(scope.opt.value)">
|
||||||
<q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
<q-item-section>
|
||||||
Настройки
|
<q-item-label>
|
||||||
</q-tooltip>
|
{{ scope.opt.label }}
|
||||||
</template>
|
</q-item-label>
|
||||||
</DivBtn>
|
</q-item-section>
|
||||||
|
</q-item>
|
||||||
|
</template>
|
||||||
|
</q-select>
|
||||||
|
|
||||||
<DivBtn v-if="!config.freeAccess" class="q-ml-sm text-white bg-secondary" :size="30" :icon-size="24" :imt="1" icon="la la-sign-out-alt" round @click.stop.prevent="logout">
|
<div class="q-mx-xs" />
|
||||||
<template #tooltip>
|
<q-input
|
||||||
<q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
v-model="librateNames" :maxlength="inputMaxLength" :debounce="inputDebounce"
|
||||||
Выход
|
class="q-mt-xs col-1" :bg-color="inputBgColor()" input-style="cursor: pointer" style="min-width: 90px;" label="Оценка" stack-label outlined dense clearable readonly
|
||||||
</q-tooltip>
|
@click.stop.prevent="selectLibRate"
|
||||||
</template>
|
>
|
||||||
</DivBtn>
|
<template v-if="librateNames" #append>
|
||||||
</div>
|
<q-icon name="la la-times-circle" class="q-field__focusable-action" @click.stop.prevent="search.librate = ''" />
|
||||||
<div class="row q-mx-md q-mb-xs items-center">
|
</template>
|
||||||
|
|
||||||
|
<q-tooltip v-if="librateNames && showTooltips" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||||
|
{{ librateNames }}
|
||||||
|
</q-tooltip>
|
||||||
|
</q-input>
|
||||||
|
</div>
|
||||||
|
<div v-show="!isExtendedSearch && !extendedParams && extendedParamsMessage" class="row q-mx-sm items-center clickable" @click.stop.prevent="extendedParams = true">
|
||||||
|
+{{ extendedParamsMessage }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-show="isExtendedSearch" class="row q-mx-md q-mb-xs items-center">
|
||||||
|
<q-input
|
||||||
|
v-model="extSearchNames"
|
||||||
|
class="col q-mt-xs" :bg-color="inputBgColor('extended')" input-style="cursor: pointer"
|
||||||
|
style="min-width: 140px; max-width: 638px;" label="Расширенный поиск" stack-label outlined dense clearable readonly
|
||||||
|
@click.stop.prevent="selectExtSearch"
|
||||||
|
>
|
||||||
|
<template v-if="extSearchNames" #append>
|
||||||
|
<q-icon name="la la-times-circle" class="q-field__focusable-action" @click.stop.prevent="clearExtSearch" />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<q-tooltip v-if="extSearchNames && showTooltips" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||||
|
{{ extSearchNames }}
|
||||||
|
</q-tooltip>
|
||||||
|
</q-input>
|
||||||
|
|
||||||
|
<div class="q-mx-xs" />
|
||||||
|
<DivBtn
|
||||||
|
class="text-grey-8 bg-yellow-1 q-mt-xs" :size="30" round
|
||||||
|
:disabled="!extSearch.author"
|
||||||
|
@me-click="extToList('author')"
|
||||||
|
>
|
||||||
|
<div style="font-size: 130%">
|
||||||
|
<b>А</b>
|
||||||
|
</div>
|
||||||
|
<template #tooltip>
|
||||||
|
<q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||||
|
В раздел "Авторы" с переносом значения author={{ extSearch.author }}
|
||||||
|
</q-tooltip>
|
||||||
|
</template>
|
||||||
|
</DivBtn>
|
||||||
|
|
||||||
|
<div class="q-mx-xs" />
|
||||||
|
<DivBtn
|
||||||
|
class="text-grey-8 bg-yellow-1 q-mt-xs" :size="30" round
|
||||||
|
:disabled="!extSearch.series"
|
||||||
|
@me-click="extToList('series')"
|
||||||
|
>
|
||||||
|
<div style="font-size: 130%">
|
||||||
|
<b>С</b>
|
||||||
|
</div>
|
||||||
|
<template #tooltip>
|
||||||
|
<q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||||
|
В раздел "Серии" с переносом значения series={{ extSearch.series }}
|
||||||
|
</q-tooltip>
|
||||||
|
</template>
|
||||||
|
</DivBtn>
|
||||||
|
|
||||||
|
<div class="q-mx-xs" />
|
||||||
|
<DivBtn
|
||||||
|
class="text-grey-8 bg-yellow-1 q-mt-xs" :size="30" round
|
||||||
|
:disabled="!extSearch.title"
|
||||||
|
@me-click="extToList('title')"
|
||||||
|
>
|
||||||
|
<div style="font-size: 130%">
|
||||||
|
<b>К</b>
|
||||||
|
</div>
|
||||||
|
<template #tooltip>
|
||||||
|
<q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||||
|
В раздел "Книги" с переносом значения title={{ extSearch.title }}
|
||||||
|
</q-tooltip>
|
||||||
|
</template>
|
||||||
|
</DivBtn>
|
||||||
|
|
||||||
|
<div class="q-mx-xs" />
|
||||||
|
<DivBtn
|
||||||
|
class="text-grey-8 bg-yellow-1 q-mt-xs" :size="30" :icon-size="24" round
|
||||||
|
icon="la la-level-up-alt"
|
||||||
|
@click.stop.prevent="cloneSearch"
|
||||||
|
>
|
||||||
|
<template #tooltip>
|
||||||
|
<q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||||
|
Клонировать поиск
|
||||||
|
</q-tooltip>
|
||||||
|
</template>
|
||||||
|
</DivBtn>
|
||||||
|
</div>
|
||||||
|
</div><!-- 1-1 -->
|
||||||
|
<!-- 1-2 -->
|
||||||
|
<div class="column q-mx-sm">
|
||||||
|
<div style="height: 3px" />
|
||||||
|
<DivBtn class="q-mt-sm text-white bg-secondary" :size="28" :icon-size="24" :imt="1" icon="la la-cog" round @click.stop.prevent="settingsDialogVisible = true">
|
||||||
|
<template #tooltip>
|
||||||
|
<q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||||
|
Настройки
|
||||||
|
</q-tooltip>
|
||||||
|
</template>
|
||||||
|
</DivBtn>
|
||||||
|
|
||||||
|
<DivBtn v-if="!config.freeAccess" class="q-mt-sm text-white bg-secondary" :size="28" :icon-size="24" :imt="1" icon="la la-sign-out-alt" round @click.stop.prevent="logout">
|
||||||
|
<template #tooltip>
|
||||||
|
<q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||||
|
Выход
|
||||||
|
</q-tooltip>
|
||||||
|
</template>
|
||||||
|
</DivBtn>
|
||||||
|
</div><!-- 1-2 -->
|
||||||
|
</div><!-- 1 -->
|
||||||
|
<!-- 2 -->
|
||||||
|
<div class="column">
|
||||||
<DivBtn
|
<DivBtn
|
||||||
class="text-grey-5 bg-yellow-1 q-mt-xs" :size="34" :icon-size="24" round
|
v-show="!isExtendedSearch && (extendedParams || !extendedParamsMessage)"
|
||||||
|
class="text-grey-6" :size="16" :icon-size="14"
|
||||||
:icon="(extendedParams ? 'la la-angle-double-up' : 'la la-angle-double-down')"
|
:icon="(extendedParams ? 'la la-angle-double-up' : 'la la-angle-double-down')"
|
||||||
|
no-shadow
|
||||||
@click.stop.prevent="extendedParams = !extendedParams"
|
@click.stop.prevent="extendedParams = !extendedParams"
|
||||||
>
|
>
|
||||||
<template #tooltip>
|
<template #tooltip>
|
||||||
@@ -67,142 +276,28 @@
|
|||||||
</q-tooltip>
|
</q-tooltip>
|
||||||
</template>
|
</template>
|
||||||
</DivBtn>
|
</DivBtn>
|
||||||
<div class="q-mx-xs" />
|
</div><!-- 2 -->
|
||||||
<q-input
|
|
||||||
ref="authorInput" v-model="search.author" :maxlength="5000" :debounce="inputDebounce"
|
|
||||||
class="q-mt-xs" :bg-color="inputBgColor('author')" style="width: 200px;" label="Автор" stack-label outlined dense clearable
|
|
||||||
>
|
|
||||||
<q-tooltip v-if="search.author" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
|
||||||
{{ search.author }}
|
|
||||||
</q-tooltip>
|
|
||||||
</q-input>
|
|
||||||
<div class="q-mx-xs" />
|
|
||||||
<q-input
|
|
||||||
v-model="search.series" :maxlength="inputMaxLength" :debounce="inputDebounce"
|
|
||||||
class="q-mt-xs" :bg-color="inputBgColor('series')" style="width: 200px;" label="Серия" stack-label outlined dense clearable
|
|
||||||
>
|
|
||||||
<q-tooltip v-if="search.series" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
|
||||||
{{ search.series }}
|
|
||||||
</q-tooltip>
|
|
||||||
</q-input>
|
|
||||||
<div class="q-mx-xs" />
|
|
||||||
<q-input
|
|
||||||
v-model="search.title" :maxlength="inputMaxLength" :debounce="inputDebounce"
|
|
||||||
class="q-mt-xs" :bg-color="inputBgColor('title')" style="width: 200px;" label="Название" stack-label outlined dense clearable
|
|
||||||
>
|
|
||||||
<q-tooltip v-if="search.title" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
|
||||||
{{ search.title }}
|
|
||||||
</q-tooltip>
|
|
||||||
</q-input>
|
|
||||||
<div class="q-mx-xs" />
|
|
||||||
<q-input
|
|
||||||
v-model="search.lang" :maxlength="inputMaxLength" :debounce="inputDebounce"
|
|
||||||
class="q-mt-xs" :bg-color="inputBgColor()" input-style="cursor: pointer" style="width: 90px;" label="Язык" stack-label outlined dense clearable readonly
|
|
||||||
@click.stop.prevent="selectLang"
|
|
||||||
>
|
|
||||||
<template v-if="search.lang" #append>
|
|
||||||
<q-icon name="la la-times-circle" class="q-field__focusable-action" @click.stop.prevent="search.lang = ''" />
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<q-tooltip v-if="search.lang && showTooltips" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
|
||||||
{{ search.lang }}
|
|
||||||
</q-tooltip>
|
|
||||||
</q-input>
|
|
||||||
<div class="q-mx-xs" />
|
|
||||||
<DivBtn
|
|
||||||
class="text-grey-8 bg-yellow-1 q-mt-xs" :size="34" :icon-size="24" round
|
|
||||||
icon="la la-level-up-alt"
|
|
||||||
@click.stop.prevent="cloneSearch"
|
|
||||||
>
|
|
||||||
<template #tooltip>
|
|
||||||
<q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
|
||||||
Клонировать поиск
|
|
||||||
</q-tooltip>
|
|
||||||
</template>
|
|
||||||
</DivBtn>
|
|
||||||
</div>
|
|
||||||
<div v-show="extendedParams" class="row q-mx-md q-mb-xs items-center">
|
|
||||||
<div style="width: 34px" />
|
|
||||||
<div class="q-mx-xs" />
|
|
||||||
<q-input
|
|
||||||
v-model="genreNames" :maxlength="inputMaxLength" :debounce="inputDebounce"
|
|
||||||
class="q-mt-xs" :bg-color="inputBgColor()" input-style="cursor: pointer" style="width: 200px;" label="Жанр" stack-label outlined dense clearable readonly
|
|
||||||
@click.stop.prevent="selectGenre"
|
|
||||||
>
|
|
||||||
<template v-if="genreNames" #append>
|
|
||||||
<q-icon name="la la-times-circle" class="q-field__focusable-action" @click.stop.prevent="search.genre = ''" />
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<q-tooltip v-if="genreNames && showTooltips" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
|
||||||
{{ genreNames }}
|
|
||||||
</q-tooltip>
|
|
||||||
</q-input>
|
|
||||||
|
|
||||||
<div class="q-mx-xs" />
|
|
||||||
<q-select
|
|
||||||
v-model="searchDate"
|
|
||||||
class="q-mt-xs"
|
|
||||||
:options="searchDateOptions"
|
|
||||||
dropdown-icon="la la-angle-down la-sm"
|
|
||||||
:bg-color="inputBgColor()"
|
|
||||||
style="width: 200px;"
|
|
||||||
label="Дата поступления" stack-label
|
|
||||||
outlined dense emit-value map-options clearable
|
|
||||||
>
|
|
||||||
<template #selected-item="scope">
|
|
||||||
<div v-if="scope.opt.value == 'manual'">
|
|
||||||
<div v-html="formatSearchDate" />
|
|
||||||
</div>
|
|
||||||
<div v-else>
|
|
||||||
{{ scope.opt.label }}
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<template #option="scope">
|
|
||||||
<q-item v-bind="scope.itemProps" @click.stop.prevent="dateSelectItemClick(scope.opt.value)">
|
|
||||||
<q-item-section>
|
|
||||||
<q-item-label>
|
|
||||||
{{ scope.opt.label }}
|
|
||||||
</q-item-label>
|
|
||||||
</q-item-section>
|
|
||||||
</q-item>
|
|
||||||
</template>
|
|
||||||
</q-select>
|
|
||||||
|
|
||||||
<div class="q-mx-xs" />
|
|
||||||
<q-input
|
|
||||||
v-model="librateNames" :maxlength="inputMaxLength" :debounce="inputDebounce"
|
|
||||||
class="q-mt-xs" :bg-color="inputBgColor()" input-style="cursor: pointer" style="width: 90px;" label="Оценка" stack-label outlined dense clearable readonly
|
|
||||||
@click.stop.prevent="selectLibRate"
|
|
||||||
>
|
|
||||||
<template v-if="librateNames" #append>
|
|
||||||
<q-icon name="la la-times-circle" class="q-field__focusable-action" @click.stop.prevent="search.librate = ''" />
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<q-tooltip v-if="librateNames && showTooltips" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
|
||||||
{{ librateNames }}
|
|
||||||
</q-tooltip>
|
|
||||||
</q-input>
|
|
||||||
</div>
|
|
||||||
<div v-show="!extendedParams && extendedParamsMessage" class="row q-mx-md items-center clickable" @click.stop.prevent="extendedParams = true">
|
|
||||||
+{{ extendedParamsMessage }}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
<!-- Tool Panel end -->
|
||||||
|
|
||||||
<div class="row items-center q-ml-lg q-mt-sm">
|
<div class="row items-center q-ml-lg q-mt-sm">
|
||||||
<div style="width: 400px; height: 50px">
|
<div style="width: 400px;">
|
||||||
<PageScroller v-show="pageCount > 1" ref="pageScroller1" v-model="search.page" :page-count="pageCount" />
|
<PageScroller v-show="pageCount > 1" ref="pageScroller1" v-model="search.page" :page-count="pageCount" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-show="list.totalFound > 0" class="text-bold" style="font-size: 120%; padding-bottom: 2px">
|
<div v-show="list.totalFound > 0" class="text-bold" style="font-size: 120%; padding-bottom: 2px">
|
||||||
{{ foundCountMessage }}
|
{{ foundCountMessage }}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div v-show="list.totalFound > 0 && isExtendedSearch" class="q-ml-md">
|
||||||
|
<q-checkbox v-model="showJson" size="36px" label="Показывать JSON" />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Формирование списка ------------------------------------------------------------------------>
|
<!-- Формирование списка ------------------------------------------------------------------------>
|
||||||
<div v-if="selectedListComponent">
|
<div v-if="selectedListComponent">
|
||||||
<div class="separator" />
|
<div class="separator" />
|
||||||
<component :is="selectedListComponent" ref="list" :list="list" :search="search" :genre-map="genreMap" @list-event="listEvent" />
|
<component :is="selectedListComponent" ref="list" :list="list" :search="search" :ext-search="extSearch" :genre-map="genreMap" @list-event="listEvent" />
|
||||||
<div class="separator" />
|
<div class="separator" />
|
||||||
</div>
|
</div>
|
||||||
<!-- Формирование списка конец ------------------------------------------------------------------>
|
<!-- Формирование списка конец ------------------------------------------------------------------>
|
||||||
@@ -224,6 +319,7 @@
|
|||||||
<SelectLibRateDialog v-model="selectLibRateDialogVisible" v-model:librate="search.librate" />
|
<SelectLibRateDialog v-model="selectLibRateDialogVisible" v-model:librate="search.librate" />
|
||||||
<SelectDateDialog v-model="selectDateDialogVisible" v-model:date="search.date" />
|
<SelectDateDialog v-model="selectDateDialogVisible" v-model:date="search.date" />
|
||||||
<BookInfoDialog v-model="bookInfoDialogVisible" :book-info="bookInfo" />
|
<BookInfoDialog v-model="bookInfoDialogVisible" :book-info="bookInfo" />
|
||||||
|
<SelectExtSearchDialog v-model="selectExtSearchDialogVisible" v-model:ext-search="extSearch" />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -234,6 +330,7 @@ import vueComponent from '../vueComponent.js';
|
|||||||
import AuthorList from './AuthorList/AuthorList.vue';
|
import AuthorList from './AuthorList/AuthorList.vue';
|
||||||
import SeriesList from './SeriesList/SeriesList.vue';
|
import SeriesList from './SeriesList/SeriesList.vue';
|
||||||
import TitleList from './TitleList/TitleList.vue';
|
import TitleList from './TitleList/TitleList.vue';
|
||||||
|
import ExtendedList from './ExtendedList/ExtendedList.vue';
|
||||||
|
|
||||||
import PageScroller from './PageScroller/PageScroller.vue';
|
import PageScroller from './PageScroller/PageScroller.vue';
|
||||||
import SettingsDialog from './SettingsDialog/SettingsDialog.vue';
|
import SettingsDialog from './SettingsDialog/SettingsDialog.vue';
|
||||||
@@ -242,6 +339,7 @@ import SelectLangDialog from './SelectLangDialog/SelectLangDialog.vue';
|
|||||||
import SelectLibRateDialog from './SelectLibRateDialog/SelectLibRateDialog.vue';
|
import SelectLibRateDialog from './SelectLibRateDialog/SelectLibRateDialog.vue';
|
||||||
import SelectDateDialog from './SelectDateDialog/SelectDateDialog.vue';
|
import SelectDateDialog from './SelectDateDialog/SelectDateDialog.vue';
|
||||||
import BookInfoDialog from './BookInfoDialog/BookInfoDialog.vue';
|
import BookInfoDialog from './BookInfoDialog/BookInfoDialog.vue';
|
||||||
|
import SelectExtSearchDialog from './SelectExtSearchDialog/SelectExtSearchDialog.vue';
|
||||||
|
|
||||||
import authorBooksStorage from './authorBooksStorage';
|
import authorBooksStorage from './authorBooksStorage';
|
||||||
import DivBtn from '../share/DivBtn.vue';
|
import DivBtn from '../share/DivBtn.vue';
|
||||||
@@ -252,10 +350,13 @@ import diffUtils from '../../share/diffUtils';
|
|||||||
|
|
||||||
import _ from 'lodash';
|
import _ from 'lodash';
|
||||||
|
|
||||||
|
const maxLimit = 1000;
|
||||||
|
|
||||||
const route2component = {
|
const route2component = {
|
||||||
'author': {component: 'AuthorList', label: 'Авторы'},
|
'author': {component: 'AuthorList', label: 'Авторы'},
|
||||||
'series': {component: 'SeriesList', label: 'Серии'},
|
'series': {component: 'SeriesList', label: 'Серии'},
|
||||||
'title': {component: 'TitleList', label: 'Книги'},
|
'title': {component: 'TitleList', label: 'Книги'},
|
||||||
|
'extended': {component: 'ExtendedList', label: 'Расширенный поиск'},
|
||||||
};
|
};
|
||||||
|
|
||||||
const componentOptions = {
|
const componentOptions = {
|
||||||
@@ -263,6 +364,7 @@ const componentOptions = {
|
|||||||
AuthorList,
|
AuthorList,
|
||||||
SeriesList,
|
SeriesList,
|
||||||
TitleList,
|
TitleList,
|
||||||
|
ExtendedList,
|
||||||
PageScroller,
|
PageScroller,
|
||||||
SettingsDialog,
|
SettingsDialog,
|
||||||
SelectGenreDialog,
|
SelectGenreDialog,
|
||||||
@@ -270,6 +372,7 @@ const componentOptions = {
|
|||||||
SelectLibRateDialog,
|
SelectLibRateDialog,
|
||||||
SelectDateDialog,
|
SelectDateDialog,
|
||||||
BookInfoDialog,
|
BookInfoDialog,
|
||||||
|
SelectExtSearchDialog,
|
||||||
Dialog,
|
Dialog,
|
||||||
DivBtn
|
DivBtn
|
||||||
},
|
},
|
||||||
@@ -292,6 +395,19 @@ const componentOptions = {
|
|||||||
this.makeTitle();
|
this.makeTitle();
|
||||||
this.updateRouteQueryFromSearch();
|
this.updateRouteQueryFromSearch();
|
||||||
this.updateSearchDate(true);
|
this.updateSearchDate(true);
|
||||||
|
|
||||||
|
//extSearch
|
||||||
|
if (this.isExtendedSearch) {
|
||||||
|
this.extSearch.page = newValue.page;
|
||||||
|
this.extSearch.limit = newValue.limit;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
deep: true,
|
||||||
|
},
|
||||||
|
extSearch: {
|
||||||
|
handler() {
|
||||||
|
this.makeTitle();
|
||||||
|
this.updateRouteQueryFromSearch();
|
||||||
},
|
},
|
||||||
deep: true,
|
deep: true,
|
||||||
},
|
},
|
||||||
@@ -310,6 +426,9 @@ const componentOptions = {
|
|||||||
langDefault() {
|
langDefault() {
|
||||||
this.updateSearchFromRouteQuery(this.$route);
|
this.updateSearchFromRouteQuery(this.$route);
|
||||||
},
|
},
|
||||||
|
showJson(newValue) {
|
||||||
|
this.setSetting('showJson', newValue);
|
||||||
|
},
|
||||||
list: {
|
list: {
|
||||||
handler(newValue) {
|
handler(newValue) {
|
||||||
this.updateGenreTreeIfNeeded();
|
this.updateGenreTreeIfNeeded();
|
||||||
@@ -337,6 +456,8 @@ const componentOptions = {
|
|||||||
if (this.getListRoute() != newValue) {
|
if (this.getListRoute() != newValue) {
|
||||||
this.updateRouteQueryFromSearch();
|
this.updateRouteQueryFromSearch();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.makeTitle();
|
||||||
},
|
},
|
||||||
searchDate() {
|
searchDate() {
|
||||||
this.updateSearchDate(false);
|
this.updateSearchDate(false);
|
||||||
@@ -362,6 +483,7 @@ class Search {
|
|||||||
selectLibRateDialogVisible = false;
|
selectLibRateDialogVisible = false;
|
||||||
selectDateDialogVisible = false;
|
selectDateDialogVisible = false;
|
||||||
bookInfoDialogVisible = false;
|
bookInfoDialogVisible = false;
|
||||||
|
selectExtSearchDialogVisible = false;
|
||||||
|
|
||||||
pageCount = 1;
|
pageCount = 1;
|
||||||
|
|
||||||
@@ -370,21 +492,8 @@ class Search {
|
|||||||
inputDebounce = 200;
|
inputDebounce = 200;
|
||||||
|
|
||||||
//search fields
|
//search fields
|
||||||
search = {
|
search = {};
|
||||||
setDefaults(search) {
|
extSearch = {};
|
||||||
return Object.assign({}, search, {
|
|
||||||
author: search.author || '',
|
|
||||||
series: search.series || '',
|
|
||||||
title: search.title || '',
|
|
||||||
genre: search.genre || '',
|
|
||||||
lang: search.lang || '',
|
|
||||||
date: search.date || '',
|
|
||||||
librate: search.librate || '',
|
|
||||||
page: search.page || 1,
|
|
||||||
limit: search.limit || 50,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
searchDate = '';
|
searchDate = '';
|
||||||
prevManualDate = '';
|
prevManualDate = '';
|
||||||
@@ -394,6 +503,7 @@ class Search {
|
|||||||
langDefault = '';
|
langDefault = '';
|
||||||
limit = 20;
|
limit = 20;
|
||||||
extendedParams = false;
|
extendedParams = false;
|
||||||
|
showJson = false;
|
||||||
|
|
||||||
//stuff
|
//stuff
|
||||||
prevList = {};
|
prevList = {};
|
||||||
@@ -423,12 +533,22 @@ class Search {
|
|||||||
{label: 'выбрать даты', value: 'manual'},
|
{label: 'выбрать даты', value: 'manual'},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
generateDefaults(obj, fields) {
|
||||||
|
obj.setDefaults = (self, value = {}) => {
|
||||||
|
for (const f of fields)
|
||||||
|
self[f] = value[f] || '';
|
||||||
|
|
||||||
|
self.page = value.page || 1;
|
||||||
|
self.limit = value.limit || 50;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
created() {
|
created() {
|
||||||
this.commit = this.$store.commit;
|
this.commit = this.$store.commit;
|
||||||
this.api = this.$root.api;
|
this.api = this.$root.api;
|
||||||
|
|
||||||
this.search = this.search.setDefaults(this.search);
|
this.generateDefaults(this.search, ['author', 'series', 'title', 'genre', 'lang', 'date', 'librate']);
|
||||||
this.search.lang = this.langDefault;
|
this.search.setDefaults(this.search);
|
||||||
|
|
||||||
this.loadSettings();
|
this.loadSettings();
|
||||||
}
|
}
|
||||||
@@ -437,6 +557,17 @@ class Search {
|
|||||||
(async() => {
|
(async() => {
|
||||||
await this.api.updateConfig();
|
await this.api.updateConfig();
|
||||||
|
|
||||||
|
//устанавливаем uiDefaults от сервера, если это необходимо
|
||||||
|
if (!this.settings.defaultsSet) {
|
||||||
|
const uiDefaults = _.cloneDeep(this.config.uiDefaults);
|
||||||
|
uiDefaults.defaultsSet = true;
|
||||||
|
this.commit('setSettings', uiDefaults);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.generateDefaults(this.extSearch, this.recStruct.map(f => f.field));
|
||||||
|
this.extSearch.setDefaults(this.extSearch);
|
||||||
|
this.search.lang = this.langDefault;
|
||||||
|
|
||||||
//для встраивания в liberama
|
//для встраивания в liberama
|
||||||
window.addEventListener('message', (event) => {
|
window.addEventListener('message', (event) => {
|
||||||
if (!_.isObject(event.data) || event.data.from != 'ExternalLibs')
|
if (!_.isObject(event.data) || event.data.from != 'ExternalLibs')
|
||||||
@@ -454,11 +585,11 @@ class Search {
|
|||||||
this.$refs.authorInput.focus();
|
this.$refs.authorInput.focus();
|
||||||
|
|
||||||
this.updateListFromRoute(this.$route);
|
this.updateListFromRoute(this.$route);
|
||||||
this.updateSearchFromRouteQuery(this.$route);
|
|
||||||
|
|
||||||
this.sendMessage({type: 'mes', data: 'hello-from-inpx-web'});
|
|
||||||
|
|
||||||
this.ready = true;
|
this.ready = true;
|
||||||
|
|
||||||
|
this.sendMessage({type: 'mes', data: 'hello-from-inpx-web'});
|
||||||
|
this.updateSearchFromRouteQuery(this.$route);
|
||||||
})();
|
})();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -472,6 +603,7 @@ class Search {
|
|||||||
this.expandedSeries = _.cloneDeep(settings.expandedSeries);
|
this.expandedSeries = _.cloneDeep(settings.expandedSeries);
|
||||||
this.abCacheEnabled = settings.abCacheEnabled;
|
this.abCacheEnabled = settings.abCacheEnabled;
|
||||||
this.langDefault = settings.langDefault;
|
this.langDefault = settings.langDefault;
|
||||||
|
this.showJson = settings.showJson;
|
||||||
}
|
}
|
||||||
|
|
||||||
recvMessage(d) {
|
recvMessage(d) {
|
||||||
@@ -481,6 +613,7 @@ class Search {
|
|||||||
this.list.liberamaReady = true;
|
this.list.liberamaReady = true;
|
||||||
this.sendMessage({type: 'mes', data: 'ready'});
|
this.sendMessage({type: 'mes', data: 'ready'});
|
||||||
this.sendCurrentUrl();
|
this.sendCurrentUrl();
|
||||||
|
this.makeTitle();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -498,6 +631,13 @@ class Search {
|
|||||||
return this.$store.state.config;
|
return this.$store.state.config;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get recStruct() {
|
||||||
|
if (this.config.dbConfig && this.config.dbConfig.inpxInfo.recStruct)
|
||||||
|
return this.config.dbConfig.inpxInfo.recStruct;
|
||||||
|
else
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
get settings() {
|
get settings() {
|
||||||
return this.$store.state.settings;
|
return this.$store.state.settings;
|
||||||
}
|
}
|
||||||
@@ -529,7 +669,13 @@ class Search {
|
|||||||
get listOptions() {
|
get listOptions() {
|
||||||
const result = [];
|
const result = [];
|
||||||
for (const [route, rec] of Object.entries(route2component))
|
for (const [route, rec] of Object.entries(route2component))
|
||||||
result.push({label: rec.label, value: route});
|
if (route == 'extended') {
|
||||||
|
if (this.config.extendedSearch) {
|
||||||
|
result.push({value: route, icon: 'la la-code', size: '10px'});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
result.push({label: rec.label, value: route, icon: rec.icon});
|
||||||
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -543,6 +689,19 @@ class Search {
|
|||||||
return result.filter(s => s).join(', ');
|
return result.filter(s => s).join(', ');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get isExtendedSearch() {
|
||||||
|
return this.selectedList === 'extended';
|
||||||
|
}
|
||||||
|
|
||||||
|
get extSearchNames() {
|
||||||
|
let result = [];
|
||||||
|
for (const f of this.recStruct) {
|
||||||
|
if (this.extSearch[f.field])
|
||||||
|
result.push(`${f.field}=${this.extSearch[f.field]}`);
|
||||||
|
}
|
||||||
|
return result.join(', ');
|
||||||
|
}
|
||||||
|
|
||||||
inputBgColor(inp) {
|
inputBgColor(inp) {
|
||||||
if (inp === this.selectedList)
|
if (inp === this.selectedList)
|
||||||
return 'white';
|
return 'white';
|
||||||
@@ -552,8 +711,12 @@ class Search {
|
|||||||
|
|
||||||
async updateListFromRoute(to) {
|
async updateListFromRoute(to) {
|
||||||
const newPath = to.path;
|
const newPath = to.path;
|
||||||
|
|
||||||
let newList = this.getListRoute(newPath);
|
let newList = this.getListRoute(newPath);
|
||||||
|
if (newList == 'extended' && !this.config.extendedSearch)
|
||||||
|
newList = '';
|
||||||
newList = (newList ? newList : 'author');
|
newList = (newList ? newList : 'author');
|
||||||
|
|
||||||
if (this.selectedList != newList)
|
if (this.selectedList != newList)
|
||||||
this.selectedList = newList;
|
this.selectedList = newList;
|
||||||
}
|
}
|
||||||
@@ -582,30 +745,35 @@ class Search {
|
|||||||
|
|
||||||
let result = `Коллекция ${this.collection}`;
|
let result = `Коллекция ${this.collection}`;
|
||||||
|
|
||||||
const search = this.search;
|
if (!this.isExtendedSearch) {
|
||||||
const specSym = new Set(['*', '#']);
|
const search = this.search;
|
||||||
const correctValue = (v) => {
|
const specSym = new Set(['*', '#']);
|
||||||
if (v) {
|
const correctValue = (v) => {
|
||||||
if (v[0] === '=')
|
if (v) {
|
||||||
v = v.substring(1);
|
if (v[0] === '=')
|
||||||
else if (!specSym.has(v[0]))
|
v = v.substring(1);
|
||||||
v = '^' + v;
|
else if (!specSym.has(v[0]))
|
||||||
|
v = '^' + v;
|
||||||
|
}
|
||||||
|
return v || '';
|
||||||
|
};
|
||||||
|
|
||||||
|
if (search.author || search.series || search.title) {
|
||||||
|
const as = (search.author ? search.author.split(',') : []);
|
||||||
|
const author = (as.length ? as[0] : '') + (as.length > 1 ? ' и др.' : '');
|
||||||
|
|
||||||
|
const a = correctValue(author);
|
||||||
|
let s = correctValue(search.series);
|
||||||
|
s = (s ? `(Серия: ${s})` : '');
|
||||||
|
let t = correctValue(search.title);
|
||||||
|
t = (t ? `"${t}"` : '');
|
||||||
|
|
||||||
|
result = [s, t].filter(v => v).join(' ');
|
||||||
|
result = [a, result].filter(v => v).join(' ');
|
||||||
}
|
}
|
||||||
return v || '';
|
} else {
|
||||||
};
|
if (this.extSearchNames)
|
||||||
|
result = this.extSearchNames;
|
||||||
if (search.author || search.series || search.title) {
|
|
||||||
const as = (search.author ? search.author.split(',') : []);
|
|
||||||
const author = (as.length ? as[0] : '') + (as.length > 1 ? ' и др.' : '');
|
|
||||||
|
|
||||||
const a = correctValue(author);
|
|
||||||
let s = correctValue(search.series);
|
|
||||||
s = (s ? `(Серия: ${s})` : '');
|
|
||||||
let t = correctValue(search.title);
|
|
||||||
t = (t ? `"${t}"` : '');
|
|
||||||
|
|
||||||
result = [s, t].filter(v => v).join(' ');
|
|
||||||
result = [a, result].filter(v => v).join(' ');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.$root.setAppTitle(result);
|
this.$root.setAppTitle(result);
|
||||||
@@ -614,8 +782,7 @@ class Search {
|
|||||||
}
|
}
|
||||||
|
|
||||||
showSearchHelp() {
|
showSearchHelp() {
|
||||||
let info = '';
|
let info = `<div style="min-width: 250px" />`;
|
||||||
info += `<div style="min-width: 250px" />`;
|
|
||||||
info += `
|
info += `
|
||||||
<p>
|
<p>
|
||||||
Для раздела <b>Авторы</b>, работу поискового движка можно описать простой фразой: найти авторов по указанным критериям.
|
Для раздела <b>Авторы</b>, работу поискового движка можно описать простой фразой: найти авторов по указанным критериям.
|
||||||
@@ -643,6 +810,11 @@ class Search {
|
|||||||
Указание простого "#" в поиске по названию означает: найти всех авторов, названия книг которых начинаются не с русской или латинской буквы
|
Указание простого "#" в поиске по названию означает: найти всех авторов, названия книг которых начинаются не с русской или латинской буквы
|
||||||
</li>
|
</li>
|
||||||
<br>
|
<br>
|
||||||
|
<li>
|
||||||
|
"~" поиск по регулярному выражению. Например, для "~^\\s" в поле названия, будут найдены
|
||||||
|
все книги, названия которых начинаются с пробельного символа
|
||||||
|
</li>
|
||||||
|
<br>
|
||||||
<li>
|
<li>
|
||||||
"?" поиск пустых значений или тех, что начинаются с этого символа. Например, "?" в поле серии означает: найти всех авторов, у которых есть книги без серий
|
"?" поиск пустых значений или тех, что начинаются с этого символа. Например, "?" в поле серии означает: найти всех авторов, у которых есть книги без серий
|
||||||
или название серии начинается с "?".
|
или название серии начинается с "?".
|
||||||
@@ -654,7 +826,7 @@ class Search {
|
|||||||
<br><br>
|
<br><br>
|
||||||
Для разделов <b>Серии</b>, <b>Книги</b> все аналогично разделу <b>Авторы</b>.
|
Для разделов <b>Серии</b>, <b>Книги</b> все аналогично разделу <b>Авторы</b>.
|
||||||
</p>
|
</p>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
this.$root.stdDialog.alert(info, 'Памятка', {iconName: 'la la-info-circle'});
|
this.$root.stdDialog.alert(info, 'Памятка', {iconName: 'la la-info-circle'});
|
||||||
}
|
}
|
||||||
@@ -743,9 +915,20 @@ class Search {
|
|||||||
this.hideTooltip();
|
this.hideTooltip();
|
||||||
this.selectLibRateDialogVisible = true;
|
this.selectLibRateDialogVisible = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
selectExtSearch() {
|
||||||
|
this.hideTooltip();
|
||||||
|
this.selectExtSearchDialogVisible = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
clearExtSearch() {
|
||||||
|
const self = this.extSearch;
|
||||||
|
self.setDefaults(self, {page: self.page, limit: self.limit});
|
||||||
|
}
|
||||||
|
|
||||||
onScroll() {
|
onScroll() {
|
||||||
const curScrollTop = this.$refs.scroller.scrollTop;
|
const curScrollTop = this.$refs.scroller.scrollTop;
|
||||||
|
const toolPanelOffset = this.$refs.toolPanel.getBoundingClientRect().top;
|
||||||
|
|
||||||
if (this.ignoreScrolling) {
|
if (this.ignoreScrolling) {
|
||||||
this.lastScrollTop = curScrollTop;
|
this.lastScrollTop = curScrollTop;
|
||||||
@@ -754,21 +937,27 @@ class Search {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (this.lastScrollTop === curScrollTop)
|
||||||
|
return; //если событие вызвано более 1 раза на 1 скролл
|
||||||
|
|
||||||
if (!this.lastScrollTop)
|
if (!this.lastScrollTop)
|
||||||
this.lastScrollTop = 0;
|
this.lastScrollTop = 0;
|
||||||
if (!this.lastScrollTop2)
|
|
||||||
this.lastScrollTop2 = 0;
|
|
||||||
|
|
||||||
if (curScrollTop - this.lastScrollTop > 0) {
|
if (curScrollTop - this.lastScrollTop > 0) { //страницу крутят вверх
|
||||||
|
if (this.$refs.toolPanel.style.position == 'sticky') //если блок приклеен к окну
|
||||||
|
this.$refs.toolPanel.style.top = `${this.lastScrollTop}px`;//приклеиваем его к позиции в родителе
|
||||||
|
|
||||||
this.$refs.toolPanel.style.position = 'relative';
|
this.$refs.toolPanel.style.position = 'relative';
|
||||||
if (this.lastScrollTop2 <= curScrollTop - this.$refs.toolPanel.clientHeight)
|
(async() => {//"отложенная" коректировка, из-за артефактов в firefox
|
||||||
this.lastScrollTop2 = 0;
|
if (toolPanelOffset < -this.$refs.toolPanel.offsetHeight) { //не даём блоку оказаться дальше своей высоты за экраном
|
||||||
|
await utils.sleep(10);
|
||||||
|
this.$refs.toolPanel.style.top = `${curScrollTop - this.$refs.toolPanel.offsetHeight}px`;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
this.$refs.toolPanel.style.top = `${this.lastScrollTop2}px`;
|
} else if (toolPanelOffset >= 0) {
|
||||||
} else {
|
this.$refs.toolPanel.style.top = '0px';
|
||||||
this.$refs.toolPanel.style.position = 'sticky';
|
this.$refs.toolPanel.style.position = 'sticky';
|
||||||
this.$refs.toolPanel.style.top = 0;
|
|
||||||
this.lastScrollTop2 = curScrollTop;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.lastScrollTop = curScrollTop;
|
this.lastScrollTop = curScrollTop;
|
||||||
@@ -778,14 +967,14 @@ class Search {
|
|||||||
this.ignoreScrolling = true;
|
this.ignoreScrolling = true;
|
||||||
await utils.sleep(ms);
|
await utils.sleep(ms);
|
||||||
await this.$nextTick();
|
await this.$nextTick();
|
||||||
await this.$nextTick();
|
|
||||||
await this.$nextTick();
|
|
||||||
this.ignoreScrolling = false;
|
this.ignoreScrolling = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
scrollToTop() {
|
scrollToTop() {
|
||||||
this.$refs.scroller.scrollTop = 0;
|
this.$refs.scroller.scrollTop = 0;
|
||||||
this.lastScrollTop = 0;
|
this.lastScrollTop = 0;
|
||||||
|
this.$refs.toolPanel.style.top = '0px';
|
||||||
|
this.$refs.toolPanel.style.position = 'sticky';
|
||||||
}
|
}
|
||||||
|
|
||||||
updatePageCount() {
|
updatePageCount() {
|
||||||
@@ -847,6 +1036,8 @@ class Search {
|
|||||||
}
|
}
|
||||||
|
|
||||||
updateSearchFromRouteQuery(to) {
|
updateSearchFromRouteQuery(to) {
|
||||||
|
if (!this.ready)
|
||||||
|
return;
|
||||||
if (this.list.liberamaReady)
|
if (this.list.liberamaReady)
|
||||||
this.sendCurrentUrl();
|
this.sendCurrentUrl();
|
||||||
|
|
||||||
@@ -855,22 +1046,34 @@ class Search {
|
|||||||
|
|
||||||
const query = to.query;
|
const query = to.query;
|
||||||
|
|
||||||
this.search = this.search.setDefaults(
|
this.search.setDefaults(this.search, {
|
||||||
Object.assign({}, this.search, {
|
author: query.author,
|
||||||
author: query.author,
|
series: query.series,
|
||||||
series: query.series,
|
title: query.title,
|
||||||
title: query.title,
|
genre: query.genre,
|
||||||
genre: query.genre,
|
lang: (typeof(query.lang) == 'string' ? query.lang : this.langDefault),
|
||||||
lang: (typeof(query.lang) == 'string' ? query.lang : this.langDefault),
|
date: query.date,
|
||||||
date: query.date,
|
librate: query.librate,
|
||||||
librate: query.librate,
|
|
||||||
page: parseInt(query.page, 10),
|
|
||||||
limit: parseInt(query.limit, 10) || this.search.limit,
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
if (this.search.limit > 1000)
|
page: parseInt(query.page, 10),
|
||||||
this.search.limit = 1000;
|
limit: parseInt(query.limit, 10) || this.search.limit,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (this.search.limit > maxLimit)
|
||||||
|
this.search.limit = maxLimit;
|
||||||
|
|
||||||
|
const queryExtSearch = {
|
||||||
|
page: this.search.page,
|
||||||
|
limit: this.search.limit,
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const f of this.recStruct) {
|
||||||
|
const field = `ex_${f.field}`;
|
||||||
|
if (query[field])
|
||||||
|
queryExtSearch[f.field] = query[field];
|
||||||
|
}
|
||||||
|
|
||||||
|
this.extSearch.setDefaults(this.extSearch, queryExtSearch);
|
||||||
}
|
}
|
||||||
|
|
||||||
updateRouteQueryFromSearch() {
|
updateRouteQueryFromSearch() {
|
||||||
@@ -880,11 +1083,12 @@ class Search {
|
|||||||
this.routeUpdating = true;
|
this.routeUpdating = true;
|
||||||
try {
|
try {
|
||||||
const oldQuery = this.$route.query;
|
const oldQuery = this.$route.query;
|
||||||
const cloned = _.cloneDeep(this.search);
|
let query = {};
|
||||||
|
|
||||||
delete cloned.setDefaults;
|
const cloned = {};
|
||||||
|
this.search.setDefaults(cloned, this.search);
|
||||||
|
|
||||||
const query = _.pickBy(cloned);
|
query = _.pickBy(cloned);
|
||||||
|
|
||||||
if (this.search.lang == this.langDefault) {
|
if (this.search.lang == this.langDefault) {
|
||||||
delete query.lang;
|
delete query.lang;
|
||||||
@@ -892,6 +1096,12 @@ class Search {
|
|||||||
query.lang = this.search.lang;
|
query.lang = this.search.lang;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for (const f of this.recStruct) {
|
||||||
|
const field = `ex_${f.field}`;
|
||||||
|
if (this.extSearch[f.field])
|
||||||
|
query[field] = this.extSearch[f.field];
|
||||||
|
}
|
||||||
|
|
||||||
const diff = diffUtils.getObjDiff(oldQuery, query);
|
const diff = diffUtils.getObjDiff(oldQuery, query);
|
||||||
if (!diffUtils.isEmptyObjDiff(diff)) {
|
if (!diffUtils.isEmptyObjDiff(diff)) {
|
||||||
this.$router.replace({path: this.selectedList, query});
|
this.$router.replace({path: this.selectedList, query});
|
||||||
@@ -990,6 +1200,12 @@ class Search {
|
|||||||
window.open(window.location.href, '_blank');
|
window.open(window.location.href, '_blank');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
extToList(list) {
|
||||||
|
if (this.extSearch[list])
|
||||||
|
this.search[list] = this.extSearch[list];
|
||||||
|
this.selectedList = list;
|
||||||
|
}
|
||||||
|
|
||||||
async logout() {
|
async logout() {
|
||||||
await this.api.logout();
|
await this.api.logout();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,205 @@
|
|||||||
|
<template>
|
||||||
|
<Dialog ref="dialog" v-model="dialogVisible">
|
||||||
|
<template #header>
|
||||||
|
<div class="row items-center">
|
||||||
|
<div style="font-size: 110%">
|
||||||
|
Расширенный поиск
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DivBtn class="q-ml-sm text-grey-5 bg-yellow-1" :size="28" :icon-size="24" icon="la la-question" round @click.stop.prevent="showSearchHelp">
|
||||||
|
<template #tooltip>
|
||||||
|
<q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||||
|
Памятка
|
||||||
|
</q-tooltip>
|
||||||
|
</template>
|
||||||
|
</DivBtn>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<div ref="box" class="column q-mt-xs overflow-auto" style="max-width: 660px; padding: 0px 10px 10px 10px;">
|
||||||
|
<div class="row">
|
||||||
|
<div v-for="f in recStruct" :key="f.field" class="row">
|
||||||
|
<div class="q-mx-xs" />
|
||||||
|
<q-input
|
||||||
|
v-model="search[f.field]" :maxlength="5000"
|
||||||
|
class="q-mt-xs" style="width: 150px;" :label="`(${f.type}) ${f.field}`"
|
||||||
|
:bg-color="bgColor[f.field] || 'white'"
|
||||||
|
stack-label outlined dense clearable
|
||||||
|
@keydown="onKeyDown"
|
||||||
|
>
|
||||||
|
<q-tooltip v-if="search[f.field]" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||||
|
{{ search[f.field] }}
|
||||||
|
</q-tooltip>
|
||||||
|
</q-input>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="row q-mt-xs q-ml-sm" style="color: red" v-html="error" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template #footer>
|
||||||
|
<q-btn class="q-px-md q-ml-sm" color="primary" dense no-caps :disabled="error !== ''" @click="apply">
|
||||||
|
Применить
|
||||||
|
</q-btn>
|
||||||
|
</template>
|
||||||
|
</Dialog>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
//-----------------------------------------------------------------------------
|
||||||
|
import vueComponent from '../../vueComponent.js';
|
||||||
|
|
||||||
|
import Dialog from '../../share/Dialog.vue';
|
||||||
|
import DivBtn from '../../share/DivBtn.vue';
|
||||||
|
|
||||||
|
import _ from 'lodash';
|
||||||
|
|
||||||
|
const componentOptions = {
|
||||||
|
components: {
|
||||||
|
Dialog,
|
||||||
|
DivBtn,
|
||||||
|
},
|
||||||
|
watch: {
|
||||||
|
modelValue(newValue) {
|
||||||
|
this.dialogVisible = newValue;
|
||||||
|
},
|
||||||
|
dialogVisible(newValue) {
|
||||||
|
this.$emit('update:modelValue', newValue);
|
||||||
|
},
|
||||||
|
extSearch: {
|
||||||
|
handler(newValue) {
|
||||||
|
this.search = _.cloneDeep(newValue);
|
||||||
|
},
|
||||||
|
deep: true,
|
||||||
|
},
|
||||||
|
search: {
|
||||||
|
handler() {
|
||||||
|
this.validate();
|
||||||
|
},
|
||||||
|
deep: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
};
|
||||||
|
class SelectExtSearchDialog {
|
||||||
|
_options = componentOptions;
|
||||||
|
_props = {
|
||||||
|
modelValue: Boolean,
|
||||||
|
extSearch: Object,
|
||||||
|
};
|
||||||
|
|
||||||
|
dialogVisible = false;
|
||||||
|
search = {};
|
||||||
|
bgColor = {};
|
||||||
|
error = '';
|
||||||
|
|
||||||
|
created() {
|
||||||
|
this.commit = this.$store.commit;
|
||||||
|
}
|
||||||
|
|
||||||
|
mounted() {
|
||||||
|
}
|
||||||
|
|
||||||
|
get config() {
|
||||||
|
return this.$store.state.config;
|
||||||
|
}
|
||||||
|
|
||||||
|
get recStruct() {
|
||||||
|
if (this.config.dbConfig && this.config.dbConfig.inpxInfo.recStruct)
|
||||||
|
return this.config.dbConfig.inpxInfo.recStruct;
|
||||||
|
else
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
validate() {
|
||||||
|
const validNumValue = (n) => {
|
||||||
|
const validChars = new Set('0123456789.'.split(''));
|
||||||
|
for (const c of n.split(''))
|
||||||
|
if (!validChars.has(c))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
const v = n.split('..');
|
||||||
|
if ( isNaN(parseInt(v[0] || '0', 10)) || isNaN(parseInt(v[1] || '0', 10)) )
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
let error = [];
|
||||||
|
const s = this.search;
|
||||||
|
for (const f of this.recStruct) {
|
||||||
|
if (f.type == 'N' && s[f.field] && !validNumValue(s[f.field])) {
|
||||||
|
error.push(`Недопустимое значение поля ${f.field}`);
|
||||||
|
this.bgColor[f.field] = 'red-2';
|
||||||
|
} else {
|
||||||
|
this.bgColor[f.field] = '';//default
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.error = error.join('<br>');
|
||||||
|
}
|
||||||
|
|
||||||
|
showSearchHelp() {
|
||||||
|
let info = `<div style="min-width: 250px" />`;
|
||||||
|
info += `
|
||||||
|
<p>
|
||||||
|
Расширенный поиск ведется непосредственно по значениям атрибутов записей описания книг.
|
||||||
|
Атрибуты можно увидеть, если включить опцию "Показывать JSON".
|
||||||
|
Названия атрибутов (кроме "_uid" и "id") соответствуют названиям полей струкутры записей из inpx-файла.
|
||||||
|
На поисковые значения действуют те же правила, что и для разделов "Авторы", "Серии", "Книги".
|
||||||
|
<br>
|
||||||
|
Для строковых значений (S):
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
без префикса: значение трактуется, как "начинается с"
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
префикс "=": поиск по точному совпадению
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
префикс "*": поиск подстроки в строке
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
префикс "#": поиск подстроки в строке, но только среди начинающихся не с латинского или кириллического символа
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
префикс "~": поиск по регулярному выражению
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
префикс "?": поиск пустых значений или тех, что начинаются с этого символа
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
Для числовых значений (N):
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
число N: поиск по точному совпадению
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
диапазон N..M: поиск по диапазону числовых значений, включая N и M. Например, поисковое значение 1024..2048 в поле "size"
|
||||||
|
найдет все ссылки на файлы размером от 1КБ до 2КБ.
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</p>
|
||||||
|
`;
|
||||||
|
|
||||||
|
this.$root.stdDialog.alert(info, 'Памятка', {iconName: 'la la-info-circle'});
|
||||||
|
}
|
||||||
|
|
||||||
|
onKeyDown(event) {
|
||||||
|
if (event.code == 'Enter')
|
||||||
|
this.apply();
|
||||||
|
}
|
||||||
|
|
||||||
|
apply() {
|
||||||
|
this.validate();
|
||||||
|
if (!this.error) {
|
||||||
|
this.$emit('update:extSearch', _.cloneDeep(this.search));
|
||||||
|
this.dialogVisible = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default vueComponent(SelectExtSearchDialog);
|
||||||
|
//-----------------------------------------------------------------------------
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
</style>
|
||||||
@@ -19,7 +19,8 @@
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<q-checkbox v-model="showCounts" size="36px" label="Показывать количество" />
|
<q-checkbox v-model="downloadAsZip" size="36px" label="Скачивать книги в виде zip-архива" />
|
||||||
|
<q-checkbox v-model="showCounts" size="36px" label="Показывать количество" />
|
||||||
<q-checkbox v-model="showRates" size="36px" label="Показывать оценки" />
|
<q-checkbox v-model="showRates" size="36px" label="Показывать оценки" />
|
||||||
<q-checkbox v-model="showInfo" size="36px" label="Показывать кнопку (инфо)" />
|
<q-checkbox v-model="showInfo" size="36px" label="Показывать кнопку (инфо)" />
|
||||||
<q-checkbox v-model="showGenres" size="36px" label="Показывать жанры" />
|
<q-checkbox v-model="showGenres" size="36px" label="Показывать жанры" />
|
||||||
@@ -60,6 +61,9 @@ const componentOptions = {
|
|||||||
limit(newValue) {
|
limit(newValue) {
|
||||||
this.commit('setSettings', {'limit': newValue});
|
this.commit('setSettings', {'limit': newValue});
|
||||||
},
|
},
|
||||||
|
downloadAsZip(newValue) {
|
||||||
|
this.commit('setSettings', {'downloadAsZip': newValue});
|
||||||
|
},
|
||||||
showCounts(newValue) {
|
showCounts(newValue) {
|
||||||
this.commit('setSettings', {'showCounts': newValue});
|
this.commit('setSettings', {'showCounts': newValue});
|
||||||
},
|
},
|
||||||
@@ -93,6 +97,7 @@ class SettingsDialog {
|
|||||||
|
|
||||||
//settings
|
//settings
|
||||||
limit = 20;
|
limit = 20;
|
||||||
|
downloadAsZip = false;
|
||||||
showCounts = true;
|
showCounts = true;
|
||||||
showRates = true;
|
showRates = true;
|
||||||
showInfo = true;
|
showInfo = true;
|
||||||
@@ -129,6 +134,7 @@ class SettingsDialog {
|
|||||||
|
|
||||||
this.limit = settings.limit;
|
this.limit = settings.limit;
|
||||||
|
|
||||||
|
this.downloadAsZip = settings.downloadAsZip;
|
||||||
this.showCounts = settings.showCounts;
|
this.showCounts = settings.showCounts;
|
||||||
this.showRates = settings.showRates;
|
this.showRates = settings.showRates;
|
||||||
this.showInfo = settings.showInfo;
|
this.showInfo = settings.showInfo;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<template>
|
<template>
|
||||||
<div ref="btn" class="button clickable row justify-center items-center" @click="clickEffect">
|
<div ref="btn" class="button clickable row justify-center items-center" :class="{disabled}" @click.stop.prevent="clickEffect">
|
||||||
<div class="row justify-center items-center no-wrap" :class="{'button-pressed': pressed}">
|
<div class="row justify-center items-center no-wrap" :class="{'button-pressed': pressed}">
|
||||||
<i :class="icon" :style="`font-size: ${iconSize}px; margin-top: ${imt}px`" />
|
<i :class="icon" :style="`font-size: ${iconSize}px; margin-top: ${imt}px`" />
|
||||||
<slot></slot>
|
<slot></slot>
|
||||||
@@ -29,8 +29,10 @@ class DivBtn {
|
|||||||
height: { type: Number, default: 0 },
|
height: { type: Number, default: 0 },
|
||||||
icon: { type: String, default: '' },
|
icon: { type: String, default: '' },
|
||||||
iconSize: { type: Number, default: 14 },
|
iconSize: { type: Number, default: 14 },
|
||||||
round: { type: Boolean },
|
round: Boolean,
|
||||||
imt: { type: Number, default: 0 },// icon margin top
|
imt: { type: Number, default: 0 },// icon margin top
|
||||||
|
disabled: Boolean,
|
||||||
|
noShadow: Boolean,
|
||||||
};
|
};
|
||||||
|
|
||||||
pressed = false;
|
pressed = false;
|
||||||
@@ -55,9 +57,17 @@ class DivBtn {
|
|||||||
style.borderRadius = `${this.size}px`;
|
style.borderRadius = `${this.size}px`;
|
||||||
else
|
else
|
||||||
style.borderRadius = `${this.size/10}px`;
|
style.borderRadius = `${this.size/10}px`;
|
||||||
|
|
||||||
|
if (!this.noShadow)
|
||||||
|
style.boxShadow = '0.5px 1px 3px #333333';
|
||||||
}
|
}
|
||||||
|
|
||||||
async clickEffect() {
|
async clickEffect(event) {
|
||||||
|
if (this.disabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.$emit('meClick', event);
|
||||||
this.pressed = true;
|
this.pressed = true;
|
||||||
await utils.sleep(100);
|
await utils.sleep(100);
|
||||||
this.pressed = false;
|
this.pressed = false;
|
||||||
@@ -71,7 +81,6 @@ export default vueComponent(DivBtn);
|
|||||||
<style scoped>
|
<style scoped>
|
||||||
.button {
|
.button {
|
||||||
position: relative;
|
position: relative;
|
||||||
box-shadow: 0.5px 1px 3px #333333;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.button:hover {
|
.button:hover {
|
||||||
|
|||||||
@@ -74,7 +74,8 @@ const componentOptions = {
|
|||||||
this.checkErrorAndEmit(true);
|
this.checkErrorAndEmit(true);
|
||||||
},
|
},
|
||||||
modelValue(newValue) {
|
modelValue(newValue) {
|
||||||
this.filteredValue = newValue;
|
if (this.ready)//исправление бага TypeError: Cannot read properties of null (reading 'emitsOptions')
|
||||||
|
this.filteredValue = newValue;
|
||||||
},
|
},
|
||||||
min() {
|
min() {
|
||||||
this.checkErrorAndEmit();
|
this.checkErrorAndEmit();
|
||||||
@@ -102,7 +103,8 @@ class NumInput {
|
|||||||
filteredValue = 0;
|
filteredValue = 0;
|
||||||
error = false;
|
error = false;
|
||||||
|
|
||||||
created() {
|
mounted() {
|
||||||
|
this.ready = true;
|
||||||
this.filteredValue = this.modelValue;
|
this.filteredValue = this.modelValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ const myRoutes = [
|
|||||||
['/author', Search],
|
['/author', Search],
|
||||||
['/series', Search],
|
['/series', Search],
|
||||||
['/title', Search],
|
['/title', Search],
|
||||||
|
['/extended', Search],
|
||||||
['/:pathMatch(.*)*', null, null, '/'],
|
['/:pathMatch(.*)*', null, null, '/'],
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -36,14 +36,14 @@ export function keyEventToCode(event) {
|
|||||||
|
|
||||||
export function wordEnding(num, type = 0) {
|
export function wordEnding(num, type = 0) {
|
||||||
const endings = [
|
const endings = [
|
||||||
['ов', '', 'а', 'а', 'а', 'ов', 'ов', 'ов', 'ов', 'ов'],
|
['ов', '', 'а', 'а', 'а', 'ов', 'ов', 'ов', 'ов', 'ов'],//0
|
||||||
['й', 'я', 'и', 'и', 'и', 'й', 'й', 'й', 'й', 'й'],
|
['й', 'я', 'и', 'и', 'и', 'й', 'й', 'й', 'й', 'й'],//1
|
||||||
['о', '', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о'],
|
['о', '', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о'],//2
|
||||||
['ий', 'ие', 'ия', 'ия', 'ия', 'ий', 'ий', 'ий', 'ий', 'ий'],
|
['ий', 'ие', 'ия', 'ия', 'ия', 'ий', 'ий', 'ий', 'ий', 'ий'],//3
|
||||||
['о', 'а', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о'],
|
['о', 'а', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о'],//4
|
||||||
['ок', 'ка', 'ки', 'ки', 'ки', 'ок', 'ок', 'ок', 'ок', 'ок'],
|
['ок', 'ка', 'ки', 'ки', 'ки', 'ок', 'ок', 'ок', 'ок', 'ок'],//5
|
||||||
['ых', 'ое', 'ых', 'ых', 'ых', 'ых', 'ых', 'ых', 'ых', 'ых'],
|
['ых', 'ое', 'ых', 'ых', 'ых', 'ых', 'ых', 'ых', 'ых', 'ых'],//6
|
||||||
['о', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о'],
|
['о', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о'],//7
|
||||||
];
|
];
|
||||||
const deci = num % 100;
|
const deci = num % 100;
|
||||||
if (deci > 10 && deci < 20) {
|
if (deci > 10 && deci < 20) {
|
||||||
|
|||||||
@@ -4,9 +4,14 @@ const state = {
|
|||||||
settings: {
|
settings: {
|
||||||
accessToken: '',
|
accessToken: '',
|
||||||
extendedParams: false,
|
extendedParams: false,
|
||||||
limit: 20,
|
|
||||||
expandedAuthor: [],
|
expandedAuthor: [],
|
||||||
expandedSeries: [],
|
expandedSeries: [],
|
||||||
|
|
||||||
|
defaultsSet: false,
|
||||||
|
|
||||||
|
//uiDefaults
|
||||||
|
limit: 20,
|
||||||
|
downloadAsZip: false,
|
||||||
showCounts: true,
|
showCounts: true,
|
||||||
showRates: true,
|
showRates: true,
|
||||||
showInfo: true,
|
showInfo: true,
|
||||||
@@ -15,6 +20,7 @@ const state = {
|
|||||||
showDeleted: false,
|
showDeleted: false,
|
||||||
abCacheEnabled: true,
|
abCacheEnabled: true,
|
||||||
langDefault: '',
|
langDefault: '',
|
||||||
|
showJson: false,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
3799
package-lock.json
generated
3799
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
58
package.json
58
package.json
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "inpx-web",
|
"name": "inpx-web",
|
||||||
"version": "1.3.3",
|
"version": "1.5.2",
|
||||||
"author": "Book Pauk <bookpauk@gmail.com>",
|
"author": "Book Pauk <bookpauk@gmail.com>",
|
||||||
"license": "CC0-1.0",
|
"license": "CC0-1.0",
|
||||||
"repository": "bookpauk/inpx-web",
|
"repository": "bookpauk/inpx-web",
|
||||||
@@ -11,10 +11,11 @@
|
|||||||
"dev": "nodemon --inspect --ignore server/.inpx-web --ignore client --exec 'node --expose-gc server --lib-dir=server/.inpx-web/lib'",
|
"dev": "nodemon --inspect --ignore server/.inpx-web --ignore client --exec 'node --expose-gc server --lib-dir=server/.inpx-web/lib'",
|
||||||
"build:client": "webpack --config build/webpack.prod.config.js",
|
"build:client": "webpack --config build/webpack.prod.config.js",
|
||||||
"build:linux": "npm run build:client && node build/prepkg.js linux && pkg -t node16-linux-x64 -C GZip --options max-old-space-size=4096,expose-gc -o dist/linux/inpx-web .",
|
"build:linux": "npm run build:client && node build/prepkg.js linux && pkg -t node16-linux-x64 -C GZip --options max-old-space-size=4096,expose-gc -o dist/linux/inpx-web .",
|
||||||
|
"build:linux-arm64": "npm run build:client && node build/prepkg.js linux-arm64 && pkg -t node16-linuxstatic-arm64 -C GZip --options max-old-space-size=4096,expose-gc -o dist/linux-arm64/inpx-web .",
|
||||||
"build:win": "npm run build:client && node build/prepkg.js win && pkg -t node16-win-x64 -C GZip --options max-old-space-size=4096,expose-gc -o dist/win/inpx-web .",
|
"build:win": "npm run build:client && node build/prepkg.js win && pkg -t node16-win-x64 -C GZip --options max-old-space-size=4096,expose-gc -o dist/win/inpx-web .",
|
||||||
"build:macos": "npm run build:client && node build/prepkg.js macos && pkg -t node16-macos-x64 -C GZip --options max-old-space-size=4096,expose-gc -o dist/macos/inpx-web .",
|
"build:macos": "npm run build:client && node build/prepkg.js macos && pkg -t node16-macos-x64 -C GZip --options max-old-space-size=4096,expose-gc -o dist/macos/inpx-web .",
|
||||||
"build:client-dev": "webpack --config build/webpack.dev.config.js",
|
"build:client-dev": "webpack --config build/webpack.dev.config.js",
|
||||||
"build:all": "npm run build:linux && npm run build:win && npm run build:macos",
|
"build:all": "npm run build:linux && npm run build:win && npm run build:macos && npm run build:linux-arm64",
|
||||||
"release": "npm run build:all && node build/release.js",
|
"release": "npm run build:all && node build/release.js",
|
||||||
"postinstall": "npm run build:client-dev"
|
"postinstall": "npm run build:client-dev"
|
||||||
},
|
},
|
||||||
@@ -24,53 +25,54 @@
|
|||||||
"assets": "dist/public.json"
|
"assets": "dist/public.json"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@babel/core": "^7.18.9",
|
"@babel/core": "^7.20.5",
|
||||||
"@babel/eslint-parser": "^7.18.9",
|
"@babel/eslint-parser": "^7.19.1",
|
||||||
"@babel/eslint-plugin": "^7.17.7",
|
"@babel/eslint-plugin": "^7.19.1",
|
||||||
"@babel/plugin-proposal-decorators": "^7.18.9",
|
"@babel/plugin-proposal-decorators": "^7.20.5",
|
||||||
"@babel/preset-env": "^7.18.9",
|
"@babel/preset-env": "^7.20.2",
|
||||||
"@vue/compiler-sfc": "^3.2.22",
|
"@vue/compiler-sfc": "^3.2.22",
|
||||||
"babel-loader": "^8.2.5",
|
"babel-loader": "^9.1.0",
|
||||||
"copy-webpack-plugin": "^11.0.0",
|
"copy-webpack-plugin": "^11.0.0",
|
||||||
"css-loader": "^6.7.1",
|
"css-loader": "^6.7.2",
|
||||||
"css-minimizer-webpack-plugin": "^4.0.0",
|
"css-minimizer-webpack-plugin": "^4.2.2",
|
||||||
"eslint": "^8.20.0",
|
"eslint": "^8.28.0",
|
||||||
"eslint-plugin-vue": "^9.3.0",
|
"eslint-plugin-vue": "^9.8.0",
|
||||||
"html-webpack-plugin": "^5.5.0",
|
"html-webpack-plugin": "^5.5.0",
|
||||||
"mini-css-extract-plugin": "^2.6.1",
|
"mini-css-extract-plugin": "^2.7.1",
|
||||||
"pkg": "^5.8.0",
|
"pkg": "^5.8.0",
|
||||||
"showdown": "^2.1.0",
|
"showdown": "^2.1.0",
|
||||||
"terser-webpack-plugin": "^5.3.3",
|
"terser-webpack-plugin": "^5.3.6",
|
||||||
"vue-eslint-parser": "^9.0.3",
|
"vue-eslint-parser": "^9.1.0",
|
||||||
"vue-loader": "^17.0.0",
|
"vue-loader": "^17.0.1",
|
||||||
"vue-style-loader": "^4.1.3",
|
"vue-style-loader": "^4.1.3",
|
||||||
"webpack": "^5.74.0",
|
"webpack": "^5.75.0",
|
||||||
"webpack-cli": "^4.10.0",
|
"webpack-cli": "^5.0.0",
|
||||||
"webpack-dev-middleware": "^5.3.3",
|
"webpack-dev-middleware": "^6.0.1",
|
||||||
"webpack-hot-middleware": "^2.25.1",
|
"webpack-hot-middleware": "^2.25.3",
|
||||||
"webpack-merge": "^5.8.0"
|
"webpack-merge": "^5.8.0"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@quasar/extras": "^1.15.0",
|
"@quasar/extras": "^1.15.6",
|
||||||
"axios": "^0.27.2",
|
"axios": "^0.27.2",
|
||||||
"chardet": "^1.5.0",
|
"chardet": "^1.5.0",
|
||||||
"dayjs": "^1.11.6",
|
"dayjs": "^1.11.6",
|
||||||
"express": "^4.18.1",
|
"express": "^4.18.2",
|
||||||
"express-basic-auth": "^1.2.1",
|
"express-basic-auth": "^1.2.1",
|
||||||
"fs-extra": "^10.1.0",
|
"fs-extra": "^10.1.0",
|
||||||
"he": "^1.2.0",
|
"he": "^1.2.0",
|
||||||
"iconv-lite": "^0.6.3",
|
"iconv-lite": "^0.6.3",
|
||||||
"jembadb": "^5.1.4",
|
"jembadb": "^5.1.7",
|
||||||
"localforage": "^1.10.0",
|
"localforage": "^1.10.0",
|
||||||
"lodash": "^4.17.21",
|
"lodash": "^4.17.21",
|
||||||
"minimist": "^1.2.6",
|
"minimist": "^1.2.7",
|
||||||
"node-stream-zip": "^1.15.0",
|
"node-stream-zip": "^1.15.0",
|
||||||
"quasar": "^2.7.5",
|
"quasar": "^2.10.2",
|
||||||
"safe-buffer": "^5.2.1",
|
"safe-buffer": "^5.2.1",
|
||||||
"vue": "^3.2.37",
|
"vue": "^3.2.37",
|
||||||
"vue-router": "^4.1.2",
|
"vue-router": "^4.1.6",
|
||||||
"vuex": "^4.0.2",
|
"vuex": "^4.1.0",
|
||||||
"vuex-persist": "^3.1.3",
|
"vuex-persist": "^3.1.3",
|
||||||
"ws": "^8.8.1"
|
"ws": "^8.11.0",
|
||||||
|
"yazl": "^2.5.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,15 +9,18 @@ module.exports = {
|
|||||||
name: pckg.name,
|
name: pckg.name,
|
||||||
|
|
||||||
execDir,
|
execDir,
|
||||||
|
libDir: '',
|
||||||
|
inpx: '',
|
||||||
|
|
||||||
accessPassword: '',
|
accessPassword: '',
|
||||||
accessTimeout: 0,
|
accessTimeout: 0,
|
||||||
|
extendedSearch: true,
|
||||||
bookReadLink: '',
|
bookReadLink: '',
|
||||||
loggingEnabled: true,
|
loggingEnabled: true,
|
||||||
|
|
||||||
//поправить в случае, если были критические изменения в DbCreator или InpxParser
|
//поправить в случае, если были критические изменения в DbCreator или InpxParser
|
||||||
//иначе будет рассинхронизация между сервером и клиентом на уровне БД
|
//иначе будет рассинхронизация между сервером и клиентом на уровне БД
|
||||||
dbVersion: '8',
|
dbVersion: '11',
|
||||||
dbCacheSize: 5,
|
dbCacheSize: 5,
|
||||||
|
|
||||||
maxPayloadSize: 500,//in MB
|
maxPayloadSize: 500,//in MB
|
||||||
@@ -30,7 +33,7 @@ module.exports = {
|
|||||||
lowMemoryMode: false,
|
lowMemoryMode: false,
|
||||||
fullOptimization: false,
|
fullOptimization: false,
|
||||||
|
|
||||||
webConfigParams: ['name', 'version', 'branch', 'bookReadLink', 'dbVersion'],
|
webConfigParams: ['name', 'version', 'branch', 'bookReadLink', 'dbVersion', 'extendedSearch', 'uiDefaults'],
|
||||||
|
|
||||||
allowRemoteLib: false,
|
allowRemoteLib: false,
|
||||||
remoteLib: false,
|
remoteLib: false,
|
||||||
@@ -45,12 +48,27 @@ module.exports = {
|
|||||||
server: {
|
server: {
|
||||||
host: '0.0.0.0',
|
host: '0.0.0.0',
|
||||||
port: '22380',
|
port: '22380',
|
||||||
|
root: '',
|
||||||
},
|
},
|
||||||
//opds: false,
|
//opds: false,
|
||||||
opds: {
|
opds: {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
user: '',
|
user: '',
|
||||||
password: '',
|
password: '',
|
||||||
|
root: '/opds',
|
||||||
|
},
|
||||||
|
uiDefaults: {
|
||||||
|
limit: 20,
|
||||||
|
downloadAsZip: false,
|
||||||
|
showCounts: true,
|
||||||
|
showRates: true,
|
||||||
|
showInfo: true,
|
||||||
|
showGenres: true,
|
||||||
|
showDates: false,
|
||||||
|
showDeleted: false,
|
||||||
|
abCacheEnabled: true,
|
||||||
|
langDefault: '',
|
||||||
|
showJson: false,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -5,8 +5,11 @@ const fs = require('fs-extra');
|
|||||||
const branchFilename = __dirname + '/application_env';
|
const branchFilename = __dirname + '/application_env';
|
||||||
|
|
||||||
const propsToSave = [
|
const propsToSave = [
|
||||||
|
'libDir',
|
||||||
|
'inpx',
|
||||||
'accessPassword',
|
'accessPassword',
|
||||||
'accessTimeout',
|
'accessTimeout',
|
||||||
|
'extendedSearch',
|
||||||
'bookReadLink',
|
'bookReadLink',
|
||||||
'loggingEnabled',
|
'loggingEnabled',
|
||||||
'dbCacheSize',
|
'dbCacheSize',
|
||||||
@@ -22,6 +25,7 @@ const propsToSave = [
|
|||||||
'remoteLib',
|
'remoteLib',
|
||||||
'server',
|
'server',
|
||||||
'opds',
|
'opds',
|
||||||
|
'uiDefaults',
|
||||||
];
|
];
|
||||||
|
|
||||||
let instance = null;
|
let instance = null;
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ module.exports = Object.assign({}, base, {
|
|||||||
server: {
|
server: {
|
||||||
host: '0.0.0.0',
|
host: '0.0.0.0',
|
||||||
port: '12380',
|
port: '12380',
|
||||||
|
root: '',
|
||||||
},
|
},
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -87,6 +87,8 @@ class WebSocketController {
|
|||||||
await this.getWorkerState(req, ws); break;
|
await this.getWorkerState(req, ws); break;
|
||||||
case 'search':
|
case 'search':
|
||||||
await this.search(req, ws); break;
|
await this.search(req, ws); break;
|
||||||
|
case 'bookSearch':
|
||||||
|
await this.bookSearch(req, ws); break;
|
||||||
case 'get-author-book-list':
|
case 'get-author-book-list':
|
||||||
await this.getAuthorBookList(req, ws); break;
|
await this.getAuthorBookList(req, ws); break;
|
||||||
case 'get-author-series-list':
|
case 'get-author-series-list':
|
||||||
@@ -165,6 +167,17 @@ class WebSocketController {
|
|||||||
this.send(result, req, ws);
|
this.send(result, req, ws);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async bookSearch(req, ws) {
|
||||||
|
if (!this.config.extendedSearch)
|
||||||
|
throw new Error('config.extendedSearch disabled');
|
||||||
|
if (!req.query)
|
||||||
|
throw new Error(`query is empty`);
|
||||||
|
|
||||||
|
const result = await this.webWorker.bookSearch(req.query);
|
||||||
|
|
||||||
|
this.send(result, req, ws);
|
||||||
|
}
|
||||||
|
|
||||||
async getAuthorBookList(req, ws) {
|
async getAuthorBookList(req, ws) {
|
||||||
const result = await this.webWorker.getAuthorBookList(req.authorId);
|
const result = await this.webWorker.getAuthorBookList(req.authorId);
|
||||||
|
|
||||||
|
|||||||
@@ -261,7 +261,7 @@ class DbCreator {
|
|||||||
|
|
||||||
//парсинг
|
//парсинг
|
||||||
const parser = new InpxParser();
|
const parser = new InpxParser();
|
||||||
await parser.parse(config.inpxFile, readFileCallback, parsedCallback);
|
await parser.parse(config.inpxFile, readFileCallback, parsedCallback);
|
||||||
|
|
||||||
//чистка памяти, ибо жрет как не в себя
|
//чистка памяти, ибо жрет как не в себя
|
||||||
authorMap = null;
|
authorMap = null;
|
||||||
@@ -337,7 +337,7 @@ class DbCreator {
|
|||||||
//сохраним поисковые таблицы
|
//сохраним поисковые таблицы
|
||||||
const chunkSize = 10000;
|
const chunkSize = 10000;
|
||||||
|
|
||||||
const saveTable = async(table, arr, nullArr, indexType = 'string') => {
|
const saveTable = async(table, arr, nullArr, indexType = 'string', delEmpty = false) => {
|
||||||
|
|
||||||
if (indexType == 'string')
|
if (indexType == 'string')
|
||||||
arr.sort((a, b) => a.value.localeCompare(b.value));
|
arr.sort((a, b) => a.value.localeCompare(b.value));
|
||||||
@@ -366,6 +366,13 @@ class DbCreator {
|
|||||||
callback({progress: i/arr.length});
|
callback({progress: i/arr.length});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (delEmpty) {
|
||||||
|
const delResult = await db.delete({table, where: `@@indexLR('value', '?', '?')`});
|
||||||
|
const statField = `${table}Count`;
|
||||||
|
if (stats[statField])
|
||||||
|
stats[statField] -= delResult.deleted;
|
||||||
|
}
|
||||||
|
|
||||||
nullArr();
|
nullArr();
|
||||||
await db.close({table});
|
await db.close({table});
|
||||||
utils.freeMemory();
|
utils.freeMemory();
|
||||||
@@ -378,7 +385,7 @@ class DbCreator {
|
|||||||
|
|
||||||
//series
|
//series
|
||||||
callback({job: 'series save', jobMessage: 'Сохранение индекса серий', jobStep: 4, progress: 0});
|
callback({job: 'series save', jobMessage: 'Сохранение индекса серий', jobStep: 4, progress: 0});
|
||||||
await saveTable('series', seriesArr, () => {seriesArr = null});
|
await saveTable('series', seriesArr, () => {seriesArr = null}, 'string', true);
|
||||||
|
|
||||||
//title
|
//title
|
||||||
callback({job: 'title save', jobMessage: 'Сохранение индекса названий', jobStep: 5, progress: 0});
|
callback({job: 'title save', jobMessage: 'Сохранение индекса названий', jobStep: 5, progress: 0});
|
||||||
@@ -446,8 +453,16 @@ class DbCreator {
|
|||||||
table: 'config'
|
table: 'config'
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const inpxInfo = parser.info;
|
||||||
|
if (inpxFilter && inpxFilter.info) {
|
||||||
|
if (inpxFilter.info.collection)
|
||||||
|
inpxInfo.collection = inpxFilter.info.collection;
|
||||||
|
if (inpxFilter.info.version)
|
||||||
|
inpxInfo.version = inpxFilter.info.version;
|
||||||
|
}
|
||||||
|
|
||||||
await db.insert({table: 'config', rows: [
|
await db.insert({table: 'config', rows: [
|
||||||
{id: 'inpxInfo', value: (inpxFilter && inpxFilter.info ? inpxFilter.info : parser.info)},
|
{id: 'inpxInfo', value: inpxInfo},
|
||||||
{id: 'stats', value: stats},
|
{id: 'stats', value: stats},
|
||||||
{id: 'inpxHash', value: await inpxHashCreator.getHash()},
|
{id: 'inpxHash', value: await inpxHashCreator.getHash()},
|
||||||
]});
|
]});
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
const fs = require('fs-extra');
|
const fs = require('fs-extra');
|
||||||
//const _ = require('lodash');
|
//const _ = require('lodash');
|
||||||
const LockQueue = require('./LockQueue');
|
|
||||||
const utils = require('./utils');
|
const utils = require('./utils');
|
||||||
|
|
||||||
const maxLimit = 1000;
|
const maxLimit = 1000;
|
||||||
@@ -21,7 +20,6 @@ class DbSearcher {
|
|||||||
|
|
||||||
this.db = db;
|
this.db = db;
|
||||||
|
|
||||||
this.lock = new LockQueue();
|
|
||||||
this.searchFlag = 0;
|
this.searchFlag = 0;
|
||||||
this.timer = null;
|
this.timer = null;
|
||||||
this.closed = false;
|
this.closed = false;
|
||||||
@@ -30,11 +28,22 @@ class DbSearcher {
|
|||||||
this.bookIdMap = {};
|
this.bookIdMap = {};
|
||||||
|
|
||||||
this.periodicCleanCache();//no await
|
this.periodicCleanCache();//no await
|
||||||
this.fillBookIdMapAll();//no await
|
}
|
||||||
|
|
||||||
|
async init() {
|
||||||
|
await this.fillBookIdMap('author');
|
||||||
|
await this.fillBookIdMap('series');
|
||||||
|
await this.fillBookIdMap('title');
|
||||||
|
await this.fillDbConfig();
|
||||||
}
|
}
|
||||||
|
|
||||||
queryKey(q) {
|
queryKey(q) {
|
||||||
return JSON.stringify([q.author, q.series, q.title, q.genre, q.lang, q.del, q.date, q.librate]);
|
const result = [];
|
||||||
|
for (const f of this.recStruct) {
|
||||||
|
result.push(q[f.field]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return JSON.stringify(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
getWhere(a) {
|
getWhere(a) {
|
||||||
@@ -54,8 +63,18 @@ class DbSearcher {
|
|||||||
a = a.substring(1);
|
a = a.substring(1);
|
||||||
where = `@indexIter('value', (v) => {
|
where = `@indexIter('value', (v) => {
|
||||||
const enru = new Set(${db.esc(enruArr)});
|
const enru = new Set(${db.esc(enruArr)});
|
||||||
return !v || (v !== ${db.esc(emptyFieldValue)} && !enru.has(v[0]) && v.indexOf(${db.esc(a)}) >= 0);
|
if (!v)
|
||||||
|
return false;
|
||||||
|
return v !== ${db.esc(emptyFieldValue)} && !enru.has(v[0]) && v.indexOf(${db.esc(a)}) >= 0;
|
||||||
})`;
|
})`;
|
||||||
|
} else if (a[0] == '~') {//RegExp
|
||||||
|
a = a.substring(1);
|
||||||
|
where = `
|
||||||
|
await (async() => {
|
||||||
|
const re = new RegExp(${db.esc(a)}, 'i');
|
||||||
|
@@indexIter('value', (v) => re.test(v) );
|
||||||
|
})()
|
||||||
|
`;
|
||||||
} else {
|
} else {
|
||||||
where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
|
where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
|
||||||
}
|
}
|
||||||
@@ -90,7 +109,7 @@ class DbSearcher {
|
|||||||
};
|
};
|
||||||
|
|
||||||
//авторы
|
//авторы
|
||||||
if (query.author && query.author !== '*') {
|
if (query.author) {
|
||||||
const key = `book-ids-author-${query.author}`;
|
const key = `book-ids-author-${query.author}`;
|
||||||
let ids = await this.getCached(key);
|
let ids = await this.getCached(key);
|
||||||
|
|
||||||
@@ -104,7 +123,7 @@ class DbSearcher {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//серии
|
//серии
|
||||||
if (query.series && query.series !== '*') {
|
if (query.series) {
|
||||||
const key = `book-ids-series-${query.series}`;
|
const key = `book-ids-series-${query.series}`;
|
||||||
let ids = await this.getCached(key);
|
let ids = await this.getCached(key);
|
||||||
|
|
||||||
@@ -118,7 +137,7 @@ class DbSearcher {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//названия
|
//названия
|
||||||
if (query.title && query.title !== '*') {
|
if (query.title) {
|
||||||
const key = `book-ids-title-${query.title}`;
|
const key = `book-ids-title-${query.title}`;
|
||||||
let ids = await this.getCached(key);
|
let ids = await this.getCached(key);
|
||||||
|
|
||||||
@@ -204,12 +223,13 @@ class DbSearcher {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//удаленные
|
//удаленные
|
||||||
if (query.del !== undefined) {
|
if (query.del) {
|
||||||
const key = `book-ids-del-${query.del}`;
|
const del = parseInt(query.del, 10) || 0;
|
||||||
|
const key = `book-ids-del-${del}`;
|
||||||
let ids = await this.getCached(key);
|
let ids = await this.getCached(key);
|
||||||
|
|
||||||
if (ids === null) {
|
if (ids === null) {
|
||||||
ids = await tableBookIds('del', `@indexLR('value', ${db.esc(query.del)}, ${db.esc(query.del)})`);
|
ids = await tableBookIds('del', `@indexLR('value', ${db.esc(del)}, ${db.esc(del)})`);
|
||||||
|
|
||||||
await this.putCached(key, ids);
|
await this.putCached(key, ids);
|
||||||
}
|
}
|
||||||
@@ -298,34 +318,28 @@ class DbSearcher {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fillBookIdMap(from) {
|
async fillDbConfig() {
|
||||||
if (this.bookIdMap[from])
|
if (!this.dbConfig) {
|
||||||
return this.bookIdMap[from];
|
const rows = await this.db.select({table: 'config'});
|
||||||
|
const config = {};
|
||||||
|
|
||||||
await this.lock.get();
|
for (const row of rows) {
|
||||||
try {
|
config[row.id] = row.value;
|
||||||
const data = await fs.readFile(`${this.config.dataDir}/db/${from}_id.map`, 'utf-8');
|
}
|
||||||
|
|
||||||
const idMap = JSON.parse(data);
|
this.dbConfig = config;
|
||||||
idMap.arr = new Uint32Array(idMap.arr);
|
this.recStruct = config.inpxInfo.recStruct;
|
||||||
idMap.map = new Map(idMap.map);
|
|
||||||
|
|
||||||
this.bookIdMap[from] = idMap;
|
|
||||||
|
|
||||||
return this.bookIdMap[from];
|
|
||||||
} finally {
|
|
||||||
this.lock.ret();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fillBookIdMapAll() {
|
async fillBookIdMap(from) {
|
||||||
try {
|
const data = await fs.readFile(`${this.config.dataDir}/db/${from}_id.map`, 'utf-8');
|
||||||
await this.fillBookIdMap('author');
|
|
||||||
await this.fillBookIdMap('series');
|
const idMap = JSON.parse(data);
|
||||||
await this.fillBookIdMap('title');
|
idMap.arr = new Uint32Array(idMap.arr);
|
||||||
} catch (e) {
|
idMap.map = new Map(idMap.map);
|
||||||
throw new Error(`DbSearcher.fillBookIdMapAll error: ${e.message}`)
|
|
||||||
}
|
this.bookIdMap[from] = idMap;
|
||||||
}
|
}
|
||||||
|
|
||||||
async tableIdsFilter(from, query) {
|
async tableIdsFilter(from, query) {
|
||||||
@@ -333,7 +347,7 @@ class DbSearcher {
|
|||||||
//то в выборку по bookId могут попасть авторы, которые отсутствуют в критерии query.author,
|
//то в выборку по bookId могут попасть авторы, которые отсутствуют в критерии query.author,
|
||||||
//поэтому дополнительно фильтруем
|
//поэтому дополнительно фильтруем
|
||||||
let result = null;
|
let result = null;
|
||||||
if (from == 'author' && query.author && query.author !== '*') {
|
if (from == 'author' && query.author) {
|
||||||
const key = `filter-ids-author-${query.author}`;
|
const key = `filter-ids-author-${query.author}`;
|
||||||
let authorIds = await this.getCached(key);
|
let authorIds = await this.getCached(key);
|
||||||
|
|
||||||
@@ -376,7 +390,7 @@ class DbSearcher {
|
|||||||
const filter = await this.tableIdsFilter(from, query);
|
const filter = await this.tableIdsFilter(from, query);
|
||||||
|
|
||||||
const tableIdsSet = new Set();
|
const tableIdsSet = new Set();
|
||||||
const idMap = await this.fillBookIdMap(from);
|
const idMap = this.bookIdMap[from];
|
||||||
let proc = 0;
|
let proc = 0;
|
||||||
let nextProc = 0;
|
let nextProc = 0;
|
||||||
for (const bookId of bookIds) {
|
for (const bookId of bookIds) {
|
||||||
@@ -534,6 +548,146 @@ class DbSearcher {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async bookSearchIds(query) {
|
||||||
|
const queryKey = this.queryKey(query);
|
||||||
|
const bookKey = `book-search-ids-${queryKey}`;
|
||||||
|
let bookIds = await this.getCached(bookKey);
|
||||||
|
|
||||||
|
if (bookIds === null) {
|
||||||
|
const db = this.db;
|
||||||
|
const filterBySearch = (bookField, searchValue) => {
|
||||||
|
searchValue = searchValue.toLowerCase();
|
||||||
|
//особая обработка префиксов
|
||||||
|
if (searchValue == emptyFieldValue) {
|
||||||
|
return `(row.${bookField} === '' || row.${bookField}.indexOf(${db.esc(emptyFieldValue)}) === 0)`;
|
||||||
|
} else if (searchValue[0] == '=') {
|
||||||
|
|
||||||
|
searchValue = searchValue.substring(1);
|
||||||
|
return `(row.${bookField}.toLowerCase().localeCompare(${db.esc(searchValue)}) === 0)`;
|
||||||
|
} else if (searchValue[0] == '*') {
|
||||||
|
|
||||||
|
searchValue = searchValue.substring(1);
|
||||||
|
return `(row.${bookField} && row.${bookField}.toLowerCase().indexOf(${db.esc(searchValue)}) >= 0)`;
|
||||||
|
} else if (searchValue[0] == '#') {
|
||||||
|
|
||||||
|
searchValue = searchValue.substring(1);
|
||||||
|
return `(row.${bookField} === '' || (!enru.has(row.${bookField}.toLowerCase()[0]) && row.${bookField}.toLowerCase().indexOf(${db.esc(searchValue)}) >= 0))`;
|
||||||
|
} else if (searchValue[0] == '~') {//RegExp
|
||||||
|
searchValue = searchValue.substring(1);
|
||||||
|
|
||||||
|
return `
|
||||||
|
(() => {
|
||||||
|
const re = new RegExp(${db.esc(searchValue)}, 'i');
|
||||||
|
return re.test(row.${bookField});
|
||||||
|
})()
|
||||||
|
`;
|
||||||
|
} else {
|
||||||
|
|
||||||
|
return `(row.${bookField}.toLowerCase().localeCompare(${db.esc(searchValue)}) >= 0 ` +
|
||||||
|
`&& row.${bookField}.toLowerCase().localeCompare(${db.esc(searchValue)} + ${db.esc(maxUtf8Char)}) <= 0)`;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const checks = ['true'];
|
||||||
|
for (const f of this.recStruct) {
|
||||||
|
if (query[f.field]) {
|
||||||
|
let searchValue = query[f.field];
|
||||||
|
if (f.type === 'S') {
|
||||||
|
checks.push(filterBySearch(f.field, searchValue));
|
||||||
|
} if (f.type === 'N') {
|
||||||
|
const v = searchValue.split('..');
|
||||||
|
|
||||||
|
if (v.length == 1) {
|
||||||
|
searchValue = parseInt(searchValue, 10);
|
||||||
|
if (isNaN(searchValue))
|
||||||
|
throw new Error(`Wrong query param, ${f.field}=${searchValue}`);
|
||||||
|
|
||||||
|
checks.push(`row.${f.field} === ${searchValue}`);
|
||||||
|
} else {
|
||||||
|
const from = parseInt(v[0] || '0', 10);
|
||||||
|
const to = parseInt(v[1] || '0', 10);
|
||||||
|
if (isNaN(from) || isNaN(to))
|
||||||
|
throw new Error(`Wrong query param, ${f.field}=${searchValue}`);
|
||||||
|
|
||||||
|
checks.push(`row.${f.field} >= ${from} && row.${f.field} <= ${to}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = await db.select({
|
||||||
|
table: 'book',
|
||||||
|
rawResult: true,
|
||||||
|
where: `
|
||||||
|
const enru = new Set(${db.esc(enruArr)});
|
||||||
|
|
||||||
|
const checkBook = (row) => {
|
||||||
|
return ${checks.join(' && ')};
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = [];
|
||||||
|
for (const id of @all()) {
|
||||||
|
const row = @unsafeRow(id);
|
||||||
|
if (checkBook(row))
|
||||||
|
result.push(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
result.sort((a, b) => {
|
||||||
|
let cmp = a.author.localeCompare(b.author);
|
||||||
|
if (cmp === 0 && (a.series || b.series)) {
|
||||||
|
cmp = (a.series && b.series ? a.series.localeCompare(b.series) : (a.series ? -1 : 1));
|
||||||
|
}
|
||||||
|
if (cmp === 0)
|
||||||
|
cmp = a.serno - b.serno;
|
||||||
|
if (cmp === 0)
|
||||||
|
cmp = a.title.localeCompare(b.title);
|
||||||
|
|
||||||
|
return cmp;
|
||||||
|
});
|
||||||
|
|
||||||
|
return new Uint32Array(result.map(row => row.id));
|
||||||
|
`
|
||||||
|
});
|
||||||
|
|
||||||
|
bookIds = rows[0].rawResult;
|
||||||
|
|
||||||
|
await this.putCached(bookKey, bookIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
return bookIds;
|
||||||
|
}
|
||||||
|
|
||||||
|
//неоптимизированный поиск по всем книгам, по всем полям
|
||||||
|
async bookSearch(query) {
|
||||||
|
if (this.closed)
|
||||||
|
throw new Error('DbSearcher closed');
|
||||||
|
|
||||||
|
this.searchFlag++;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const db = this.db;
|
||||||
|
|
||||||
|
const ids = await this.bookSearchIds(query);
|
||||||
|
|
||||||
|
const totalFound = ids.length;
|
||||||
|
let limit = (query.limit ? query.limit : 100);
|
||||||
|
limit = (limit > maxLimit ? maxLimit : limit);
|
||||||
|
const offset = (query.offset ? query.offset : 0);
|
||||||
|
|
||||||
|
const slice = ids.slice(offset, offset + limit);
|
||||||
|
|
||||||
|
//выборка найденных значений
|
||||||
|
const found = await db.select({
|
||||||
|
table: 'book',
|
||||||
|
where: `@@id(${db.esc(Array.from(slice))})`
|
||||||
|
});
|
||||||
|
|
||||||
|
return {found, totalFound};
|
||||||
|
} finally {
|
||||||
|
this.searchFlag--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async opdsQuery(from, query) {
|
async opdsQuery(from, query) {
|
||||||
if (this.closed)
|
if (this.closed)
|
||||||
throw new Error('DbSearcher closed');
|
throw new Error('DbSearcher closed');
|
||||||
@@ -570,10 +724,11 @@ class DbSearcher {
|
|||||||
const s = row.value.substring(0, depth);
|
const s = row.value.substring(0, depth);
|
||||||
let g = group.get(s);
|
let g = group.get(s);
|
||||||
if (!g) {
|
if (!g) {
|
||||||
g = {id: row.id, name: row.name, value: s, count: 0};
|
g = {id: row.id, name: row.name, value: s, count: 0, bookCount: 0};
|
||||||
group.set(s, g);
|
group.set(s, g);
|
||||||
}
|
}
|
||||||
g.count++;
|
g.count++;
|
||||||
|
g.bookCount += row.bookCount;
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = Array.from(group.values());
|
const result = Array.from(group.values());
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ class FileDownloader {
|
|||||||
|
|
||||||
let options = {
|
let options = {
|
||||||
headers: {
|
headers: {
|
||||||
|
'accept-encoding': 'gzip, compress, deflate',
|
||||||
'user-agent': userAgent,
|
'user-agent': userAgent,
|
||||||
timeout: 300*1000,
|
timeout: 300*1000,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,12 +1,32 @@
|
|||||||
const path = require('path');
|
const path = require('path');
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
const ZipReader = require('./ZipReader');
|
const ZipReader = require('./ZipReader');
|
||||||
|
const utils = require('./utils');
|
||||||
|
|
||||||
const collectionInfo = 'collection.info';
|
const collectionInfo = 'collection.info';
|
||||||
const structureInfo = 'structure.info';
|
const structureInfo = 'structure.info';
|
||||||
const versionInfo = 'version.info';
|
const versionInfo = 'version.info';
|
||||||
|
|
||||||
const defaultStructure = 'AUTHOR;GENRE;TITLE;SERIES;SERNO;FILE;SIZE;LIBID;DEL;EXT;DATE;LANG;LIBRATE;KEYWORDS';
|
const defaultStructure = 'AUTHOR;GENRE;TITLE;SERIES;SERNO;FILE;SIZE;LIBID;DEL;EXT;DATE;LANG;LIBRATE;KEYWORDS';
|
||||||
|
//'AUTHOR;GENRE;TITLE;SERIES;SERNO;FILE;SIZE;LIBID;DEL;EXT;DATE;INSNO;FOLDER;LANG;LIBRATE;KEYWORDS;'
|
||||||
|
const recStructType = {
|
||||||
|
author: 'S',
|
||||||
|
genre: 'S',
|
||||||
|
title: 'S',
|
||||||
|
series: 'S',
|
||||||
|
serno: 'N',
|
||||||
|
file: 'S',
|
||||||
|
size: 'N',
|
||||||
|
libid: 'S',
|
||||||
|
del: 'N',
|
||||||
|
ext: 'S',
|
||||||
|
date: 'S',
|
||||||
|
insno: 'N',
|
||||||
|
folder: 'S',
|
||||||
|
lang: 'S',
|
||||||
|
librate: 'N',
|
||||||
|
keywords: 'S',
|
||||||
|
}
|
||||||
|
|
||||||
class InpxParser {
|
class InpxParser {
|
||||||
constructor() {
|
constructor() {
|
||||||
@@ -24,6 +44,21 @@ class InpxParser {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getRecStruct(structure) {
|
||||||
|
const result = [];
|
||||||
|
let struct = structure;
|
||||||
|
//folder есть всегда
|
||||||
|
if (!struct.includes('folder'))
|
||||||
|
struct = struct.concat(['folder']);
|
||||||
|
|
||||||
|
for (const field of struct) {
|
||||||
|
if (utils.hasProp(recStructType, field))
|
||||||
|
result.push({field, type: recStructType[field]});
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
async parse(inpxFile, readFileCallback, parsedCallback) {
|
async parse(inpxFile, readFileCallback, parsedCallback) {
|
||||||
if (!readFileCallback)
|
if (!readFileCallback)
|
||||||
readFileCallback = async() => {};
|
readFileCallback = async() => {};
|
||||||
@@ -61,11 +96,11 @@ class InpxParser {
|
|||||||
info.version = await this.safeExtractToString(zipReader, versionInfo);
|
info.version = await this.safeExtractToString(zipReader, versionInfo);
|
||||||
|
|
||||||
//структура
|
//структура
|
||||||
let inpxStructure = info.structure;
|
if (!info.structure)
|
||||||
if (!inpxStructure)
|
info.structure = defaultStructure;
|
||||||
inpxStructure = defaultStructure;
|
const structure = info.structure.toLowerCase().split(';');
|
||||||
inpxStructure = inpxStructure.toLowerCase();
|
|
||||||
const structure = inpxStructure.split(';');
|
info.recStruct = this.getRecStruct(structure);
|
||||||
|
|
||||||
//парсим inp-файлы
|
//парсим inp-файлы
|
||||||
this.chunk = [];
|
this.chunk = [];
|
||||||
|
|||||||
@@ -68,7 +68,8 @@ class RemoteLib {
|
|||||||
|
|
||||||
const buf = await this.down.load(`${this.remoteHost}${link}`, {decompress: false});
|
const buf = await this.down.load(`${this.remoteHost}${link}`, {decompress: false});
|
||||||
|
|
||||||
const publicPath = `${this.config.publicFilesDir}${link}`;
|
const hash = path.basename(link);
|
||||||
|
const publicPath = `${this.config.bookDir}/${hash}`;
|
||||||
|
|
||||||
await fs.writeFile(publicPath, buf);
|
await fs.writeFile(publicPath, buf);
|
||||||
|
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ class WebWorker {
|
|||||||
|
|
||||||
const dirConfig = [
|
const dirConfig = [
|
||||||
{
|
{
|
||||||
dir: config.filesDir,
|
dir: config.bookDir,
|
||||||
maxSize: config.maxFilesDirSize,
|
maxSize: config.maxFilesDirSize,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -210,6 +210,7 @@ class WebWorker {
|
|||||||
|
|
||||||
//поисковый движок
|
//поисковый движок
|
||||||
this.dbSearcher = new DbSearcher(config, db);
|
this.dbSearcher = new DbSearcher(config, db);
|
||||||
|
await this.dbSearcher.init();
|
||||||
|
|
||||||
//stuff
|
//stuff
|
||||||
db.wwCache = {};
|
db.wwCache = {};
|
||||||
@@ -267,6 +268,17 @@ class WebWorker {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async bookSearch(query) {
|
||||||
|
this.checkMyState();
|
||||||
|
|
||||||
|
const result = await this.dbSearcher.bookSearch(query);
|
||||||
|
|
||||||
|
const config = await this.dbConfig();
|
||||||
|
result.inpxHash = (config.inpxHash ? config.inpxHash : '');
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
async opdsQuery(from, query) {
|
async opdsQuery(from, query) {
|
||||||
this.checkMyState();
|
this.checkMyState();
|
||||||
|
|
||||||
@@ -379,8 +391,8 @@ class WebWorker {
|
|||||||
hash = await this.remoteLib.downloadBook(bookUid);
|
hash = await this.remoteLib.downloadBook(bookUid);
|
||||||
}
|
}
|
||||||
|
|
||||||
const link = `${this.config.filesPathStatic}/${hash}`;
|
const link = `${this.config.bookPathStatic}/${hash}`;
|
||||||
const bookFile = `${this.config.filesDir}/${hash}`;
|
const bookFile = `${this.config.bookDir}/${hash}`;
|
||||||
const bookFileDesc = `${bookFile}.d.json`;
|
const bookFileDesc = `${bookFile}.d.json`;
|
||||||
|
|
||||||
if (!await fs.pathExists(bookFile) || !await fs.pathExists(bookFileDesc)) {
|
if (!await fs.pathExists(bookFile) || !await fs.pathExists(bookFileDesc)) {
|
||||||
@@ -421,20 +433,28 @@ class WebWorker {
|
|||||||
const db = this.db;
|
const db = this.db;
|
||||||
let link = '';
|
let link = '';
|
||||||
|
|
||||||
//найдем bookPath и downFileName
|
//найдем downFileName и bookPath
|
||||||
let rows = await db.select({table: 'book', where: `@@hash('_uid', ${db.esc(bookUid)})`});
|
let rows = await db.select({table: 'book', where: `@@hash('_uid', ${db.esc(bookUid)})`});
|
||||||
if (!rows.length)
|
if (!rows.length)
|
||||||
throw new Error('404 Файл не найден');
|
throw new Error('404 Файл не найден');
|
||||||
|
|
||||||
const book = rows[0];
|
const book = rows[0];
|
||||||
let downFileName = book.file;
|
let downFileName = book.file;
|
||||||
const author = book.author.split(',');
|
const authors = book.author.split(',');
|
||||||
const at = [author[0], book.title];
|
let author = authors[0];
|
||||||
downFileName = utils.makeValidFileNameOrEmpty(at.filter(r => r).join(' - '))
|
author = author.split(' ').filter(r => r.trim());
|
||||||
|
for (let i = 1; i < author.length; i++)
|
||||||
|
author[i] = `${(i === 1 ? ' ' : '')}${author[i][0]}.`;
|
||||||
|
if (authors.length > 1)
|
||||||
|
author.push(' и др.');
|
||||||
|
|
||||||
|
const at = [author.join(''), (book.title ? `_${book.title}` : '')];
|
||||||
|
downFileName = utils.makeValidFileNameOrEmpty(at.filter(r => r).join(''))
|
||||||
|| utils.makeValidFileNameOrEmpty(at[0])
|
|| utils.makeValidFileNameOrEmpty(at[0])
|
||||||
|| utils.makeValidFileNameOrEmpty(at[1])
|
|| utils.makeValidFileNameOrEmpty(at[1])
|
||||||
|| downFileName;
|
|| downFileName;
|
||||||
downFileName = downFileName.substring(0, 100);
|
if (downFileName.length > 50)
|
||||||
|
downFileName = `${downFileName.substring(0, 50)}_`;
|
||||||
|
|
||||||
const ext = `.${book.ext}`;
|
const ext = `.${book.ext}`;
|
||||||
if (downFileName.substring(downFileName.length - ext.length) != ext)
|
if (downFileName.substring(downFileName.length - ext.length) != ext)
|
||||||
@@ -446,11 +466,11 @@ class WebWorker {
|
|||||||
rows = await db.select({table: 'file_hash', where: `@@id(${db.esc(bookPath)})`});
|
rows = await db.select({table: 'file_hash', where: `@@id(${db.esc(bookPath)})`});
|
||||||
if (rows.length) {//хеш найден по bookPath
|
if (rows.length) {//хеш найден по bookPath
|
||||||
const hash = rows[0].hash;
|
const hash = rows[0].hash;
|
||||||
const bookFile = `${this.config.filesDir}/${hash}`;
|
const bookFile = `${this.config.bookDir}/${hash}`;
|
||||||
const bookFileDesc = `${bookFile}.d.json`;
|
const bookFileDesc = `${bookFile}.d.json`;
|
||||||
|
|
||||||
if (await fs.pathExists(bookFile) && await fs.pathExists(bookFileDesc)) {
|
if (await fs.pathExists(bookFile) && await fs.pathExists(bookFileDesc)) {
|
||||||
link = `${this.config.filesPathStatic}/${hash}`;
|
link = `${this.config.bookPathStatic}/${hash}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -478,7 +498,7 @@ class WebWorker {
|
|||||||
|
|
||||||
let bookInfo = await this.getBookLink(bookUid);
|
let bookInfo = await this.getBookLink(bookUid);
|
||||||
const hash = path.basename(bookInfo.link);
|
const hash = path.basename(bookInfo.link);
|
||||||
const bookFile = `${this.config.filesDir}/${hash}`;
|
const bookFile = `${this.config.bookDir}/${hash}`;
|
||||||
const bookFileInfo = `${bookFile}.i.json`;
|
const bookFileInfo = `${bookFile}.i.json`;
|
||||||
|
|
||||||
let rows = await db.select({table: 'book', where: `@@hash('_uid', ${db.esc(bookUid)})`});
|
let rows = await db.select({table: 'book', where: `@@hash('_uid', ${db.esc(bookUid)})`});
|
||||||
@@ -500,7 +520,7 @@ class WebWorker {
|
|||||||
result.fb2 = fb2.rawNodes;
|
result.fb2 = fb2.rawNodes;
|
||||||
|
|
||||||
if (cover) {
|
if (cover) {
|
||||||
result.cover = `${this.config.filesPathStatic}/${hash}${coverExt}`;
|
result.cover = `${this.config.bookPathStatic}/${hash}${coverExt}`;
|
||||||
await fs.writeFile(`${bookFile}${coverExt}`, cover);
|
await fs.writeFile(`${bookFile}${coverExt}`, cover);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
const StreamZip = require('node-stream-zip');
|
const StreamUnzip = require('node-stream-zip');
|
||||||
|
|
||||||
class ZipReader {
|
class ZipReader {
|
||||||
constructor() {
|
constructor() {
|
||||||
@@ -14,7 +14,7 @@ class ZipReader {
|
|||||||
if (this.zip)
|
if (this.zip)
|
||||||
throw new Error('Zip file is already open');
|
throw new Error('Zip file is already open');
|
||||||
|
|
||||||
const zip = new StreamZip.async({file: zipFile, skipEntryNameValidation: true});
|
const zip = new StreamUnzip.async({file: zipFile, skipEntryNameValidation: true});
|
||||||
|
|
||||||
if (zipEntries)
|
if (zipEntries)
|
||||||
this.zipEntries = await zip.entries();
|
this.zipEntries = await zip.entries();
|
||||||
|
|||||||
@@ -70,9 +70,6 @@ class Fb2Helper {
|
|||||||
if (coverImage.count) {
|
if (coverImage.count) {
|
||||||
const coverAttrs = coverImage.attrs();
|
const coverAttrs = coverImage.attrs();
|
||||||
const href = coverAttrs[`${parser.xlinkNS}:href`];
|
const href = coverAttrs[`${parser.xlinkNS}:href`];
|
||||||
let coverType = coverAttrs['content-type'];
|
|
||||||
coverType = (coverType == 'image/jpg' || coverType == 'application/octet-stream' ? 'image/jpeg' : coverType);
|
|
||||||
coverExt = (coverType == 'image/png' ? '.png' : '.jpg');
|
|
||||||
|
|
||||||
if (href) {
|
if (href) {
|
||||||
const binaryId = (href[0] == '#' ? href.substring(1) : href);
|
const binaryId = (href[0] == '#' ? href.substring(1) : href);
|
||||||
@@ -84,6 +81,10 @@ class Fb2Helper {
|
|||||||
return;
|
return;
|
||||||
|
|
||||||
if (attrs.id === binaryId) {
|
if (attrs.id === binaryId) {
|
||||||
|
let coverType = attrs['content-type'];
|
||||||
|
coverType = (coverType == 'image/jpg' || coverType == 'application/octet-stream' ? 'image/jpeg' : coverType);
|
||||||
|
coverExt = (coverType == 'image/png' ? '.png' : '.jpg');
|
||||||
|
|
||||||
const base64 = node.text();
|
const base64 = node.text();
|
||||||
cover = (base64 ? Buffer.from(base64, 'base64') : null);
|
cover = (base64 ? Buffer.from(base64, 'base64') : null);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -283,7 +283,7 @@ class Fb2Parser extends XmlParser {
|
|||||||
};
|
};
|
||||||
|
|
||||||
for (const [tag, s] of Object.entries(substs)) {
|
for (const [tag, s] of Object.entries(substs)) {
|
||||||
const r = new RegExp(`${tag}`, 'g');
|
const r = new RegExp(tag, 'g');
|
||||||
xmlString = xmlString.replace(r, s);
|
xmlString = xmlString.replace(r, s);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
const BasePage = require('./BasePage');
|
const BasePage = require('./BasePage');
|
||||||
|
const utils = require('../utils');
|
||||||
|
|
||||||
class AuthorPage extends BasePage {
|
class AuthorPage extends BasePage {
|
||||||
constructor(config) {
|
constructor(config) {
|
||||||
@@ -11,17 +12,22 @@ class AuthorPage extends BasePage {
|
|||||||
sortBooks(bookList) {
|
sortBooks(bookList) {
|
||||||
//схлопывание серий
|
//схлопывание серий
|
||||||
const books = [];
|
const books = [];
|
||||||
const seriesSet = new Set();
|
const seriesMap = new Map();
|
||||||
for (const book of bookList) {
|
for (const book of bookList) {
|
||||||
if (book.series) {
|
if (book.series) {
|
||||||
if (!seriesSet.has(book.series)) {
|
let seriesIndex = seriesMap.get(book.series);
|
||||||
|
if (seriesIndex === undefined) {
|
||||||
|
seriesIndex = books.length;
|
||||||
books.push({
|
books.push({
|
||||||
type: 'series',
|
type: 'series',
|
||||||
book
|
book,
|
||||||
|
bookCount: 0,
|
||||||
});
|
});
|
||||||
|
|
||||||
seriesSet.add(book.series);
|
seriesMap.set(book.series, seriesIndex);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
books[seriesIndex].bookCount++;
|
||||||
} else {
|
} else {
|
||||||
books.push({
|
books.push({
|
||||||
type: 'book',
|
type: 'book',
|
||||||
@@ -60,7 +66,7 @@ class AuthorPage extends BasePage {
|
|||||||
author: req.query.author || '',
|
author: req.query.author || '',
|
||||||
series: req.query.series || '',
|
series: req.query.series || '',
|
||||||
genre: req.query.genre || '',
|
genre: req.query.genre || '',
|
||||||
del: 0,
|
del: '0',
|
||||||
|
|
||||||
all: req.query.all || '',
|
all: req.query.all || '',
|
||||||
depth: 0,
|
depth: 0,
|
||||||
@@ -80,7 +86,7 @@ class AuthorPage extends BasePage {
|
|||||||
|
|
||||||
if (bookList.books) {
|
if (bookList.books) {
|
||||||
let books = bookList.books;
|
let books = bookList.books;
|
||||||
const booksAll = this.filterBooks(books, {del: 0});
|
const booksAll = this.filterBooks(books);
|
||||||
const filtered = (query.all ? booksAll : this.filterBooks(books, query));
|
const filtered = (query.all ? booksAll : this.filterBooks(books, query));
|
||||||
const sorted = this.sortSeriesBooks(filtered);
|
const sorted = this.sortSeriesBooks(filtered);
|
||||||
|
|
||||||
@@ -99,21 +105,16 @@ class AuthorPage extends BasePage {
|
|||||||
for (const book of sorted) {
|
for (const book of sorted) {
|
||||||
const title = `${book.serno ? `${book.serno}. `: ''}${book.title || 'Без названия'} (${book.ext})`;
|
const title = `${book.serno ? `${book.serno}. `: ''}${book.title || 'Без названия'} (${book.ext})`;
|
||||||
|
|
||||||
const e = {
|
|
||||||
id: book._uid,
|
|
||||||
title,
|
|
||||||
link: this.acqLink({href: `/book?uid=${encodeURIComponent(book._uid)}`}),
|
|
||||||
};
|
|
||||||
|
|
||||||
if (query.all) {
|
|
||||||
e.content = {
|
|
||||||
'*ATTRS': {type: 'text'},
|
|
||||||
'*TEXT': this.bookAuthor(book.author),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
entry.push(
|
entry.push(
|
||||||
this.makeEntry(e)
|
this.makeEntry({
|
||||||
|
id: book._uid,
|
||||||
|
title,
|
||||||
|
link: this.acqLink({href: `/book?uid=${encodeURIComponent(book._uid)}`}),
|
||||||
|
content: {
|
||||||
|
'*ATTRS': {type: 'text'},
|
||||||
|
'*TEXT': this.bookAuthor(book.author),
|
||||||
|
},
|
||||||
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -134,6 +135,10 @@ class AuthorPage extends BasePage {
|
|||||||
link: this.navLink({
|
link: this.navLink({
|
||||||
href: `/${this.id}?author=${encodeURIComponent(query.author)}` +
|
href: `/${this.id}?author=${encodeURIComponent(query.author)}` +
|
||||||
`&series=${encodeURIComponent(b.book.series)}&genre=${encodeURIComponent(query.genre)}`}),
|
`&series=${encodeURIComponent(b.book.series)}&genre=${encodeURIComponent(query.genre)}`}),
|
||||||
|
content: {
|
||||||
|
'*ATTRS': {type: 'text'},
|
||||||
|
'*TEXT': `${b.bookCount} книг${utils.wordEnding(b.bookCount, 8)} по автору${(query.genre ? ' (в выбранном жанре)' : '')}`,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
@@ -143,6 +148,10 @@ class AuthorPage extends BasePage {
|
|||||||
id: b.book._uid,
|
id: b.book._uid,
|
||||||
title,
|
title,
|
||||||
link: this.acqLink({href: `/book?uid=${encodeURIComponent(b.book._uid)}`}),
|
link: this.acqLink({href: `/book?uid=${encodeURIComponent(b.book._uid)}`}),
|
||||||
|
content: {
|
||||||
|
'*ATTRS': {type: 'text'},
|
||||||
|
'*TEXT': this.bookAuthor(b.book.author),
|
||||||
|
},
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -162,14 +171,27 @@ class AuthorPage extends BasePage {
|
|||||||
//навигация по каталогу
|
//навигация по каталогу
|
||||||
const queryRes = await this.opdsQuery('author', query, '[Остальные авторы]');
|
const queryRes = await this.opdsQuery('author', query, '[Остальные авторы]');
|
||||||
|
|
||||||
for (const rec of queryRes) {
|
for (const rec of queryRes) {
|
||||||
entry.push(
|
const e = {
|
||||||
this.makeEntry({
|
id: rec.id,
|
||||||
id: rec.id,
|
title: this.bookAuthor(rec.title),
|
||||||
title: this.bookAuthor(rec.title),
|
link: this.navLink({href: `/${this.id}?author=${rec.q}&genre=${encodeURIComponent(query.genre)}`}),
|
||||||
link: this.navLink({href: `/${this.id}?author=${rec.q}&genre=${encodeURIComponent(query.genre)}`}),
|
};
|
||||||
})
|
|
||||||
);
|
let countStr = '';
|
||||||
|
if (rec.count)
|
||||||
|
countStr = `${rec.count} автор${utils.wordEnding(rec.count, 0)}${(query.genre ? ' (в выбранном жанре)' : '')}`;
|
||||||
|
if (!countStr && rec.bookCount && !query.genre)
|
||||||
|
countStr = `${rec.bookCount} книг${utils.wordEnding(rec.bookCount, 8)}`;
|
||||||
|
|
||||||
|
if (countStr) {
|
||||||
|
e.content = {
|
||||||
|
'*ATTRS': {type: 'text'},
|
||||||
|
'*TEXT': countStr,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
entry.push(this.makeEntry(e));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ const ruAlphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыь
|
|||||||
const enAlphabet = 'abcdefghijklmnopqrstuvwxyz';
|
const enAlphabet = 'abcdefghijklmnopqrstuvwxyz';
|
||||||
const enruArr = (ruAlphabet + enAlphabet).split('');
|
const enruArr = (ruAlphabet + enAlphabet).split('');
|
||||||
const enru = new Set(enruArr);
|
const enru = new Set(enruArr);
|
||||||
|
const ruOnly = new Set(ruAlphabet.split(''));
|
||||||
|
|
||||||
class BasePage {
|
class BasePage {
|
||||||
constructor(config) {
|
constructor(config) {
|
||||||
@@ -19,6 +20,13 @@ class BasePage {
|
|||||||
this.webWorker = new WebWorker(config);
|
this.webWorker = new WebWorker(config);
|
||||||
this.rootTag = 'feed';
|
this.rootTag = 'feed';
|
||||||
this.opdsRoot = config.opdsRoot;
|
this.opdsRoot = config.opdsRoot;
|
||||||
|
|
||||||
|
this.showDeleted = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
escape(s) {
|
||||||
|
//костыль для koreader, не понимает hex-экранирование вида '
|
||||||
|
return he.escape(s).replace(/'/g, ''').replace(/`/g, '`');
|
||||||
}
|
}
|
||||||
|
|
||||||
makeEntry(entry = {}) {
|
makeEntry(entry = {}) {
|
||||||
@@ -27,7 +35,7 @@ class BasePage {
|
|||||||
if (!entry.title)
|
if (!entry.title)
|
||||||
throw new Error('makeEntry: no title');
|
throw new Error('makeEntry: no title');
|
||||||
|
|
||||||
entry.title = he.escape(entry.title);
|
entry.title = this.escape(entry.title);
|
||||||
|
|
||||||
const result = {
|
const result = {
|
||||||
updated: (new Date()).toISOString().substring(0, 19) + 'Z',
|
updated: (new Date()).toISOString().substring(0, 19) + 'Z',
|
||||||
@@ -45,7 +53,7 @@ class BasePage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
makeLink(attrs) {
|
makeLink(attrs) {
|
||||||
attrs.href = he.escape(attrs.href);
|
attrs.href = this.escape(attrs.href);
|
||||||
return {'*ATTRS': attrs};
|
return {'*ATTRS': attrs};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,6 +148,7 @@ class BasePage {
|
|||||||
id: row.id,
|
id: row.id,
|
||||||
title: (row[from] || 'Без автора'),
|
title: (row[from] || 'Без автора'),
|
||||||
q: `=${encodeURIComponent(row[from])}`,
|
q: `=${encodeURIComponent(row[from])}`,
|
||||||
|
bookCount: row.bookCount,
|
||||||
};
|
};
|
||||||
|
|
||||||
result.push(rec);
|
result.push(rec);
|
||||||
@@ -161,6 +170,7 @@ class BasePage {
|
|||||||
return await this.search(from, query);
|
return await this.search(from, query);
|
||||||
} else {
|
} else {
|
||||||
let len = 0;
|
let len = 0;
|
||||||
|
const enResult = [];
|
||||||
for (const row of queryRes.found) {
|
for (const row of queryRes.found) {
|
||||||
const value = row.value;
|
const value = row.value;
|
||||||
len += value.length;
|
len += value.length;
|
||||||
@@ -171,21 +181,30 @@ class BasePage {
|
|||||||
id: row.id,
|
id: row.id,
|
||||||
title: row.name,
|
title: row.name,
|
||||||
q: `=${encodeURIComponent(row.name)}`,
|
q: `=${encodeURIComponent(row.name)}`,
|
||||||
|
bookCount: row.bookCount,
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
rec = {
|
rec = {
|
||||||
id: row.id,
|
id: row.id,
|
||||||
title: `${value.toUpperCase().replace(/ /g, spaceChar)}~`,
|
title: `${value.toUpperCase().replace(/ /g, spaceChar)}~`,
|
||||||
q: encodeURIComponent(value),
|
q: encodeURIComponent(value),
|
||||||
|
count: row.count,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (query.depth > 1 || enru.has(value[0])) {
|
if (query.depth > 1 || enru.has(value[0]) ) {
|
||||||
result.push(rec);
|
//такой костыль из-за проблем с локалями в pkg
|
||||||
|
//русский язык всегда идет первым!
|
||||||
|
if (ruOnly.has(value[0]))
|
||||||
|
result.push(rec)
|
||||||
|
else
|
||||||
|
enResult.push(rec);
|
||||||
} else {
|
} else {
|
||||||
others.push(rec);
|
others.push(rec);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
result = result.concat(enResult);
|
||||||
|
|
||||||
if (query[from] && query.depth > 1 && result.length < 10 && len > prevLen) {
|
if (query[from] && query.depth > 1 && result.length < 10 && len > prevLen) {
|
||||||
//рекурсия, с увеличением глубины, для облегчения навигации
|
//рекурсия, с увеличением глубины, для облегчения навигации
|
||||||
const newQuery = _.cloneDeep(query);
|
const newQuery = _.cloneDeep(query);
|
||||||
@@ -195,13 +214,13 @@ class BasePage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!query.others && others.length)
|
if (!query.others && others.length)
|
||||||
result.unshift({id: 'other', title: otherTitle, q: '___others'});
|
result.unshift({id: 'other', title: otherTitle, q: '___others', count: others.length});
|
||||||
|
|
||||||
return (!query.others ? result : others);
|
return (!query.others ? result : others);
|
||||||
}
|
}
|
||||||
|
|
||||||
//скопировано из BaseList.js, часть функционала не используется
|
//скопировано из BaseList.js, часть функционала не используется
|
||||||
filterBooks(books, query) {
|
filterBooks(books, query = {}) {
|
||||||
const s = query;
|
const s = query;
|
||||||
|
|
||||||
const splitAuthor = (author) => {
|
const splitAuthor = (author) => {
|
||||||
@@ -238,7 +257,14 @@ class BasePage {
|
|||||||
} else if (searchValue[0] == '#') {
|
} else if (searchValue[0] == '#') {
|
||||||
|
|
||||||
searchValue = searchValue.substring(1);
|
searchValue = searchValue.substring(1);
|
||||||
return !bookValue || (bookValue !== emptyFieldValue && !enru.has(bookValue[0]) && bookValue.indexOf(searchValue) >= 0);
|
if (!bookValue)
|
||||||
|
return false;
|
||||||
|
return bookValue !== emptyFieldValue && !enru.has(bookValue[0]) && bookValue.indexOf(searchValue) >= 0;
|
||||||
|
} else if (searchValue[0] == '~') {//RegExp
|
||||||
|
|
||||||
|
searchValue = searchValue.substring(1);
|
||||||
|
const re = new RegExp(searchValue, 'i');
|
||||||
|
return re.test(bookValue);
|
||||||
} else {
|
} else {
|
||||||
//where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
|
//where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
|
||||||
return bookValue.localeCompare(searchValue) >= 0 && bookValue.localeCompare(searchValue + maxUtf8Char) <= 0;
|
return bookValue.localeCompare(searchValue) >= 0 && bookValue.localeCompare(searchValue + maxUtf8Char) <= 0;
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
const path = require('path');
|
const path = require('path');
|
||||||
const _ = require('lodash');
|
const _ = require('lodash');
|
||||||
const he = require('he');
|
|
||||||
const dayjs = require('dayjs');
|
const dayjs = require('dayjs');
|
||||||
|
|
||||||
const BasePage = require('./BasePage');
|
const BasePage = require('./BasePage');
|
||||||
@@ -128,7 +127,19 @@ class BookPage extends BasePage {
|
|||||||
|
|
||||||
if (bookInfo) {
|
if (bookInfo) {
|
||||||
const {genreMap} = await this.getGenres();
|
const {genreMap} = await this.getGenres();
|
||||||
const fileFormat = `${bookInfo.book.ext}+zip`;
|
|
||||||
|
//format
|
||||||
|
const ext = bookInfo.book.ext;
|
||||||
|
let fileFormat = `${ext}+zip`;
|
||||||
|
let downHref = bookInfo.link;
|
||||||
|
|
||||||
|
if (ext === 'mobi') {
|
||||||
|
fileFormat = 'x-mobipocket-ebook';
|
||||||
|
} else if (ext == 'epub') {
|
||||||
|
//
|
||||||
|
} else {
|
||||||
|
downHref = `${bookInfo.link}/zip`;
|
||||||
|
}
|
||||||
|
|
||||||
//entry
|
//entry
|
||||||
const e = this.makeEntry({
|
const e = this.makeEntry({
|
||||||
@@ -178,12 +189,12 @@ class BookPage extends BasePage {
|
|||||||
if (content) {
|
if (content) {
|
||||||
e.content = {
|
e.content = {
|
||||||
'*ATTRS': {type: 'text/html'},
|
'*ATTRS': {type: 'text/html'},
|
||||||
'*TEXT': he.escape(content),
|
'*TEXT': this.escape(content),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
//links
|
//links
|
||||||
e.link = [ this.downLink({href: bookInfo.link, type: `application/${fileFormat}`}) ];
|
e.link = [ this.downLink({href: downHref, type: `application/${fileFormat}`}) ];
|
||||||
if (bookInfo.cover) {
|
if (bookInfo.cover) {
|
||||||
let coverType = 'image/jpeg';
|
let coverType = 'image/jpeg';
|
||||||
if (path.extname(bookInfo.cover) == '.png')
|
if (path.extname(bookInfo.cover) == '.png')
|
||||||
|
|||||||
@@ -13,13 +13,17 @@ class GenrePage extends BasePage {
|
|||||||
const result = {};
|
const result = {};
|
||||||
|
|
||||||
const query = {
|
const query = {
|
||||||
from: req.query.from || '',
|
from: req.query.from || 'search',
|
||||||
|
term: req.query.term || '',
|
||||||
section: req.query.section || '',
|
section: req.query.section || '',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let searchQuery = '';
|
||||||
|
if (query.from == 'search')
|
||||||
|
searchQuery = `&type=title&term=${encodeURIComponent(query.term)}`;
|
||||||
|
|
||||||
const entry = [];
|
const entry = [];
|
||||||
if (query.from) {
|
if (query.from) {
|
||||||
|
|
||||||
if (query.section) {
|
if (query.section) {
|
||||||
//выбираем подразделы
|
//выбираем подразделы
|
||||||
const {genreSection} = await this.getGenres();
|
const {genreSection} = await this.getGenres();
|
||||||
@@ -34,7 +38,7 @@ class GenrePage extends BasePage {
|
|||||||
this.makeEntry({
|
this.makeEntry({
|
||||||
id: ++id,
|
id: ++id,
|
||||||
title: g.name,
|
title: g.name,
|
||||||
link: this.navLink({href: `/${encodeURIComponent(query.from)}?genre=${encodeURIComponent(g.value)}`}),
|
link: this.navLink({href: `/${encodeURIComponent(query.from)}?genre=${encodeURIComponent(g.value)}${searchQuery}`}),
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -43,7 +47,7 @@ class GenrePage extends BasePage {
|
|||||||
this.makeEntry({
|
this.makeEntry({
|
||||||
id: 'whole_section',
|
id: 'whole_section',
|
||||||
title: '[Весь раздел]',
|
title: '[Весь раздел]',
|
||||||
link: this.navLink({href: `/${encodeURIComponent(query.from)}?genre=${encodeURIComponent(all.join(','))}`}),
|
link: this.navLink({href: `/${encodeURIComponent(query.from)}?genre=${encodeURIComponent(all.join(','))}${searchQuery}`}),
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -56,7 +60,7 @@ class GenrePage extends BasePage {
|
|||||||
this.makeEntry({
|
this.makeEntry({
|
||||||
id: ++id,
|
id: ++id,
|
||||||
title: section.name,
|
title: section.name,
|
||||||
link: this.navLink({href: `/genre?from=${encodeURIComponent(query.from)}§ion=${encodeURIComponent(section.name)}`}),
|
link: this.navLink({href: `/genre?from=${encodeURIComponent(query.from)}§ion=${encodeURIComponent(section.name)}${searchQuery}`}),
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ const BasePage = require('./BasePage');
|
|||||||
const AuthorPage = require('./AuthorPage');
|
const AuthorPage = require('./AuthorPage');
|
||||||
const SeriesPage = require('./SeriesPage');
|
const SeriesPage = require('./SeriesPage');
|
||||||
const TitlePage = require('./TitlePage');
|
const TitlePage = require('./TitlePage');
|
||||||
|
const GenrePage = require('./GenrePage');
|
||||||
|
|
||||||
class RootPage extends BasePage {
|
class RootPage extends BasePage {
|
||||||
constructor(config) {
|
constructor(config) {
|
||||||
@@ -13,6 +14,7 @@ class RootPage extends BasePage {
|
|||||||
this.authorPage = new AuthorPage(config);
|
this.authorPage = new AuthorPage(config);
|
||||||
this.seriesPage = new SeriesPage(config);
|
this.seriesPage = new SeriesPage(config);
|
||||||
this.titlePage = new TitlePage(config);
|
this.titlePage = new TitlePage(config);
|
||||||
|
this.genrePage = new GenrePage(config);
|
||||||
}
|
}
|
||||||
|
|
||||||
async body(req) {
|
async body(req) {
|
||||||
@@ -30,6 +32,7 @@ class RootPage extends BasePage {
|
|||||||
this.authorPage.myEntry(),
|
this.authorPage.myEntry(),
|
||||||
this.seriesPage.myEntry(),
|
this.seriesPage.myEntry(),
|
||||||
this.titlePage.myEntry(),
|
this.titlePage.myEntry(),
|
||||||
|
this.genrePage.myEntry(),
|
||||||
];
|
];
|
||||||
|
|
||||||
return this.makeBody(result, req);
|
return this.makeBody(result, req);
|
||||||
|
|||||||
60
server/core/opds/SearchHelpPage.js
Normal file
60
server/core/opds/SearchHelpPage.js
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
const BasePage = require('./BasePage');
|
||||||
|
|
||||||
|
class SearchHelpPage extends BasePage {
|
||||||
|
constructor(config) {
|
||||||
|
super(config);
|
||||||
|
|
||||||
|
this.id = 'search_help';
|
||||||
|
this.title = 'Памятка по поиску';
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
async body(req) {
|
||||||
|
const result = {};
|
||||||
|
|
||||||
|
result.link = this.baseLinks(req, true);
|
||||||
|
|
||||||
|
const content = `
|
||||||
|
Формат поискового значения:
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
без префикса: значение трактуется, как "начинается с"
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
префикс "=": поиск по точному совпадению
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
префикс "*": поиск подстроки в строке
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
префикс "#": поиск подстроки в строке, но только среди значений, начинающихся не с латинского или кириллического символа
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
префикс "~": поиск по регулярному выражению
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
префикс "?": поиск пустых значений или тех, что начинаются с этого символа
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
`;
|
||||||
|
const entry = [
|
||||||
|
this.makeEntry({
|
||||||
|
id: 'help',
|
||||||
|
title: this.title,
|
||||||
|
content: {
|
||||||
|
'*ATTRS': {type: 'text/html'},
|
||||||
|
'*TEXT': this.escape(content),
|
||||||
|
},
|
||||||
|
link: [
|
||||||
|
this.downLink({href: '/book/fake-link', type: `application/fb2+zip`})
|
||||||
|
],
|
||||||
|
})
|
||||||
|
];
|
||||||
|
|
||||||
|
result.entry = entry;
|
||||||
|
|
||||||
|
return this.makeBody(result, req);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = SearchHelpPage;
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
const BasePage = require('./BasePage');
|
const BasePage = require('./BasePage');
|
||||||
|
const utils = require('../utils');
|
||||||
|
|
||||||
class SearchPage extends BasePage {
|
class SearchPage extends BasePage {
|
||||||
constructor(config) {
|
constructor(config) {
|
||||||
@@ -14,43 +15,57 @@ class SearchPage extends BasePage {
|
|||||||
const query = {
|
const query = {
|
||||||
type: req.query.type || '',
|
type: req.query.type || '',
|
||||||
term: req.query.term || '',
|
term: req.query.term || '',
|
||||||
|
genre: req.query.genre || '',
|
||||||
page: parseInt(req.query.page, 10) || 1,
|
page: parseInt(req.query.page, 10) || 1,
|
||||||
};
|
};
|
||||||
|
|
||||||
let entry = [];
|
let entry = [];
|
||||||
if (query.type) {
|
if (query.type) {
|
||||||
if (['author', 'series', 'title'].includes(query.type)) {
|
if (['author', 'series', 'title'].includes(query.type)) {
|
||||||
const from = query.type;
|
try {
|
||||||
const page = query.page;
|
const from = query.type;
|
||||||
|
const page = query.page;
|
||||||
|
|
||||||
const limit = 100;
|
const limit = 100;
|
||||||
const offset = (page - 1)*limit;
|
const offset = (page - 1)*limit;
|
||||||
const queryRes = await this.webWorker.search(from, {[from]: query.term, del: 0, offset, limit});
|
const queryRes = await this.webWorker.search(from, {[from]: query.term, genre: query.genre, del: '0', offset, limit});
|
||||||
|
|
||||||
const found = queryRes.found;
|
const found = queryRes.found;
|
||||||
|
|
||||||
for (let i = 0; i < found.length; i++) {
|
for (let i = 0; i < found.length; i++) {
|
||||||
if (i >= limit)
|
const row = found[i];
|
||||||
break;
|
if (!row.bookCount)
|
||||||
|
continue;
|
||||||
|
|
||||||
const row = found[i];
|
entry.push(
|
||||||
|
this.makeEntry({
|
||||||
|
id: row.id,
|
||||||
|
title: `${(from === 'series' ? 'Серия: ': '')}${from === 'author' ? this.bookAuthor(row[from]) : row[from]}`,
|
||||||
|
link: this.navLink({href: `/${from}?${from}==${encodeURIComponent(row[from])}`}),
|
||||||
|
content: {
|
||||||
|
'*ATTRS': {type: 'text'},
|
||||||
|
'*TEXT': `${row.bookCount} книг${utils.wordEnding(row.bookCount, 8)}`,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (queryRes.totalFound > offset + found.length) {
|
||||||
|
entry.push(
|
||||||
|
this.makeEntry({
|
||||||
|
id: 'next_page',
|
||||||
|
title: '[Следующая страница]',
|
||||||
|
link: this.navLink({href: `/${this.id}?type=${from}&term=${encodeURIComponent(query.term)}&genre=${encodeURIComponent(query.genre)}&page=${page + 1}`}),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch(e) {
|
||||||
entry.push(
|
entry.push(
|
||||||
this.makeEntry({
|
this.makeEntry({
|
||||||
id: row.id,
|
id: 'error',
|
||||||
title: row[from],
|
title: `Ошибка: ${e.message}`,
|
||||||
link: this.navLink({href: `/${from}?${from}==${encodeURIComponent(row[from])}`}),
|
link: this.navLink({href: `/fake-error-link`}),
|
||||||
}),
|
})
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (queryRes.totalFound > offset + found.length) {
|
|
||||||
entry.push(
|
|
||||||
this.makeEntry({
|
|
||||||
id: 'next_page',
|
|
||||||
title: '[Следующая страница]',
|
|
||||||
link: this.navLink({href: `/${this.id}?type=${from}&term=${encodeURIComponent(query.term)}&page=${page + 1}`}),
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -61,16 +76,46 @@ class SearchPage extends BasePage {
|
|||||||
id: 'search_author',
|
id: 'search_author',
|
||||||
title: 'Поиск авторов',
|
title: 'Поиск авторов',
|
||||||
link: this.navLink({href: `/${this.id}?type=author&term=${encodeURIComponent(query.term)}`}),
|
link: this.navLink({href: `/${this.id}?type=author&term=${encodeURIComponent(query.term)}`}),
|
||||||
|
content: {
|
||||||
|
'*ATTRS': {type: 'text'},
|
||||||
|
'*TEXT': `Искать по именам авторов`,
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
this.makeEntry({
|
this.makeEntry({
|
||||||
id: 'search_series',
|
id: 'search_series',
|
||||||
title: 'Поиск серий',
|
title: 'Поиск серий',
|
||||||
link: this.navLink({href: `/${this.id}?type=series&term=${encodeURIComponent(query.term)}`}),
|
link: this.navLink({href: `/${this.id}?type=series&term=${encodeURIComponent(query.term)}`}),
|
||||||
|
content: {
|
||||||
|
'*ATTRS': {type: 'text'},
|
||||||
|
'*TEXT': `Искать по названиям серий`,
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
this.makeEntry({
|
this.makeEntry({
|
||||||
id: 'search_title',
|
id: 'search_title',
|
||||||
title: 'Поиск книг',
|
title: 'Поиск книг',
|
||||||
link: this.navLink({href: `/${this.id}?type=title&term=${encodeURIComponent(query.term)}`}),
|
link: this.navLink({href: `/${this.id}?type=title&term=${encodeURIComponent(query.term)}`}),
|
||||||
|
content: {
|
||||||
|
'*ATTRS': {type: 'text'},
|
||||||
|
'*TEXT': `Искать по названиям книг`,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
this.makeEntry({
|
||||||
|
id: 'search_genre',
|
||||||
|
title: 'Поиск книг в жанре',
|
||||||
|
link: this.navLink({href: `/genre?from=search&term=${encodeURIComponent(query.term)}`}),
|
||||||
|
content: {
|
||||||
|
'*ATTRS': {type: 'text'},
|
||||||
|
'*TEXT': `Искать по названиям книг в выбранном жанре`,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
this.makeEntry({
|
||||||
|
id: 'search_help',
|
||||||
|
title: '[Памятка по поиску]',
|
||||||
|
link: this.acqLink({href: `/search-help`}),
|
||||||
|
content: {
|
||||||
|
'*ATTRS': {type: 'text'},
|
||||||
|
'*TEXT': `Описание формата поискового значения`,
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
const BasePage = require('./BasePage');
|
const BasePage = require('./BasePage');
|
||||||
|
const utils = require('../utils');
|
||||||
|
|
||||||
class SeriesPage extends BasePage {
|
class SeriesPage extends BasePage {
|
||||||
constructor(config) {
|
constructor(config) {
|
||||||
@@ -25,7 +26,7 @@ class SeriesPage extends BasePage {
|
|||||||
const query = {
|
const query = {
|
||||||
series: req.query.series || '',
|
series: req.query.series || '',
|
||||||
genre: req.query.genre || '',
|
genre: req.query.genre || '',
|
||||||
del: 0,
|
del: '0',
|
||||||
|
|
||||||
all: req.query.all || '',
|
all: req.query.all || '',
|
||||||
depth: 0,
|
depth: 0,
|
||||||
@@ -45,7 +46,7 @@ class SeriesPage extends BasePage {
|
|||||||
|
|
||||||
if (bookList.books) {
|
if (bookList.books) {
|
||||||
let books = bookList.books;
|
let books = bookList.books;
|
||||||
const booksAll = this.filterBooks(books, {del: 0});
|
const booksAll = this.filterBooks(books);
|
||||||
const filtered = (query.all ? booksAll : this.filterBooks(books, query));
|
const filtered = (query.all ? booksAll : this.filterBooks(books, query));
|
||||||
const sorted = this.sortSeriesBooks(filtered);
|
const sorted = this.sortSeriesBooks(filtered);
|
||||||
|
|
||||||
@@ -63,21 +64,16 @@ class SeriesPage extends BasePage {
|
|||||||
for (const book of sorted) {
|
for (const book of sorted) {
|
||||||
const title = `${book.serno ? `${book.serno}. `: ''}${book.title || 'Без названия'} (${book.ext})`;
|
const title = `${book.serno ? `${book.serno}. `: ''}${book.title || 'Без названия'} (${book.ext})`;
|
||||||
|
|
||||||
const e = {
|
|
||||||
id: book._uid,
|
|
||||||
title,
|
|
||||||
link: this.acqLink({href: `/book?uid=${encodeURIComponent(book._uid)}`}),
|
|
||||||
};
|
|
||||||
|
|
||||||
if (query.all) {
|
|
||||||
e.content = {
|
|
||||||
'*ATTRS': {type: 'text'},
|
|
||||||
'*TEXT': this.bookAuthor(book.author),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
entry.push(
|
entry.push(
|
||||||
this.makeEntry(e)
|
this.makeEntry({
|
||||||
|
id: book._uid,
|
||||||
|
title,
|
||||||
|
link: this.acqLink({href: `/book?uid=${encodeURIComponent(book._uid)}`}),
|
||||||
|
content: {
|
||||||
|
'*ATTRS': {type: 'text'},
|
||||||
|
'*TEXT': this.bookAuthor(book.author),
|
||||||
|
},
|
||||||
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -95,14 +91,27 @@ class SeriesPage extends BasePage {
|
|||||||
//навигация по каталогу
|
//навигация по каталогу
|
||||||
const queryRes = await this.opdsQuery('series', query, '[Остальные серии]');
|
const queryRes = await this.opdsQuery('series', query, '[Остальные серии]');
|
||||||
|
|
||||||
for (const rec of queryRes) {
|
for (const rec of queryRes) {
|
||||||
entry.push(
|
const e = {
|
||||||
this.makeEntry({
|
id: rec.id,
|
||||||
id: rec.id,
|
title: (rec.count ? rec.title : `Серия: ${rec.title}`),
|
||||||
title: rec.title,
|
link: this.navLink({href: `/${this.id}?series=${rec.q}&genre=${encodeURIComponent(query.genre)}`}),
|
||||||
link: this.navLink({href: `/${this.id}?series=${rec.q}&genre=${encodeURIComponent(query.genre)}`}),
|
};
|
||||||
})
|
|
||||||
);
|
let countStr = '';
|
||||||
|
if (rec.count)
|
||||||
|
countStr = `${rec.count} сери${utils.wordEnding(rec.count, 1)}${(query.genre ? ' (в выбранном жанре)' : '')}`;
|
||||||
|
if (!countStr && rec.bookCount && !query.genre)
|
||||||
|
countStr = `${rec.bookCount} книг${utils.wordEnding(rec.bookCount, 8)}`;
|
||||||
|
|
||||||
|
if (countStr) {
|
||||||
|
e.content = {
|
||||||
|
'*ATTRS': {type: 'text'},
|
||||||
|
'*TEXT': countStr,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
entry.push(this.makeEntry(e));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
const BasePage = require('./BasePage');
|
const BasePage = require('./BasePage');
|
||||||
|
const utils = require('../utils');
|
||||||
|
|
||||||
class TitlePage extends BasePage {
|
class TitlePage extends BasePage {
|
||||||
constructor(config) {
|
constructor(config) {
|
||||||
@@ -14,7 +15,7 @@ class TitlePage extends BasePage {
|
|||||||
const query = {
|
const query = {
|
||||||
title: req.query.title || '',
|
title: req.query.title || '',
|
||||||
genre: req.query.genre || '',
|
genre: req.query.genre || '',
|
||||||
del: 0,
|
del: '0',
|
||||||
|
|
||||||
depth: 0,
|
depth: 0,
|
||||||
};
|
};
|
||||||
@@ -65,14 +66,27 @@ class TitlePage extends BasePage {
|
|||||||
//навигация по каталогу
|
//навигация по каталогу
|
||||||
const queryRes = await this.opdsQuery('title', query, '[Остальные названия]');
|
const queryRes = await this.opdsQuery('title', query, '[Остальные названия]');
|
||||||
|
|
||||||
for (const rec of queryRes) {
|
for (const rec of queryRes) {
|
||||||
entry.push(
|
const e = {
|
||||||
this.makeEntry({
|
id: rec.id,
|
||||||
id: rec.id,
|
title: rec.title,
|
||||||
title: rec.title,
|
link: this.navLink({href: `/${this.id}?title=${rec.q}&genre=${encodeURIComponent(query.genre)}`}),
|
||||||
link: this.navLink({href: `/${this.id}?title=${rec.q}&genre=${encodeURIComponent(query.genre)}`}),
|
};
|
||||||
})
|
|
||||||
);
|
let countStr = '';
|
||||||
|
if (rec.count)
|
||||||
|
countStr = `${rec.count} назван${utils.wordEnding(rec.count, 3)}${(query.genre ? ' (в выбранном жанре)' : '')}`;
|
||||||
|
if (!countStr && rec.bookCount && !query.genre)
|
||||||
|
countStr = `${rec.bookCount} книг${utils.wordEnding(rec.bookCount, 8)}`;
|
||||||
|
|
||||||
|
if (countStr) {
|
||||||
|
e.content = {
|
||||||
|
'*ATTRS': {type: 'text'},
|
||||||
|
'*TEXT': countStr,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
entry.push(this.makeEntry(e));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,12 +9,15 @@ const BookPage = require('./BookPage');
|
|||||||
|
|
||||||
const OpensearchPage = require('./OpensearchPage');
|
const OpensearchPage = require('./OpensearchPage');
|
||||||
const SearchPage = require('./SearchPage');
|
const SearchPage = require('./SearchPage');
|
||||||
|
const SearchHelpPage = require('./SearchHelpPage');
|
||||||
|
|
||||||
|
const log = new (require('../AppLogger'))().log;//singleton
|
||||||
|
|
||||||
module.exports = function(app, config) {
|
module.exports = function(app, config) {
|
||||||
if (!config.opds || !config.opds.enabled)
|
if (!config.opds || !config.opds.enabled)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
const opdsRoot = '/opds';
|
const opdsRoot = config.opds.root || '/opds';
|
||||||
config.opdsRoot = opdsRoot;
|
config.opdsRoot = opdsRoot;
|
||||||
|
|
||||||
const root = new RootPage(config);
|
const root = new RootPage(config);
|
||||||
@@ -26,6 +29,7 @@ module.exports = function(app, config) {
|
|||||||
|
|
||||||
const opensearch = new OpensearchPage(config);
|
const opensearch = new OpensearchPage(config);
|
||||||
const search = new SearchPage(config);
|
const search = new SearchPage(config);
|
||||||
|
const searchHelp = new SearchHelpPage(config);
|
||||||
|
|
||||||
const routes = [
|
const routes = [
|
||||||
['', root],
|
['', root],
|
||||||
@@ -38,6 +42,7 @@ module.exports = function(app, config) {
|
|||||||
|
|
||||||
['/opensearch', opensearch],
|
['/opensearch', opensearch],
|
||||||
['/search', search],
|
['/search', search],
|
||||||
|
['/search-help', searchHelp],
|
||||||
];
|
];
|
||||||
|
|
||||||
const pages = new Map();
|
const pages = new Map();
|
||||||
@@ -60,10 +65,8 @@ module.exports = function(app, config) {
|
|||||||
next();
|
next();
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
log(LM_ERR, `OPDS: ${e.message}, url: ${req.originalUrl}`);
|
||||||
res.status(500).send({error: e.message});
|
res.status(500).send({error: e.message});
|
||||||
if (config.branch == 'development') {
|
|
||||||
console.error({error: e.message, url: req.originalUrl});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -109,9 +109,10 @@ function gzipFile(inputFile, outputFile, level = 1) {
|
|||||||
.pipe(gzip).on('error', reject)
|
.pipe(gzip).on('error', reject)
|
||||||
.pipe(output).on('error', reject)
|
.pipe(output).on('error', reject)
|
||||||
.on('finish', (err) => {
|
.on('finish', (err) => {
|
||||||
if (err) reject(err);
|
if (err) reject(err);
|
||||||
else resolve();
|
else resolve();
|
||||||
});
|
}
|
||||||
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -125,9 +126,10 @@ function gunzipFile(inputFile, outputFile) {
|
|||||||
.pipe(gzip).on('error', reject)
|
.pipe(gzip).on('error', reject)
|
||||||
.pipe(output).on('error', reject)
|
.pipe(output).on('error', reject)
|
||||||
.on('finish', (err) => {
|
.on('finish', (err) => {
|
||||||
if (err) reject(err);
|
if (err) reject(err);
|
||||||
else resolve();
|
else resolve();
|
||||||
});
|
}
|
||||||
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -174,6 +176,26 @@ function makeValidFileNameOrEmpty(fileName) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function wordEnding(num, type = 0) {
|
||||||
|
const endings = [
|
||||||
|
['ов', '', 'а', 'а', 'а', 'ов', 'ов', 'ов', 'ов', 'ов'],//0
|
||||||
|
['й', 'я', 'и', 'и', 'и', 'й', 'й', 'й', 'й', 'й'],//1
|
||||||
|
['о', '', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о'],//2
|
||||||
|
['ий', 'ие', 'ия', 'ия', 'ия', 'ий', 'ий', 'ий', 'ий', 'ий'],//3
|
||||||
|
['о', 'а', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о'],//4
|
||||||
|
['ок', 'ка', 'ки', 'ки', 'ки', 'ок', 'ок', 'ок', 'ок', 'ок'],//5
|
||||||
|
['ых', 'ое', 'ых', 'ых', 'ых', 'ых', 'ых', 'ых', 'ых', 'ых'],//6
|
||||||
|
['о', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о'],//7
|
||||||
|
['', 'а', 'и', 'и', 'и', '', '', '', '', ''],//8
|
||||||
|
];
|
||||||
|
const deci = num % 100;
|
||||||
|
if (deci > 10 && deci < 20) {
|
||||||
|
return endings[type][0];
|
||||||
|
} else {
|
||||||
|
return endings[type][num % 10];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
sleep,
|
sleep,
|
||||||
processLoop,
|
processLoop,
|
||||||
@@ -193,4 +215,5 @@ module.exports = {
|
|||||||
toUnixPath,
|
toUnixPath,
|
||||||
makeValidFileName,
|
makeValidFileName,
|
||||||
makeValidFileNameOrEmpty,
|
makeValidFileNameOrEmpty,
|
||||||
|
wordEnding,
|
||||||
};
|
};
|
||||||
@@ -734,8 +734,8 @@ class XmlParser extends NodeBase {
|
|||||||
} else if (tag === '*ATTRS') {
|
} else if (tag === '*ATTRS') {
|
||||||
//пропускаем
|
//пропускаем
|
||||||
} else {
|
} else {
|
||||||
if (typeof(objNode) === 'string') {
|
if (typeof(objNode) === 'string' || typeof(objNode) === 'number') {
|
||||||
result.push(this.createNode(tag, null, [this.createText(objNode).raw]).raw);
|
result.push(this.createNode(tag, null, [this.createText(objNode.toString()).raw]).raw);
|
||||||
} else if (Array.isArray(objNode)) {
|
} else if (Array.isArray(objNode)) {
|
||||||
for (const n of objNode) {
|
for (const n of objNode) {
|
||||||
if (typeof(n) === 'string') {
|
if (typeof(n) === 'string') {
|
||||||
@@ -747,6 +747,8 @@ class XmlParser extends NodeBase {
|
|||||||
|
|
||||||
} else if (typeof(objNode) === 'object') {
|
} else if (typeof(objNode) === 'object') {
|
||||||
result.push(this.createNode(tag, (objNode['*ATTRS'] ? Object.entries(objNode['*ATTRS']) : null), objectToNodes(objNode)).raw);
|
result.push(this.createNode(tag, (objNode['*ATTRS'] ? Object.entries(objNode['*ATTRS']) : null), objectToNodes(objNode)).raw);
|
||||||
|
} else {
|
||||||
|
throw new Error(`Unknown node type "${typeof(objNode)}" of node: ${objNode}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ module.exports = async(config) => {
|
|||||||
|
|
||||||
if (await fs.pathExists(verFile)) {
|
if (await fs.pathExists(verFile)) {
|
||||||
const curPublicVersion = await fs.readFile(verFile, 'utf8');
|
const curPublicVersion = await fs.readFile(verFile, 'utf8');
|
||||||
if (curPublicVersion == config.version)
|
if (curPublicVersion == config.version + config.rootPathStatic)
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -26,6 +26,6 @@ module.exports = async(config) => {
|
|||||||
await zipReader.close();
|
await zipReader.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
await fs.writeFile(verFile, config.version);
|
await fs.writeFile(verFile, config.version + config.rootPathStatic);
|
||||||
await fs.remove(zipFile);
|
await fs.remove(zipFile);
|
||||||
};
|
};
|
||||||
@@ -16,16 +16,16 @@ let branch = '';
|
|||||||
const argvStrings = ['host', 'port', 'app-dir', 'lib-dir', 'inpx'];
|
const argvStrings = ['host', 'port', 'app-dir', 'lib-dir', 'inpx'];
|
||||||
|
|
||||||
function showHelp(defaultConfig) {
|
function showHelp(defaultConfig) {
|
||||||
console.log(utils.versionText(config));
|
console.log(utils.versionText(defaultConfig));
|
||||||
console.log(
|
console.log(
|
||||||
`Usage: ${config.name} [options]
|
`Usage: ${defaultConfig.name} [options]
|
||||||
|
|
||||||
Options:
|
Options:
|
||||||
--help Print ${config.name} command line options
|
--help Print ${defaultConfig.name} command line options
|
||||||
--host=<ip> Set web server host, default: ${defaultConfig.server.host}
|
--host=<ip> Set web server host, default: ${defaultConfig.server.host}
|
||||||
--port=<port> Set web server port, default: ${defaultConfig.server.port}
|
--port=<port> Set web server port, default: ${defaultConfig.server.port}
|
||||||
--app-dir=<dirpath> Set application working directory, default: <execDir>/.${config.name}
|
--app-dir=<dirpath> Set application working directory, default: <execDir>/.${defaultConfig.name}
|
||||||
--lib-dir=<dirpath> Set library directory, default: the same as ${config.name} executable's
|
--lib-dir=<dirpath> Set library directory, default: the same as ${defaultConfig.name} executable's
|
||||||
--inpx=<filepath> Set INPX collection file, default: the one that found in library dir
|
--inpx=<filepath> Set INPX collection file, default: the one that found in library dir
|
||||||
--recreate Force recreation of the search database on start
|
--recreate Force recreation of the search database on start
|
||||||
`
|
`
|
||||||
@@ -50,13 +50,14 @@ async function init() {
|
|||||||
config.logDir = `${config.dataDir}/log`;
|
config.logDir = `${config.dataDir}/log`;
|
||||||
config.publicDir = `${config.dataDir}/public`;
|
config.publicDir = `${config.dataDir}/public`;
|
||||||
config.publicFilesDir = `${config.dataDir}/public-files`;
|
config.publicFilesDir = `${config.dataDir}/public-files`;
|
||||||
config.filesPathStatic = `/book`;
|
config.rootPathStatic = config.server.root || '';
|
||||||
config.filesDir = `${config.publicFilesDir}${config.filesPathStatic}`;
|
config.bookPathStatic = `${config.rootPathStatic}/book`;
|
||||||
|
config.bookDir = `${config.publicFilesDir}/book`;
|
||||||
|
|
||||||
configManager.config = config;
|
configManager.config = config;
|
||||||
|
|
||||||
await fs.ensureDir(config.dataDir);
|
await fs.ensureDir(config.dataDir);
|
||||||
await fs.ensureDir(config.filesDir);
|
await fs.ensureDir(config.bookDir);
|
||||||
await fs.ensureDir(config.tempDir);
|
await fs.ensureDir(config.tempDir);
|
||||||
await fs.emptyDir(config.tempDir);
|
await fs.emptyDir(config.tempDir);
|
||||||
|
|
||||||
@@ -83,7 +84,7 @@ async function init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!config.remoteLib) {
|
if (!config.remoteLib) {
|
||||||
const libDir = argv['lib-dir'];
|
const libDir = argv['lib-dir'] || config.libDir;
|
||||||
if (libDir) {
|
if (libDir) {
|
||||||
if (await fs.pathExists(libDir)) {
|
if (await fs.pathExists(libDir)) {
|
||||||
config.libDir = libDir;
|
config.libDir = libDir;
|
||||||
@@ -94,11 +95,12 @@ async function init() {
|
|||||||
config.libDir = config.execDir;
|
config.libDir = config.execDir;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (argv.inpx) {
|
const inpxFile = argv.inpx || config.inpx;
|
||||||
if (await fs.pathExists(argv.inpx)) {
|
if (inpxFile) {
|
||||||
config.inpxFile = argv.inpx;
|
if (await fs.pathExists(inpxFile)) {
|
||||||
|
config.inpxFile = inpxFile;
|
||||||
} else {
|
} else {
|
||||||
throw new Error(`File "${argv.inpx}" not found`);
|
throw new Error(`File "${inpxFile}" not found`);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const inpxFiles = [];
|
const inpxFiles = [];
|
||||||
@@ -156,6 +158,8 @@ async function main() {
|
|||||||
|
|
||||||
const opds = require('./core/opds');
|
const opds = require('./core/opds');
|
||||||
opds(app, config);
|
opds(app, config);
|
||||||
|
|
||||||
|
const initStatic = require('./static');
|
||||||
initStatic(app, config);
|
initStatic(app, config);
|
||||||
|
|
||||||
const webAccess = new (require('./core/WebAccess'))(config);
|
const webAccess = new (require('./core/WebAccess'))(config);
|
||||||
@@ -179,63 +183,6 @@ async function main() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function initStatic(app, config) {
|
|
||||||
/*
|
|
||||||
publicFilesDir = `${config.dataDir}/public-files`;
|
|
||||||
filesPathStatic = `/book`;
|
|
||||||
filesDir = `${config.publicFilesDir}${config.filesPathStatic}`;
|
|
||||||
*/
|
|
||||||
const filesPath = `${config.filesPathStatic}/`;
|
|
||||||
//загрузка или восстановление файлов в /files, при необходимости
|
|
||||||
app.use(async(req, res, next) => {
|
|
||||||
if ((req.method !== 'GET' && req.method !== 'HEAD') ||
|
|
||||||
!(req.path.indexOf(filesPath) === 0)
|
|
||||||
) {
|
|
||||||
return next();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (path.extname(req.path) == '') {
|
|
||||||
const bookFile = `${config.publicFilesDir}${req.path}`;
|
|
||||||
const bookFileDesc = `${bookFile}.d.json`;
|
|
||||||
|
|
||||||
let downFileName = '';
|
|
||||||
//восстановим из json-файла описания
|
|
||||||
try {
|
|
||||||
if (await fs.pathExists(bookFile) && await fs.pathExists(bookFileDesc)) {
|
|
||||||
await utils.touchFile(bookFile);
|
|
||||||
await utils.touchFile(bookFileDesc);
|
|
||||||
|
|
||||||
let desc = await fs.readFile(bookFileDesc, 'utf8');
|
|
||||||
desc = JSON.parse(desc);
|
|
||||||
downFileName = desc.downFileName;
|
|
||||||
} else {
|
|
||||||
await fs.remove(bookFile);
|
|
||||||
await fs.remove(bookFileDesc);
|
|
||||||
}
|
|
||||||
} catch(e) {
|
|
||||||
log(LM_ERR, e.message);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (downFileName)
|
|
||||||
res.downFileName = downFileName;
|
|
||||||
}
|
|
||||||
|
|
||||||
return next();
|
|
||||||
});
|
|
||||||
|
|
||||||
//заголовки при отдаче
|
|
||||||
app.use(config.filesPathStatic, express.static(config.filesDir, {
|
|
||||||
setHeaders: (res) => {
|
|
||||||
if (res.downFileName) {
|
|
||||||
res.set('Content-Encoding', 'gzip');
|
|
||||||
res.set('Content-Disposition', `inline; filename*=UTF-8''${encodeURIComponent(res.downFileName)}`);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|
||||||
app.use(express.static(config.publicDir));
|
|
||||||
}
|
|
||||||
|
|
||||||
(async() => {
|
(async() => {
|
||||||
try {
|
try {
|
||||||
await init();
|
await init();
|
||||||
|
|||||||
127
server/static.js
Normal file
127
server/static.js
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
const fs = require('fs-extra');
|
||||||
|
const path = require('path');
|
||||||
|
const yazl = require('yazl');
|
||||||
|
|
||||||
|
const express = require('express');
|
||||||
|
const utils = require('./core/utils');
|
||||||
|
const webAppDir = require('../build/appdir');
|
||||||
|
|
||||||
|
const log = new (require('./core/AppLogger'))().log;//singleton
|
||||||
|
|
||||||
|
function generateZip(zipFile, dataFile, dataFileInZip) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const zip = new yazl.ZipFile();
|
||||||
|
zip.addFile(dataFile, dataFileInZip);
|
||||||
|
zip.outputStream
|
||||||
|
.pipe(fs.createWriteStream(zipFile)).on('error', reject)
|
||||||
|
.on('finish', (err) => {
|
||||||
|
if (err) reject(err);
|
||||||
|
else resolve();
|
||||||
|
}
|
||||||
|
);
|
||||||
|
zip.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = (app, config) => {
|
||||||
|
/*
|
||||||
|
config.bookPathStatic = `${config.rootPathStatic}/book`;
|
||||||
|
config.bookDir = `${config.publicFilesDir}/book`;
|
||||||
|
*/
|
||||||
|
//загрузка или восстановление файлов в /public-files, при необходимости
|
||||||
|
app.use([`${config.bookPathStatic}/:fileName/:fileType`, `${config.bookPathStatic}/:fileName`], async(req, res, next) => {
|
||||||
|
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const fileName = req.params.fileName;
|
||||||
|
const fileType = req.params.fileType;
|
||||||
|
|
||||||
|
if (path.extname(fileName) === '') {//восстановление файлов {hash}.raw, {hash}.zip
|
||||||
|
let bookFile = `${config.bookDir}/${fileName}`;
|
||||||
|
const bookFileDesc = `${bookFile}.d.json`;
|
||||||
|
|
||||||
|
//восстановим из json-файла описания
|
||||||
|
if (await fs.pathExists(bookFile) && await fs.pathExists(bookFileDesc)) {
|
||||||
|
await utils.touchFile(bookFile);
|
||||||
|
await utils.touchFile(bookFileDesc);
|
||||||
|
|
||||||
|
let desc = await fs.readFile(bookFileDesc, 'utf8');
|
||||||
|
let downFileName = (JSON.parse(desc)).downFileName;
|
||||||
|
let gzipped = true;
|
||||||
|
|
||||||
|
if (!req.acceptsEncodings('gzip') || fileType) {
|
||||||
|
const rawFile = `${bookFile}.raw`;
|
||||||
|
//не принимает gzip, тогда распакуем
|
||||||
|
if (!await fs.pathExists(rawFile))
|
||||||
|
await utils.gunzipFile(bookFile, rawFile);
|
||||||
|
|
||||||
|
gzipped = false;
|
||||||
|
|
||||||
|
if (fileType === undefined || fileType === 'raw') {
|
||||||
|
bookFile = rawFile;
|
||||||
|
} else if (fileType === 'zip') {
|
||||||
|
//создаем zip-файл
|
||||||
|
bookFile += '.zip';
|
||||||
|
if (!await fs.pathExists(bookFile))
|
||||||
|
await generateZip(bookFile, rawFile, downFileName);
|
||||||
|
downFileName += '.zip';
|
||||||
|
} else {
|
||||||
|
throw new Error(`Unsupported file type: ${fileType}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//отдача файла
|
||||||
|
if (gzipped)
|
||||||
|
res.set('Content-Encoding', 'gzip');
|
||||||
|
res.set('Content-Disposition', `inline; filename*=UTF-8''${encodeURIComponent(downFileName)}`);
|
||||||
|
res.sendFile(bookFile);
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
await fs.remove(bookFile);
|
||||||
|
await fs.remove(bookFileDesc);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch(e) {
|
||||||
|
log(LM_ERR, e.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return next();
|
||||||
|
});
|
||||||
|
|
||||||
|
//иначе просто отдаем запрошенный файл из /public-files
|
||||||
|
app.use(config.bookPathStatic, express.static(config.bookDir));
|
||||||
|
|
||||||
|
if (config.rootPathStatic) {
|
||||||
|
//подмена rootPath в файлах статики WebApp при необходимости
|
||||||
|
app.use(config.rootPathStatic, async(req, res, next) => {
|
||||||
|
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const reqPath = (req.path == '/' ? '/index.html' : req.path);
|
||||||
|
const ext = path.extname(reqPath);
|
||||||
|
if (ext == '.html' || ext == '.js' || ext == '.css') {
|
||||||
|
const reqFile = `${config.publicDir}${reqPath}`;
|
||||||
|
const flagFile = `${reqFile}.replaced`;
|
||||||
|
|
||||||
|
if (!await fs.pathExists(flagFile) && await fs.pathExists(reqFile)) {
|
||||||
|
const content = await fs.readFile(reqFile, 'utf8');
|
||||||
|
const re = new RegExp(`/${webAppDir}`, 'g');
|
||||||
|
await fs.writeFile(reqFile, content.replace(re, `${config.rootPathStatic}/${webAppDir}`));
|
||||||
|
await fs.writeFile(flagFile, '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch(e) {
|
||||||
|
log(LM_ERR, e.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return next();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
//статика файлов WebApp
|
||||||
|
app.use(config.rootPathStatic, express.static(config.publicDir));
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user