Улучшено скачивание файлов - добавлено читабельное имя файла

This commit is contained in:
Book Pauk
2022-09-26 16:04:26 +07:00
parent 92303cadc3
commit afef0ed04c
6 changed files with 87 additions and 21 deletions

View File

@@ -124,9 +124,9 @@ class Api {
}
}
async request(params) {
async request(params, timeoutSecs = 10) {
while (1) {// eslint-disable-line
const response = await wsc.message(await wsc.send(params));
const response = await wsc.message(await wsc.send(params), timeoutSecs);
if (response && response.error == 'server_busy') {
await this.showBusyDialog();
@@ -166,8 +166,8 @@ class Api {
return response;
}
async getBookLink(bookPath) {
const response = await this.request({action: 'get-book-link', bookPath});
async getBookLink(params) {
const response = await this.request(Object.assign({action: 'get-book-link'}, params), 120);
if (response.error) {
throw new Error(response.error);

View File

@@ -555,26 +555,51 @@ class Search {
}
async download(book, copy = false) {
let downloadFlag = true;
if (this.downloadFlag)
return;
this.downloadFlag = true;
(async() => {
await utils.sleep(200);
if (downloadFlag)
if (this.downloadFlag)
this.loadingMessage2 = 'Подготовка файла...';
})();
try {
const bookPath = `${book.folder}/${book.file}.${book.ext}`;
try {
const makeValidFilenameOrEmpty = (s) => {
try {
return utils.makeValidFilename(s);
} catch(e) {
return '';
}
};
const response = await this.api.getBookLink(bookPath);
//имя файла
let downFileName = 'default-name';
const author = book.author.split(',');
const at = [author[0], book.title];
downFileName = makeValidFilenameOrEmpty(at.filter(r => r).join(' - '))
|| makeValidFilenameOrEmpty(at[0])
|| makeValidFilenameOrEmpty(at[1])
|| downFileName;
downFileName = `${downFileName.substring(0, 100)}.${book.ext}`;
const bookPath = `${book.folder}/${book.file}.${book.ext}`;
//подготовка
const response = await this.api.getBookLink({bookPath, downFileName});
const href = `${window.location.origin}${response.link}`;
const link = response.link;
const href = `${window.location.origin}${link}`;
if (!copy) {
//скачивание
const d = this.$refs.download;
d.href = href;
d.download = downFileName;
d.click();
} else {
//копирование ссылки
if (utils.copyTextToClipboard(href))
this.$root.notify.success('Ссылка успешно скопирована');
else
@@ -583,7 +608,7 @@ class Search {
} catch(e) {
this.$root.stdDialog.alert(e.message, 'Ошибка');
} finally {
downloadFlag = false;
this.downloadFlag = false;
this.loadingMessage2 = '';
}
}

View File

@@ -54,3 +54,16 @@ export async function copyTextToClipboard(text) {
return result;
}
export function makeValidFilename(filename, repl = '_') {
let f = filename.replace(/[\x00\\/:*"<>|]/g, repl); // eslint-disable-line no-control-regex
f = f.trim();
while (f.length && (f[f.length - 1] == '.' || f[f.length - 1] == '_')) {
f = f.substring(0, f.length - 1);
}
if (f)
return f;
else
throw new Error('Invalid filename');
}