Compare commits
202 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9c0c83143f | ||
|
|
ac074c4c00 | ||
|
|
9a3ce1e184 | ||
|
|
e17053141d | ||
|
|
320e5aec2a | ||
|
|
2d8c1c655a | ||
|
|
7e268fec0b | ||
|
|
1de8af197e | ||
|
|
d01c0744e5 | ||
|
|
175511ba45 | ||
|
|
4edcc4c88d | ||
|
|
915716880c | ||
|
|
77a7678565 | ||
|
|
49fd516d45 | ||
|
|
7e4b548583 | ||
|
|
981d862fa7 | ||
|
|
fc35a5aa97 | ||
|
|
d52d9d7f20 | ||
|
|
a3b83f93c3 | ||
|
|
2efdc6b0aa | ||
|
|
1e7d81b181 | ||
|
|
bbf7b43aa3 | ||
|
|
5aefa9e558 | ||
|
|
605aba7a05 | ||
|
|
5a43cd0e46 | ||
|
|
307b9adfa3 | ||
|
|
85a23578e7 | ||
|
|
db0b3c8c62 | ||
|
|
e820c82c56 | ||
|
|
ac29dbebba | ||
|
|
84843fb6bd | ||
|
|
74ece78175 | ||
|
|
b2fcf8d043 | ||
|
|
9ce33715d2 | ||
|
|
76fc64c1b7 | ||
|
|
b0edc3561e | ||
|
|
c3810d1ff5 | ||
|
|
deeac0be14 | ||
|
|
70593b5d22 | ||
|
|
4c90844f46 | ||
|
|
3e2599f233 | ||
|
|
8687931274 | ||
|
|
50f7a7800d | ||
|
|
eb2fbd20ae | ||
|
|
24d609d8f1 | ||
|
|
4b4f7bd697 | ||
|
|
bf6cf4238a | ||
|
|
1daf619a2d | ||
|
|
7e8d616c65 | ||
|
|
d9e19ff9b7 | ||
|
|
6be1b94b96 | ||
|
|
d6aa43d01b | ||
|
|
14a877d6d1 | ||
|
|
82eb78f433 | ||
|
|
8e5e0104a4 | ||
|
|
636e34bdc1 | ||
|
|
2c687c7af9 | ||
|
|
27fc46c410 | ||
|
|
a7cd019a97 | ||
|
|
12304c13a1 | ||
|
|
d87e2ce632 | ||
|
|
a2423fb704 | ||
|
|
192b92cab8 | ||
|
|
386a937239 | ||
|
|
06300e30b4 | ||
|
|
371d5646ae | ||
|
|
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 | ||
|
|
90c3faadcf | ||
|
|
e594206759 | ||
|
|
80b21371a4 | ||
|
|
af575a87a2 | ||
|
|
a6aa8d8e95 | ||
|
|
aa436feae7 | ||
|
|
abce84999f | ||
|
|
74bb3f2362 | ||
|
|
abcbbc86bc | ||
|
|
d859202fb1 | ||
|
|
d71c235ebc | ||
|
|
49583d3407 | ||
|
|
a7f71562b4 | ||
|
|
f93269ac8b | ||
|
|
79f85f362a | ||
|
|
bf9ae0b9e1 | ||
|
|
678562525f | ||
|
|
abb3baf94b | ||
|
|
59b4f48897 | ||
|
|
dca59e02dd | ||
|
|
9bc92a7346 | ||
|
|
53264da6bd | ||
|
|
53e328ac2d | ||
|
|
59c2d73c05 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,5 +1,4 @@
|
||||
/node_modules
|
||||
/server/.inpx-web*
|
||||
/server/inpx-web-filter.json
|
||||
/dist
|
||||
dev*.sh
|
||||
109
CHANGELOG.md
Normal file
109
CHANGELOG.md
Normal file
@@ -0,0 +1,109 @@
|
||||
1.5.7 / 2024-04-04
|
||||
|
||||
- В параметр bookReadLink конфига добавлен вариант замены DOWNLOAD_URI на uri из ссылки для скачивания книги (#29)
|
||||
- В параметры командной строки добавлена возможность задавать путь к файлу конфигурации, а все остальные настройки приложения можно указать в нем самом (#30)
|
||||
|
||||
1.5.6 / 2024-03-25
|
||||
|
||||
- Добавлен вывод version.info в статистику по коллекции (#27)
|
||||
- Убрано (по умолчанию) ежеминутное журналирование статистики сервера. В конфиг добавлен параметр logServerStats (#26)
|
||||
- В конфиг добавлен параметр logQueries для журналирования запросов и времени их выполнения
|
||||
- Добавлена расшифровка имен жанров в информации о книге (#24)
|
||||
|
||||
1.5.5 / 2023-04-25
|
||||
|
||||
- Улучшение работы с inpx: теперь понимает zip-архивы, вложенные в каталоги (библиотека Траума)
|
||||
- Улучшение работы с zip-файлами: теперь понимает кодировку cp866 в именах файлов
|
||||
|
||||
1.5.4 / 2023-04-12
|
||||
|
||||
- Добавлена возможность поиска по типу файла
|
||||
- Улучшена работа с inpx, теперь понимает файлы в каталогах (без zip-архива)
|
||||
- В readme добавлен раздел "Запуск без сборки релиза" для запуска inpx-web на любых платформах
|
||||
- Исправления мелких багов
|
||||
|
||||
1.5.3 / 2023-03-02
|
||||
|
||||
- OPDS: исправление проблемы поиска для koreader
|
||||
- OPDS: улучшено скачивание для не-fb2 форматов файлов (djvu, pdf и пр.)
|
||||
- Добавлена полоска уведомления о выходе новой версии (отключается в настройках веб-интерфейса).
|
||||
Проверка новой версии настраивается параметром checkReleaseLink в конфиге сервера (#15)
|
||||
|
||||
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.2 / 2022-11-27
|
||||
------------------
|
||||
|
||||
- Изменения механизма ограничения доступа по паролю:
|
||||
- появилась возможность выхода из сессии
|
||||
- в конфиг добавлена настройка таймаута для автозавершения сессии
|
||||
- Добавлено отображение количества книг в серии в разделе "Авторы"
|
||||
|
||||
1.3.1 / 2022-11-25
|
||||
------------------
|
||||
|
||||
- Улучшена кроссплатформенность приложения
|
||||
|
||||
1.3.0 / 2022-11-24
|
||||
------------------
|
||||
|
||||
- Добавлен OPDS-сервер для inpx-коллекции
|
||||
- Произведена небольшая оптимизация поисковой БД
|
||||
- Добавлен релиз для macos, без тестирования
|
||||
|
||||
1.2.4 / 2022-11-14
|
||||
------------------
|
||||
|
||||
- Добавлена возможность посмотреть обложку в увеличении
|
||||
- Исправление выявленных недочетов
|
||||
|
||||
1.2.3 / 2022-11-12
|
||||
------------------
|
||||
|
||||
- Добавлено диалоговое окно "Информация о книге"
|
||||
- Небольшие изменения интерфейса, добавлена кнопка "Клонировать поиск"
|
||||
|
||||
1.1.4 / 2022-11-03
|
||||
------------------
|
||||
|
||||
- Исправлен баг "Не качает книги #1"
|
||||
|
||||
1.1.2 / 2022-10-31
|
||||
------------------
|
||||
|
||||
- Добавлены разделы "Серии" и "Книги"
|
||||
- Расширена форма поиска: добавлен поиск по датам поступления и оценкам
|
||||
|
||||
154
README.md
154
README.md
@@ -19,6 +19,8 @@ OPDS-сервер доступен по адресу [http://127.0.0.1:12380/opd
|
||||
Для указания местоположения .inpx-файла или папки с файлами библиотеки, воспользуйтесь [параметрами командной строки](#cli).
|
||||
Дополнительные параметры сервера настраиваются в [конфигурационном файле](#config).
|
||||
|
||||
[Отблагодарить автора проекта](https://donatty.com/liberama)
|
||||
|
||||
##
|
||||
* [Возможности программы](#capabilities)
|
||||
* [Использование](#usage)
|
||||
@@ -27,7 +29,8 @@ OPDS-сервер доступен по адресу [http://127.0.0.1:12380/opd
|
||||
* [Удаленная библиотека](#remotelib)
|
||||
* [Фильтр по авторам и книгам](#filter)
|
||||
* [Настройка https с помощью nginx](#https)
|
||||
* [Сборка проекта](#build)
|
||||
* [Сборка релизов](#build)
|
||||
* [Запуск без сборки релиза](#native_run)
|
||||
* [Разработка](#development)
|
||||
|
||||
<a id="capabilities" />
|
||||
@@ -42,7 +45,7 @@ OPDS-сервер доступен по адресу [http://127.0.0.1:12380/opd
|
||||
- фильтр авторов и книг при создании поисковой БД для создания своей коллекции "на лету"
|
||||
- подхват изменений .inpx-файла (периодическая проверка), автоматическое пересоздание поисковой БД
|
||||
- мощная оптимизация, хорошая скорость поиска
|
||||
- релизы под Linux и Windows
|
||||
- релизы под Linux, MacOS и Windows
|
||||
|
||||
<a id="usage" />
|
||||
|
||||
@@ -66,34 +69,95 @@ Options:
|
||||
--help Показать опции командной строки
|
||||
--host=<ip> Задать имя хоста для веб сервера, по умолчанию: 0.0.0.0
|
||||
--port=<port> Задать порт для веб сервера, по умолчанию: 12380
|
||||
--app-dir=<dirpath> Задать рабочую директорию, по умолчанию: <execDir>/.inpx-web
|
||||
--config=<filepath> Задать файл конфигурации, по умолчанию: <dataDir>/config.json
|
||||
--data-dir=<dirpath> (или --app-dir) Задать рабочую директорию, по умолчанию: <execDir>/.inpx-web
|
||||
--lib-dir=<dirpath> Задать директорию библиотеки (с zip-архивами), по умолчанию: там же, где лежит файл приложения
|
||||
--inpx=<filepath> Задать путь к файлу .inpx, по умолчанию: тот, что найдется в директории библиотеки
|
||||
--recreate Принудительно пересоздать поисковую БД при запуске приложения
|
||||
--unsafe-filter Использовать небезопасный фильтр на свой страх и риск
|
||||
```
|
||||
|
||||
<a id="config" />
|
||||
|
||||
### Конфигурация
|
||||
При первом запуске в рабочей директории будет создан конфигурационный файл `config.json`:
|
||||
|
||||
По умолчанию, при первом запуске в рабочей директории будет создан конфигурационный файл `config.json`.
|
||||
При необходимости, можно настроить нужный параметр в этом файле вручную. Параметры командной
|
||||
строки имеют больший приоритет, чем настройки из `config.json`.
|
||||
|
||||
```js
|
||||
{
|
||||
// рабочая директория приложения, аналог параметра командной строки --data-dir (или --app-dir)
|
||||
// пустая строка: использовать значение по умолчанию - <execDir>/.inpx-web
|
||||
// где execDir - директория файла приложения
|
||||
"dataDir": "",
|
||||
|
||||
// директория для хранения временных файлов
|
||||
// пустая строка: использовать значение по умолчанию - <dataDir>/tmp
|
||||
// специальное значение "${OS}" указывается для использования системного каталога:
|
||||
// "${OS}" => "<os_temporary_dir>/inpx-web"
|
||||
"tempDir": "",
|
||||
|
||||
// директория для хранения логов
|
||||
// пустая строка: использовать значение по умолчанию - <dataDir>/logs
|
||||
"logDir": "",
|
||||
|
||||
// директория библиотеки (с zip-архивами), аналог параметра командной строки --lib-dir
|
||||
// пустая строка: использовать значение по умолчанию - директорию файла приложения (execDir)
|
||||
"libDir": "",
|
||||
|
||||
// путь к файлу .inpx, аналог параметра командной строки --inpx
|
||||
// пустая строка: использовать значение по умолчанию - inpx-файл, что найдется в директории библиотеки
|
||||
"inpx": "",
|
||||
|
||||
// конфигурационный файл для фильтра по авторам и книгам (см. ниже)
|
||||
// пустая строка: использовать значение по умолчанию - файл filter.json в директории файла конфигурации
|
||||
"inpxFilterFile": "",
|
||||
|
||||
// разрешить(true)/запретить(false) перезаписывать файл конфигурации, если появились новые параметры для настройки
|
||||
// файл перезаписывается с сохранением всех предыдущих настроек и с новыми по умолчанию
|
||||
// бывает полезно при выходе новых версий приложения
|
||||
"allowConfigRewrite": false,
|
||||
|
||||
// разрешить(true)/запретить(false) использовать небезопасный фильтр (см. ниже)
|
||||
// аналог параметра командной строки --unsafe-filter
|
||||
"allowUnsafeFilter": false,
|
||||
|
||||
// пароль для ограничения доступа к веб-интерфейсу сервера
|
||||
// пустое значение - доступ без ограничений
|
||||
"accessPassword": "",
|
||||
|
||||
// таймаут автозавершения сессии доступа к веб-интерфейсу (если задан accessPassword),
|
||||
// при неактивности в течение указанного времени (в минутах), пароль будет запрошен заново
|
||||
// 0 - отключить таймаут, время доступа по паролю не ограничено
|
||||
"accessTimeout": 0,
|
||||
|
||||
// включить(true)/выключить(false) возможность расширенного поиска (раздел "</>")
|
||||
// расширенный поиск не оптимизирован, поэтому может сильно нагружать сервер
|
||||
// чтобы ускорить поиск, увеличьте параметр dbCacheSize
|
||||
"extendedSearch": true,
|
||||
|
||||
// содержимое кнопки-ссылки "(читать)", если не задано - кнопка "(читать)" не показывается
|
||||
// пример: "https://omnireader.ru/#/reader?url=${DOWNLOAD_LINK}"
|
||||
// на место ${DOWNLOAD_LINK} будет подставлена ссылка на скачивание файла книги
|
||||
// пример: "https://mydomain.ru/#/reader?url=http://127.0.0.1:8086${DOWNLOAD_URI}"
|
||||
// на место ${DOWNLOAD_URI} будут подставлены параметры (без имени хоста) из ссылки на скачивание файла книги
|
||||
"bookReadLink": "",
|
||||
|
||||
// включить(true)/выключить(false) журналирование
|
||||
"loggingEnabled": true,
|
||||
|
||||
// включить/выключить ежеминутный вывод в лог memUsage и loadAvg
|
||||
"logServerStats": false,
|
||||
|
||||
// включить/выключить вывод в лог запросов и времени их выполнения
|
||||
"logQueries": false,
|
||||
|
||||
// максимальный размер кеша каждой таблицы в БД, в блоках (требуется примерно 1-10Мб памяти на один блок)
|
||||
// если надо кешировать всю БД, можно поставить значение от 1000 и больше
|
||||
"dbCacheSize": 5,
|
||||
|
||||
// максимальный размер в байтах директории закешированных файлов в <раб.дир>/public/files
|
||||
// максимальный размер в байтах директории закешированных файлов в <раб.дир>/public-files
|
||||
// чистка каждый час
|
||||
"maxFilesDirSize": 1073741824,
|
||||
|
||||
@@ -134,24 +198,52 @@ Options:
|
||||
"remoteLib": false,
|
||||
|
||||
// настройки веб-сервера
|
||||
// парамертр root указывает путь для кореневой страницы inpx-web
|
||||
// например для "root": "/library", веб-интерфейс будет доступен по адресу http://127.0.0.1:12380/library
|
||||
// root необходим при настройке reverse-proxy и встраивании inpx-web в уже существующий сервер
|
||||
"server": {
|
||||
"host": "0.0.0.0",
|
||||
"port": "12380"
|
||||
"port": "12380",
|
||||
"root": ""
|
||||
},
|
||||
|
||||
// настройки opds-сервера
|
||||
// user, password используются для Basic HTTP authentication
|
||||
// параметр root задает путь для доступа к opds-серверу
|
||||
"opds": {
|
||||
"enabled": true,
|
||||
"user": "",
|
||||
"password": ""
|
||||
"password": "",
|
||||
"root": "/opds"
|
||||
},
|
||||
|
||||
// страница для скачивания свежего релиза
|
||||
"latestReleaseLink": "https://github.com/bookpauk/inpx-web/releases/latest",
|
||||
|
||||
// api для проверки новой версии,
|
||||
// пустая строка - отключить проверку выхода новых версий
|
||||
"checkReleaseLink": "https://api.github.com/repos/bookpauk/inpx-web/releases/latest",
|
||||
|
||||
// настройки по умолчанию для веб-интерфейса
|
||||
// устанавливаются при первой загрузке страницы в браузере
|
||||
// дальнейшие изменения настроек с помощью веб-интерфейса уже сохраняются в самом браузере
|
||||
"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 (в расширенном поиске)
|
||||
"showNewReleaseAvailable": true // уведомлять о выходе новой версии
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
При необходимости, можно настроить нужный параметр в этом файле вручную. Параметры командной
|
||||
строки имеют больший приоритет, чем настройки из `config.json`.
|
||||
|
||||
<a id="remotelib" />
|
||||
|
||||
### Удаленная библиотека
|
||||
@@ -186,13 +278,12 @@ Options:
|
||||
### Фильтр по авторам и книгам
|
||||
|
||||
При создании поисковой БД, во время загрузки и парсинга .inpx-файла, имеется возможность
|
||||
отфильтровать авторов и книги, задав определенные критерии. Для этого небходимо создать
|
||||
в рабочей директории (там же, где `config.json`) файл `filter.json` следующего вида:
|
||||
отфильтровать авторов и книги, задав определенные критерии. По умолчанию, для этого небходимо создать
|
||||
в директории конфигурационного файла (там же, где `config.json`) файл `filter.json` следующего вида:
|
||||
```json
|
||||
{
|
||||
"info": {
|
||||
"collection": "Новое название коллекции",
|
||||
"structure": "",
|
||||
"version": "1.0.0"
|
||||
},
|
||||
"filter": "(r) => r.del == 0",
|
||||
@@ -233,8 +324,10 @@ Options:
|
||||
}
|
||||
```
|
||||
Использование `filter` небезопасно, т.к. позволяет выполнить произвольный js-код внутри программы,
|
||||
поэтому запуск приложения в этом случае должен сопровождаться дополнительным параметром командной строки `--unsafe-filter`.
|
||||
поэтому запуск приложения в этом случае должен сопровождаться дополнительным параметром командной строки `--unsafe-filter`
|
||||
или разрешением в конфиге `allowUnsafeFilter`.
|
||||
Названия атрибутов inpxRec соответствуют названиям в нижнем регистре из структуры structure.info в .inpx-файле.
|
||||
Файл `filter.json` можно расположить где угодно, что задается параметром `inpxFilterFile` в конфиге.
|
||||
<a id="https" />
|
||||
|
||||
### Настройка https с помощью nginx
|
||||
@@ -270,23 +363,46 @@ sudo service nginx reload
|
||||
|
||||
<a id="build" />
|
||||
|
||||
### Сборка проекта
|
||||
### Сборка релизов
|
||||
Сборка только в среде Linux.
|
||||
Необходима версия node.js не ниже 16.
|
||||
|
||||
Для сборки linux-arm64 необходимо предварительно установить [QEMU](https://wiki.debian.org/QemuUserEmulation).
|
||||
|
||||
```sh
|
||||
git clone https://github.com/bookpauk/inpx-web
|
||||
cd inpx-web
|
||||
npm i
|
||||
```
|
||||
|
||||
#### Релизы
|
||||
```sh
|
||||
npm run release
|
||||
```
|
||||
|
||||
Результат сборки будет доступен в каталоге `dist/release`
|
||||
|
||||
<a id="native_run" />
|
||||
|
||||
### Запуск без сборки релиза
|
||||
Т.к. сборщик pkg поддерживает не все платформы, то не всегда удается собрать релиз.
|
||||
Однако, можно скачать и запустить inpx-web нативным путем, с помощью nodejs.
|
||||
Ниже пример для Ubuntu, для других линуксов различия не принципиальны:
|
||||
|
||||
```sh
|
||||
# установка nodejs v16 и выше:
|
||||
curl -s https://deb.nodesource.com/setup_16.x | sudo bash
|
||||
sudo apt install nodejs -y
|
||||
|
||||
# подготовка
|
||||
git clone https://github.com/bookpauk/inpx-web
|
||||
cd inpx-web
|
||||
npm i
|
||||
npm run build:client && node build/prepkg.js linux
|
||||
|
||||
# удалим файл development-среды, чтобы запускался в production-режиме
|
||||
rm ./server/config/application_env
|
||||
|
||||
# запуск inpx-web, тут же будет создан каталог .inpx-web
|
||||
node server --app-dir=.inpx-web
|
||||
```
|
||||
|
||||
<a id="development" />
|
||||
|
||||
### Разработка
|
||||
|
||||
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}`;
|
||||
|
||||
async function build() {
|
||||
if (platform != 'linux' && platform != 'win' && platform != 'macos')
|
||||
throw new Error(`Unknown platform: ${platform}`);
|
||||
if (!platform)
|
||||
throw new Error(`Please set platform`);
|
||||
|
||||
await fs.emptyDir(outDir);
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ const path = require('path');
|
||||
const { execSync } = require('child_process');
|
||||
|
||||
const pckg = require('../package.json');
|
||||
const platform = process.argv[2];
|
||||
|
||||
const distDir = path.resolve(__dirname, '../dist');
|
||||
const outDir = `${distDir}/release`;
|
||||
@@ -20,9 +21,14 @@ async function makeRelease(target) {
|
||||
async function main() {
|
||||
try {
|
||||
await fs.emptyDir(outDir);
|
||||
if (platform) {
|
||||
await makeRelease(platform);
|
||||
} else {
|
||||
await makeRelease('win');
|
||||
await makeRelease('linux');
|
||||
await makeRelease('linux-arm64');
|
||||
await makeRelease('macos');
|
||||
}
|
||||
} catch(e) {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
|
||||
@@ -2,6 +2,8 @@ const path = require('path');
|
||||
const DefinePlugin = require('webpack').DefinePlugin;
|
||||
const { VueLoaderPlugin } = require('vue-loader');
|
||||
|
||||
const appdir = require('./appdir');
|
||||
|
||||
const clientDir = path.resolve(__dirname, '../client');
|
||||
|
||||
module.exports = {
|
||||
@@ -12,7 +14,7 @@ module.exports = {
|
||||
},
|
||||
entry: [`${clientDir}/main.js`],
|
||||
output: {
|
||||
publicPath: '/app/',
|
||||
publicPath: `/${appdir}/`,
|
||||
clean: true
|
||||
},
|
||||
|
||||
|
||||
@@ -16,9 +16,8 @@ module.exports = merge(baseWpConfig, {
|
||||
mode: 'development',
|
||||
devtool: 'inline-source-map',
|
||||
output: {
|
||||
path: `${publicDir}/app`,
|
||||
path: `${publicDir}${baseWpConfig.output.publicPath}`,
|
||||
filename: 'bundle.js',
|
||||
clean: true
|
||||
},
|
||||
|
||||
module: {
|
||||
|
||||
@@ -18,9 +18,8 @@ fs.emptyDirSync(publicDir);
|
||||
module.exports = merge(baseWpConfig, {
|
||||
mode: 'production',
|
||||
output: {
|
||||
path: `${publicDir}/app`,
|
||||
path: `${publicDir}${baseWpConfig.output.publicPath}`,
|
||||
filename: 'bundle.[contenthash].js',
|
||||
clean: true
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
|
||||
@@ -60,10 +60,21 @@ const componentOptions = {
|
||||
settings() {
|
||||
this.loadSettings();
|
||||
},
|
||||
modelValue(newValue) {
|
||||
this.accessGranted = newValue;
|
||||
},
|
||||
accessGranted(newValue) {
|
||||
this.$emit('update:modelValue', newValue);
|
||||
}
|
||||
},
|
||||
};
|
||||
class Api {
|
||||
_options = componentOptions;
|
||||
_props = {
|
||||
modelValue: Boolean,
|
||||
};
|
||||
accessGranted = false;
|
||||
|
||||
busyDialogVisible = false;
|
||||
mainMessage = '';
|
||||
jobMessage = '';
|
||||
@@ -98,10 +109,6 @@ class Api {
|
||||
}
|
||||
}
|
||||
|
||||
get config() {
|
||||
return this.$store.state.config;
|
||||
}
|
||||
|
||||
get settings() {
|
||||
return this.$store.state.settings;
|
||||
}
|
||||
@@ -123,7 +130,13 @@ class Api {
|
||||
});
|
||||
|
||||
if (result && result.value) {
|
||||
const accessToken = utils.toHex(cryptoUtils.sha256(result.value));
|
||||
//получим свежую соль
|
||||
const response = await wsc.message(await wsc.send({}), 10);
|
||||
let salt = '';
|
||||
if (response && response.error == 'need_access_token' && response.salt)
|
||||
salt = response.salt;
|
||||
|
||||
const accessToken = utils.toHex(cryptoUtils.sha256(result.value + salt));
|
||||
this.commit('setSettings', {accessToken});
|
||||
}
|
||||
} finally {
|
||||
@@ -192,10 +205,13 @@ class Api {
|
||||
const response = await wsc.message(await wsc.send(params), timeoutSecs);
|
||||
|
||||
if (response && response.error == 'need_access_token') {
|
||||
this.accessGranted = false;
|
||||
await this.showPasswordDialog();
|
||||
} else if (response && response.error == 'server_busy') {
|
||||
this.accessGranted = true;
|
||||
await this.showBusyDialog();
|
||||
} else {
|
||||
this.accessGranted = true;
|
||||
if (response.error) {
|
||||
throw new Error(response.error);
|
||||
}
|
||||
@@ -219,10 +235,18 @@ class Api {
|
||||
return await this.request({action: 'search', from, query}, 30);
|
||||
}
|
||||
|
||||
async bookSearch(query) {
|
||||
return await this.request({action: 'bookSearch', query}, 30);
|
||||
}
|
||||
|
||||
async getAuthorBookList(authorId) {
|
||||
return await this.request({action: 'get-author-book-list', authorId});
|
||||
}
|
||||
|
||||
async getAuthorSeriesList(authorId) {
|
||||
return await this.request({action: 'get-author-series-list', authorId});
|
||||
}
|
||||
|
||||
async getSeriesBookList(series) {
|
||||
return await this.request({action: 'get-series-book-list', series});
|
||||
}
|
||||
@@ -242,6 +266,12 @@ class Api {
|
||||
async getConfig() {
|
||||
return await this.request({action: 'get-config'});
|
||||
}
|
||||
|
||||
async logout() {
|
||||
await this.request({action: 'logout'});
|
||||
this.accessGranted = false;
|
||||
await this.request({action: 'test'});
|
||||
}
|
||||
}
|
||||
|
||||
export default vueComponent(Api);
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
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);
|
||||
@@ -1,10 +1,10 @@
|
||||
<template>
|
||||
<div class="fit row">
|
||||
<Api ref="api" />
|
||||
<Api ref="api" v-model="accessGranted" />
|
||||
<Notify ref="notify" />
|
||||
<StdDialog ref="stdDialog" />
|
||||
|
||||
<router-view v-slot="{ Component }">
|
||||
<router-view v-if="accessGranted" v-slot="{ Component }">
|
||||
<keep-alive>
|
||||
<component :is="Component" class="col" />
|
||||
</keep-alive>
|
||||
@@ -37,6 +37,7 @@ const componentOptions = {
|
||||
};
|
||||
class App {
|
||||
_options = componentOptions;
|
||||
accessGranted = false;
|
||||
|
||||
created() {
|
||||
this.commit = this.$store.commit;
|
||||
|
||||
@@ -54,6 +54,10 @@
|
||||
<div class="clickable2 q-ml-xs q-py-sm text-bold" @click="selectSeries(book.series)">
|
||||
Серия: {{ book.series }}
|
||||
</div>
|
||||
|
||||
<div class="q-ml-sm text-bold" style="color: #555">
|
||||
{{ getSeriesBookCount(item, book) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="isExpandedSeries(book) && book.seriesBooks">
|
||||
@@ -122,9 +126,9 @@
|
||||
</div>
|
||||
<!-- Формирование списка конец ------------------------------------------------------------------>
|
||||
|
||||
<div v-if="!refreshing && !tableData.length" class="row items-center q-ml-md" style="font-size: 120%">
|
||||
<div v-if="!refreshing && (!tableData.length || error)" class="row items-center q-ml-md" style="font-size: 120%">
|
||||
<q-icon class="la la-meh q-mr-xs" size="28px" />
|
||||
Поиск не дал результатов
|
||||
{{ (error ? error : 'Поиск не дал результатов') }}
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -184,6 +188,26 @@ class AuthorList extends BaseList {
|
||||
return `(${result})`;
|
||||
}
|
||||
|
||||
getSeriesBookCount(item, book) {
|
||||
let result = '';
|
||||
if (!this.showCounts || book.type != 'series')
|
||||
return result;
|
||||
|
||||
let count = book.seriesBooks.length;
|
||||
result = `${count}`;
|
||||
if (item.seriesLoaded) {
|
||||
const rec = item.seriesLoaded[book.series];
|
||||
// заплатка для исправления https://github.com/bookpauk/inpx-web/issues/10
|
||||
// по невыясненным причинам rec иногда равен undefined
|
||||
if (rec) {
|
||||
const totalCount = (this.showDeleted ? rec.bookCount + rec.bookDelCount : rec.bookCount);
|
||||
result += `/${totalCount}`;
|
||||
}
|
||||
}
|
||||
|
||||
return `(${result})`;
|
||||
}
|
||||
|
||||
async expandAuthor(item) {
|
||||
this.$emit('listEvent', {action: 'ignoreScroll'});
|
||||
|
||||
@@ -209,6 +233,19 @@ class AuthorList extends BaseList {
|
||||
}
|
||||
}
|
||||
|
||||
async getAuthorSeries(item) {
|
||||
if (item.seriesLoaded)
|
||||
return;
|
||||
|
||||
const series = await this.loadAuthorSeries(item.key);
|
||||
const loaded = {};
|
||||
for (const s of series) {
|
||||
loaded[s.series] = {bookCount: s.bookCount, bookDelCount: s.bookDelCount};
|
||||
}
|
||||
|
||||
item.seriesLoaded = loaded;
|
||||
}
|
||||
|
||||
async getAuthorBooks(item) {
|
||||
if (item.books) {
|
||||
if (item.count > this.maxItemCount) {
|
||||
@@ -310,6 +347,7 @@ class AuthorList extends BaseList {
|
||||
}
|
||||
|
||||
item.booksLoaded = books;
|
||||
this.getAuthorSeries(item);//no await
|
||||
this.showMore(item);
|
||||
|
||||
await this.$nextTick();
|
||||
@@ -342,6 +380,7 @@ class AuthorList extends BaseList {
|
||||
name: rec.author.replace(/,/g, ', '),
|
||||
count,
|
||||
booksLoaded: false,
|
||||
seriesLoaded: false,
|
||||
books: false,
|
||||
bookLoading: false,
|
||||
showMore: false,
|
||||
@@ -399,6 +438,7 @@ class AuthorList extends BaseList {
|
||||
if (this.refreshing)
|
||||
return;
|
||||
|
||||
this.error = '';
|
||||
this.refreshing = true;
|
||||
|
||||
(async() => {
|
||||
@@ -428,7 +468,12 @@ class AuthorList extends BaseList {
|
||||
this.highlightPageScroller(query);
|
||||
}
|
||||
} catch (e) {
|
||||
this.$root.stdDialog.alert(e.message, 'Ошибка');
|
||||
this.list.queryFound = 0;
|
||||
this.list.totalFound = 0;
|
||||
this.searchResult = {found: []};
|
||||
await this.updateTableData();
|
||||
//this.$root.stdDialog.alert(e.message, 'Ошибка');
|
||||
this.error = `Ошибка: ${e.message}`;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import axios from 'axios';
|
||||
import dayjs from 'dayjs';
|
||||
import _ from 'lodash';
|
||||
|
||||
@@ -20,12 +21,15 @@ const componentOptions = {
|
||||
this.loadSettings();
|
||||
},
|
||||
search: {
|
||||
handler(newValue) {
|
||||
this.limit = newValue.limit;
|
||||
|
||||
if (this.pageCount > 1)
|
||||
this.prevPage = this.search.page;
|
||||
|
||||
handler() {
|
||||
if (!this.isExtendedSearch)
|
||||
this.refresh();
|
||||
},
|
||||
deep: true,
|
||||
},
|
||||
extSearch: {
|
||||
handler() {
|
||||
if (this.isExtendedSearch)
|
||||
this.refresh();
|
||||
},
|
||||
deep: true,
|
||||
@@ -40,9 +44,11 @@ export default class BaseList {
|
||||
_props = {
|
||||
list: Object,
|
||||
search: Object,
|
||||
extSearch: Object,
|
||||
genreMap: Object,
|
||||
};
|
||||
|
||||
error = '';
|
||||
loadingMessage = '';
|
||||
loadingMessage2 = '';
|
||||
|
||||
@@ -50,6 +56,7 @@ export default class BaseList {
|
||||
expandedAuthor = [];
|
||||
expandedSeries = [];
|
||||
|
||||
downloadAsZip = false;
|
||||
showCounts = true;
|
||||
showRates = true;
|
||||
showGenres = true;
|
||||
@@ -66,6 +73,7 @@ export default class BaseList {
|
||||
tableData = [];
|
||||
|
||||
created() {
|
||||
this.isExtendedSearch = false;
|
||||
this.commit = this.$store.commit;
|
||||
this.api = this.$root.api;
|
||||
|
||||
@@ -81,6 +89,7 @@ export default class BaseList {
|
||||
|
||||
this.expandedAuthor = _.cloneDeep(settings.expandedAuthor);
|
||||
this.expandedSeries = _.cloneDeep(settings.expandedSeries);
|
||||
this.downloadAsZip = settings.downloadAsZip;
|
||||
this.showCounts = settings.showCounts;
|
||||
this.showRates = settings.showRates;
|
||||
this.showGenres = settings.showGenres;
|
||||
@@ -105,16 +114,19 @@ export default class BaseList {
|
||||
}
|
||||
|
||||
selectAuthor(author) {
|
||||
this.search.author = `=${author}`;
|
||||
const search = (this.isExtendedSearch ? this.extSearch : this.search);
|
||||
search.author = `=${author}`;
|
||||
this.scrollToTop();
|
||||
}
|
||||
|
||||
selectSeries(series) {
|
||||
this.search.series = `=${series}`;
|
||||
const search = (this.isExtendedSearch ? this.extSearch : this.search);
|
||||
search.series = `=${series}`;
|
||||
}
|
||||
|
||||
selectTitle(title) {
|
||||
this.search.title = `=${title}`;
|
||||
const search = (this.isExtendedSearch ? this.extSearch : this.search);
|
||||
search.title = `=${title}`;
|
||||
}
|
||||
|
||||
async download(book, action) {
|
||||
@@ -133,13 +145,20 @@ export default class BaseList {
|
||||
const response = await this.api.getBookLink(book._uid);
|
||||
|
||||
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') {
|
||||
//скачивание
|
||||
const d = this.$refs.download;
|
||||
d.href = href;
|
||||
d.download = response.downFileName;
|
||||
|
||||
d.click();
|
||||
} else if (action == 'copyLink') {
|
||||
@@ -159,7 +178,18 @@ export default class BaseList {
|
||||
if (this.list.liberamaReady) {
|
||||
this.$emit('listEvent', {action: 'submitUrl', data: href});
|
||||
} else {
|
||||
const url = this.config.bookReadLink.replace('${DOWNLOAD_LINK}', href);
|
||||
const bookReadLink = this.config.bookReadLink;
|
||||
let url = bookReadLink;
|
||||
|
||||
if (bookReadLink.indexOf('${DOWNLOAD_LINK}') >= 0) {
|
||||
url = bookReadLink.replace('${DOWNLOAD_LINK}', href);
|
||||
|
||||
} else if (bookReadLink.indexOf('${DOWNLOAD_URI}') >= 0) {
|
||||
const hrefUrl = new URL(href);
|
||||
const urlWithoutHost = hrefUrl.pathname + hrefUrl.search + hrefUrl.hash;
|
||||
url = bookReadLink.replace('${DOWNLOAD_URI}', urlWithoutHost);
|
||||
}
|
||||
|
||||
window.open(url, '_blank');
|
||||
}
|
||||
} else if (action == 'bookInfo') {
|
||||
@@ -253,7 +283,30 @@ export default class BaseList {
|
||||
result = await this.api.getAuthorBookList(authorId);
|
||||
}
|
||||
|
||||
return (result.books ? JSON.parse(result.books) : []);
|
||||
return result.books;
|
||||
} catch (e) {
|
||||
this.$root.stdDialog.alert(e.message, 'Ошибка');
|
||||
}
|
||||
}
|
||||
|
||||
async loadAuthorSeries(authorId) {
|
||||
try {
|
||||
let result;
|
||||
|
||||
if (this.abCacheEnabled) {
|
||||
const key = `author-${authorId}-series-${this.list.inpxHash}`;
|
||||
const data = await authorBooksStorage.getData(key);
|
||||
if (data) {
|
||||
result = JSON.parse(data);
|
||||
} else {
|
||||
result = await this.api.getAuthorSeriesList(authorId);
|
||||
await authorBooksStorage.setData(key, JSON.stringify(result));
|
||||
}
|
||||
} else {
|
||||
result = await this.api.getAuthorSeriesList(authorId);
|
||||
}
|
||||
|
||||
return result.series;
|
||||
} catch (e) {
|
||||
this.$root.stdDialog.alert(e.message, 'Ошибка');
|
||||
}
|
||||
@@ -276,7 +329,7 @@ export default class BaseList {
|
||||
result = await this.api.getSeriesBookList(series);
|
||||
}
|
||||
|
||||
return (result.books ? JSON.parse(result.books) : []);
|
||||
return result.books;
|
||||
} catch (e) {
|
||||
this.$root.stdDialog.alert(e.message, 'Ошибка');
|
||||
}
|
||||
@@ -330,6 +383,7 @@ export default class BaseList {
|
||||
bookValue = emptyFieldValue;
|
||||
|
||||
bookValue = bookValue.toLowerCase();
|
||||
if (searchValue[0] !== '~')
|
||||
searchValue = searchValue.toLowerCase();
|
||||
|
||||
//особая обработка префиксов
|
||||
@@ -344,7 +398,14 @@ export default class BaseList {
|
||||
} else if (searchValue[0] == '#') {
|
||||
|
||||
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 {
|
||||
//where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
|
||||
return bookValue.localeCompare(searchValue) >= 0 && bookValue.localeCompare(searchValue + maxUtf8Char) <= 0;
|
||||
@@ -402,6 +463,13 @@ export default class BaseList {
|
||||
librateFound = searchLibrate.has(book.librate);
|
||||
}
|
||||
|
||||
//ext
|
||||
let extFound = !s.ext;
|
||||
if (!extFound) {
|
||||
const searchExt = new Set(s.ext.split('|'));
|
||||
extFound = searchExt.has(book.ext.toLowerCase() || emptyFieldValue);
|
||||
}
|
||||
|
||||
return (this.showDeleted || !book.del)
|
||||
&& authorFound
|
||||
&& filterBySearch(book.series, s.series)
|
||||
@@ -410,6 +478,7 @@ export default class BaseList {
|
||||
&& langFound
|
||||
&& dateFound
|
||||
&& librateFound
|
||||
&& extFound
|
||||
;
|
||||
});
|
||||
}
|
||||
@@ -483,9 +552,9 @@ export default class BaseList {
|
||||
}
|
||||
|
||||
getQuery() {
|
||||
let newQuery = _.cloneDeep(this.search);
|
||||
newQuery = newQuery.setDefaults(newQuery);
|
||||
delete newQuery.setDefaults;
|
||||
const search = (this.isExtendedSearch ? this.extSearch : this.search);
|
||||
const newQuery = {};
|
||||
search.setDefaults(newQuery, search);
|
||||
|
||||
//дата
|
||||
if (newQuery.date) {
|
||||
@@ -496,8 +565,8 @@ export default class BaseList {
|
||||
newQuery.offset = (newQuery.page - 1)*newQuery.limit;
|
||||
|
||||
//del
|
||||
if (!this.showDeleted)
|
||||
newQuery.del = 0;
|
||||
if (!newQuery.del && !this.showDeleted)
|
||||
newQuery.del = '0';
|
||||
|
||||
return newQuery;
|
||||
}
|
||||
|
||||
@@ -18,9 +18,9 @@
|
||||
|
||||
<div class="row q-mt-sm no-wrap">
|
||||
<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 = ''" />
|
||||
<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 overflow-hidden" style="border: 1px solid #ccc; font-size: 300%">
|
||||
<i>{{ book.ext }}</i>
|
||||
</div>
|
||||
</div>
|
||||
@@ -118,6 +118,7 @@ class BookInfoDialog {
|
||||
_props = {
|
||||
modelValue: Boolean,
|
||||
bookInfo: Object,
|
||||
genreMap: Object,
|
||||
};
|
||||
|
||||
dialogVisible = false;
|
||||
@@ -169,6 +170,19 @@ class BookInfoDialog {
|
||||
return `${size.toFixed(1)} ${unit}`;
|
||||
}
|
||||
|
||||
convertGenres(genreArr) {
|
||||
let result = [];
|
||||
if (genreArr) {
|
||||
for (const genre of genreArr) {
|
||||
const g = genre.trim();
|
||||
const name = this.genreMap.get(g);
|
||||
result.push(name ? name : g);
|
||||
}
|
||||
}
|
||||
|
||||
return result.join(', ');
|
||||
}
|
||||
|
||||
get inpx() {
|
||||
const mapping = [
|
||||
{name: 'fileInfo', label: 'Информация о файле', value: [
|
||||
@@ -211,6 +225,9 @@ class BookInfoDialog {
|
||||
if (nodePath == 'titleInfo/author')
|
||||
return value.split(',').join(', ');
|
||||
|
||||
if (nodePath == 'titleInfo/genre')
|
||||
return this.convertGenres(value.split(','));
|
||||
|
||||
if (nodePath == 'titleInfo/librate' && !value)
|
||||
return null;
|
||||
|
||||
@@ -279,11 +296,16 @@ class BookInfoDialog {
|
||||
}
|
||||
}
|
||||
|
||||
const self = this;
|
||||
this.fb2 = parser.bookInfoList(infoObj, {
|
||||
valueToString(value, nodePath, origVTS) {//eslint-disable-line no-unused-vars
|
||||
if (nodePath == 'documentInfo/historyHtml' && value)
|
||||
return value.replace(/<p>/g, `<p class="p-history">`);
|
||||
|
||||
if ((nodePath == 'titleInfo/genre' || nodePath == 'srcTitleInfo/genre') && value) {
|
||||
return self.convertGenres(value);
|
||||
}
|
||||
|
||||
return origVTS(value, nodePath);
|
||||
},
|
||||
});
|
||||
@@ -317,7 +339,7 @@ export default vueComponent(BookInfoDialog);
|
||||
min-width: 100px;
|
||||
}
|
||||
|
||||
.poster {
|
||||
.poster, .no-poster {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
</div>
|
||||
|
||||
<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')">
|
||||
{{ bookAuthor }}
|
||||
</div>
|
||||
@@ -46,7 +46,7 @@
|
||||
<div class="clickable2" :class="titleColor" @click.stop.prevent="emit('titleClick')">
|
||||
{{ book.title }}
|
||||
</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 }}
|
||||
</div>
|
||||
|
||||
@@ -79,10 +79,10 @@
|
||||
{{ bookDate }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-show="false">
|
||||
{{ book }}
|
||||
<div v-show="showJson && mode == 'extended'">
|
||||
<pre style="font-size: 80%; white-space: pre-wrap;">{{ book }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -117,6 +117,7 @@ class BookView {
|
||||
showGenres = true;
|
||||
showDeleted = false;
|
||||
showDates = false;
|
||||
showJson = false;
|
||||
|
||||
created() {
|
||||
this.loadSettings();
|
||||
@@ -130,6 +131,7 @@ class BookView {
|
||||
this.showGenres = settings.showGenres;
|
||||
this.showDates = settings.showDates;
|
||||
this.showDeleted = settings.showDeleted;
|
||||
this.showJson = settings.showJson;
|
||||
}
|
||||
|
||||
get settings() {
|
||||
|
||||
134
client/components/Search/ExtendedList/ExtendedList.vue
Normal file
134
client/components/Search/ExtendedList/ExtendedList.vue
Normal file
@@ -0,0 +1,134 @@
|
||||
<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 || error)" class="row items-center q-ml-md" style="font-size: 120%">
|
||||
<q-icon class="la la-meh q-mr-xs" size="28px" />
|
||||
{{ (error ? error : 'Поиск не дал результатов') }}
|
||||
</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.error = '';
|
||||
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.list.queryFound = 0;
|
||||
this.list.totalFound = 0;
|
||||
this.searchResult = {found: []};
|
||||
await this.updateTableData();
|
||||
//this.$root.stdDialog.alert(e.message, 'Ошибка');
|
||||
this.error = `Ошибка: ${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,8 +1,27 @@
|
||||
<template>
|
||||
<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="toolPanel" class="tool-panel q-pb-xs column bg-cyan-2" style="position: sticky; top: 0; z-index: 10;">
|
||||
<div class="header q-mx-md q-mb-xs q-mt-sm row items-center">
|
||||
<!-- Tool Panel begin -->
|
||||
<div ref="toolPanel" class="tool-panel column bg-cyan-2" style="position: sticky; top: 0; z-index: 10;">
|
||||
<!-- Обновление -->
|
||||
<div v-show="showNewReleaseAvailable && newReleaseAvailable" class="row q-py-sm bg-green-4 items-center">
|
||||
<div class="q-ml-sm" style="font-size: 120%">
|
||||
Доступна новая версия <b>{{ config.name }} v{{ config.latestVersion }}</b>
|
||||
</div>
|
||||
<DivBtn class="q-ml-sm q-px-sm bg-white" :size="20" @click.stop.prevent="openReleasePage">
|
||||
Скачать
|
||||
</DivBtn>
|
||||
<DivBtn class="q-ml-sm q-px-sm bg-white" :size="20" @click.stop.prevent="settingsDialogVisible = true">
|
||||
Отключить уведомление
|
||||
</DivBtn>
|
||||
</div>
|
||||
|
||||
<!-- 1 -->
|
||||
<div class="row">
|
||||
<!-- 1-1 -->
|
||||
<div class="column col">
|
||||
<div class="header q-mb-xs q-ml-sm q-mt-sm row items-center">
|
||||
<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">
|
||||
@@ -19,6 +38,7 @@
|
||||
no-caps
|
||||
rounded
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="row items-center q-ml-sm" style="font-size: 150%;">
|
||||
<div class="q-mr-xs">
|
||||
@@ -27,42 +47,20 @@
|
||||
<div class="clickable" @click.stop.prevent="showCollectionInfo">
|
||||
{{ collection }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col"></div>
|
||||
|
||||
<DivBtn class="q-ml-md text-white bg-secondary" :size="30" :icon-size="24" icon="la la-question" round @click.stop.prevent="showSearchHelp">
|
||||
<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>
|
||||
|
||||
<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 #tooltip>
|
||||
<q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||
Настройки
|
||||
</q-tooltip>
|
||||
</template>
|
||||
</DivBtn>
|
||||
</div>
|
||||
<div class="row q-mx-md q-mb-xs items-center">
|
||||
<DivBtn
|
||||
class="text-grey-5 bg-yellow-1 q-mt-xs" :size="34" :icon-size="24" round
|
||||
:icon="(extendedParams ? 'la la-angle-double-up' : 'la la-angle-double-down')"
|
||||
@click.stop.prevent="extendedParams = !extendedParams"
|
||||
>
|
||||
<template #tooltip>
|
||||
<q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||
{{ `${(extendedParams ? 'Скрыть' : 'Показать')} дополнительные критерии поиска` }}
|
||||
</q-tooltip>
|
||||
</template>
|
||||
</DivBtn>
|
||||
<div class="q-mx-xs" />
|
||||
</div>
|
||||
<div v-show="!isExtendedSearch" class="row q-mx-sm q-mb-xs items-center" style="max-width: 1024px">
|
||||
<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
|
||||
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 }}
|
||||
@@ -71,7 +69,7 @@
|
||||
<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
|
||||
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 }}
|
||||
@@ -80,7 +78,7 @@
|
||||
<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
|
||||
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 }}
|
||||
@@ -89,7 +87,7 @@
|
||||
<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
|
||||
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>
|
||||
@@ -102,7 +100,7 @@
|
||||
</q-input>
|
||||
<div class="q-mx-xs" />
|
||||
<DivBtn
|
||||
class="text-grey-8 bg-yellow-1 q-mt-xs" :size="34" :icon-size="24" round
|
||||
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"
|
||||
>
|
||||
@@ -113,12 +111,10 @@
|
||||
</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" />
|
||||
<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" :bg-color="inputBgColor()" input-style="cursor: pointer" style="width: 200px;" label="Жанр" stack-label outlined dense clearable readonly
|
||||
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>
|
||||
@@ -133,11 +129,11 @@
|
||||
<div class="q-mx-xs" />
|
||||
<q-select
|
||||
v-model="searchDate"
|
||||
class="q-mt-xs"
|
||||
class="q-mt-xs col-3"
|
||||
:options="searchDateOptions"
|
||||
dropdown-icon="la la-angle-down la-sm"
|
||||
:bg-color="inputBgColor()"
|
||||
style="width: 200px;"
|
||||
style="min-width: 140px;"
|
||||
label="Дата поступления" stack-label
|
||||
outlined dense emit-value map-options clearable
|
||||
>
|
||||
@@ -164,7 +160,7 @@
|
||||
<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
|
||||
class="q-mt-xs col-2" :bg-color="inputBgColor()" input-style="cursor: pointer" style="min-width: 140px;" label="Оценка" stack-label outlined dense clearable readonly
|
||||
@click.stop.prevent="selectLibRate"
|
||||
>
|
||||
<template v-if="librateNames" #append>
|
||||
@@ -175,26 +171,161 @@
|
||||
{{ librateNames }}
|
||||
</q-tooltip>
|
||||
</q-input>
|
||||
|
||||
<div class="q-mx-xs" />
|
||||
<q-input
|
||||
v-model="search.ext" :maxlength="inputMaxLength" :debounce="inputDebounce"
|
||||
class="q-mt-xs col-2" :bg-color="inputBgColor()" input-style="cursor: pointer" style="min-width: 140px;" label="Тип файла" stack-label outlined dense clearable readonly
|
||||
@click.stop.prevent="selectExt"
|
||||
>
|
||||
<template v-if="search.ext" #append>
|
||||
<q-icon name="la la-times-circle" class="q-field__focusable-action" @click.stop.prevent="search.ext = ''" />
|
||||
</template>
|
||||
|
||||
<q-tooltip v-if="search.ext && showTooltips" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||
{{ search.ext }}
|
||||
</q-tooltip>
|
||||
</q-input>
|
||||
</div>
|
||||
<div v-show="!extendedParams && extendedParamsMessage" class="row q-mx-md items-center clickable" @click.stop.prevent="extendedParams = true">
|
||||
<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
|
||||
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')"
|
||||
no-shadow
|
||||
@click.stop.prevent="extendedParams = !extendedParams"
|
||||
>
|
||||
<template #tooltip>
|
||||
<q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
|
||||
{{ `${(extendedParams ? 'Скрыть' : 'Показать')} дополнительные критерии поиска` }}
|
||||
</q-tooltip>
|
||||
</template>
|
||||
</DivBtn>
|
||||
</div><!-- 2 -->
|
||||
</div>
|
||||
<!-- Tool Panel end -->
|
||||
|
||||
<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" />
|
||||
</div>
|
||||
|
||||
<div v-show="list.totalFound > 0" class="text-bold" style="font-size: 120%; padding-bottom: 2px">
|
||||
{{ foundCountMessage }}
|
||||
</div>
|
||||
|
||||
<div v-show="list.totalFound > 0 && isExtendedSearch" class="q-ml-md">
|
||||
<q-checkbox v-model="showJson" size="36px" label="Показывать JSON" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Формирование списка ------------------------------------------------------------------------>
|
||||
<div v-if="selectedListComponent">
|
||||
<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>
|
||||
<!-- Формирование списка конец ------------------------------------------------------------------>
|
||||
@@ -215,7 +346,9 @@
|
||||
<SelectLangDialog v-model="selectLangDialogVisible" v-model:lang="search.lang" :lang-list="langList" :lang-default="langDefault" />
|
||||
<SelectLibRateDialog v-model="selectLibRateDialogVisible" v-model:librate="search.librate" />
|
||||
<SelectDateDialog v-model="selectDateDialogVisible" v-model:date="search.date" />
|
||||
<BookInfoDialog v-model="bookInfoDialogVisible" :book-info="bookInfo" />
|
||||
<SelectExtDialog v-model="selectExtDialogVisible" v-model:ext="search.ext" :ext-list="extList" />
|
||||
<BookInfoDialog v-model="bookInfoDialogVisible" :book-info="bookInfo" :genre-map="genreMap" />
|
||||
<SelectExtSearchDialog v-model="selectExtSearchDialogVisible" v-model:ext-search="extSearch" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -226,6 +359,7 @@ import vueComponent from '../vueComponent.js';
|
||||
import AuthorList from './AuthorList/AuthorList.vue';
|
||||
import SeriesList from './SeriesList/SeriesList.vue';
|
||||
import TitleList from './TitleList/TitleList.vue';
|
||||
import ExtendedList from './ExtendedList/ExtendedList.vue';
|
||||
|
||||
import PageScroller from './PageScroller/PageScroller.vue';
|
||||
import SettingsDialog from './SettingsDialog/SettingsDialog.vue';
|
||||
@@ -233,7 +367,9 @@ import SelectGenreDialog from './SelectGenreDialog/SelectGenreDialog.vue';
|
||||
import SelectLangDialog from './SelectLangDialog/SelectLangDialog.vue';
|
||||
import SelectLibRateDialog from './SelectLibRateDialog/SelectLibRateDialog.vue';
|
||||
import SelectDateDialog from './SelectDateDialog/SelectDateDialog.vue';
|
||||
import SelectExtDialog from './SelectExtDialog/SelectExtDialog.vue';
|
||||
import BookInfoDialog from './BookInfoDialog/BookInfoDialog.vue';
|
||||
import SelectExtSearchDialog from './SelectExtSearchDialog/SelectExtSearchDialog.vue';
|
||||
|
||||
import authorBooksStorage from './authorBooksStorage';
|
||||
import DivBtn from '../share/DivBtn.vue';
|
||||
@@ -244,10 +380,13 @@ import diffUtils from '../../share/diffUtils';
|
||||
|
||||
import _ from 'lodash';
|
||||
|
||||
const maxLimit = 1000;
|
||||
|
||||
const route2component = {
|
||||
'author': {component: 'AuthorList', label: 'Авторы'},
|
||||
'series': {component: 'SeriesList', label: 'Серии'},
|
||||
'title': {component: 'TitleList', label: 'Книги'},
|
||||
'extended': {component: 'ExtendedList', label: 'Расширенный поиск'},
|
||||
};
|
||||
|
||||
const componentOptions = {
|
||||
@@ -255,13 +394,16 @@ const componentOptions = {
|
||||
AuthorList,
|
||||
SeriesList,
|
||||
TitleList,
|
||||
ExtendedList,
|
||||
PageScroller,
|
||||
SettingsDialog,
|
||||
SelectGenreDialog,
|
||||
SelectLangDialog,
|
||||
SelectLibRateDialog,
|
||||
SelectDateDialog,
|
||||
SelectExtDialog,
|
||||
BookInfoDialog,
|
||||
SelectExtSearchDialog,
|
||||
Dialog,
|
||||
DivBtn
|
||||
},
|
||||
@@ -284,6 +426,19 @@ const componentOptions = {
|
||||
this.makeTitle();
|
||||
this.updateRouteQueryFromSearch();
|
||||
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,
|
||||
},
|
||||
@@ -302,6 +457,9 @@ const componentOptions = {
|
||||
langDefault() {
|
||||
this.updateSearchFromRouteQuery(this.$route);
|
||||
},
|
||||
showJson(newValue) {
|
||||
this.setSetting('showJson', newValue);
|
||||
},
|
||||
list: {
|
||||
handler(newValue) {
|
||||
this.updateGenreTreeIfNeeded();
|
||||
@@ -329,6 +487,8 @@ const componentOptions = {
|
||||
if (this.getListRoute() != newValue) {
|
||||
this.updateRouteQueryFromSearch();
|
||||
}
|
||||
|
||||
this.makeTitle();
|
||||
},
|
||||
searchDate() {
|
||||
this.updateSearchDate(false);
|
||||
@@ -353,7 +513,9 @@ class Search {
|
||||
selectLangDialogVisible = false;
|
||||
selectLibRateDialogVisible = false;
|
||||
selectDateDialogVisible = false;
|
||||
selectExtDialogVisible = false;
|
||||
bookInfoDialogVisible = false;
|
||||
selectExtSearchDialogVisible = false;
|
||||
|
||||
pageCount = 1;
|
||||
|
||||
@@ -362,21 +524,8 @@ class Search {
|
||||
inputDebounce = 200;
|
||||
|
||||
//search fields
|
||||
search = {
|
||||
setDefaults(search) {
|
||||
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,
|
||||
});
|
||||
},
|
||||
};
|
||||
search = {};
|
||||
extSearch = {};
|
||||
|
||||
searchDate = '';
|
||||
prevManualDate = '';
|
||||
@@ -386,6 +535,8 @@ class Search {
|
||||
langDefault = '';
|
||||
limit = 20;
|
||||
extendedParams = false;
|
||||
showJson = false;
|
||||
showNewReleaseAvailable = true;
|
||||
|
||||
//stuff
|
||||
prevList = {};
|
||||
@@ -399,6 +550,7 @@ class Search {
|
||||
genreTree = [];
|
||||
genreMap = new Map();
|
||||
langList = [];
|
||||
extList = [];
|
||||
genreTreeInpxHash = '';
|
||||
showTooltips = true;
|
||||
|
||||
@@ -415,18 +567,42 @@ class Search {
|
||||
{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() {
|
||||
this.commit = this.$store.commit;
|
||||
this.api = this.$root.api;
|
||||
|
||||
this.search = this.search.setDefaults(this.search);
|
||||
this.search.lang = this.langDefault;
|
||||
this.generateDefaults(this.search, ['author', 'series', 'title', 'genre', 'lang', 'date', 'librate', 'ext']);
|
||||
this.search.setDefaults(this.search);
|
||||
|
||||
this.loadSettings();
|
||||
}
|
||||
|
||||
mounted() {
|
||||
(async() => {
|
||||
//для срабатывания watch.config
|
||||
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
|
||||
window.addEventListener('message', (event) => {
|
||||
if (!_.isObject(event.data) || event.data.from != 'ExternalLibs')
|
||||
@@ -444,11 +620,11 @@ class Search {
|
||||
this.$refs.authorInput.focus();
|
||||
|
||||
this.updateListFromRoute(this.$route);
|
||||
this.updateSearchFromRouteQuery(this.$route);
|
||||
|
||||
this.sendMessage({type: 'mes', data: 'hello-from-inpx-web'});
|
||||
|
||||
this.ready = true;
|
||||
|
||||
this.sendMessage({type: 'mes', data: 'hello-from-inpx-web'});
|
||||
this.updateSearchFromRouteQuery(this.$route);
|
||||
})();
|
||||
}
|
||||
|
||||
@@ -462,6 +638,8 @@ class Search {
|
||||
this.expandedSeries = _.cloneDeep(settings.expandedSeries);
|
||||
this.abCacheEnabled = settings.abCacheEnabled;
|
||||
this.langDefault = settings.langDefault;
|
||||
this.showJson = settings.showJson;
|
||||
this.showNewReleaseAvailable = settings.showNewReleaseAvailable;
|
||||
}
|
||||
|
||||
recvMessage(d) {
|
||||
@@ -471,6 +649,7 @@ class Search {
|
||||
this.list.liberamaReady = true;
|
||||
this.sendMessage({type: 'mes', data: 'ready'});
|
||||
this.sendCurrentUrl();
|
||||
this.makeTitle();
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -488,6 +667,17 @@ class Search {
|
||||
return this.$store.state.config;
|
||||
}
|
||||
|
||||
get newReleaseAvailable() {
|
||||
return (this.config.latestVersion && this.config.version != this.config.latestVersion);
|
||||
}
|
||||
|
||||
get recStruct() {
|
||||
if (this.config.dbConfig && this.config.dbConfig.inpxInfo.recStruct)
|
||||
return this.config.dbConfig.inpxInfo.recStruct;
|
||||
else
|
||||
return [];
|
||||
}
|
||||
|
||||
get settings() {
|
||||
return this.$store.state.settings;
|
||||
}
|
||||
@@ -519,7 +709,13 @@ class Search {
|
||||
get listOptions() {
|
||||
const result = [];
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -529,10 +725,24 @@ class Search {
|
||||
result.push(s.genre ? 'Жанр' : '');
|
||||
result.push(s.date ? 'Дата поступления' : '');
|
||||
result.push(s.librate ? 'Оценка' : '');
|
||||
result.push(s.ext ? 'Тип файла' : '');
|
||||
|
||||
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) {
|
||||
if (inp === this.selectedList)
|
||||
return 'white';
|
||||
@@ -542,8 +752,12 @@ class Search {
|
||||
|
||||
async updateListFromRoute(to) {
|
||||
const newPath = to.path;
|
||||
|
||||
let newList = this.getListRoute(newPath);
|
||||
if (newList == 'extended' && !this.config.extendedSearch)
|
||||
newList = '';
|
||||
newList = (newList ? newList : 'author');
|
||||
|
||||
if (this.selectedList != newList)
|
||||
this.selectedList = newList;
|
||||
}
|
||||
@@ -555,14 +769,19 @@ class Search {
|
||||
}
|
||||
|
||||
openReleasePage() {
|
||||
window.open('https://github.com/bookpauk/inpx-web/releases', '_blank');
|
||||
if (this.config.latestReleaseLink)
|
||||
window.open(this.config.latestReleaseLink, '_blank');
|
||||
}
|
||||
|
||||
makeProjectName() {
|
||||
const collection = this.config.dbConfig.inpxInfo.collection.split('\n');
|
||||
this.collection = collection[0].trim();
|
||||
|
||||
this.projectName = `${this.config.name} v${this.config.webAppVersion}`;
|
||||
let projectName = `${this.config.name} v${this.config.webAppVersion}`;
|
||||
if (this.newReleaseAvailable)
|
||||
projectName += `, доступно обновление: v${this.config.latestVersion}`;
|
||||
|
||||
this.projectName = projectName;
|
||||
this.makeTitle();
|
||||
}
|
||||
|
||||
@@ -572,6 +791,7 @@ class Search {
|
||||
|
||||
let result = `Коллекция ${this.collection}`;
|
||||
|
||||
if (!this.isExtendedSearch) {
|
||||
const search = this.search;
|
||||
const specSym = new Set(['*', '#']);
|
||||
const correctValue = (v) => {
|
||||
@@ -597,6 +817,10 @@ class Search {
|
||||
result = [s, t].filter(v => v).join(' ');
|
||||
result = [a, result].filter(v => v).join(' ');
|
||||
}
|
||||
} else {
|
||||
if (this.extSearchNames)
|
||||
result = this.extSearchNames;
|
||||
}
|
||||
|
||||
this.$root.setAppTitle(result);
|
||||
if (this.list.liberamaReady)
|
||||
@@ -604,8 +828,7 @@ class Search {
|
||||
}
|
||||
|
||||
showSearchHelp() {
|
||||
let info = '';
|
||||
info += `<div style="min-width: 250px" />`;
|
||||
let info = `<div style="min-width: 250px" />`;
|
||||
info += `
|
||||
<p>
|
||||
Для раздела <b>Авторы</b>, работу поискового движка можно описать простой фразой: найти авторов по указанным критериям.
|
||||
@@ -633,6 +856,11 @@ class Search {
|
||||
Указание простого "#" в поиске по названию означает: найти всех авторов, названия книг которых начинаются не с русской или латинской буквы
|
||||
</li>
|
||||
<br>
|
||||
<li>
|
||||
"~" поиск по регулярному выражению. Например, для "~^\\s" в поле названия, будут найдены
|
||||
все книги, названия которых начинаются с пробельного символа
|
||||
</li>
|
||||
<br>
|
||||
<li>
|
||||
"?" поиск пустых значений или тех, что начинаются с этого символа. Например, "?" в поле серии означает: найти всех авторов, у которых есть книги без серий
|
||||
или название серии начинается с "?".
|
||||
@@ -703,6 +931,10 @@ class Search {
|
||||
<b>collection.info:</b>
|
||||
<pre>${inpxInfo.collection}</pre>
|
||||
</div>
|
||||
<div><hr/>
|
||||
<b>version.info:</b>
|
||||
<pre>${inpxInfo.version}</pre>
|
||||
</div>
|
||||
`;
|
||||
|
||||
this.$root.stdDialog.alert(info, 'Статистика по коллекции', {iconName: 'la la-info-circle'});
|
||||
@@ -734,8 +966,24 @@ class Search {
|
||||
this.selectLibRateDialogVisible = true;
|
||||
}
|
||||
|
||||
selectExt() {
|
||||
this.hideTooltip();
|
||||
this.selectExtDialogVisible = true;
|
||||
}
|
||||
|
||||
selectExtSearch() {
|
||||
this.hideTooltip();
|
||||
this.selectExtSearchDialogVisible = true;
|
||||
}
|
||||
|
||||
clearExtSearch() {
|
||||
const self = this.extSearch;
|
||||
self.setDefaults(self, {page: self.page, limit: self.limit});
|
||||
}
|
||||
|
||||
onScroll() {
|
||||
const curScrollTop = this.$refs.scroller.scrollTop;
|
||||
const toolPanelOffset = this.$refs.toolPanel.getBoundingClientRect().top;
|
||||
|
||||
if (this.ignoreScrolling) {
|
||||
this.lastScrollTop = curScrollTop;
|
||||
@@ -744,21 +992,27 @@ class Search {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.lastScrollTop === curScrollTop)
|
||||
return; //если событие вызвано более 1 раза на 1 скролл
|
||||
|
||||
if (!this.lastScrollTop)
|
||||
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';
|
||||
if (this.lastScrollTop2 <= curScrollTop - this.$refs.toolPanel.clientHeight)
|
||||
this.lastScrollTop2 = 0;
|
||||
(async() => {//"отложенная" коректировка, из-за артефактов в firefox
|
||||
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 {
|
||||
} else if (toolPanelOffset >= 0) {
|
||||
this.$refs.toolPanel.style.top = '0px';
|
||||
this.$refs.toolPanel.style.position = 'sticky';
|
||||
this.$refs.toolPanel.style.top = 0;
|
||||
this.lastScrollTop2 = curScrollTop;
|
||||
}
|
||||
|
||||
this.lastScrollTop = curScrollTop;
|
||||
@@ -768,14 +1022,14 @@ class Search {
|
||||
this.ignoreScrolling = true;
|
||||
await utils.sleep(ms);
|
||||
await this.$nextTick();
|
||||
await this.$nextTick();
|
||||
await this.$nextTick();
|
||||
this.ignoreScrolling = false;
|
||||
}
|
||||
|
||||
scrollToTop() {
|
||||
this.$refs.scroller.scrollTop = 0;
|
||||
this.lastScrollTop = 0;
|
||||
this.$refs.toolPanel.style.top = '0px';
|
||||
this.$refs.toolPanel.style.position = 'sticky';
|
||||
}
|
||||
|
||||
updatePageCount() {
|
||||
@@ -837,6 +1091,8 @@ class Search {
|
||||
}
|
||||
|
||||
updateSearchFromRouteQuery(to) {
|
||||
if (!this.ready)
|
||||
return;
|
||||
if (this.list.liberamaReady)
|
||||
this.sendCurrentUrl();
|
||||
|
||||
@@ -845,8 +1101,7 @@ class Search {
|
||||
|
||||
const query = to.query;
|
||||
|
||||
this.search = this.search.setDefaults(
|
||||
Object.assign({}, this.search, {
|
||||
this.search.setDefaults(this.search, {
|
||||
author: query.author,
|
||||
series: query.series,
|
||||
title: query.title,
|
||||
@@ -854,13 +1109,27 @@ class Search {
|
||||
lang: (typeof(query.lang) == 'string' ? query.lang : this.langDefault),
|
||||
date: query.date,
|
||||
librate: query.librate,
|
||||
ext: query.ext,
|
||||
|
||||
page: parseInt(query.page, 10),
|
||||
limit: parseInt(query.limit, 10) || this.search.limit,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
if (this.search.limit > 1000)
|
||||
this.search.limit = 1000;
|
||||
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() {
|
||||
@@ -870,11 +1139,12 @@ class Search {
|
||||
this.routeUpdating = true;
|
||||
try {
|
||||
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) {
|
||||
delete query.lang;
|
||||
@@ -882,6 +1152,12 @@ class Search {
|
||||
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);
|
||||
if (!diffUtils.isEmptyObjDiff(diff)) {
|
||||
this.$router.replace({path: this.selectedList, query});
|
||||
@@ -925,6 +1201,7 @@ class Search {
|
||||
}
|
||||
|
||||
this.langList = result.langList;
|
||||
this.extList = result.extList;
|
||||
this.genreTreeInpxHash = result.inpxHash;
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -979,6 +1256,16 @@ class Search {
|
||||
cloneSearch() {
|
||||
window.open(window.location.href, '_blank');
|
||||
}
|
||||
|
||||
extToList(list) {
|
||||
if (this.extSearch[list])
|
||||
this.search[list] = this.extSearch[list];
|
||||
this.selectedList = list;
|
||||
}
|
||||
|
||||
async logout() {
|
||||
await this.api.logout();
|
||||
}
|
||||
}
|
||||
|
||||
export default vueComponent(Search);
|
||||
|
||||
187
client/components/Search/SelectExtDialog/SelectExtDialog.vue
Normal file
187
client/components/Search/SelectExtDialog/SelectExtDialog.vue
Normal file
@@ -0,0 +1,187 @@
|
||||
<template>
|
||||
<Dialog ref="dialog" v-model="dialogVisible">
|
||||
<template #header>
|
||||
<div class="row items-center">
|
||||
<div style="font-size: 110%">
|
||||
Выбрать типы файлов
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div ref="box" class="column q-mt-xs overflow-auto no-wrap" style="width: 370px; padding: 0px 10px 10px 10px;">
|
||||
<div v-show="extList.length" class="checkbox-tick-all">
|
||||
<div class="row items-center">
|
||||
<q-option-group
|
||||
v-model="ticked"
|
||||
:options="optionsPre"
|
||||
type="checkbox"
|
||||
inline
|
||||
>
|
||||
<template #label="opt">
|
||||
<div class="row items-center" style="width: 35px">
|
||||
<span>{{ opt.label }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</q-option-group>
|
||||
</div>
|
||||
|
||||
<q-checkbox v-model="tickAll" label="Выбрать/снять все" toggle-order="ft" @update:model-value="makeTickAll" />
|
||||
</div>
|
||||
|
||||
<q-option-group
|
||||
v-model="ticked"
|
||||
:options="options"
|
||||
type="checkbox"
|
||||
>
|
||||
</q-option-group>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<q-btn class="q-px-md q-ml-sm" color="primary" dense no-caps @click="okClick">
|
||||
OK
|
||||
</q-btn>
|
||||
</template>
|
||||
</Dialog>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
//-----------------------------------------------------------------------------
|
||||
import vueComponent from '../../vueComponent.js';
|
||||
|
||||
import Dialog from '../../share/Dialog.vue';
|
||||
|
||||
const componentOptions = {
|
||||
components: {
|
||||
Dialog
|
||||
},
|
||||
watch: {
|
||||
modelValue(newValue) {
|
||||
this.dialogVisible = newValue;
|
||||
if (newValue)
|
||||
this.init();//no await
|
||||
},
|
||||
dialogVisible(newValue) {
|
||||
this.$emit('update:modelValue', newValue);
|
||||
},
|
||||
ext() {
|
||||
this.updateTicked();
|
||||
},
|
||||
ticked() {
|
||||
this.checkAllTicked();
|
||||
this.updateExt();
|
||||
},
|
||||
}
|
||||
};
|
||||
class SelectExtDialog {
|
||||
_options = componentOptions;
|
||||
_props = {
|
||||
modelValue: Boolean,
|
||||
ext: {type: String, value: ''},
|
||||
extList: Array,
|
||||
};
|
||||
|
||||
dialogVisible = false;
|
||||
|
||||
ticked = [];
|
||||
tickAll = false;
|
||||
|
||||
created() {
|
||||
this.commit = this.$store.commit;
|
||||
}
|
||||
|
||||
mounted() {
|
||||
this.updateTicked();
|
||||
}
|
||||
|
||||
async init() {
|
||||
//await this.$refs.dialog.waitShown();
|
||||
}
|
||||
|
||||
get options() {
|
||||
const result = [];
|
||||
|
||||
for (const ext of this.extList) {
|
||||
if (ext.length <= 4)
|
||||
result.push({label: ext, value: ext});
|
||||
}
|
||||
|
||||
for (const ext of this.extList) {
|
||||
if (ext.length > 4)
|
||||
result.push({label: ext, value: ext});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
get optionsPre() {
|
||||
const result = [];
|
||||
|
||||
for (const ext of ['fb2', 'epub', 'mobi', 'pdf', 'djvu', 'doc', 'docx', 'rtf', 'xml', 'html', 'txt', 'zip']) {
|
||||
if (this.extList.includes(ext)) {
|
||||
result.push({label: ext, value: ext});
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
makeTickAll() {
|
||||
if (this.tickAll) {
|
||||
const newTicked = [];
|
||||
for (const ext of this.extList) {
|
||||
newTicked.push(ext);
|
||||
}
|
||||
this.ticked = newTicked;
|
||||
} else {
|
||||
this.ticked = [];
|
||||
this.tickAll = false;
|
||||
}
|
||||
}
|
||||
|
||||
checkAllTicked() {
|
||||
const ticked = new Set(this.ticked);
|
||||
|
||||
let newTickAll = !!(this.extList.length);
|
||||
for (const ext of this.extList) {
|
||||
if (!ticked.has(ext)) {
|
||||
newTickAll = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.ticked.length && !newTickAll) {
|
||||
this.tickAll = undefined;
|
||||
} else {
|
||||
this.tickAll = newTickAll;
|
||||
}
|
||||
}
|
||||
|
||||
updateTicked() {
|
||||
this.ticked = this.ext.split('|').filter(s => s);
|
||||
}
|
||||
|
||||
updateExt() {
|
||||
this.$emit('update:ext', this.ticked.join('|'));
|
||||
}
|
||||
|
||||
okClick() {
|
||||
this.dialogVisible = false;
|
||||
}
|
||||
}
|
||||
|
||||
export default vueComponent(SelectExtDialog);
|
||||
//-----------------------------------------------------------------------------
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.checkbox-tick-all {
|
||||
border-bottom: 1px solid #bbbbbb;
|
||||
margin-bottom: 7px;
|
||||
padding: 5px 5px 2px 0px;
|
||||
}
|
||||
|
||||
.clickable {
|
||||
color: blue;
|
||||
cursor: pointer;
|
||||
}
|
||||
</style>
|
||||
@@ -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><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>
|
||||
@@ -96,9 +96,9 @@
|
||||
</div>
|
||||
<!-- Формирование списка конец ------------------------------------------------------------------>
|
||||
|
||||
<div v-if="!refreshing && !tableData.length" class="row items-center q-ml-md" style="font-size: 120%">
|
||||
<div v-if="!refreshing && (!tableData.length || error)" class="row items-center q-ml-md" style="font-size: 120%">
|
||||
<q-icon class="la la-meh q-mr-xs" size="28px" />
|
||||
Поиск не дал результатов
|
||||
{{ (error ? error : 'Поиск не дал результатов') }}
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -234,6 +234,7 @@ class SeriesList extends BaseList {
|
||||
if (this.refreshing)
|
||||
return;
|
||||
|
||||
this.error = '';
|
||||
this.refreshing = true;
|
||||
|
||||
(async() => {
|
||||
@@ -263,7 +264,12 @@ class SeriesList extends BaseList {
|
||||
this.highlightPageScroller(query);
|
||||
}
|
||||
} catch (e) {
|
||||
this.$root.stdDialog.alert(e.message, 'Ошибка');
|
||||
this.list.queryFound = 0;
|
||||
this.list.totalFound = 0;
|
||||
this.searchResult = {found: []};
|
||||
await this.updateTableData();
|
||||
//this.$root.stdDialog.alert(e.message, 'Ошибка');
|
||||
this.error = `Ошибка: ${e.message}`;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
/>
|
||||
</div>
|
||||
|
||||
<q-checkbox v-show="config.latestVersion" v-model="showNewReleaseAvailable" 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="showInfo" size="36px" label="Показывать кнопку (инфо)" />
|
||||
@@ -60,6 +62,9 @@ const componentOptions = {
|
||||
limit(newValue) {
|
||||
this.commit('setSettings', {'limit': newValue});
|
||||
},
|
||||
downloadAsZip(newValue) {
|
||||
this.commit('setSettings', {'downloadAsZip': newValue});
|
||||
},
|
||||
showCounts(newValue) {
|
||||
this.commit('setSettings', {'showCounts': newValue});
|
||||
},
|
||||
@@ -81,6 +86,9 @@ const componentOptions = {
|
||||
abCacheEnabled(newValue) {
|
||||
this.commit('setSettings', {'abCacheEnabled': newValue});
|
||||
},
|
||||
showNewReleaseAvailable(newValue) {
|
||||
this.commit('setSettings', {'showNewReleaseAvailable': newValue});
|
||||
},
|
||||
}
|
||||
};
|
||||
class SettingsDialog {
|
||||
@@ -93,6 +101,7 @@ class SettingsDialog {
|
||||
|
||||
//settings
|
||||
limit = 20;
|
||||
downloadAsZip = false;
|
||||
showCounts = true;
|
||||
showRates = true;
|
||||
showInfo = true;
|
||||
@@ -100,6 +109,7 @@ class SettingsDialog {
|
||||
showDates = true;
|
||||
showDeleted = false;
|
||||
abCacheEnabled = true;
|
||||
showNewReleaseAvailable = true;
|
||||
|
||||
limitOptions = [
|
||||
{label: '10', value: 10},
|
||||
@@ -120,6 +130,10 @@ class SettingsDialog {
|
||||
mounted() {
|
||||
}
|
||||
|
||||
get config() {
|
||||
return this.$store.state.config;
|
||||
}
|
||||
|
||||
get settings() {
|
||||
return this.$store.state.settings;
|
||||
}
|
||||
@@ -129,6 +143,7 @@ class SettingsDialog {
|
||||
|
||||
this.limit = settings.limit;
|
||||
|
||||
this.downloadAsZip = settings.downloadAsZip;
|
||||
this.showCounts = settings.showCounts;
|
||||
this.showRates = settings.showRates;
|
||||
this.showInfo = settings.showInfo;
|
||||
@@ -136,6 +151,7 @@ class SettingsDialog {
|
||||
this.showDates = settings.showDates;
|
||||
this.showDeleted = settings.showDeleted;
|
||||
this.abCacheEnabled = settings.abCacheEnabled;
|
||||
this.showNewReleaseAvailable = settings.showNewReleaseAvailable;
|
||||
}
|
||||
|
||||
okClick() {
|
||||
|
||||
@@ -22,9 +22,9 @@
|
||||
</div>
|
||||
<!-- Формирование списка конец ------------------------------------------------------------------>
|
||||
|
||||
<div v-if="!refreshing && !tableData.length" class="row items-center q-ml-md" style="font-size: 120%">
|
||||
<div v-if="!refreshing && (!tableData.length || error)" class="row items-center q-ml-md" style="font-size: 120%">
|
||||
<q-icon class="la la-meh q-mr-xs" size="28px" />
|
||||
Поиск не дал результатов
|
||||
{{ (error ? error : 'Поиск не дал результатов') }}
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -95,6 +95,7 @@ class TitleList extends BaseList {
|
||||
if (this.refreshing)
|
||||
return;
|
||||
|
||||
this.error = '';
|
||||
this.refreshing = true;
|
||||
|
||||
(async() => {
|
||||
@@ -124,7 +125,12 @@ class TitleList extends BaseList {
|
||||
this.highlightPageScroller(query);
|
||||
}
|
||||
} catch (e) {
|
||||
this.$root.stdDialog.alert(e.message, 'Ошибка');
|
||||
this.list.queryFound = 0;
|
||||
this.list.totalFound = 0;
|
||||
this.searchResult = {found: []};
|
||||
await this.updateTableData();
|
||||
//this.$root.stdDialog.alert(e.message, 'Ошибка');
|
||||
this.error = `Ошибка: ${e.message}`;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
|
||||
@@ -8,6 +8,8 @@ const abStore = localForage.createInstance({
|
||||
name: 'authorBooksStorage'
|
||||
});
|
||||
|
||||
const storageVersion = '1';
|
||||
|
||||
class AuthorBooksStorage {
|
||||
constructor() {
|
||||
}
|
||||
@@ -17,6 +19,8 @@ class AuthorBooksStorage {
|
||||
}
|
||||
|
||||
async setData(key, data) {
|
||||
key += storageVersion;
|
||||
|
||||
if (typeof data !== 'string')
|
||||
throw new Error('AuthorBooksStorage: data must be a string');
|
||||
|
||||
@@ -25,6 +29,8 @@ class AuthorBooksStorage {
|
||||
}
|
||||
|
||||
async getData(key) {
|
||||
key += storageVersion;
|
||||
|
||||
const item = await abStore.getItem(key);
|
||||
|
||||
//обновим addTime
|
||||
@@ -34,9 +40,9 @@ class AuthorBooksStorage {
|
||||
return item;
|
||||
}
|
||||
|
||||
async removeData(key) {
|
||||
await abStore.removeItem(key);
|
||||
await abStore.removeItem(`addTime-${key}`);
|
||||
async _removeData(fullKey) {
|
||||
await abStore.removeItem(fullKey);
|
||||
await abStore.removeItem(`addTime-${fullKey}`);
|
||||
}
|
||||
|
||||
async cleanStorage() {
|
||||
@@ -62,7 +68,7 @@ class AuthorBooksStorage {
|
||||
}
|
||||
|
||||
if (size > maxDataSize && toDel) {
|
||||
await this.removeData(toDel);
|
||||
await this._removeData(toDel);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<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}">
|
||||
<i :class="icon" :style="`font-size: ${iconSize}px; margin-top: ${imt}px`" />
|
||||
<slot></slot>
|
||||
@@ -29,8 +29,10 @@ class DivBtn {
|
||||
height: { type: Number, default: 0 },
|
||||
icon: { type: String, default: '' },
|
||||
iconSize: { type: Number, default: 14 },
|
||||
round: { type: Boolean },
|
||||
round: Boolean,
|
||||
imt: { type: Number, default: 0 },// icon margin top
|
||||
disabled: Boolean,
|
||||
noShadow: Boolean,
|
||||
};
|
||||
|
||||
pressed = false;
|
||||
@@ -55,9 +57,17 @@ class DivBtn {
|
||||
style.borderRadius = `${this.size}px`;
|
||||
else
|
||||
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;
|
||||
await utils.sleep(100);
|
||||
this.pressed = false;
|
||||
@@ -71,7 +81,6 @@ export default vueComponent(DivBtn);
|
||||
<style scoped>
|
||||
.button {
|
||||
position: relative;
|
||||
box-shadow: 0.5px 1px 3px #333333;
|
||||
}
|
||||
|
||||
.button:hover {
|
||||
@@ -80,8 +89,10 @@ export default vueComponent(DivBtn);
|
||||
}
|
||||
|
||||
.button-pressed {
|
||||
margin-left: 2px;
|
||||
margin-top: 2px;
|
||||
margin-left: 1px;
|
||||
margin-top: 1px;
|
||||
margin-right: -1px;
|
||||
margin-bottom: -1px;
|
||||
}
|
||||
|
||||
.clickable {
|
||||
|
||||
@@ -74,6 +74,7 @@ const componentOptions = {
|
||||
this.checkErrorAndEmit(true);
|
||||
},
|
||||
modelValue(newValue) {
|
||||
if (this.ready)//исправление бага TypeError: Cannot read properties of null (reading 'emitsOptions')
|
||||
this.filteredValue = newValue;
|
||||
},
|
||||
min() {
|
||||
@@ -102,7 +103,8 @@ class NumInput {
|
||||
filteredValue = 0;
|
||||
error = false;
|
||||
|
||||
created() {
|
||||
mounted() {
|
||||
this.ready = true;
|
||||
this.filteredValue = this.modelValue;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ const myRoutes = [
|
||||
['/author', Search],
|
||||
['/series', Search],
|
||||
['/title', Search],
|
||||
['/extended', Search],
|
||||
['/:pathMatch(.*)*', null, null, '/'],
|
||||
];
|
||||
|
||||
|
||||
@@ -36,14 +36,14 @@ export function keyEventToCode(event) {
|
||||
|
||||
export function wordEnding(num, type = 0) {
|
||||
const endings = [
|
||||
['ов', '', 'а', 'а', 'а', 'ов', 'ов', 'ов', 'ов', 'ов'],
|
||||
['й', 'я', 'и', 'и', 'и', 'й', 'й', 'й', 'й', 'й'],
|
||||
['о', '', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о'],
|
||||
['ий', 'ие', 'ия', 'ия', 'ия', 'ий', 'ий', 'ий', 'ий', 'ий'],
|
||||
['о', 'а', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о'],
|
||||
['ок', 'ка', 'ки', 'ки', 'ки', 'ок', 'ок', 'ок', 'ок', 'ок'],
|
||||
['ых', 'ое', 'ых', 'ых', 'ых', 'ых', 'ых', 'ых', 'ых', 'ых'],
|
||||
['о', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о'],
|
||||
['ов', '', 'а', 'а', 'а', 'ов', 'ов', 'ов', 'ов', 'ов'],//0
|
||||
['й', 'я', 'и', 'и', 'и', 'й', 'й', 'й', 'й', 'й'],//1
|
||||
['о', '', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о'],//2
|
||||
['ий', 'ие', 'ия', 'ия', 'ия', 'ий', 'ий', 'ий', 'ий', 'ий'],//3
|
||||
['о', 'а', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о'],//4
|
||||
['ок', 'ка', 'ки', 'ки', 'ки', 'ок', 'ок', 'ок', 'ок', 'ок'],//5
|
||||
['ых', 'ое', 'ых', 'ых', 'ых', 'ых', 'ых', 'ых', 'ых', 'ых'],//6
|
||||
['о', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о', 'о'],//7
|
||||
];
|
||||
const deci = num % 100;
|
||||
if (deci > 10 && deci < 20) {
|
||||
@@ -87,35 +87,6 @@ export async function copyTextToClipboard(text) {
|
||||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
export function formatDate(d, format = 'normal') {
|
||||
switch (format) {
|
||||
case 'normal':
|
||||
return `${d.getDate().toString().padStart(2, '0')}.${(d.getMonth() + 1).toString().padStart(2, '0')}.${d.getFullYear()} ` +
|
||||
`${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`;
|
||||
case 'coDate':
|
||||
return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`;
|
||||
case 'coMonth':
|
||||
return `${(d.getMonth() + 1).toString().padStart(2, '0')}`;
|
||||
case 'noDate':
|
||||
return `${d.getDate().toString().padStart(2, '0')}.${(d.getMonth() + 1).toString().padStart(2, '0')}.${d.getFullYear()}`;
|
||||
|
||||
default:
|
||||
throw new Error('formatDate: unknown date format');
|
||||
}
|
||||
}
|
||||
|
||||
export function parseDate(sqlDate) {
|
||||
const d = sqlDate.split('-');
|
||||
const result = new Date();
|
||||
result.setDate(parseInt(d[2], 10));
|
||||
result.setMonth(parseInt(d[1], 10) - 1);
|
||||
result.setYear(parseInt(d[0], 10));
|
||||
|
||||
return result;
|
||||
}
|
||||
*/
|
||||
|
||||
export function isDigit(c) {
|
||||
return !isNaN(parseInt(c, 10));
|
||||
}
|
||||
|
||||
@@ -4,9 +4,14 @@ const state = {
|
||||
settings: {
|
||||
accessToken: '',
|
||||
extendedParams: false,
|
||||
limit: 20,
|
||||
expandedAuthor: [],
|
||||
expandedSeries: [],
|
||||
|
||||
defaultsSet: false,
|
||||
|
||||
//uiDefaults
|
||||
limit: 20,
|
||||
downloadAsZip: false,
|
||||
showCounts: true,
|
||||
showRates: true,
|
||||
showInfo: true,
|
||||
@@ -15,6 +20,8 @@ const state = {
|
||||
showDeleted: false,
|
||||
abCacheEnabled: true,
|
||||
langDefault: '',
|
||||
showJson: false,
|
||||
showNewReleaseAvailable: true,
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
9380
package-lock.json
generated
9380
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
72
package.json
72
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "inpx-web",
|
||||
"version": "1.3.0",
|
||||
"version": "1.5.8",
|
||||
"author": "Book Pauk <bookpauk@gmail.com>",
|
||||
"license": "CC0-1.0",
|
||||
"repository": "bookpauk/inpx-web",
|
||||
@@ -11,11 +11,16 @@
|
||||
"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: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: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: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:linux": "npm run build:linux && node build/release.js linux",
|
||||
"release:win": "npm run build:win && node build/release.js win",
|
||||
"release:macos": "npm run build:macos && node build/release.js macos",
|
||||
"release:arm64": "npm run build:linux-arm64 && node build/release.js arm64",
|
||||
"postinstall": "npm run build:client-dev"
|
||||
},
|
||||
"bin": "server/index.js",
|
||||
@@ -24,53 +29,54 @@
|
||||
"assets": "dist/public.json"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.18.9",
|
||||
"@babel/eslint-parser": "^7.18.9",
|
||||
"@babel/eslint-plugin": "^7.17.7",
|
||||
"@babel/plugin-proposal-decorators": "^7.18.9",
|
||||
"@babel/preset-env": "^7.18.9",
|
||||
"@babel/core": "^7.24.3",
|
||||
"@babel/eslint-parser": "^7.24.1",
|
||||
"@babel/eslint-plugin": "^7.23.5",
|
||||
"@babel/plugin-proposal-decorators": "^7.24.1",
|
||||
"@babel/preset-env": "^7.24.3",
|
||||
"@vue/compiler-sfc": "^3.2.22",
|
||||
"babel-loader": "^8.2.5",
|
||||
"babel-loader": "^9.1.3",
|
||||
"copy-webpack-plugin": "^11.0.0",
|
||||
"css-loader": "^6.7.1",
|
||||
"css-minimizer-webpack-plugin": "^4.0.0",
|
||||
"eslint": "^8.20.0",
|
||||
"eslint-plugin-vue": "^9.3.0",
|
||||
"html-webpack-plugin": "^5.5.0",
|
||||
"mini-css-extract-plugin": "^2.6.1",
|
||||
"pkg": "^5.8.0",
|
||||
"css-loader": "^6.10.0",
|
||||
"css-minimizer-webpack-plugin": "^4.2.2",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-plugin-vue": "^9.23.0",
|
||||
"html-webpack-plugin": "^5.6.0",
|
||||
"mini-css-extract-plugin": "^2.8.1",
|
||||
"pkg": "^5.8.1",
|
||||
"showdown": "^2.1.0",
|
||||
"terser-webpack-plugin": "^5.3.3",
|
||||
"vue-eslint-parser": "^9.0.3",
|
||||
"vue-loader": "^17.0.0",
|
||||
"terser-webpack-plugin": "^5.3.10",
|
||||
"vue-eslint-parser": "^9.4.2",
|
||||
"vue-loader": "^17.4.2",
|
||||
"vue-style-loader": "^4.1.3",
|
||||
"webpack": "^5.74.0",
|
||||
"webpack-cli": "^4.10.0",
|
||||
"webpack-dev-middleware": "^5.3.3",
|
||||
"webpack-hot-middleware": "^2.25.1",
|
||||
"webpack-merge": "^5.8.0"
|
||||
"webpack": "^5.91.0",
|
||||
"webpack-cli": "^5.1.4",
|
||||
"webpack-dev-middleware": "^6.1.2",
|
||||
"webpack-hot-middleware": "^2.26.1",
|
||||
"webpack-merge": "^5.10.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@quasar/extras": "^1.15.0",
|
||||
"@quasar/extras": "^1.16.9",
|
||||
"axios": "^0.27.2",
|
||||
"chardet": "^1.5.0",
|
||||
"dayjs": "^1.11.6",
|
||||
"express": "^4.18.1",
|
||||
"chardet": "^1.6.0",
|
||||
"dayjs": "^1.11.10",
|
||||
"express": "^4.19.1",
|
||||
"express-basic-auth": "^1.2.1",
|
||||
"fs-extra": "^10.1.0",
|
||||
"he": "^1.2.0",
|
||||
"iconv-lite": "^0.6.3",
|
||||
"jembadb": "^5.1.3",
|
||||
"jembadb": "^5.1.7",
|
||||
"localforage": "^1.10.0",
|
||||
"lodash": "^4.17.21",
|
||||
"minimist": "^1.2.6",
|
||||
"minimist": "^1.2.8",
|
||||
"node-stream-zip": "^1.15.0",
|
||||
"quasar": "^2.7.5",
|
||||
"quasar": "^2.15.1",
|
||||
"safe-buffer": "^5.2.1",
|
||||
"vue": "^3.2.37",
|
||||
"vue-router": "^4.1.2",
|
||||
"vuex": "^4.0.2",
|
||||
"vue-router": "^4.3.0",
|
||||
"vuex": "^4.1.0",
|
||||
"vuex-persist": "^3.1.3",
|
||||
"ws": "^8.8.1"
|
||||
"ws": "^8.16.0",
|
||||
"yazl": "^2.5.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,17 +6,30 @@ const execDir = path.resolve(__dirname, '..');
|
||||
module.exports = {
|
||||
branch: 'unknown',
|
||||
version: pckg.version,
|
||||
latestVersion: '',
|
||||
name: pckg.name,
|
||||
|
||||
execDir,
|
||||
dataDir: '',
|
||||
tempDir: '',
|
||||
logDir: '',
|
||||
libDir: '',
|
||||
inpx: '',
|
||||
inpxFilterFile: '',
|
||||
|
||||
allowConfigRewrite: false,
|
||||
allowUnsafeFilter: false,
|
||||
accessPassword: '',
|
||||
accessTimeout: 0,
|
||||
extendedSearch: true,
|
||||
bookReadLink: '',
|
||||
loggingEnabled: true,
|
||||
logServerStats: false,
|
||||
logQueries: false,
|
||||
|
||||
//поправить в случае, если были критические изменения в DbCreator или InpxParser
|
||||
//иначе будет рассинхронизация между сервером и клиентом на уровне БД
|
||||
dbVersion: '8',
|
||||
//иначе будет рассинхронизация по кешу между сервером и клиентом на уровне БД
|
||||
dbVersion: '12',
|
||||
dbCacheSize: 5,
|
||||
|
||||
maxPayloadSize: 500,//in MB
|
||||
@@ -29,7 +42,7 @@ module.exports = {
|
||||
lowMemoryMode: false,
|
||||
fullOptimization: false,
|
||||
|
||||
webConfigParams: ['name', 'version', 'branch', 'bookReadLink', 'dbVersion'],
|
||||
webConfigParams: ['name', 'version', 'latestVersion', 'branch', 'bookReadLink', 'dbVersion', 'extendedSearch', 'latestReleaseLink', 'uiDefaults'],
|
||||
|
||||
allowRemoteLib: false,
|
||||
remoteLib: false,
|
||||
@@ -44,12 +57,32 @@ module.exports = {
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: '22380',
|
||||
root: '',
|
||||
},
|
||||
//opds: false,
|
||||
opds: {
|
||||
enabled: true,
|
||||
user: '',
|
||||
password: '',
|
||||
root: '/opds',
|
||||
},
|
||||
|
||||
latestReleaseLink: 'https://github.com/bookpauk/inpx-web/releases/latest',
|
||||
checkReleaseLink: 'https://api.github.com/repos/bookpauk/inpx-web/releases/latest',
|
||||
|
||||
uiDefaults: {
|
||||
limit: 20,
|
||||
downloadAsZip: false,
|
||||
showCounts: true,
|
||||
showRates: true,
|
||||
showInfo: true,
|
||||
showGenres: true,
|
||||
showDates: false,
|
||||
showDeleted: false,
|
||||
abCacheEnabled: true,
|
||||
langDefault: '',
|
||||
showJson: false,
|
||||
showNewReleaseAvailable: true,
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -5,9 +5,21 @@ const fs = require('fs-extra');
|
||||
const branchFilename = __dirname + '/application_env';
|
||||
|
||||
const propsToSave = [
|
||||
'dataDir',
|
||||
'tempDir',
|
||||
'logDir',
|
||||
'libDir',
|
||||
'inpx',
|
||||
'inpxFilterFile',
|
||||
'allowConfigRewrite',
|
||||
'allowUnsafeFilter',
|
||||
'accessPassword',
|
||||
'accessTimeout',
|
||||
'extendedSearch',
|
||||
'bookReadLink',
|
||||
'loggingEnabled',
|
||||
'logServerStats',
|
||||
'logQueries',
|
||||
'dbCacheSize',
|
||||
'maxFilesDirSize',
|
||||
'queryCacheEnabled',
|
||||
@@ -21,6 +33,9 @@ const propsToSave = [
|
||||
'remoteLib',
|
||||
'server',
|
||||
'opds',
|
||||
'latestReleaseLink',
|
||||
'checkReleaseLink',
|
||||
'uiDefaults',
|
||||
];
|
||||
|
||||
let instance = null;
|
||||
@@ -37,7 +52,7 @@ class ConfigManager {
|
||||
return instance;
|
||||
}
|
||||
|
||||
async init(dataDir) {
|
||||
async init(defaultDataDir, configFile) {
|
||||
if (this.inited)
|
||||
throw new Error('already inited');
|
||||
|
||||
@@ -54,14 +69,17 @@ class ConfigManager {
|
||||
this.branchConfigFile = __dirname + `/${this.branch}.js`;
|
||||
const config = require(this.branchConfigFile);
|
||||
|
||||
if (dataDir) {
|
||||
config.dataDir = path.resolve(dataDir);
|
||||
} else {
|
||||
config.dataDir = `${config.execDir}/.${config.name}`;
|
||||
if (!defaultDataDir) {
|
||||
defaultDataDir = `${config.execDir}/.${config.name}`;
|
||||
}
|
||||
|
||||
if (configFile) {
|
||||
config.configFile = path.resolve(configFile);
|
||||
} else {
|
||||
await fs.ensureDir(defaultDataDir);
|
||||
config.configFile = `${defaultDataDir}/config.json`;
|
||||
}
|
||||
|
||||
await fs.ensureDir(config.dataDir);
|
||||
this._userConfigFile = `${config.dataDir}/config.json`;
|
||||
this._config = config;
|
||||
|
||||
this.inited = true;
|
||||
@@ -77,37 +95,31 @@ class ConfigManager {
|
||||
Object.assign(this._config, value);
|
||||
}
|
||||
|
||||
get userConfigFile() {
|
||||
return this._userConfigFile;
|
||||
}
|
||||
|
||||
set userConfigFile(value) {
|
||||
if (value)
|
||||
this._userConfigFile = value;
|
||||
}
|
||||
|
||||
async load() {
|
||||
try {
|
||||
if (!this.inited)
|
||||
throw new Error('not inited');
|
||||
|
||||
if (await fs.pathExists(this.userConfigFile)) {
|
||||
const data = JSON.parse(await fs.readFile(this.userConfigFile, 'utf8'));
|
||||
if (await fs.pathExists(this._config.configFile)) {
|
||||
const data = JSON.parse(await fs.readFile(this._config.configFile, 'utf8'));
|
||||
const config = _.pick(data, propsToSave);
|
||||
|
||||
this.config = config;
|
||||
|
||||
//сохраним конфиг, если не все атрибуты присутствуют в файле конфига
|
||||
for (const prop of propsToSave)
|
||||
if (config.allowConfigRewrite) {
|
||||
for (const prop of propsToSave) {
|
||||
if (!Object.prototype.hasOwnProperty.call(config, prop)) {
|
||||
await this.save();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
await this.save();
|
||||
}
|
||||
} catch(e) {
|
||||
throw new Error(`Error while loading "${this.userConfigFile}": ${e.message}`);
|
||||
throw new Error(`Error while loading "${this._config.configFile}": ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,7 +128,7 @@ class ConfigManager {
|
||||
throw new Error('not inited');
|
||||
|
||||
const dataToSave = _.pick(this._config, propsToSave);
|
||||
await fs.writeFile(this.userConfigFile, JSON.stringify(dataToSave, null, 4));
|
||||
await fs.writeFile(this._config.configFile, JSON.stringify(dataToSave, null, 4));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ module.exports = Object.assign({}, base, {
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: '12380',
|
||||
root: '',
|
||||
},
|
||||
|
||||
});
|
||||
|
||||
@@ -10,12 +10,11 @@ const cleanPeriod = 1*60*1000;//1 минута
|
||||
const closeSocketOnIdle = 5*60*1000;//5 минут
|
||||
|
||||
class WebSocketController {
|
||||
constructor(wss, config) {
|
||||
constructor(wss, webAccess, config) {
|
||||
this.config = config;
|
||||
this.isDevelopment = (config.branch == 'development');
|
||||
this.accessToken = '';
|
||||
if (config.accessPassword)
|
||||
this.accessToken = utils.getBufHash(config.accessPassword, 'sha256', 'hex');
|
||||
|
||||
this.webAccess = webAccess;
|
||||
|
||||
this.workerState = new WorkerState();
|
||||
this.webWorker = new WebWorker(config);
|
||||
@@ -32,52 +31,69 @@ class WebSocketController {
|
||||
});
|
||||
});
|
||||
|
||||
setTimeout(() => { this.periodicClean(); }, cleanPeriod);
|
||||
this.periodicClean();//no await
|
||||
}
|
||||
|
||||
periodicClean() {
|
||||
async periodicClean() {
|
||||
while (1) {//eslint-disable-line no-constant-condition
|
||||
try {
|
||||
const now = Date.now();
|
||||
|
||||
//почистим ws-клиентов
|
||||
this.wss.clients.forEach((ws) => {
|
||||
if (!ws.lastActivity || now - ws.lastActivity > closeSocketOnIdle - 50) {
|
||||
ws.terminate();
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
setTimeout(() => { this.periodicClean(); }, cleanPeriod);
|
||||
} catch(e) {
|
||||
log(LM_ERR, `WebSocketController.periodicClean error: ${e.message}`);
|
||||
}
|
||||
|
||||
await utils.sleep(cleanPeriod);
|
||||
}
|
||||
}
|
||||
|
||||
async onMessage(ws, message) {
|
||||
let req = {};
|
||||
try {
|
||||
if (this.isDevelopment) {
|
||||
log(`WebSocket-IN: ${message.substr(0, 4000)}`);
|
||||
if (this.isDevelopment || this.config.logQueries) {
|
||||
log(`WebSocket-IN: ${utils.cutString(message)}`);
|
||||
}
|
||||
|
||||
req = JSON.parse(message);
|
||||
req.__startTime = Date.now();
|
||||
|
||||
ws.lastActivity = Date.now();
|
||||
|
||||
//pong for WebSocketConnection
|
||||
this.send({_rok: 1}, req, ws);
|
||||
|
||||
if (this.accessToken && req.accessToken !== this.accessToken) {
|
||||
await utils.sleep(1000);
|
||||
throw new Error('need_access_token');
|
||||
//access
|
||||
if (!await this.webAccess.hasAccess(req.accessToken)) {
|
||||
await utils.sleep(500);
|
||||
const salt = this.webAccess.newToken();
|
||||
this.send({error: 'need_access_token', salt}, req, ws);
|
||||
return;
|
||||
}
|
||||
|
||||
//api
|
||||
switch (req.action) {
|
||||
case 'test':
|
||||
await this.test(req, ws); break;
|
||||
case 'logout':
|
||||
await this.logout(req, ws); break;
|
||||
case 'get-config':
|
||||
await this.getConfig(req, ws); break;
|
||||
case 'get-worker-state':
|
||||
await this.getWorkerState(req, ws); break;
|
||||
case 'search':
|
||||
await this.search(req, ws); break;
|
||||
case 'bookSearch':
|
||||
await this.bookSearch(req, ws); break;
|
||||
case 'get-author-book-list':
|
||||
await this.getAuthorBookList(req, ws); break;
|
||||
case 'get-author-series-list':
|
||||
await this.getAuthorSeriesList(req, ws); break;
|
||||
case 'get-series-book-list':
|
||||
await this.getSeriesBookList(req, ws); break;
|
||||
case 'get-genre-tree':
|
||||
@@ -108,8 +124,9 @@ class WebSocketController {
|
||||
const message = JSON.stringify(r);
|
||||
ws.send(message);
|
||||
|
||||
if (this.isDevelopment) {
|
||||
log(`WebSocket-OUT: ${message.substr(0, 200)}`);
|
||||
if (this.isDevelopment || this.config.logQueries) {
|
||||
log(`WebSocket-OUT: ${utils.cutString(message)}`);
|
||||
log(`${Date.now() - req.__startTime}ms`);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -120,9 +137,15 @@ class WebSocketController {
|
||||
this.send({message: `${this.config.name} project is awesome`}, req, ws);
|
||||
}
|
||||
|
||||
async logout(req, ws) {
|
||||
await this.webAccess.deleteAccess(req.accessToken);
|
||||
this.send({success: true}, req, ws);
|
||||
}
|
||||
|
||||
async getConfig(req, ws) {
|
||||
const config = _.pick(this.config, this.config.webConfigParams);
|
||||
config.dbConfig = await this.webWorker.dbConfig();
|
||||
config.freeAccess = this.webAccess.freeAccess;
|
||||
|
||||
this.send(config, req, ws);
|
||||
}
|
||||
@@ -146,12 +169,29 @@ class WebSocketController {
|
||||
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) {
|
||||
const result = await this.webWorker.getAuthorBookList(req.authorId);
|
||||
|
||||
this.send(result, req, ws);
|
||||
}
|
||||
|
||||
async getAuthorSeriesList(req, ws) {
|
||||
const result = await this.webWorker.getAuthorSeriesList(req.authorId);
|
||||
|
||||
this.send(result, req, ws);
|
||||
}
|
||||
|
||||
async getSeriesBookList(req, ws) {
|
||||
const result = await this.webWorker.getSeriesBookList(req.series);
|
||||
|
||||
|
||||
@@ -64,6 +64,8 @@ class DbCreator {
|
||||
let dateArr = [];
|
||||
let librateMap = new Map();//оценка
|
||||
let librateArr = [];
|
||||
let extMap = new Map();//тип файла
|
||||
let extArr = [];
|
||||
|
||||
let uidSet = new Set();//уникальные идентификаторы
|
||||
|
||||
@@ -215,6 +217,9 @@ class DbCreator {
|
||||
|
||||
//оценка
|
||||
parseField(rec.librate, librateMap, librateArr, rec.id);
|
||||
|
||||
//тип файла
|
||||
parseField(rec.ext, extMap, extArr, rec.id);
|
||||
};
|
||||
|
||||
//основная процедура парсинга
|
||||
@@ -272,6 +277,8 @@ class DbCreator {
|
||||
delMap = null;
|
||||
dateMap = null;
|
||||
librateMap = null;
|
||||
extMap = null;
|
||||
|
||||
uidSet = null;
|
||||
|
||||
await db.close({table: 'book'});
|
||||
@@ -337,7 +344,7 @@ class DbCreator {
|
||||
//сохраним поисковые таблицы
|
||||
const chunkSize = 10000;
|
||||
|
||||
const saveTable = async(table, arr, nullArr, indexType = 'string') => {
|
||||
const saveTable = async(table, arr, nullArr, indexType = 'string', delEmpty = false) => {
|
||||
|
||||
if (indexType == 'string')
|
||||
arr.sort((a, b) => a.value.localeCompare(b.value));
|
||||
@@ -366,6 +373,13 @@ class DbCreator {
|
||||
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();
|
||||
await db.close({table});
|
||||
utils.freeMemory();
|
||||
@@ -378,7 +392,7 @@ class DbCreator {
|
||||
|
||||
//series
|
||||
callback({job: 'series save', jobMessage: 'Сохранение индекса серий', jobStep: 4, progress: 0});
|
||||
await saveTable('series', seriesArr, () => {seriesArr = null});
|
||||
await saveTable('series', seriesArr, () => {seriesArr = null}, 'string', true);
|
||||
|
||||
//title
|
||||
callback({job: 'title save', jobMessage: 'Сохранение индекса названий', jobStep: 5, progress: 0});
|
||||
@@ -401,6 +415,9 @@ class DbCreator {
|
||||
//librate
|
||||
await saveTable('librate', librateArr, () => {librateArr = null}, 'number');
|
||||
|
||||
//ext
|
||||
await saveTable('ext', extArr, () => {extArr = null});
|
||||
|
||||
//кэш-таблицы запросов
|
||||
await db.create({table: 'query_cache'});
|
||||
await db.create({table: 'query_time'});
|
||||
@@ -446,8 +463,16 @@ class DbCreator {
|
||||
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: [
|
||||
{id: 'inpxInfo', value: (inpxFilter && inpxFilter.info ? inpxFilter.info : parser.info)},
|
||||
{id: 'inpxInfo', value: inpxInfo},
|
||||
{id: 'stats', value: stats},
|
||||
{id: 'inpxHash', value: await inpxHashCreator.getHash()},
|
||||
]});
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
const fs = require('fs-extra');
|
||||
//const _ = require('lodash');
|
||||
const LockQueue = require('./LockQueue');
|
||||
const utils = require('./utils');
|
||||
|
||||
const maxLimit = 1000;
|
||||
@@ -21,7 +20,6 @@ class DbSearcher {
|
||||
|
||||
this.db = db;
|
||||
|
||||
this.lock = new LockQueue();
|
||||
this.searchFlag = 0;
|
||||
this.timer = null;
|
||||
this.closed = false;
|
||||
@@ -30,16 +28,28 @@ class DbSearcher {
|
||||
this.bookIdMap = {};
|
||||
|
||||
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) {
|
||||
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) {
|
||||
const db = this.db;
|
||||
|
||||
if (a[0] !== '~')
|
||||
a = a.toLowerCase();
|
||||
let where;
|
||||
|
||||
@@ -54,8 +64,18 @@ class DbSearcher {
|
||||
a = a.substring(1);
|
||||
where = `@indexIter('value', (v) => {
|
||||
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 {
|
||||
where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
|
||||
}
|
||||
@@ -90,7 +110,7 @@ class DbSearcher {
|
||||
};
|
||||
|
||||
//авторы
|
||||
if (query.author && query.author !== '*') {
|
||||
if (query.author) {
|
||||
const key = `book-ids-author-${query.author}`;
|
||||
let ids = await this.getCached(key);
|
||||
|
||||
@@ -104,7 +124,7 @@ class DbSearcher {
|
||||
}
|
||||
|
||||
//серии
|
||||
if (query.series && query.series !== '*') {
|
||||
if (query.series) {
|
||||
const key = `book-ids-series-${query.series}`;
|
||||
let ids = await this.getCached(key);
|
||||
|
||||
@@ -118,7 +138,7 @@ class DbSearcher {
|
||||
}
|
||||
|
||||
//названия
|
||||
if (query.title && query.title !== '*') {
|
||||
if (query.title) {
|
||||
const key = `book-ids-title-${query.title}`;
|
||||
let ids = await this.getCached(key);
|
||||
|
||||
@@ -204,12 +224,13 @@ class DbSearcher {
|
||||
}
|
||||
|
||||
//удаленные
|
||||
if (query.del !== undefined) {
|
||||
const key = `book-ids-del-${query.del}`;
|
||||
if (query.del) {
|
||||
const del = parseInt(query.del, 10) || 0;
|
||||
const key = `book-ids-del-${del}`;
|
||||
let ids = await this.getCached(key);
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -268,6 +289,42 @@ class DbSearcher {
|
||||
idsArr.push(ids);
|
||||
}
|
||||
|
||||
//тип файла
|
||||
if (query.ext) {
|
||||
const key = `book-ids-ext-${query.ext}`;
|
||||
let ids = await this.getCached(key);
|
||||
|
||||
if (ids === null) {
|
||||
const extRows = await db.select({
|
||||
table: 'ext',
|
||||
rawResult: true,
|
||||
where: `
|
||||
const exts = ${db.esc(query.ext.split('|'))};
|
||||
|
||||
const ids = new Set();
|
||||
for (const l of exts) {
|
||||
for (const id of @indexLR('value', l, l))
|
||||
ids.add(id);
|
||||
}
|
||||
|
||||
const result = new Set();
|
||||
for (const id of ids) {
|
||||
const row = @unsafeRow(id);
|
||||
for (const bookId of row.bookIds)
|
||||
result.add(bookId);
|
||||
}
|
||||
|
||||
return new Uint32Array(result);
|
||||
`
|
||||
});
|
||||
|
||||
ids = extRows[0].rawResult;
|
||||
await this.putCached(key, ids);
|
||||
}
|
||||
|
||||
idsArr.push(ids);
|
||||
}
|
||||
|
||||
if (idsArr.length > 1) {
|
||||
//ищем пересечение множеств
|
||||
let proc = 0;
|
||||
@@ -298,12 +355,21 @@ class DbSearcher {
|
||||
}
|
||||
}
|
||||
|
||||
async fillBookIdMap(from) {
|
||||
if (this.bookIdMap[from])
|
||||
return this.bookIdMap[from];
|
||||
async fillDbConfig() {
|
||||
if (!this.dbConfig) {
|
||||
const rows = await this.db.select({table: 'config'});
|
||||
const config = {};
|
||||
|
||||
await this.lock.get();
|
||||
try {
|
||||
for (const row of rows) {
|
||||
config[row.id] = row.value;
|
||||
}
|
||||
|
||||
this.dbConfig = config;
|
||||
this.recStruct = config.inpxInfo.recStruct;
|
||||
}
|
||||
}
|
||||
|
||||
async fillBookIdMap(from) {
|
||||
const data = await fs.readFile(`${this.config.dataDir}/db/${from}_id.map`, 'utf-8');
|
||||
|
||||
const idMap = JSON.parse(data);
|
||||
@@ -311,21 +377,6 @@ class DbSearcher {
|
||||
idMap.map = new Map(idMap.map);
|
||||
|
||||
this.bookIdMap[from] = idMap;
|
||||
|
||||
return this.bookIdMap[from];
|
||||
} finally {
|
||||
this.lock.ret();
|
||||
}
|
||||
}
|
||||
|
||||
async fillBookIdMapAll() {
|
||||
try {
|
||||
await this.fillBookIdMap('author');
|
||||
await this.fillBookIdMap('series');
|
||||
await this.fillBookIdMap('title');
|
||||
} catch (e) {
|
||||
throw new Error(`DbSearcher.fillBookIdMapAll error: ${e.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
async tableIdsFilter(from, query) {
|
||||
@@ -333,7 +384,7 @@ class DbSearcher {
|
||||
//то в выборку по bookId могут попасть авторы, которые отсутствуют в критерии query.author,
|
||||
//поэтому дополнительно фильтруем
|
||||
let result = null;
|
||||
if (from == 'author' && query.author && query.author !== '*') {
|
||||
if (from == 'author' && query.author) {
|
||||
const key = `filter-ids-author-${query.author}`;
|
||||
let authorIds = await this.getCached(key);
|
||||
|
||||
@@ -376,7 +427,7 @@ class DbSearcher {
|
||||
const filter = await this.tableIdsFilter(from, query);
|
||||
|
||||
const tableIdsSet = new Set();
|
||||
const idMap = await this.fillBookIdMap(from);
|
||||
const idMap = this.bookIdMap[from];
|
||||
let proc = 0;
|
||||
let nextProc = 0;
|
||||
for (const bookId of bookIds) {
|
||||
@@ -534,6 +585,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) {
|
||||
if (this.closed)
|
||||
throw new Error('DbSearcher closed');
|
||||
@@ -570,10 +761,11 @@ class DbSearcher {
|
||||
const s = row.value.substring(0, depth);
|
||||
let g = group.get(s);
|
||||
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);
|
||||
}
|
||||
g.count++;
|
||||
g.bookCount += row.bookCount;
|
||||
}
|
||||
|
||||
const result = Array.from(group.values());
|
||||
@@ -599,7 +791,7 @@ class DbSearcher {
|
||||
throw new Error('DbSearcher closed');
|
||||
|
||||
if (!authorId && !author)
|
||||
return {author: '', books: ''};
|
||||
return {author: '', books: []};
|
||||
|
||||
this.searchFlag++;
|
||||
|
||||
@@ -625,14 +817,60 @@ class DbSearcher {
|
||||
const rows = await this.restoreBooks('author', [authorId]);
|
||||
|
||||
let authorName = '';
|
||||
let books = '';
|
||||
let books = [];
|
||||
|
||||
if (rows.length) {
|
||||
authorName = rows[0].name;
|
||||
books = rows[0].books;
|
||||
}
|
||||
|
||||
return {author: authorName, books: (books && books.length ? JSON.stringify(books) : '')};
|
||||
return {author: authorName, books};
|
||||
} finally {
|
||||
this.searchFlag--;
|
||||
}
|
||||
}
|
||||
|
||||
async getAuthorSeriesList(authorId) {
|
||||
if (this.closed)
|
||||
throw new Error('DbSearcher closed');
|
||||
|
||||
if (!authorId)
|
||||
return {author: '', series: []};
|
||||
|
||||
this.searchFlag++;
|
||||
|
||||
try {
|
||||
const db = this.db;
|
||||
|
||||
//выборка книг автора по authorId
|
||||
const bookList = await this.getAuthorBookList(authorId);
|
||||
const books = bookList.books;
|
||||
const seriesSet = new Set();
|
||||
for (const book of books) {
|
||||
if (book.series)
|
||||
seriesSet.add(book.series.toLowerCase());
|
||||
}
|
||||
|
||||
let series = [];
|
||||
if (seriesSet.size) {
|
||||
//выборка серий по названиям
|
||||
series = await db.select({
|
||||
table: 'series',
|
||||
map: `(r) => ({id: r.id, series: r.name, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
|
||||
where: `
|
||||
const seriesArr = ${db.esc(Array.from(seriesSet))};
|
||||
const ids = new Set();
|
||||
for (const value of seriesArr) {
|
||||
for (const id of @dirtyIndexLR('value', value, value))
|
||||
ids.add(id);
|
||||
}
|
||||
|
||||
return ids;
|
||||
`
|
||||
});
|
||||
}
|
||||
|
||||
return {author: bookList.author, series};
|
||||
} finally {
|
||||
this.searchFlag--;
|
||||
}
|
||||
@@ -643,7 +881,7 @@ class DbSearcher {
|
||||
throw new Error('DbSearcher closed');
|
||||
|
||||
if (!series)
|
||||
return {books: ''};
|
||||
return {books: []};
|
||||
|
||||
this.searchFlag++;
|
||||
|
||||
@@ -659,7 +897,7 @@ class DbSearcher {
|
||||
where: `return Array.from(@dirtyIndexLR('value', ${db.esc(series)}, ${db.esc(series)}))`
|
||||
});
|
||||
|
||||
let books;
|
||||
let books = [];
|
||||
if (rows.length && rows[0].rawResult.length) {
|
||||
//выборка книг серии
|
||||
const bookRows = await this.restoreBooks('series', [rows[0].rawResult[0]])
|
||||
@@ -668,7 +906,7 @@ class DbSearcher {
|
||||
books = bookRows[0].books;
|
||||
}
|
||||
|
||||
return {books: (books && books.length ? JSON.stringify(books) : '')};
|
||||
return {books};
|
||||
} finally {
|
||||
this.searchFlag--;
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ class FileDownloader {
|
||||
|
||||
let options = {
|
||||
headers: {
|
||||
'accept-encoding': 'gzip, compress, deflate',
|
||||
'user-agent': userAgent,
|
||||
timeout: 300*1000,
|
||||
},
|
||||
|
||||
@@ -1,12 +1,32 @@
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const ZipReader = require('./ZipReader');
|
||||
const utils = require('./utils');
|
||||
|
||||
const collectionInfo = 'collection.info';
|
||||
const structureInfo = 'structure.info';
|
||||
const versionInfo = 'version.info';
|
||||
|
||||
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 {
|
||||
constructor() {
|
||||
@@ -24,6 +44,21 @@ class InpxParser {
|
||||
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) {
|
||||
if (!readFileCallback)
|
||||
readFileCallback = async() => {};
|
||||
@@ -61,11 +96,11 @@ class InpxParser {
|
||||
info.version = await this.safeExtractToString(zipReader, versionInfo);
|
||||
|
||||
//структура
|
||||
let inpxStructure = info.structure;
|
||||
if (!inpxStructure)
|
||||
inpxStructure = defaultStructure;
|
||||
inpxStructure = inpxStructure.toLowerCase();
|
||||
const structure = inpxStructure.split(';');
|
||||
if (!info.structure)
|
||||
info.structure = defaultStructure;
|
||||
const structure = info.structure.toLowerCase().split(';');
|
||||
|
||||
info.recStruct = this.getRecStruct(structure);
|
||||
|
||||
//парсим inp-файлы
|
||||
this.chunk = [];
|
||||
|
||||
@@ -16,8 +16,6 @@ class RemoteLib {
|
||||
this.config = config;
|
||||
|
||||
this.wsc = new WebSocketConnection(config.remoteLib.url, 10, 30, {rejectUnauthorized: false});
|
||||
if (config.remoteLib.accessPassword)
|
||||
this.accessToken = utils.getBufHash(config.remoteLib.accessPassword, 'sha256', 'hex');
|
||||
|
||||
this.remoteHost = config.remoteLib.url.replace(/^ws:\/\//, 'http://').replace(/^wss:\/\//, 'https://');
|
||||
|
||||
@@ -31,7 +29,7 @@ class RemoteLib {
|
||||
return instance;
|
||||
}
|
||||
|
||||
async wsRequest(query) {
|
||||
async wsRequest(query, recurse = false) {
|
||||
if (this.accessToken)
|
||||
query.accessToken = this.accessToken;
|
||||
|
||||
@@ -40,6 +38,11 @@ class RemoteLib {
|
||||
120
|
||||
);
|
||||
|
||||
if (!recurse && response && response.error == 'need_access_token' && this.config.remoteLib.accessPassword) {
|
||||
this.accessToken = utils.getBufHash(this.config.remoteLib.accessPassword + response.salt, 'sha256', 'hex');
|
||||
return await this.wsRequest(query, true);
|
||||
}
|
||||
|
||||
if (response.error)
|
||||
throw new Error(response.error);
|
||||
|
||||
@@ -65,7 +68,8 @@ class RemoteLib {
|
||||
|
||||
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);
|
||||
|
||||
|
||||
154
server/core/WebAccess.js
Normal file
154
server/core/WebAccess.js
Normal file
@@ -0,0 +1,154 @@
|
||||
const { JembaDbThread } = require('jembadb');
|
||||
const utils = require('../core/utils');
|
||||
const log = new (require('../core/AppLogger'))().log;//singleton
|
||||
const asyncExit = new (require('./AsyncExit'))();
|
||||
|
||||
const cleanPeriod = 1*60*1000;//1 минута
|
||||
const cleanUnusedTokenTimeout = 5*60*1000;//5 минут
|
||||
|
||||
class WebAccess {
|
||||
constructor(config) {
|
||||
this.config = config;
|
||||
|
||||
this.freeAccess = (config.accessPassword === '');
|
||||
this.accessTimeout = config.accessTimeout*60*1000;
|
||||
this.accessMap = new Map();
|
||||
|
||||
asyncExit.add(this.closeDb.bind(this));
|
||||
|
||||
setTimeout(() => { this.periodicClean(); }, cleanPeriod);
|
||||
}
|
||||
|
||||
async init() {
|
||||
const config = this.config;
|
||||
const dbPath = `${config.dataDir}/web-access`;
|
||||
const db = new JembaDbThread();//в отдельном потоке
|
||||
await db.lock({
|
||||
dbPath,
|
||||
create: true,
|
||||
softLock: true,
|
||||
|
||||
tableDefaults: {
|
||||
cacheSize: config.dbCacheSize,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
//открываем таблицы
|
||||
await db.openAll();
|
||||
} catch(e) {
|
||||
if (
|
||||
e.message.indexOf('corrupted') >= 0
|
||||
|| e.message.indexOf('Unexpected token') >= 0
|
||||
|| e.message.indexOf('invalid stored block lengths') >= 0
|
||||
) {
|
||||
log(LM_ERR, `DB ${dbPath} corrupted`);
|
||||
log(`Open "${dbPath}" with auto repair`);
|
||||
await db.openAll({autoRepair: true});
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
await db.create({table: 'access', quietIfExists: true});
|
||||
//проверим, нужно ли обнулить таблицу access
|
||||
const pass = utils.getBufHash(this.config.accessPassword, 'sha256', 'hex');
|
||||
await db.create({table: 'config', quietIfExists: true});
|
||||
let rows = await db.select({table: 'config', where: `@@id('pass')`});
|
||||
|
||||
if (!rows.length || rows[0].value !== pass) {
|
||||
//пароль сменился в конфиге, обнуляем токены
|
||||
await db.truncate({table: 'access'});
|
||||
await db.insert({table: 'config', replace: true, rows: [{id: 'pass', value: pass}]});
|
||||
}
|
||||
|
||||
//загрузим токены сессий
|
||||
rows = await db.select({table: 'access'});
|
||||
for (const row of rows)
|
||||
this.accessMap.set(row.id, row.value);
|
||||
|
||||
this.db = db;
|
||||
}
|
||||
|
||||
async closeDb() {
|
||||
if (this.db) {
|
||||
await this.db.unlock();
|
||||
this.db = null;
|
||||
}
|
||||
}
|
||||
|
||||
async periodicClean() {
|
||||
while (1) {//eslint-disable-line no-constant-condition
|
||||
try {
|
||||
const now = Date.now();
|
||||
|
||||
//почистим accessMap
|
||||
if (!this.freeAccess) {
|
||||
for (const [accessToken, accessRec] of this.accessMap) {
|
||||
if ( !(accessRec.used > 0 || now - accessRec.time < cleanUnusedTokenTimeout)
|
||||
|| !(this.accessTimeout === 0 || now - accessRec.time < this.accessTimeout)
|
||||
) {
|
||||
await this.deleteAccess(accessToken);
|
||||
} else if (!accessRec.saved) {
|
||||
await this.saveAccess(accessToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch(e) {
|
||||
log(LM_ERR, `WebAccess.periodicClean error: ${e.message}`);
|
||||
}
|
||||
|
||||
await utils.sleep(cleanPeriod);
|
||||
}
|
||||
}
|
||||
|
||||
async hasAccess(accessToken) {
|
||||
if (this.freeAccess)
|
||||
return true;
|
||||
|
||||
const accessRec = this.accessMap.get(accessToken);
|
||||
if (accessRec) {
|
||||
const now = Date.now();
|
||||
|
||||
if (this.accessTimeout === 0 || now - accessRec.time < this.accessTimeout) {
|
||||
accessRec.used++;
|
||||
accessRec.time = now;
|
||||
accessRec.saved = false;
|
||||
if (accessRec.used === 1)
|
||||
await this.saveAccess(accessToken);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
async deleteAccess(accessToken) {
|
||||
await this.db.delete({table: 'access', where: `@@id(${this.db.esc(accessToken)})`});
|
||||
this.accessMap.delete(accessToken);
|
||||
}
|
||||
|
||||
async saveAccess(accessToken) {
|
||||
const value = this.accessMap.get(accessToken);
|
||||
if (!value || value.saved)
|
||||
return;
|
||||
|
||||
value.saved = true;
|
||||
await this.db.insert({
|
||||
table: 'access',
|
||||
replace: true,
|
||||
rows: [{id: accessToken, value}]
|
||||
});
|
||||
}
|
||||
|
||||
newToken() {
|
||||
const salt = utils.randomHexString(32);
|
||||
const accessToken = utils.getBufHash(this.config.accessPassword + salt, 'sha256', 'hex');
|
||||
this.accessMap.set(accessToken, {time: Date.now(), used: 0});
|
||||
|
||||
return salt;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WebAccess;
|
||||
@@ -2,6 +2,7 @@ const os = require('os');
|
||||
const path = require('path');
|
||||
const fs = require('fs-extra');
|
||||
const _ = require('lodash');
|
||||
const iconv = require('iconv-lite');
|
||||
|
||||
const ZipReader = require('./ZipReader');
|
||||
const WorkerState = require('./WorkerState');//singleton
|
||||
@@ -10,8 +11,9 @@ const DbCreator = require('./DbCreator');
|
||||
const DbSearcher = require('./DbSearcher');
|
||||
const InpxHashCreator = require('./InpxHashCreator');
|
||||
const RemoteLib = require('./RemoteLib');//singleton
|
||||
const FileDownloader = require('./FileDownloader');
|
||||
|
||||
const ayncExit = new (require('./AsyncExit'))();
|
||||
const asyncExit = new (require('./AsyncExit'))();
|
||||
const log = new (require('./AppLogger'))().log;//singleton
|
||||
const utils = require('./utils');
|
||||
const genreTree = require('./genres');
|
||||
@@ -28,7 +30,8 @@ const stateToText = {
|
||||
[ssDbCreating]: 'Создание поисковой базы',
|
||||
};
|
||||
|
||||
const cleanDirPeriod = 60*60*1000;//каждый час
|
||||
const cleanDirInterval = 60*60*1000;//каждый час
|
||||
const checkReleaseInterval = 7*60*60*1000;//каждые 7 часов
|
||||
|
||||
//singleton
|
||||
let instance = null;
|
||||
@@ -53,20 +56,21 @@ class WebWorker {
|
||||
this.db = null;
|
||||
this.dbSearcher = null;
|
||||
|
||||
ayncExit.add(this.closeDb.bind(this));
|
||||
asyncExit.add(this.closeDb.bind(this));
|
||||
|
||||
this.loadOrCreateDb();//no await
|
||||
this.periodicLogServerStats();//no await
|
||||
|
||||
const dirConfig = [
|
||||
{
|
||||
dir: config.filesDir,
|
||||
dir: config.bookDir,
|
||||
maxSize: config.maxFilesDirSize,
|
||||
},
|
||||
];
|
||||
|
||||
this.periodicCleanDir(dirConfig);//no await
|
||||
this.periodicCheckInpx();//no await
|
||||
this.periodicCheckNewRelease();//no await
|
||||
|
||||
instance = this;
|
||||
}
|
||||
@@ -210,6 +214,7 @@ class WebWorker {
|
||||
|
||||
//поисковый движок
|
||||
this.dbSearcher = new DbSearcher(config, db);
|
||||
await this.dbSearcher.init();
|
||||
|
||||
//stuff
|
||||
db.wwCache = {};
|
||||
@@ -221,7 +226,7 @@ class WebWorker {
|
||||
this.logServerStats();
|
||||
} catch (e) {
|
||||
log(LM_FATAL, e.message);
|
||||
ayncExit.exit(1);
|
||||
asyncExit.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,6 +272,17 @@ class WebWorker {
|
||||
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) {
|
||||
this.checkMyState();
|
||||
|
||||
@@ -279,6 +295,12 @@ class WebWorker {
|
||||
return await this.dbSearcher.getAuthorBookList(authorId, author);
|
||||
}
|
||||
|
||||
async getAuthorSeriesList(authorId) {
|
||||
this.checkMyState();
|
||||
|
||||
return await this.dbSearcher.getAuthorSeriesList(authorId);
|
||||
}
|
||||
|
||||
async getSeriesBookList(series) {
|
||||
this.checkMyState();
|
||||
|
||||
@@ -292,7 +314,7 @@ class WebWorker {
|
||||
|
||||
let result;
|
||||
const db = this.db;
|
||||
if (!db.wwCache.genres) {
|
||||
if (!db.wwCache.genreTree) {
|
||||
const genres = _.cloneDeep(genreTree);
|
||||
const last = genres[genres.length - 1];
|
||||
|
||||
@@ -329,52 +351,94 @@ class WebWorker {
|
||||
rows = await db.select({table: 'lang', map: `(r) => ({value: r.value})`});
|
||||
const langs = rows.map(r => r.value);
|
||||
|
||||
// exts
|
||||
rows = await db.select({table: 'ext', map: `(r) => ({value: r.value})`});
|
||||
const exts = rows.map(r => r.value);
|
||||
|
||||
result = {
|
||||
genreTree: genres,
|
||||
langList: langs,
|
||||
extList: exts,
|
||||
inpxHash: (config.inpxHash ? config.inpxHash : ''),
|
||||
};
|
||||
|
||||
db.wwCache.genres = result;
|
||||
db.wwCache.genreTree = result;
|
||||
} else {
|
||||
result = db.wwCache.genres;
|
||||
result = db.wwCache.genreTree;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async extractBook(bookPath) {
|
||||
async getGenreMap() {
|
||||
this.checkMyState();
|
||||
|
||||
let result;
|
||||
const db = this.db;
|
||||
if (!db.wwCache.genreMap) {
|
||||
const genreTree = await this.getGenreTree();
|
||||
|
||||
result = new Map();
|
||||
for (const section of genreTree.genreTree) {
|
||||
for (const g of section.value)
|
||||
result.set(g.value, g.name);
|
||||
}
|
||||
|
||||
db.wwCache.genreMap = result;
|
||||
} else {
|
||||
result = db.wwCache.genreMap;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async extractBook(libFolder, libFile) {
|
||||
const outFile = `${this.config.tempDir}/${utils.randomHexString(30)}`;
|
||||
|
||||
const folder = `${this.config.libDir}/${path.dirname(bookPath)}`;
|
||||
const file = path.basename(bookPath);
|
||||
libFolder = libFolder.replace(/\\/g, '/').replace(/\/\//g, '/');
|
||||
|
||||
const folder = `${this.config.libDir}/${libFolder}`;
|
||||
const file = libFile;
|
||||
|
||||
const fullPath = `${folder}/${file}`;
|
||||
|
||||
if (!file || await fs.pathExists(fullPath)) {// файл есть на диске
|
||||
|
||||
await fs.copy(fullPath, outFile);
|
||||
return outFile;
|
||||
} else {// файл в zip-архиве
|
||||
const zipReader = new ZipReader();
|
||||
await zipReader.open(folder);
|
||||
|
||||
try {
|
||||
await zipReader.extractToFile(file, outFile);
|
||||
|
||||
if (!await fs.pathExists(outFile)) {//не удалось найти в архиве, попробуем имя файла в кодировке cp866
|
||||
await zipReader.extractToFile(iconv.encode(file, 'cp866').toString(), outFile);
|
||||
}
|
||||
|
||||
return outFile;
|
||||
} finally {
|
||||
await zipReader.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async restoreBook(bookUid, bookPath, downFileName) {
|
||||
async restoreBook(bookUid, libFolder, libFile, downFileName) {
|
||||
const db = this.db;
|
||||
|
||||
let extractedFile = '';
|
||||
let hash = '';
|
||||
|
||||
if (!this.remoteLib) {
|
||||
extractedFile = await this.extractBook(bookPath);
|
||||
extractedFile = await this.extractBook(libFolder, libFile);
|
||||
hash = await utils.getFileHash(extractedFile, 'sha256', 'hex');
|
||||
} else {
|
||||
hash = await this.remoteLib.downloadBook(bookUid);
|
||||
}
|
||||
|
||||
const link = `${this.config.filesPathStatic}/${hash}`;
|
||||
const bookFile = `${this.config.filesDir}/${hash}`;
|
||||
const link = `${this.config.bookPathStatic}/${hash}`;
|
||||
const bookFile = `${this.config.bookDir}/${hash}`;
|
||||
const bookFileDesc = `${bookFile}.d.json`;
|
||||
|
||||
if (!await fs.pathExists(bookFile) || !await fs.pathExists(bookFileDesc)) {
|
||||
@@ -387,7 +451,7 @@ class WebWorker {
|
||||
await utils.touchFile(bookFile);
|
||||
}
|
||||
|
||||
await fs.writeFile(bookFileDesc, JSON.stringify({bookPath, downFileName}));
|
||||
await fs.writeFile(bookFileDesc, JSON.stringify({libFolder, libFile, downFileName}));
|
||||
} else {
|
||||
if (extractedFile)
|
||||
await fs.remove(extractedFile);
|
||||
@@ -400,8 +464,7 @@ class WebWorker {
|
||||
table: 'file_hash',
|
||||
replace: true,
|
||||
rows: [
|
||||
{id: bookPath, hash},
|
||||
{id: hash, bookPath, downFileName}
|
||||
{id: bookUid, hash},
|
||||
]
|
||||
});
|
||||
|
||||
@@ -415,47 +478,56 @@ class WebWorker {
|
||||
const db = this.db;
|
||||
let link = '';
|
||||
|
||||
//найдем bookPath и downFileName
|
||||
//найдем downFileName, libFolder, libFile
|
||||
let rows = await db.select({table: 'book', where: `@@hash('_uid', ${db.esc(bookUid)})`});
|
||||
if (!rows.length)
|
||||
throw new Error('404 Файл не найден');
|
||||
|
||||
const book = rows[0];
|
||||
let downFileName = book.file;
|
||||
const author = book.author.split(',');
|
||||
const at = [author[0], book.title];
|
||||
downFileName = utils.makeValidFileNameOrEmpty(at.filter(r => r).join(' - '))
|
||||
const authors = book.author.split(',');
|
||||
let author = authors[0];
|
||||
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[1])
|
||||
|| downFileName;
|
||||
downFileName = downFileName.substring(0, 100);
|
||||
if (downFileName.length > 50)
|
||||
downFileName = `${downFileName.substring(0, 50)}_`;
|
||||
|
||||
const ext = `.${book.ext}`;
|
||||
if (downFileName.substring(downFileName.length - ext.length) != ext)
|
||||
downFileName += ext;
|
||||
|
||||
const bookPath = `${book.folder}/${book.file}${ext}`;
|
||||
const libFolder = book.folder;
|
||||
const libFile = `${book.file}${ext}`;
|
||||
|
||||
//найдем хеш
|
||||
rows = await db.select({table: 'file_hash', where: `@@id(${db.esc(bookPath)})`});
|
||||
if (rows.length) {//хеш найден по bookPath
|
||||
rows = await db.select({table: 'file_hash', where: `@@id(${db.esc(bookUid)})`});
|
||||
if (rows.length) {//хеш найден по bookUid
|
||||
const hash = rows[0].hash;
|
||||
const bookFile = `${this.config.filesDir}/${hash}`;
|
||||
const bookFile = `${this.config.bookDir}/${hash}`;
|
||||
const bookFileDesc = `${bookFile}.d.json`;
|
||||
|
||||
if (await fs.pathExists(bookFile) && await fs.pathExists(bookFileDesc)) {
|
||||
link = `${this.config.filesPathStatic}/${hash}`;
|
||||
link = `${this.config.bookPathStatic}/${hash}`;
|
||||
}
|
||||
}
|
||||
|
||||
if (!link) {
|
||||
link = await this.restoreBook(bookUid, bookPath, downFileName)
|
||||
link = await this.restoreBook(bookUid, libFolder, libFile, downFileName);
|
||||
}
|
||||
|
||||
if (!link)
|
||||
throw new Error('404 Файл не найден');
|
||||
|
||||
return {link, bookPath, downFileName};
|
||||
return {link, libFolder, libFile, downFileName};
|
||||
} catch(e) {
|
||||
log(LM_ERR, `getBookLink error: ${e.message}`);
|
||||
if (e.message.indexOf('ENOENT') >= 0)
|
||||
@@ -472,7 +544,7 @@ class WebWorker {
|
||||
|
||||
let bookInfo = await this.getBookLink(bookUid);
|
||||
const hash = path.basename(bookInfo.link);
|
||||
const bookFile = `${this.config.filesDir}/${hash}`;
|
||||
const bookFile = `${this.config.bookDir}/${hash}`;
|
||||
const bookFileInfo = `${bookFile}.i.json`;
|
||||
|
||||
let rows = await db.select({table: 'book', where: `@@hash('_uid', ${db.esc(bookUid)})`});
|
||||
@@ -494,7 +566,7 @@ class WebWorker {
|
||||
result.fb2 = fb2.rawNodes;
|
||||
|
||||
if (cover) {
|
||||
result.cover = `${this.config.filesPathStatic}/${hash}${coverExt}`;
|
||||
result.cover = `${this.config.bookPathStatic}/${hash}${coverExt}`;
|
||||
await fs.writeFile(`${bookFile}${coverExt}`, cover);
|
||||
}
|
||||
}
|
||||
@@ -554,16 +626,16 @@ class WebWorker {
|
||||
let loadAvg = os.loadavg();
|
||||
loadAvg = loadAvg.map(v => v.toFixed(2));
|
||||
|
||||
log(`Server info [ memUsage: ${memUsage.toFixed(2)}MB, loadAvg: (${loadAvg.join(', ')}) ]`);
|
||||
|
||||
if (this.config.server.ready)
|
||||
log(`Server accessible at http://127.0.0.1:${this.config.server.port} (listening on ${this.config.server.host}:${this.config.server.port})`);
|
||||
log(`Server stats [ memUsage: ${memUsage.toFixed(2)}MB, loadAvg: (${loadAvg.join(', ')}) ]`);
|
||||
} catch (e) {
|
||||
log(LM_ERR, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
async periodicLogServerStats() {
|
||||
if (!this.config.logServerStats)
|
||||
return;
|
||||
|
||||
while (1) {// eslint-disable-line
|
||||
this.logServerStats();
|
||||
await utils.sleep(60*1000);
|
||||
@@ -587,8 +659,6 @@ class WebWorker {
|
||||
}
|
||||
}
|
||||
|
||||
log(LM_WARN, `clean dir ${dir}, maxSize=${maxSize}, found ${files.length} files, total size=${size}`);
|
||||
|
||||
files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
|
||||
|
||||
let i = 0;
|
||||
@@ -601,8 +671,11 @@ class WebWorker {
|
||||
i++;
|
||||
}
|
||||
|
||||
if (i) {
|
||||
log(LM_WARN, `clean dir ${dir}, maxSize=${maxSize}, found ${files.length} files, total size=${size}`);
|
||||
log(LM_WARN, `removed ${i} files`);
|
||||
}
|
||||
}
|
||||
|
||||
async periodicCleanDir(dirConfig) {
|
||||
try {
|
||||
@@ -612,7 +685,7 @@ class WebWorker {
|
||||
let lastCleanDirTime = 0;
|
||||
while (1) {// eslint-disable-line no-constant-condition
|
||||
//чистка папок
|
||||
if (Date.now() - lastCleanDirTime >= cleanDirPeriod) {
|
||||
if (Date.now() - lastCleanDirTime >= cleanDirInterval) {
|
||||
for (const config of dirConfig) {
|
||||
try {
|
||||
await this.cleanDir(config);
|
||||
@@ -628,7 +701,7 @@ class WebWorker {
|
||||
}
|
||||
} catch (e) {
|
||||
log(LM_FATAL, e.message);
|
||||
ayncExit.exit(1);
|
||||
asyncExit.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -655,7 +728,7 @@ class WebWorker {
|
||||
log('inpx file: changes found, recreating DB');
|
||||
await this.recreateDb();
|
||||
} else {
|
||||
log('inpx file: no changes');
|
||||
//log('inpx file: no changes');
|
||||
}
|
||||
} catch(e) {
|
||||
log(LM_ERR, `periodicCheckInpx: ${e.message}`);
|
||||
@@ -664,6 +737,27 @@ class WebWorker {
|
||||
await utils.sleep(inpxCheckInterval*60*1000);
|
||||
}
|
||||
}
|
||||
|
||||
async periodicCheckNewRelease() {
|
||||
const checkReleaseLink = this.config.checkReleaseLink;
|
||||
if (!checkReleaseLink)
|
||||
return;
|
||||
const down = new FileDownloader(1024*1024);
|
||||
|
||||
while (1) {// eslint-disable-line no-constant-condition
|
||||
try {
|
||||
let release = await down.load(checkReleaseLink);
|
||||
release = JSON.parse(release.toString());
|
||||
|
||||
if (release.tag_name)
|
||||
this.config.latestVersion = release.tag_name;
|
||||
} catch(e) {
|
||||
log(LM_ERR, `periodicCheckNewRelease: ${e.message}`);
|
||||
}
|
||||
|
||||
await utils.sleep(checkReleaseInterval);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WebWorker;
|
||||
@@ -1,4 +1,4 @@
|
||||
const StreamZip = require('node-stream-zip');
|
||||
const StreamUnzip = require('node-stream-zip');
|
||||
|
||||
class ZipReader {
|
||||
constructor() {
|
||||
@@ -14,7 +14,7 @@ class ZipReader {
|
||||
if (this.zip)
|
||||
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)
|
||||
this.zipEntries = await zip.entries();
|
||||
|
||||
@@ -35,7 +35,7 @@ class Fb2Helper {
|
||||
if (m) {
|
||||
let enc = m[1].toLowerCase();
|
||||
if (enc != 'utf-8') {
|
||||
//enc может не соответсвовать реальной кодировке файла, поэтому:
|
||||
//если кодировка не определена в getEncoding, используем enc
|
||||
if (encoding.indexOf('ISO-8859') >= 0) {
|
||||
encoding = enc;
|
||||
}
|
||||
@@ -70,9 +70,6 @@ class Fb2Helper {
|
||||
if (coverImage.count) {
|
||||
const coverAttrs = coverImage.attrs();
|
||||
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) {
|
||||
const binaryId = (href[0] == '#' ? href.substring(1) : href);
|
||||
@@ -84,6 +81,10 @@ class Fb2Helper {
|
||||
return;
|
||||
|
||||
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();
|
||||
cover = (base64 ? Buffer.from(base64, 'base64') : null);
|
||||
}
|
||||
|
||||
@@ -283,7 +283,7 @@ class Fb2Parser extends XmlParser {
|
||||
};
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ function getEncoding(buf) {
|
||||
let selected = getEncodingLite(buf);
|
||||
|
||||
if (selected == 'ISO-8859-5' && buf.length > 10) {
|
||||
const charsetAll = chardet.analyse(buf.slice(0, 20000));
|
||||
const charsetAll = chardet.analyse(buf.slice(0, 100000));
|
||||
for (const charset of charsetAll) {
|
||||
if (charset.name.indexOf('ISO-8859') < 0) {
|
||||
selected = charset.name;
|
||||
@@ -39,9 +39,7 @@ function getEncodingLite(buf, returnAll) {
|
||||
'u': 0,
|
||||
};
|
||||
|
||||
const len = buf.length;
|
||||
const blockSize = (len > 5*3000 ? 3000 : len);
|
||||
let counter = 0;
|
||||
const len = (buf.length > 100000 ? 100000 : buf.length);
|
||||
let i = 0;
|
||||
let totalChecked = 0;
|
||||
while (i < len) {
|
||||
@@ -76,13 +74,6 @@ function getEncodingLite(buf, returnAll) {
|
||||
if (char > 207 && char < 240) charsets['i'] += lowerCase;
|
||||
if (char > 175 && char < 208) charsets['i'] += upperCase;
|
||||
}
|
||||
|
||||
counter++;
|
||||
|
||||
if (counter > blockSize) {
|
||||
counter = 0;
|
||||
i += Math.round(len/2 - 2*blockSize);
|
||||
}
|
||||
}
|
||||
|
||||
let sorted = Object.keys(charsets).map(function(key) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const BasePage = require('./BasePage');
|
||||
const utils = require('../utils');
|
||||
|
||||
class AuthorPage extends BasePage {
|
||||
constructor(config) {
|
||||
@@ -11,17 +12,22 @@ class AuthorPage extends BasePage {
|
||||
sortBooks(bookList) {
|
||||
//схлопывание серий
|
||||
const books = [];
|
||||
const seriesSet = new Set();
|
||||
const seriesMap = new Map();
|
||||
for (const book of bookList) {
|
||||
if (book.series) {
|
||||
if (!seriesSet.has(book.series)) {
|
||||
let seriesIndex = seriesMap.get(book.series);
|
||||
if (seriesIndex === undefined) {
|
||||
seriesIndex = books.length;
|
||||
books.push({
|
||||
type: 'series',
|
||||
book
|
||||
book,
|
||||
bookCount: 0,
|
||||
});
|
||||
|
||||
seriesSet.add(book.series);
|
||||
seriesMap.set(book.series, seriesIndex);
|
||||
}
|
||||
|
||||
books[seriesIndex].bookCount++;
|
||||
} else {
|
||||
books.push({
|
||||
type: 'book',
|
||||
@@ -60,7 +66,7 @@ class AuthorPage extends BasePage {
|
||||
author: req.query.author || '',
|
||||
series: req.query.series || '',
|
||||
genre: req.query.genre || '',
|
||||
del: 0,
|
||||
del: '0',
|
||||
|
||||
all: req.query.all || '',
|
||||
depth: 0,
|
||||
@@ -79,8 +85,8 @@ class AuthorPage extends BasePage {
|
||||
const bookList = await this.webWorker.getSeriesBookList(query.series);
|
||||
|
||||
if (bookList.books) {
|
||||
let books = JSON.parse(bookList.books);
|
||||
const booksAll = this.filterBooks(books, {del: 0});
|
||||
let books = bookList.books;
|
||||
const booksAll = this.filterBooks(books);
|
||||
const filtered = (query.all ? booksAll : this.filterBooks(books, query));
|
||||
const sorted = this.sortSeriesBooks(filtered);
|
||||
|
||||
@@ -99,21 +105,16 @@ class AuthorPage extends BasePage {
|
||||
for (const book of sorted) {
|
||||
const title = `${book.serno ? `${book.serno}. `: ''}${book.title || 'Без названия'} (${book.ext})`;
|
||||
|
||||
const e = {
|
||||
entry.push(
|
||||
this.makeEntry({
|
||||
id: book._uid,
|
||||
title,
|
||||
link: this.acqLink({href: `/book?uid=${encodeURIComponent(book._uid)}`}),
|
||||
};
|
||||
|
||||
if (query.all) {
|
||||
e.content = {
|
||||
content: {
|
||||
'*ATTRS': {type: 'text'},
|
||||
'*TEXT': this.bookAuthor(book.author),
|
||||
}
|
||||
}
|
||||
|
||||
entry.push(
|
||||
this.makeEntry(e)
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -122,7 +123,7 @@ class AuthorPage extends BasePage {
|
||||
const bookList = await this.webWorker.getAuthorBookList(0, query.author.substring(1));
|
||||
|
||||
if (bookList.books) {
|
||||
let books = JSON.parse(bookList.books);
|
||||
let books = bookList.books;
|
||||
books = this.sortBooks(this.filterBooks(books, query));
|
||||
|
||||
for (const b of books) {
|
||||
@@ -134,6 +135,10 @@ class AuthorPage extends BasePage {
|
||||
link: this.navLink({
|
||||
href: `/${this.id}?author=${encodeURIComponent(query.author)}` +
|
||||
`&series=${encodeURIComponent(b.book.series)}&genre=${encodeURIComponent(query.genre)}`}),
|
||||
content: {
|
||||
'*ATTRS': {type: 'text'},
|
||||
'*TEXT': `${b.bookCount} книг${utils.wordEnding(b.bookCount, 8)} по автору${(query.genre ? ' (в выбранном жанре)' : '')}`,
|
||||
},
|
||||
})
|
||||
);
|
||||
} else {
|
||||
@@ -143,6 +148,10 @@ class AuthorPage extends BasePage {
|
||||
id: b.book._uid,
|
||||
title,
|
||||
link: this.acqLink({href: `/book?uid=${encodeURIComponent(b.book._uid)}`}),
|
||||
content: {
|
||||
'*ATTRS': {type: 'text'},
|
||||
'*TEXT': this.bookAuthor(b.book.author),
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -163,13 +172,26 @@ class AuthorPage extends BasePage {
|
||||
const queryRes = await this.opdsQuery('author', query, '[Остальные авторы]');
|
||||
|
||||
for (const rec of queryRes) {
|
||||
entry.push(
|
||||
this.makeEntry({
|
||||
const e = {
|
||||
id: rec.id,
|
||||
title: this.bookAuthor(rec.title),
|
||||
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 enruArr = (ruAlphabet + enAlphabet).split('');
|
||||
const enru = new Set(enruArr);
|
||||
const ruOnly = new Set(ruAlphabet.split(''));
|
||||
|
||||
class BasePage {
|
||||
constructor(config) {
|
||||
@@ -19,6 +20,13 @@ class BasePage {
|
||||
this.webWorker = new WebWorker(config);
|
||||
this.rootTag = 'feed';
|
||||
this.opdsRoot = config.opdsRoot;
|
||||
|
||||
this.showDeleted = false;
|
||||
}
|
||||
|
||||
escape(s) {
|
||||
//костыль для koreader, не понимает hex-экранирование вида '
|
||||
return he.escape(s).replace(/'/g, ''').replace(/`/g, '`');
|
||||
}
|
||||
|
||||
makeEntry(entry = {}) {
|
||||
@@ -27,7 +35,7 @@ class BasePage {
|
||||
if (!entry.title)
|
||||
throw new Error('makeEntry: no title');
|
||||
|
||||
entry.title = he.escape(entry.title);
|
||||
entry.title = this.escape(entry.title);
|
||||
|
||||
const result = {
|
||||
updated: (new Date()).toISOString().substring(0, 19) + 'Z',
|
||||
@@ -45,7 +53,7 @@ class BasePage {
|
||||
}
|
||||
|
||||
makeLink(attrs) {
|
||||
attrs.href = he.escape(attrs.href);
|
||||
attrs.href = this.escape(attrs.href);
|
||||
return {'*ATTRS': attrs};
|
||||
}
|
||||
|
||||
@@ -140,6 +148,7 @@ class BasePage {
|
||||
id: row.id,
|
||||
title: (row[from] || 'Без автора'),
|
||||
q: `=${encodeURIComponent(row[from])}`,
|
||||
bookCount: row.bookCount,
|
||||
};
|
||||
|
||||
result.push(rec);
|
||||
@@ -161,6 +170,7 @@ class BasePage {
|
||||
return await this.search(from, query);
|
||||
} else {
|
||||
let len = 0;
|
||||
const enResult = [];
|
||||
for (const row of queryRes.found) {
|
||||
const value = row.value;
|
||||
len += value.length;
|
||||
@@ -171,21 +181,30 @@ class BasePage {
|
||||
id: row.id,
|
||||
title: row.name,
|
||||
q: `=${encodeURIComponent(row.name)}`,
|
||||
bookCount: row.bookCount,
|
||||
};
|
||||
} else {
|
||||
rec = {
|
||||
id: row.id,
|
||||
title: `${value.toUpperCase().replace(/ /g, spaceChar)}~`,
|
||||
q: encodeURIComponent(value),
|
||||
count: row.count,
|
||||
};
|
||||
}
|
||||
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 {
|
||||
others.push(rec);
|
||||
}
|
||||
}
|
||||
|
||||
result = result.concat(enResult);
|
||||
|
||||
if (query[from] && query.depth > 1 && result.length < 10 && len > prevLen) {
|
||||
//рекурсия, с увеличением глубины, для облегчения навигации
|
||||
const newQuery = _.cloneDeep(query);
|
||||
@@ -195,13 +214,13 @@ class BasePage {
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
//скопировано из BaseList.js, часть функционала не используется
|
||||
filterBooks(books, query) {
|
||||
filterBooks(books, query = {}) {
|
||||
const s = query;
|
||||
|
||||
const splitAuthor = (author) => {
|
||||
@@ -224,6 +243,7 @@ class BasePage {
|
||||
bookValue = emptyFieldValue;
|
||||
|
||||
bookValue = bookValue.toLowerCase();
|
||||
if (searchValue[0] !== '~')
|
||||
searchValue = searchValue.toLowerCase();
|
||||
|
||||
//особая обработка префиксов
|
||||
@@ -238,7 +258,14 @@ class BasePage {
|
||||
} else if (searchValue[0] == '#') {
|
||||
|
||||
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 {
|
||||
//where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
|
||||
return bookValue.localeCompare(searchValue) >= 0 && bookValue.localeCompare(searchValue + maxUtf8Char) <= 0;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
const path = require('path');
|
||||
const _ = require('lodash');
|
||||
const he = require('he');
|
||||
const dayjs = require('dayjs');
|
||||
|
||||
const BasePage = require('./BasePage');
|
||||
@@ -25,6 +24,19 @@ class BookPage extends BasePage {
|
||||
return `${size.toFixed(1)} ${unit}`;
|
||||
}
|
||||
|
||||
convertGenres(genreArr) {
|
||||
let result = [];
|
||||
if (genreArr) {
|
||||
for (const genre of genreArr) {
|
||||
const g = genre.trim();
|
||||
const name = this.genreMap.get(g);
|
||||
result.push(name ? name : g);
|
||||
}
|
||||
}
|
||||
|
||||
return result.join(', ');
|
||||
}
|
||||
|
||||
inpxInfo(bookRec) {
|
||||
const mapping = [
|
||||
{name: 'fileInfo', label: 'Информация о файле', value: [
|
||||
@@ -67,6 +79,9 @@ class BookPage extends BasePage {
|
||||
if (nodePath == 'titleInfo/author')
|
||||
return value.split(',').join(', ');
|
||||
|
||||
if (nodePath == 'titleInfo/genre')
|
||||
return this.convertGenres(value.split(','));
|
||||
|
||||
if (nodePath == 'titleInfo/librate' && !value)
|
||||
return null;
|
||||
|
||||
@@ -119,6 +134,7 @@ class BookPage extends BasePage {
|
||||
async body(req) {
|
||||
const result = {};
|
||||
|
||||
this.genreMap = await this.webWorker.getGenreMap();
|
||||
result.link = this.baseLinks(req, true);
|
||||
|
||||
const bookUid = req.query.uid;
|
||||
@@ -128,7 +144,19 @@ class BookPage extends BasePage {
|
||||
|
||||
if (bookInfo) {
|
||||
const {genreMap} = await this.getGenres();
|
||||
const fileFormat = `${bookInfo.book.ext}+zip`;
|
||||
|
||||
//format
|
||||
const ext = bookInfo.book.ext;
|
||||
const formats = {
|
||||
[`${ext}+zip`]: `${bookInfo.link}/zip`,
|
||||
[ext]: bookInfo.link,
|
||||
};
|
||||
|
||||
if (ext === 'mobi') {
|
||||
formats['x-mobipocket-ebook'] = bookInfo.link;
|
||||
} else if (ext == 'epub') {
|
||||
formats[`${ext}+zip`] = bookInfo.link;
|
||||
}
|
||||
|
||||
//entry
|
||||
const e = this.makeEntry({
|
||||
@@ -136,8 +164,13 @@ class BookPage extends BasePage {
|
||||
title: bookInfo.book.title || 'Без названия',
|
||||
});
|
||||
|
||||
//author bookInfo
|
||||
if (bookInfo.book.author) {
|
||||
e.author = bookInfo.book.author.split(',').map(a => ({name: a}));
|
||||
}
|
||||
|
||||
e['dc:language'] = bookInfo.book.lang;
|
||||
e['dc:format'] = fileFormat;
|
||||
e['dc:format'] = ext;
|
||||
|
||||
//genre
|
||||
const genre = bookInfo.book.genre.split(',');
|
||||
@@ -161,12 +194,23 @@ class BookPage extends BasePage {
|
||||
const infoObj = parser.bookInfo();
|
||||
|
||||
if (infoObj.titleInfo) {
|
||||
if (infoObj.titleInfo.author.length) {
|
||||
//author fb2Info
|
||||
if (!e.author && infoObj.titleInfo.author.length) {
|
||||
e.author = infoObj.titleInfo.author.map(a => ({name: a}));
|
||||
}
|
||||
|
||||
ann = infoObj.titleInfo.annotationHtml || '';
|
||||
const infoList = parser.bookInfoList(infoObj);
|
||||
const self = this;
|
||||
const infoList = parser.bookInfoList(infoObj, {
|
||||
valueToString(value, nodePath, origVTS) {//eslint-disable-line no-unused-vars
|
||||
if ((nodePath == 'titleInfo/genre' || nodePath == 'srcTitleInfo/genre') && value) {
|
||||
return self.convertGenres(value);
|
||||
}
|
||||
|
||||
return origVTS(value, nodePath);
|
||||
},
|
||||
});
|
||||
|
||||
info += this.htmlInfo('Fb2 инфо', infoList);
|
||||
}
|
||||
}
|
||||
@@ -178,12 +222,15 @@ class BookPage extends BasePage {
|
||||
if (content) {
|
||||
e.content = {
|
||||
'*ATTRS': {type: 'text/html'},
|
||||
'*TEXT': he.escape(content),
|
||||
'*TEXT': this.escape(content),
|
||||
};
|
||||
}
|
||||
|
||||
//links
|
||||
e.link = [ this.downLink({href: bookInfo.link, type: `application/${fileFormat}`}) ];
|
||||
e.link = [];
|
||||
for (const [fileFormat, downHref] of Object.entries(formats))
|
||||
e.link.push(this.downLink({href: downHref, type: `application/${fileFormat}`}));
|
||||
|
||||
if (bookInfo.cover) {
|
||||
let coverType = 'image/jpeg';
|
||||
if (path.extname(bookInfo.cover) == '.png')
|
||||
|
||||
@@ -13,13 +13,17 @@ class GenrePage extends BasePage {
|
||||
const result = {};
|
||||
|
||||
const query = {
|
||||
from: req.query.from || '',
|
||||
from: req.query.from || 'search',
|
||||
term: req.query.term || '',
|
||||
section: req.query.section || '',
|
||||
};
|
||||
|
||||
let searchQuery = '';
|
||||
if (query.from == 'search')
|
||||
searchQuery = `&type=title&term=${encodeURIComponent(query.term)}`;
|
||||
|
||||
const entry = [];
|
||||
if (query.from) {
|
||||
|
||||
if (query.section) {
|
||||
//выбираем подразделы
|
||||
const {genreSection} = await this.getGenres();
|
||||
@@ -34,7 +38,7 @@ class GenrePage extends BasePage {
|
||||
this.makeEntry({
|
||||
id: ++id,
|
||||
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({
|
||||
id: 'whole_section',
|
||||
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({
|
||||
id: ++id,
|
||||
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 SeriesPage = require('./SeriesPage');
|
||||
const TitlePage = require('./TitlePage');
|
||||
const GenrePage = require('./GenrePage');
|
||||
|
||||
class RootPage extends BasePage {
|
||||
constructor(config) {
|
||||
@@ -13,6 +14,7 @@ class RootPage extends BasePage {
|
||||
this.authorPage = new AuthorPage(config);
|
||||
this.seriesPage = new SeriesPage(config);
|
||||
this.titlePage = new TitlePage(config);
|
||||
this.genrePage = new GenrePage(config);
|
||||
}
|
||||
|
||||
async body(req) {
|
||||
@@ -30,6 +32,7 @@ class RootPage extends BasePage {
|
||||
this.authorPage.myEntry(),
|
||||
this.seriesPage.myEntry(),
|
||||
this.titlePage.myEntry(),
|
||||
this.genrePage.myEntry(),
|
||||
];
|
||||
|
||||
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,6 @@
|
||||
const BasePage = require('./BasePage');
|
||||
const utils = require('../utils');
|
||||
const iconv = require('iconv-lite');
|
||||
|
||||
class SearchPage extends BasePage {
|
||||
constructor(config) {
|
||||
@@ -14,32 +16,44 @@ class SearchPage extends BasePage {
|
||||
const query = {
|
||||
type: req.query.type || '',
|
||||
term: req.query.term || '',
|
||||
genre: req.query.genre || '',
|
||||
page: parseInt(req.query.page, 10) || 1,
|
||||
};
|
||||
|
||||
let entry = [];
|
||||
if (query.type) {
|
||||
if (['author', 'series', 'title'].includes(query.type)) {
|
||||
try {
|
||||
const from = query.type;
|
||||
const page = query.page;
|
||||
|
||||
const limit = 100;
|
||||
const offset = (page - 1)*limit;
|
||||
const queryRes = await this.webWorker.search(from, {[from]: query.term, del: 0, offset, limit});
|
||||
|
||||
const searchQuery = {[from]: query.term, genre: query.genre, del: '0', offset, limit};
|
||||
let queryRes = await this.webWorker.search(from, searchQuery);
|
||||
|
||||
if (queryRes.totalFound === 0) { // не нашли ничего, проверим, может term в кодировке ISO-8859-1 (баг koreader)
|
||||
searchQuery[from] = iconv.encode(query.term, 'ISO-8859-1').toString();
|
||||
queryRes = await this.webWorker.search(from, searchQuery);
|
||||
}
|
||||
|
||||
const found = queryRes.found;
|
||||
|
||||
for (let i = 0; i < found.length; i++) {
|
||||
if (i >= limit)
|
||||
break;
|
||||
|
||||
const row = found[i];
|
||||
if (!row.bookCount)
|
||||
continue;
|
||||
|
||||
entry.push(
|
||||
this.makeEntry({
|
||||
id: row.id,
|
||||
title: row[from],
|
||||
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)}`,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -49,8 +63,17 @@ class SearchPage extends BasePage {
|
||||
this.makeEntry({
|
||||
id: 'next_page',
|
||||
title: '[Следующая страница]',
|
||||
link: this.navLink({href: `/${this.id}?type=${from}&term=${encodeURIComponent(query.term)}&page=${page + 1}`}),
|
||||
}),
|
||||
link: this.navLink({href: `/${this.id}?type=${from}&term=${encodeURIComponent(query.term)}&genre=${encodeURIComponent(query.genre)}&page=${page + 1}`}),
|
||||
})
|
||||
);
|
||||
}
|
||||
} catch(e) {
|
||||
entry.push(
|
||||
this.makeEntry({
|
||||
id: 'error',
|
||||
title: `Ошибка: ${e.message}`,
|
||||
link: this.navLink({href: `/fake-error-link`}),
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -61,16 +84,46 @@ class SearchPage extends BasePage {
|
||||
id: 'search_author',
|
||||
title: 'Поиск авторов',
|
||||
link: this.navLink({href: `/${this.id}?type=author&term=${encodeURIComponent(query.term)}`}),
|
||||
content: {
|
||||
'*ATTRS': {type: 'text'},
|
||||
'*TEXT': `Искать по именам авторов`,
|
||||
},
|
||||
}),
|
||||
this.makeEntry({
|
||||
id: 'search_series',
|
||||
title: 'Поиск серий',
|
||||
link: this.navLink({href: `/${this.id}?type=series&term=${encodeURIComponent(query.term)}`}),
|
||||
content: {
|
||||
'*ATTRS': {type: 'text'},
|
||||
'*TEXT': `Искать по названиям серий`,
|
||||
},
|
||||
}),
|
||||
this.makeEntry({
|
||||
id: 'search_title',
|
||||
title: 'Поиск книг',
|
||||
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 utils = require('../utils');
|
||||
|
||||
class SeriesPage extends BasePage {
|
||||
constructor(config) {
|
||||
@@ -25,7 +26,7 @@ class SeriesPage extends BasePage {
|
||||
const query = {
|
||||
series: req.query.series || '',
|
||||
genre: req.query.genre || '',
|
||||
del: 0,
|
||||
del: '0',
|
||||
|
||||
all: req.query.all || '',
|
||||
depth: 0,
|
||||
@@ -44,8 +45,8 @@ class SeriesPage extends BasePage {
|
||||
const bookList = await this.webWorker.getSeriesBookList(query.series.substring(1));
|
||||
|
||||
if (bookList.books) {
|
||||
let books = JSON.parse(bookList.books);
|
||||
const booksAll = this.filterBooks(books, {del: 0});
|
||||
let books = bookList.books;
|
||||
const booksAll = this.filterBooks(books);
|
||||
const filtered = (query.all ? booksAll : this.filterBooks(books, query));
|
||||
const sorted = this.sortSeriesBooks(filtered);
|
||||
|
||||
@@ -63,21 +64,16 @@ class SeriesPage extends BasePage {
|
||||
for (const book of sorted) {
|
||||
const title = `${book.serno ? `${book.serno}. `: ''}${book.title || 'Без названия'} (${book.ext})`;
|
||||
|
||||
const e = {
|
||||
entry.push(
|
||||
this.makeEntry({
|
||||
id: book._uid,
|
||||
title,
|
||||
link: this.acqLink({href: `/book?uid=${encodeURIComponent(book._uid)}`}),
|
||||
};
|
||||
|
||||
if (query.all) {
|
||||
e.content = {
|
||||
content: {
|
||||
'*ATTRS': {type: 'text'},
|
||||
'*TEXT': this.bookAuthor(book.author),
|
||||
}
|
||||
}
|
||||
|
||||
entry.push(
|
||||
this.makeEntry(e)
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -96,13 +92,26 @@ class SeriesPage extends BasePage {
|
||||
const queryRes = await this.opdsQuery('series', query, '[Остальные серии]');
|
||||
|
||||
for (const rec of queryRes) {
|
||||
entry.push(
|
||||
this.makeEntry({
|
||||
const e = {
|
||||
id: rec.id,
|
||||
title: rec.title,
|
||||
title: (rec.count ? rec.title : `Серия: ${rec.title}`),
|
||||
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 utils = require('../utils');
|
||||
|
||||
class TitlePage extends BasePage {
|
||||
constructor(config) {
|
||||
@@ -14,7 +15,7 @@ class TitlePage extends BasePage {
|
||||
const query = {
|
||||
title: req.query.title || '',
|
||||
genre: req.query.genre || '',
|
||||
del: 0,
|
||||
del: '0',
|
||||
|
||||
depth: 0,
|
||||
};
|
||||
@@ -66,13 +67,26 @@ class TitlePage extends BasePage {
|
||||
const queryRes = await this.opdsQuery('title', query, '[Остальные названия]');
|
||||
|
||||
for (const rec of queryRes) {
|
||||
entry.push(
|
||||
this.makeEntry({
|
||||
const e = {
|
||||
id: rec.id,
|
||||
title: rec.title,
|
||||
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 SearchPage = require('./SearchPage');
|
||||
const SearchHelpPage = require('./SearchHelpPage');
|
||||
|
||||
const log = new (require('../AppLogger'))().log;//singleton
|
||||
|
||||
module.exports = function(app, config) {
|
||||
if (!config.opds || !config.opds.enabled)
|
||||
return;
|
||||
|
||||
const opdsRoot = '/opds';
|
||||
const opdsRoot = config.opds.root || '/opds';
|
||||
config.opdsRoot = opdsRoot;
|
||||
|
||||
const root = new RootPage(config);
|
||||
@@ -26,6 +29,7 @@ module.exports = function(app, config) {
|
||||
|
||||
const opensearch = new OpensearchPage(config);
|
||||
const search = new SearchPage(config);
|
||||
const searchHelp = new SearchHelpPage(config);
|
||||
|
||||
const routes = [
|
||||
['', root],
|
||||
@@ -38,6 +42,7 @@ module.exports = function(app, config) {
|
||||
|
||||
['/opensearch', opensearch],
|
||||
['/search', search],
|
||||
['/search-help', searchHelp],
|
||||
];
|
||||
|
||||
const pages = new Map();
|
||||
@@ -60,10 +65,8 @@ module.exports = function(app, config) {
|
||||
next();
|
||||
}
|
||||
} catch (e) {
|
||||
log(LM_ERR, `OPDS: ${e.message}, url: ${req.originalUrl}`);
|
||||
res.status(500).send({error: e.message});
|
||||
if (config.branch == 'development') {
|
||||
console.error({error: e.message, url: req.originalUrl});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -71,7 +74,12 @@ module.exports = function(app, config) {
|
||||
if (config.opds.password) {
|
||||
if (!config.opds.user)
|
||||
throw new Error('User must not be empty if password set');
|
||||
|
||||
/*
|
||||
app.use((req, res, next) => {
|
||||
console.log(req.headers);
|
||||
next();
|
||||
});
|
||||
*/
|
||||
app.use(opdsPaths, basicAuth({
|
||||
users: {[config.opds.user]: config.opds.password},
|
||||
challenge: true,
|
||||
|
||||
@@ -12,7 +12,7 @@ function processLoop() {
|
||||
}
|
||||
|
||||
function versionText(config) {
|
||||
return `${config.name} v${config.version}, Node.js ${process.version}`;
|
||||
return `${config.name} v${config.version}, Node.js ${process.version}, ${process.platform}`;
|
||||
}
|
||||
|
||||
async function findFiles(callback, dir, recursive = true) {
|
||||
@@ -111,7 +111,8 @@ function gzipFile(inputFile, outputFile, level = 1) {
|
||||
.on('finish', (err) => {
|
||||
if (err) reject(err);
|
||||
else resolve();
|
||||
});
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -127,7 +128,8 @@ function gunzipFile(inputFile, outputFile) {
|
||||
.on('finish', (err) => {
|
||||
if (err) reject(err);
|
||||
else resolve();
|
||||
});
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -174,6 +176,40 @@ 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];
|
||||
}
|
||||
}
|
||||
|
||||
function cutString(data, len = 500) {
|
||||
try {
|
||||
if (!data)
|
||||
return '';
|
||||
|
||||
if (typeof(data) !== 'string')
|
||||
data = JSON.stringify(data);
|
||||
|
||||
return `${data.substring(0, len)}${data.length > len ? ' ...' : ''}`;
|
||||
} catch (e) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
sleep,
|
||||
processLoop,
|
||||
@@ -193,4 +229,6 @@ module.exports = {
|
||||
toUnixPath,
|
||||
makeValidFileName,
|
||||
makeValidFileNameOrEmpty,
|
||||
wordEnding,
|
||||
cutString,
|
||||
};
|
||||
@@ -734,8 +734,8 @@ class XmlParser extends NodeBase {
|
||||
} else if (tag === '*ATTRS') {
|
||||
//пропускаем
|
||||
} else {
|
||||
if (typeof(objNode) === 'string') {
|
||||
result.push(this.createNode(tag, null, [this.createText(objNode).raw]).raw);
|
||||
if (typeof(objNode) === 'string' || typeof(objNode) === 'number') {
|
||||
result.push(this.createNode(tag, null, [this.createText(objNode.toString()).raw]).raw);
|
||||
} else if (Array.isArray(objNode)) {
|
||||
for (const n of objNode) {
|
||||
if (typeof(n) === 'string') {
|
||||
@@ -747,6 +747,8 @@ class XmlParser extends NodeBase {
|
||||
|
||||
} else if (typeof(objNode) === 'object') {
|
||||
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)) {
|
||||
const curPublicVersion = await fs.readFile(verFile, 'utf8');
|
||||
if (curPublicVersion == config.version)
|
||||
if (curPublicVersion == config.version + config.rootPathStatic)
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -26,6 +26,6 @@ module.exports = async(config) => {
|
||||
await zipReader.close();
|
||||
}
|
||||
|
||||
await fs.writeFile(verFile, config.version);
|
||||
await fs.writeFile(verFile, config.version + config.rootPathStatic);
|
||||
await fs.remove(zipFile);
|
||||
};
|
||||
140
server/index.js
140
server/index.js
@@ -1,5 +1,6 @@
|
||||
const fs = require('fs-extra');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
|
||||
const express = require('express');
|
||||
const http = require('http');
|
||||
@@ -13,32 +14,35 @@ let log;
|
||||
let config;
|
||||
let argv;
|
||||
let branch = '';
|
||||
const argvStrings = ['host', 'port', 'app-dir', 'lib-dir', 'inpx'];
|
||||
const argvStrings = ['host', 'port', 'config', 'data-dir', 'app-dir', 'lib-dir', 'inpx'];
|
||||
|
||||
function showHelp(defaultConfig) {
|
||||
console.log(utils.versionText(config));
|
||||
console.log(utils.versionText(defaultConfig));
|
||||
console.log(
|
||||
`Usage: ${config.name} [options]
|
||||
`Usage: ${defaultConfig.name} [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}
|
||||
--port=<port> Set web server port, default: ${defaultConfig.server.port}
|
||||
--app-dir=<dirpath> Set application working directory, default: <execDir>/.${config.name}
|
||||
--lib-dir=<dirpath> Set library directory, default: the same as ${config.name} executable's
|
||||
--config=<filepath> Set config filename, default: <dataDir>/config.json
|
||||
--data-dir=<dirpath> (or --app-dir) Set application working directory, default: <execDir>/.${defaultConfig.name}
|
||||
--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
|
||||
--recreate Force recreation of the search database on start
|
||||
--unsafe-filter Use filter config at your own risk
|
||||
`
|
||||
);
|
||||
}
|
||||
|
||||
async function init() {
|
||||
argv = require('minimist')(process.argv.slice(2), {string: argvStrings});
|
||||
const dataDir = argv['app-dir'];
|
||||
const argvDataDir = argv['data-dir'] || argv['app-dir'];
|
||||
const configFile = argv['config'];
|
||||
|
||||
//config
|
||||
const configManager = new (require('./config'))();//singleton
|
||||
await configManager.init(dataDir);
|
||||
await configManager.init(argvDataDir, configFile);
|
||||
const defaultConfig = configManager.config;
|
||||
|
||||
await configManager.load();
|
||||
@@ -46,17 +50,22 @@ async function init() {
|
||||
branch = config.branch;
|
||||
|
||||
//dirs
|
||||
config.tempDir = `${config.dataDir}/tmp`;
|
||||
config.logDir = `${config.dataDir}/log`;
|
||||
config.dataDir = config.dataDir || argvDataDir || `${config.execDir}/.${config.name}`;
|
||||
config.tempDir = config.tempDir || `${config.dataDir}/tmp`;
|
||||
if (config.tempDir === '${OS}')
|
||||
config.tempDir = `${os.tmpdir()}/${config.name}`
|
||||
|
||||
config.logDir = config.logDir || `${config.dataDir}/log`;
|
||||
config.publicDir = `${config.dataDir}/public`;
|
||||
config.publicFilesDir = `${config.dataDir}/public-files`;
|
||||
config.filesPathStatic = `/book`;
|
||||
config.filesDir = `${config.publicFilesDir}${config.filesPathStatic}`;
|
||||
config.rootPathStatic = config.server.root || '';
|
||||
config.bookPathStatic = `${config.rootPathStatic}/book`;
|
||||
config.bookDir = `${config.publicFilesDir}/book`;
|
||||
|
||||
configManager.config = config;
|
||||
|
||||
await fs.ensureDir(config.dataDir);
|
||||
await fs.ensureDir(config.filesDir);
|
||||
await fs.ensureDir(config.bookDir);
|
||||
await fs.ensureDir(config.tempDir);
|
||||
await fs.emptyDir(config.tempDir);
|
||||
|
||||
@@ -83,7 +92,7 @@ async function init() {
|
||||
}
|
||||
|
||||
if (!config.remoteLib) {
|
||||
const libDir = argv['lib-dir'];
|
||||
const libDir = argv['lib-dir'] || config.libDir;
|
||||
if (libDir) {
|
||||
if (await fs.pathExists(libDir)) {
|
||||
config.libDir = libDir;
|
||||
@@ -94,11 +103,12 @@ async function init() {
|
||||
config.libDir = config.execDir;
|
||||
}
|
||||
|
||||
if (argv.inpx) {
|
||||
if (await fs.pathExists(argv.inpx)) {
|
||||
config.inpxFile = argv.inpx;
|
||||
const inpxFile = argv.inpx || config.inpx;
|
||||
if (inpxFile) {
|
||||
if (await fs.pathExists(inpxFile)) {
|
||||
config.inpxFile = inpxFile;
|
||||
} else {
|
||||
throw new Error(`File "${argv.inpx}" not found`);
|
||||
throw new Error(`File "${inpxFile}" not found`);
|
||||
}
|
||||
} else {
|
||||
const inpxFiles = [];
|
||||
@@ -125,14 +135,34 @@ async function init() {
|
||||
}
|
||||
|
||||
config.recreateDb = argv.recreate || false;
|
||||
config.inpxFilterFile = `${config.dataDir}/filter.json`;
|
||||
config.allowUnsafeFilter = argv['unsafe-filter'] || false;
|
||||
config.inpxFilterFile = config.inpxFilterFile || `${path.dirname(config.configFile)}/filter.json`;
|
||||
config.allowUnsafeFilter = argv['unsafe-filter'] || config.allowUnsafeFilter || false;
|
||||
|
||||
//web app
|
||||
if (branch !== 'development') {
|
||||
const createWebApp = require('./createWebApp');
|
||||
await createWebApp(config);
|
||||
}
|
||||
|
||||
//log dirs
|
||||
for (const prop of ['configFile', 'dataDir', 'tempDir', 'logDir']) {
|
||||
log(`${prop}: ${config[prop]}`);
|
||||
}
|
||||
|
||||
if (await fs.pathExists(config.inpxFilterFile))
|
||||
log(`inpxFilterFile: ${config.inpxFilterFile}`)
|
||||
}
|
||||
|
||||
function logQueries(app) {
|
||||
app.use(function(req, res, next) {
|
||||
const start = Date.now();
|
||||
log(`${req.method} ${req.originalUrl} ${utils.cutString(req.body)}`);
|
||||
//log(`${JSON.stringify(req.headers, null, 2)}`)
|
||||
res.once('finish', () => {
|
||||
log(`${Date.now() - start}ms`);
|
||||
});
|
||||
next();
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
@@ -156,10 +186,19 @@ async function main() {
|
||||
|
||||
const opds = require('./core/opds');
|
||||
opds(app, config);
|
||||
|
||||
const initStatic = require('./static');
|
||||
initStatic(app, config);
|
||||
|
||||
const webAccess = new (require('./core/WebAccess'))(config);
|
||||
await webAccess.init();
|
||||
|
||||
const { WebSocketController } = require('./controllers');
|
||||
new WebSocketController(wss, config);
|
||||
new WebSocketController(wss, webAccess, config);
|
||||
|
||||
if (config.logQueries) {
|
||||
logQueries(app);
|
||||
}
|
||||
|
||||
if (devModule) {
|
||||
devModule.logErrors(app);
|
||||
@@ -172,67 +211,10 @@ async function main() {
|
||||
|
||||
server.listen(config.server.port, config.server.host, () => {
|
||||
config.server.ready = true;
|
||||
log(`Server ready`);
|
||||
log(`Server accessible at http://127.0.0.1:${config.server.port} (listening on ${config.server.host}:${config.server.port})`);
|
||||
});
|
||||
}
|
||||
|
||||
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() => {
|
||||
try {
|
||||
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