13 Commits
1.0.0 ... 1.0.2

Author SHA1 Message Date
Book Pauk
420c0f2464 Merge branch 'release/1.0.2' 2022-10-16 00:16:14 +07:00
Book Pauk
7e86621fcd Мелкая поправка 2022-10-15 22:02:36 +07:00
Book Pauk
4ddabd1ca9 1.0.2 2022-10-15 22:02:22 +07:00
Book Pauk
061f50b714 Исправлена отдача статики под Windows 2022-10-15 21:51:45 +07:00
Book Pauk
8aab918ac5 Поправил баг 2022-10-15 21:04:56 +07:00
Book Pauk
9aa9261b6a Улучшение работы RemoteLib.downloadInpxFile 2022-10-15 20:59:42 +07:00
Book Pauk
0894a38978 Рефакторинг 2022-10-15 18:59:13 +07:00
Book Pauk
f519bf3f67 Добавлено пояснение в случае неуспешного копирования ссылки 2022-10-15 18:43:14 +07:00
Book Pauk
ecf0aada37 Merge tag '1.0.1' into develop
1.0.1
2022-10-14 21:18:04 +07:00
Book Pauk
eb9bf89854 Merge branch 'release/1.0.1' 2022-10-14 21:17:59 +07:00
Book Pauk
e1418678e0 1.0.1 2022-10-14 21:17:18 +07:00
Book Pauk
ecc7e2b2c3 Исправление багов 2022-10-14 21:16:26 +07:00
Book Pauk
7799bba9f2 Merge tag '1.0.0' into develop
1.0.0
2022-10-14 20:29:20 +07:00
11 changed files with 107 additions and 48 deletions

View File

@@ -842,10 +842,16 @@ class Search {
d.click();
} else if (action == 'copyLink') {
//копирование ссылки
if (utils.copyTextToClipboard(href))
if (await utils.copyTextToClipboard(href))
this.$root.notify.success('Ссылка успешно скопирована');
else
this.$root.notify.error('Копирование ссылки не удалось');
this.$root.stdDialog.alert(
`Копирование ссылки не удалось. Пожалуйста, попробуйте еще раз.
<br><br>
<b>Пояснение</b>: вероятно, браузер запретил копирование, т.к. прошло<br>
слишком много времени с момента нажатия на кнопку (инициация<br>
пользовательского события). Сейчас ссылка уже закеширована,<br>
поэтому повторная попытка должна быть успешной.`, 'Ошибка');
} else if (action == 'readBook') {
//читать
if (this.liberamaReady) {

View File

@@ -48,7 +48,29 @@ export function wordEnding(num, type = 0) {
}
}
export function fallbackCopyTextToClipboard(text) {
let textArea = document.createElement('textarea');
textArea.value = text;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
let result = false;
try {
result = document.execCommand('copy');
} catch (e) {
console.error(e);
}
document.body.removeChild(textArea);
return result;
}
export async function copyTextToClipboard(text) {
if (!navigator.clipboard) {
return fallbackCopyTextToClipboard(text);
}
let result = false;
try {
await navigator.clipboard.writeText(text);

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "inpx-web",
"version": "1.0.0",
"version": "1.0.2",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "inpx-web",
"version": "1.0.0",
"version": "1.0.2",
"hasInstallScript": true,
"license": "CC0-1.0",
"dependencies": {

View File

@@ -1,6 +1,6 @@
{
"name": "inpx-web",
"version": "1.0.0",
"version": "1.0.2",
"author": "Book Pauk <bookpauk@gmail.com>",
"license": "CC0-1.0",
"repository": "bookpauk/inpx-web",

View File

@@ -1,4 +1,3 @@
const fs = require('fs-extra');
const _ = require('lodash');
const WebSocket = require ('ws');
@@ -182,9 +181,9 @@ class WebSocketController {
if (!this.config.allowRemoteLib)
throw new Error('Remote lib access disabled');
const data = await fs.readFile(this.config.inpxFile, 'base64');
const result = await this.webWorker.getInpxFile(req);
this.send({data}, req, ws);
this.send(result, req, ws);
}
}

View File

@@ -9,10 +9,10 @@ class FileDownloader {
this.limitDownloadSize = limitDownloadSize;
}
async load(url, callback, abort) {
async load(url, opts, callback, abort) {
let errMes = '';
const options = {
let options = {
headers: {
'user-agent': userAgent,
timeout: 300*1000,
@@ -22,6 +22,8 @@ class FileDownloader {
}),
responseType: 'stream',
};
if (opts)
options = Object.assign({}, opts, options);
try {
const res = await axios.get(url, options);

View File

@@ -23,6 +23,14 @@ class InpxHashCreator {
return utils.getBufHash(joinedHash, 'sha256', 'hex');
}
async getInpxFileHash() {
return (
await fs.pathExists(this.config.inpxFile) ?
await utils.getFileHash(this.config.inpxFile, 'sha256', 'hex') :
''
);
}
}
module.exports = InpxHashCreator;

View File

@@ -4,6 +4,7 @@ const utils = require('./utils');
const FileDownloader = require('./FileDownloader');
const WebSocketConnection = require('./WebSocketConnection');
const InpxHashCreator = require('./InpxHashCreator');
const log = new (require('./AppLogger'))().log;//singleton
//singleton
@@ -20,10 +21,9 @@ class RemoteLib {
this.remoteHost = config.remoteLib.url.replace(/^ws:\/\//, 'http://').replace(/^wss:\/\//, 'https://');
this.inpxFile = `${config.tempDir}/${utils.randomHexString(20)}`;
this.lastUpdateTime = 0;
this.down = new FileDownloader(config.maxPayloadSize*1024*1024);
this.inpxHashCreator = new InpxHashCreator(config);
this.inpxFileHash = '';
instance = this;
}
@@ -46,17 +46,16 @@ class RemoteLib {
return response;
}
async downloadInpxFile(getPeriod = 0) {
if (getPeriod && Date.now() - this.lastUpdateTime < getPeriod)
return this.inpxFile;
async downloadInpxFile() {
if (!this.inpxFileHash)
this.inpxFileHash = await this.inpxHashCreator.getInpxFileHash();
const response = await this.wsRequest({action: 'get-inpx-file'});
const response = await this.wsRequest({action: 'get-inpx-file', inpxFileHash: this.inpxFileHash});
await fs.writeFile(this.inpxFile, response.data, 'base64');
this.lastUpdateTime = Date.now();
return this.inpxFile;
if (response.data) {
await fs.writeFile(this.config.inpxFile, response.data, 'base64');
this.inpxFileHash = '';
}
}
async downloadBook(bookPath, downFileName) {
@@ -64,9 +63,10 @@ class RemoteLib {
const response = await await this.wsRequest({action: 'get-book-link', bookPath, downFileName});
const link = response.link;
const buf = await this.down.load(`${this.remoteHost}${link}`);
const buf = await this.down.load(`${this.remoteHost}${link}`, {decompress: false});
const publicPath = `${this.config.publicDir}${link}`;
await fs.writeFile(publicPath, buf);
return path.basename(link);

View File

@@ -1,7 +1,6 @@
const os = require('os');
const path = require('path');
const fs = require('fs-extra');
const zlib = require('zlib');
const _ = require('lodash');
const ZipReader = require('./ZipReader');
@@ -44,6 +43,9 @@ class WebWorker {
this.remoteLib = new RemoteLib(config);
}
this.inpxHashCreator = new InpxHashCreator(config);
this.inpxFileHash = '';
this.wState = this.workerState.getControl('server_state');
this.myState = '';
this.db = null;
@@ -137,6 +139,8 @@ class WebWorker {
const config = this.config;
const dbPath = `${config.dataDir}/db`;
this.inpxFileHash = await this.inpxHashCreator.getInpxFileHash();
//пересоздаем БД из INPX если нужно
if (config.recreateDb || recreate)
await fs.remove(dbPath);
@@ -310,20 +314,6 @@ class WebWorker {
}
}
//async
gzipFile(inputFile, outputFile, level = 1) {
return new Promise((resolve, reject) => {
const gzip = zlib.createGzip({level});
const input = fs.createReadStream(inputFile);
const output = fs.createWriteStream(outputFile);
input.pipe(gzip).pipe(output).on('finish', (err) => {
if (err) reject(err);
else resolve();
});
});
}
async restoreBook(bookPath, downFileName) {
const db = this.db;
@@ -344,7 +334,7 @@ class WebWorker {
await fs.ensureDir(path.dirname(publicPath));
const tmpFile = `${this.config.tempDir}/${utils.randomHexString(30)}`;
await this.gzipFile(extractedFile, tmpFile, 4);
await utils.gzipFile(extractedFile, tmpFile, 4);
await fs.remove(extractedFile);
await fs.move(tmpFile, publicPath, {overwrite: true});
} else {
@@ -442,6 +432,18 @@ class WebWorker {
}
}
async getInpxFile(params) {
let data = null;
if (params.inpxFileHash && this.inpxFileHash && params.inpxFileHash === this.inpxFileHash) {
data = false;
}
if (data === null)
data = await fs.readFile(this.config.inpxFile, 'base64');
return {data};
}
logServerStats() {
try {
const memUsage = process.memoryUsage().rss/(1024*1024);//Mb
@@ -451,7 +453,7 @@ class WebWorker {
log(`Server info [ memUsage: ${memUsage.toFixed(2)}MB, loadAvg: (${loadAvg.join(', ')}) ]`);
if (this.config.server.ready)
log(`Server accessible on http://127.0.0.1:${this.config.server.port} (listening on ${this.config.server.host}:${this.config.server.port})`);
log(`Server accessible at http://127.0.0.1:${this.config.server.port} (listening on ${this.config.server.host}:${this.config.server.port})`);
} catch (e) {
log(LM_ERR, e.message);
}
@@ -531,18 +533,16 @@ class WebWorker {
if (!inpxCheckInterval)
return;
const inpxHashCreator = new InpxHashCreator(this.config);
while (1) {// eslint-disable-line no-constant-condition
try {
while (this.myState != ssNormal)
await utils.sleep(1000);
if (this.remoteLib) {
await this.remoteLib.downloadInpxFile(60*1000);
await this.remoteLib.downloadInpxFile();
}
const newInpxHash = await inpxHashCreator.getHash();
const newInpxHash = await this.inpxHashCreator.getHash();
const dbConfig = await this.dbConfig();
const currentInpxHash = (dbConfig.inpxHash ? dbConfig.inpxHash : '');

View File

@@ -1,5 +1,6 @@
const fs = require('fs-extra');
const path = require('path');
const zlib = require('zlib');
const crypto = require('crypto');
function sleep(ms) {
@@ -93,6 +94,24 @@ function randomHexString(len) {
return crypto.randomBytes(len).toString('hex')
}
//async
function gzipFile(inputFile, outputFile, level = 1) {
return new Promise((resolve, reject) => {
const gzip = zlib.createGzip({level});
const input = fs.createReadStream(inputFile);
const output = fs.createWriteStream(outputFile);
input.pipe(gzip).pipe(output).on('finish', (err) => {
if (err) reject(err);
else resolve();
});
});
}
function toUnixPath(dir) {
return dir.replace(/\\/g, '/');
}
module.exports = {
sleep,
versionText,
@@ -104,4 +123,6 @@ module.exports = {
getBufHash,
intersectSet,
randomHexString,
gzipFile,
toUnixPath,
};

View File

@@ -114,9 +114,10 @@ async function init() {
}
}
} else {
config.inpxFile = `${config.tempDir}/${utils.randomHexString(20)}`;
const RemoteLib = require('./core/RemoteLib');//singleton
const remoteLib = new RemoteLib(config);
config.inpxFile = await remoteLib.downloadInpxFile();
await remoteLib.downloadInpxFile();
}
config.recreateDb = argv.recreate || false;
@@ -207,10 +208,10 @@ function initStatic(app, config) {
const filesDir = `${config.publicDir}/files`;
app.use(express.static(config.publicDir, {
setHeaders: (res, filePath) => {
res.set('Cache-Control', 'no-cache');
res.set('Expires', '-1');
//res.set('Cache-Control', 'no-cache');
//res.set('Expires', '-1');
if (path.dirname(filePath) == filesDir) {
if (utils.toUnixPath(path.dirname(filePath)) == utils.toUnixPath(filesDir)) {
res.set('Content-Encoding', 'gzip');
if (res.downFileName)