diff --git a/client/api/reader.js b/client/api/reader.js
index 4e7a99da..b8081bd8 100644
--- a/client/api/reader.js
+++ b/client/api/reader.js
@@ -5,11 +5,11 @@ import {Buffer} from 'safe-buffer';
import * as utils from '../share/utils';
const api = axios.create({
- baseURL: '/api/reader'
+ baseURL: '/api/reader'
});
const workerApi = axios.create({
- baseURL: '/api/worker'
+ baseURL: '/api/worker'
});
class Reader {
diff --git a/client/components/Reader/HelpPage/DonateHelpPage/DonateHelpPage.vue b/client/components/Reader/HelpPage/DonateHelpPage/DonateHelpPage.vue
index 9b7bdc14..637ce6e7 100644
--- a/client/components/Reader/HelpPage/DonateHelpPage/DonateHelpPage.vue
+++ b/client/components/Reader/HelpPage/DonateHelpPage/DonateHelpPage.vue
@@ -53,11 +53,10 @@ class DonateHelpPage extends Vue {
async copyAddress(address, prefix) {
const result = await copyTextToClipboard(address);
- const msg = (result ? `${prefix}-адрес ${address} успешно скопирован в буфер обмена` : 'Копирование не удалось');
if (result)
- this.$notify.success({message: msg});
+ this.$notify.success({message: `${prefix}-адрес ${address} успешно скопирован в буфер обмена`});
else
- this.$notify.error({message: msg});
+ this.$notify.error({message: 'Копирование не удалось'});
}
}
//-----------------------------------------------------------------------------
diff --git a/client/components/Reader/HelpPage/HelpPage.vue b/client/components/Reader/HelpPage/HelpPage.vue
index e3273813..98d6aafb 100644
--- a/client/components/Reader/HelpPage/HelpPage.vue
+++ b/client/components/Reader/HelpPage/HelpPage.vue
@@ -16,6 +16,9 @@
+
+
+
@@ -36,6 +39,7 @@ import CommonHelpPage from './CommonHelpPage/CommonHelpPage.vue';
import HotkeysHelpPage from './HotkeysHelpPage/HotkeysHelpPage.vue';
import MouseHelpPage from './MouseHelpPage/MouseHelpPage.vue';
import DonateHelpPage from './DonateHelpPage/DonateHelpPage.vue';
+import VersionHistoryPage from './VersionHistoryPage/VersionHistoryPage.vue';
export default @Component({
components: {
@@ -44,6 +48,7 @@ export default @Component({
HotkeysHelpPage,
MouseHelpPage,
DonateHelpPage,
+ VersionHistoryPage,
},
})
class HelpPage extends Vue {
@@ -57,6 +62,10 @@ class HelpPage extends Vue {
this.selectedTab = 'donate';
}
+ activateVersionHistoryHelpPage() {
+ this.selectedTab = 'releases';
+ }
+
keyHook(event) {
if (event.type == 'keydown' && (event.code == 'Escape')) {
this.close();
diff --git a/client/components/Reader/HelpPage/VersionHistoryPage/VersionHistoryPage.vue b/client/components/Reader/HelpPage/VersionHistoryPage/VersionHistoryPage.vue
new file mode 100644
index 00000000..3b42f24e
--- /dev/null
+++ b/client/components/Reader/HelpPage/VersionHistoryPage/VersionHistoryPage.vue
@@ -0,0 +1,81 @@
+
+
+
+
+ {{ item }}
+
+
+
+
+
История версий:
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/client/components/Reader/LoaderPage/LoaderPage.vue b/client/components/Reader/LoaderPage/LoaderPage.vue
index 3f2bedfb..160d792c 100644
--- a/client/components/Reader/LoaderPage/LoaderPage.vue
+++ b/client/components/Reader/LoaderPage/LoaderPage.vue
@@ -18,6 +18,10 @@
Загрузить файл с диска
+
+ Из буфера обмена
+
+
Комментарии
@@ -26,6 +30,8 @@
Помочь проекту
{{ version }}
+
+
@@ -33,12 +39,17 @@
//-----------------------------------------------------------------------------
import Vue from 'vue';
import Component from 'vue-class-component';
+import PasteTextPage from './PasteTextPage/PasteTextPage.vue';
export default @Component({
+ components: {
+ PasteTextPage,
+ },
})
class LoaderPage extends Vue {
bookUrl = null;
loadPercent = 0;
+ pasteTextActive = false;
created() {
this.commit = this.$store.commit;
@@ -83,12 +94,27 @@ class LoaderPage extends Vue {
}
loadFile() {
- const file = this.$refs.file.files[0];
+ const file = this.$refs.file.files[0];
this.$refs.file.value = '';
if (file)
this.$emit('load-file', {file});
}
+ loadBufferClick() {
+ this.pasteTextToggle();
+ }
+
+ loadBuffer(opts) {
+ if (opts.buffer.length) {
+ const file = new File([opts.buffer], 'dummyName-PasteFromClipboard');
+ this.$emit('load-file', {file});
+ }
+ }
+
+ pasteTextToggle() {
+ this.pasteTextActive = !this.pasteTextActive;
+ }
+
openHelp() {
this.$emit('help-toggle');
}
@@ -102,6 +128,10 @@ class LoaderPage extends Vue {
}
keyHook(event) {
+ if (this.pasteTextActive) {
+ return this.$refs.pasteTextPage.keyHook(event);
+ }
+
//недостатки сторонних ui
const input = this.$refs.input.$refs.input;
if (document.activeElement === input && event.type == 'keydown' && event.code == 'Enter') {
diff --git a/client/components/Reader/LoaderPage/PasteTextPage/PasteTextPage.vue b/client/components/Reader/LoaderPage/PasteTextPage/PasteTextPage.vue
new file mode 100644
index 00000000..b17fcd05
--- /dev/null
+++ b/client/components/Reader/LoaderPage/PasteTextPage/PasteTextPage.vue
@@ -0,0 +1,133 @@
+
+
+
+
+
+ Вставьте текст и нажмите
+ Загрузить
+
+ или F2
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/client/components/Reader/Reader.vue b/client/components/Reader/Reader.vue
index bbef9b77..b0caaf99 100644
--- a/client/components/Reader/Reader.vue
+++ b/client/components/Reader/Reader.vue
@@ -7,35 +7,35 @@
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
@@ -68,13 +68,27 @@
@start-text-search="startTextSearch"
@stop-text-search="stopTextSearch">
-
+
+
+
+
+
+ Посмотреть историю версий
+
+
+
+
@@ -101,6 +115,7 @@ import ServerStorage from './ServerStorage/ServerStorage.vue';
import bookManager from './share/bookManager';
import readerApi from '../../api/reader';
import * as utils from '../../share/utils';
+import {versionHistory} from './versionHistory';
export default @Component({
components: {
@@ -167,11 +182,15 @@ class Reader extends Vue {
allowUrlParamBookPos = false;
showRefreshIcon = true;
mostRecentBookReactive = null;
+ showToolButton = {};
actionList = [];
actionCur = -1;
hidden = false;
+ whatsNewVisible = false;
+ whatsNewContent = '';
+
created() {
this.loading = true;
this.commit = this.$store.commit;
@@ -223,14 +242,17 @@ class Reader extends Vue {
if (this.$root.rootRoute == '/reader') {
if (this.routeParamUrl) {
- await this.loadBook({url: this.routeParamUrl, bookPos: this.routeParamPos});
+ await this.loadBook({url: this.routeParamUrl, bookPos: this.routeParamPos, force: this.routeParamRefresh});
} else {
this.loaderActive = true;
}
}
this.checkSetStorageAccessKey();
+ this.checkActivateDonateHelpPage();
this.loading = false;
+
+ await this.showWhatsNew();
})();
}
@@ -241,6 +263,8 @@ class Reader extends Vue {
this.showClickMapPage = settings.showClickMapPage;
this.clickControl = settings.clickControl;
this.blinkCachedLoad = settings.blinkCachedLoad;
+ this.showWhatsNewDialog = settings.showWhatsNewDialog;
+ this.showToolButton = settings.showToolButton;
}
checkSetStorageAccessKey() {
@@ -257,6 +281,56 @@ class Reader extends Vue {
}
}
+ checkActivateDonateHelpPage() {
+ const q = this.$route.query;
+
+ if (q['donate']) {
+ this.$router.replace(`/reader`);
+ this.helpToggle();
+ this.$nextTick(() => {
+ this.$refs.helpPage.activateDonateHelpPage();
+ });
+ }
+ }
+
+ checkBookPosPercent() {
+ const q = this.$route.query;
+ if (q['__pp']) {
+ let pp = q['__pp'];
+ if (pp) {
+ pp = parseFloat(pp) || 0;
+ const recent = this.mostRecentBook();
+ (async() => {
+ await utils.sleep(100);
+ this.bookPos = Math.floor(recent.textLength*pp/100);
+ })();
+ }
+ }
+ }
+
+ async showWhatsNew() {
+ await utils.sleep(2000);
+
+ const whatsNew = versionHistory[0];
+ if (this.showWhatsNewDialog &&
+ whatsNew.showUntil >= utils.formatDate(new Date(), 'coDate') &&
+ whatsNew.header != this.whatsNewContentHash) {
+ this.whatsNewContent = 'Версия ' + whatsNew.header + whatsNew.content;
+ this.whatsNewVisible = true;
+ }
+ }
+
+ openVersionHistory() {
+ this.whatsNewVisible = false;
+ this.versionHistoryToggle();
+ }
+
+ whatsNewDisable() {
+ this.whatsNewVisible = false;
+ const whatsNew = versionHistory[0];
+ this.commit('reader/setWhatsNewContentHash', whatsNew.header);
+ }
+
get routeParamPos() {
let result = undefined;
const q = this.$route.query;
@@ -293,6 +367,11 @@ class Reader extends Vue {
return decodeURIComponent(result);
}
+ get routeParamRefresh() {
+ const q = this.$route.query;
+ return !!q['__refresh'];
+ }
+
bookPosChanged(event) {
if (event.bookPosSeen !== undefined)
this.bookPosSeen = event.bookPosSeen;
@@ -353,6 +432,10 @@ class Reader extends Vue {
return this.$store.state.reader.settings;
}
+ get whatsNewContentHash() {
+ return this.$store.state.reader.whatsNewContentHash;
+ }
+
addAction(pos) {
let a = this.actionList;
if (!a.length || a[a.length - 1] != pos) {
@@ -523,6 +606,15 @@ class Reader extends Vue {
}
}
+ versionHistoryToggle() {
+ this.helpToggle();
+ if (this.helpActive) {
+ this.$nextTick(() => {
+ this.$refs.helpPage.activateVersionHistoryHelpPage();
+ });
+ }
+ }
+
refreshBook() {
if (this.mostRecentBook()) {
this.loadBook({url: this.mostRecentBook().url, force: true});
@@ -708,7 +800,7 @@ class Reader extends Vue {
this.progressActive = true;
- await this.$nextTick()
+ await this.$nextTick();
const progress = this.$refs.page;
@@ -743,6 +835,7 @@ class Reader extends Vue {
progress.hide(); this.progressActive = false;
this.blinkCachedLoadMessage();
+ this.checkBookPosPercent();
await this.activateClickMapPage();
return;
}
@@ -791,6 +884,7 @@ class Reader extends Vue {
} else
this.stopBlink = true;
+ this.checkBookPosPercent();
await this.activateClickMapPage();
} catch (e) {
progress.hide(); this.progressActive = false;
@@ -1010,4 +1104,10 @@ i {
.clear {
color: rgba(0,0,0,0);
}
-
\ No newline at end of file
+
+.clickable {
+ color: blue;
+ text-decoration: underline;
+ cursor: pointer;
+}
+
diff --git a/client/components/Reader/SettingsPage/SettingsPage.vue b/client/components/Reader/SettingsPage/SettingsPage.vue
index 67ee8932..a2d3af99 100644
--- a/client/components/Reader/SettingsPage/SettingsPage.vue
+++ b/client/components/Reader/SettingsPage/SettingsPage.vue
@@ -106,6 +106,7 @@
+
@@ -345,6 +346,28 @@
+
+
+
+
+
+
+ {{item.text}}
+
+
+
+
+
+
+
+
+
+
+ Включить управление кликом
+
+
+
+
@@ -380,14 +403,12 @@
-
+
-
- Включить управление кликом
-
+
@@ -406,7 +427,7 @@
Предупреждать о загрузке из кэша
-
+
Показывать уведомления и ошибки от
@@ -415,8 +436,21 @@
Показывать сообщения синхронизации
+
+
+
+ Показывать уведомления "Что нового"
+ при каждом выходе новой версии читалки
+
+ Показывать уведомление "Что нового"
+
+
+
-
+
+
+
+
Добавление параметра "__p" в строке браузера
@@ -450,6 +484,7 @@
+
Установить по умолчанию
@@ -517,12 +552,14 @@ class SettingsPage extends Vue {
fonts = [];
serverStorageKeyVisible = false;
+ toolButtons = [];
created() {
this.commit = this.$store.commit;
this.reader = this.$store.state.reader;
this.form = {};
+ this.toolButtons = rstore.toolButtons;
this.settingsChanged();
}
@@ -536,6 +573,7 @@ class SettingsPage extends Vue {
this.form = Object.assign({}, this.form, {[prop]: newValue});
});
}
+
this.fontBold = (this.fontWeight == 'bold');
this.fontItalic = (this.fontStyle == 'italic');
@@ -642,6 +680,10 @@ class SettingsPage extends Vue {
}
}
+ changeShowToolButton(buttonName) {
+ this.showToolButton = Object.assign({}, this.showToolButton, {[buttonName]: !this.showToolButton[buttonName]});
+ }
+
async addProfile() {
try {
if (Object.keys(this.profiles).length >= 100) {
diff --git a/client/components/Reader/TextPage/TextPage.vue b/client/components/Reader/TextPage/TextPage.vue
index 7593113c..10a73e6b 100644
--- a/client/components/Reader/TextPage/TextPage.vue
+++ b/client/components/Reader/TextPage/TextPage.vue
@@ -171,6 +171,13 @@ class TextPage extends Vue {
this.fontShift = this.fontVertShift/100;
this.textShift = this.textVertShift/100 + this.fontShift;
+ //statusBar
+ this.$refs.statusBar.style.left = '0px';
+ this.$refs.statusBar.style.top = (this.statusBarTop ? 1 : this.realHeight - this.statusBarHeight) + 'px';
+
+ this.statusBarColor = this.hex2rgba(this.textColor || '#000000', this.statusBarColorAlpha);
+ this.statusBarClickable = this.drawHelper.statusBarClickable(this.statusBarTop, this.statusBarHeight);
+
//drawHelper
this.drawHelper.realWidth = this.realWidth;
this.drawHelper.realHeight = this.realHeight;
@@ -197,13 +204,19 @@ class TextPage extends Vue {
this.drawHelper.context = this.context;
//сообщение "Загрузка шрифтов..."
- const flText = 'Загрузка шрифта...';
- this.$refs.fontsLoading.innerHTML = flText;
- const fontsLoadingStyle = this.$refs.fontsLoading.style;
- fontsLoadingStyle.position = 'absolute';
- fontsLoadingStyle.fontSize = this.fontSize + 'px';
- fontsLoadingStyle.top = (this.realHeight/2 - 2*this.fontSize) + 'px';
- fontsLoadingStyle.left = (this.realWidth - this.drawHelper.measureText(flText, {}))/2 + 'px';
+ this.$refs.fontsLoading.innerHTML = '';
+ (async() => {
+ await sleep(500);
+ const flText = 'Загрузка шрифта';
+ this.$refs.fontsLoading.innerHTML = flText + ' ';
+ const fontsLoadingStyle = this.$refs.fontsLoading.style;
+ fontsLoadingStyle.position = 'absolute';
+ fontsLoadingStyle.fontSize = this.fontSize + 'px';
+ fontsLoadingStyle.top = (this.realHeight/2 - 2*this.fontSize) + 'px';
+ fontsLoadingStyle.left = (this.realWidth - this.drawHelper.measureText(flText, {}))/2 + 'px';
+ await sleep(10500);
+ this.$refs.fontsLoading.innerHTML = '';
+ })();
//parsed
if (this.parsed) {
@@ -225,13 +238,6 @@ class TextPage extends Vue {
this.parsed.imageFitWidth = this.imageFitWidth;
}
- //statusBar
- this.$refs.statusBar.style.left = '0px';
- this.$refs.statusBar.style.top = (this.statusBarTop ? 1 : this.realHeight - this.statusBarHeight) + 'px';
-
- this.statusBarColor = this.hex2rgba(this.textColor || '#000000', this.statusBarColorAlpha);
- this.statusBarClickable = this.drawHelper.statusBarClickable(this.statusBarTop, this.statusBarHeight);
-
//scrolling page
const pageSpace = this.scrollHeight - this.pageLineCount*this.lineHeight;
let y = pageSpace/2;
diff --git a/client/components/Reader/versionHistory.js b/client/components/Reader/versionHistory.js
new file mode 100644
index 00000000..6f8b0206
--- /dev/null
+++ b/client/components/Reader/versionHistory.js
@@ -0,0 +1,97 @@
+export const versionHistory = [
+{
+ showUntil: '2019-06-05',
+ header: '0.6.7 (2019-05-30)',
+ content:
+`
+
+ - добавлен диалог "Что нового"
+ - в справку добавлена история версий проекта
+ - добавлена возможность настройки отображаемых кнопок на панели управления
+ - некоторые кнопки на панели управления были скрыты по умолчанию
+ - на страницу загрузки добавлена возможность загрузки книги из буфера обмена
+ - добавлен GET-параметр вида "/reader?__refresh=1&url=..." для принудительного обновления загружаемого текста
+ - добавлен GET-параметр вида "/reader?__pp=50.5&url=..." для указания позиции в книге в процентах
+ - исправления багов и недочетов
+
+`
+},
+
+{
+ showUntil: '2019-03-29',
+ header: '0.6.6 (2019-03-29)',
+ content:
+`
+
+ - в справку добавлено описание настройки браузеров для автономной работы читалки (без доступа к интернету)
+ - оптимизации процесса синхронизации, внутренние переделки
+
+`
+},
+
+{
+ showUntil: '2019-03-24',
+ header: '0.6.4 (2019-03-24)',
+ content:
+`
+
+ - исправления багов, оптимизации
+ - добавлена возможность синхронизации данных между устройствами
+
+`
+},
+
+{
+ showUntil: '2019-03-04',
+ header: '0.5.4 (2019-03-04)',
+ content:
+`
+
+ - добавлена поддержка форматов pdf, epub, mobi
+ - (0.5.2) добавлена поддержка форматов rtf, doc, docx
+ - (0.4.2) фильтр для СИ больше не вырезает изображения
+ - (0.4.0) добавлено отображение картинок в fb2
+
+`
+},
+
+{
+ showUntil: '2019-02-17',
+ header: '0.3.0 (2019-02-17)',
+ content:
+`
+
+ - поправки багов
+ - улучшено распознавание текста
+ - изменена верстка страницы - убрано позиционирование каждого слова
+
+`
+},
+
+{
+ showUntil: '2019-02-14',
+ header: '0.1.7 (2019-02-14)',
+ content:
+`
+
+ - увеличены верхние границы отступов и др.размеров
+ - добавлена настройка для удаления/вставки пустых параграфов
+ - добавлена настройка включения/отключения управления кликом
+ - добавлена возможность сброса настроек
+ - убран автоматический редирект на последнюю загруженную книгу, если не задан url в маршруте
+
+`
+},
+
+{
+ showUntil: '2019-02-12',
+ header: '0.1.0 (2019-02-12)',
+ content:
+`
+
+ - первый деплой проекта, длительность разработки - 2 месяца
+
+`
+},
+
+]
\ No newline at end of file
diff --git a/client/element.js b/client/element.js
index 02aeb0fb..0e489f93 100644
--- a/client/element.js
+++ b/client/element.js
@@ -86,8 +86,8 @@ import './theme/form-item.css';
import ElColorPicker from 'element-ui/lib/color-picker';
import './theme/color-picker.css';
-//import ElDialog from 'element-ui/lib/dialog';
-//import './theme/dialog.css';
+import ElDialog from 'element-ui/lib/dialog';
+import './theme/dialog.css';
import Notification from 'element-ui/lib/notification';
import './theme/notification.css';
@@ -106,7 +106,7 @@ const components = {
ElCol, ElContainer, ElAside, ElMain, ElHeader,
ElInput, ElInputNumber, ElSelect, ElOption, ElTable, ElTableColumn,
ElProgress, ElSlider, ElForm, ElFormItem,
- ElColorPicker,
+ ElColorPicker, ElDialog,
};
for (let name in components) {
diff --git a/client/share/utils.js b/client/share/utils.js
index ba3d3d26..612610ce 100644
--- a/client/share/utils.js
+++ b/client/share/utils.js
@@ -39,6 +39,8 @@ export function formatDate(d, 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')}`;
}
}
diff --git a/client/store/modules/reader.js b/client/store/modules/reader.js
index 09fb4913..92933c10 100644
--- a/client/store/modules/reader.js
+++ b/client/store/modules/reader.js
@@ -1,3 +1,16 @@
+//занчение toolButtons.name не должно совпадать с settingDefaults-propertyName
+const toolButtons = [
+ {name: 'undoAction', show: true, text: 'Действие назад'},
+ {name: 'redoAction', show: true, text: 'Действие вперед'},
+ {name: 'fullScreen', show: true, text: 'На весь экран'},
+ {name: 'scrolling', show: false, text: 'Плавный скроллинг'},
+ {name: 'setPosition', show: true, text: 'На страницу'},
+ {name: 'search', show: true, text: 'Найти в тексте'},
+ {name: 'copyText', show: false, text: 'Скопировать текст со страницы'},
+ {name: 'refresh', show: true, text: 'Принудительно обновить книгу'},
+ {name: 'history', show: true, text: 'Открыть недавние'},
+];
+
const fonts = [
{name: 'ReaderDefault', label: 'По-умолчанию', fontVertShift: 0},
{name: 'GEO_1', label: 'BPG Arial', fontVertShift: 10},
@@ -166,14 +179,18 @@ const settingDefaults = {
imageHeightLines: 100,
imageFitWidth: true,
showServerStorageMessages: true,
+ showWhatsNewDialog: true,
fontShifts: {},
+ showToolButton: {},
};
for (const font of fonts)
settingDefaults.fontShifts[font.name] = font.fontVertShift;
for (const font of webFonts)
settingDefaults.fontShifts[font.name] = font.fontVertShift;
+for (const button of toolButtons)
+ settingDefaults.showToolButton[button.name] = button.show;
// initial state
const state = {
@@ -183,6 +200,7 @@ const state = {
profiles: {},
profilesRev: 0,
allowProfilesSave: false,//подстраховка для разработки
+ whatsNewContentHash: '',
currentProfile: '',
settings: Object.assign({}, settingDefaults),
settingsRev: {},
@@ -214,6 +232,9 @@ const mutations = {
setAllowProfilesSave(state, value) {
state.allowProfilesSave = value;
},
+ setWhatsNewContentHash(state, value) {
+ state.whatsNewContentHash = value;
+ },
setCurrentProfile(state, value) {
state.currentProfile = value;
},
@@ -226,6 +247,7 @@ const mutations = {
};
export default {
+ toolButtons,
fonts,
webFonts,
settingDefaults,
diff --git a/package.json b/package.json
index 83774c3d..4b7a4ff6 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "Liberama",
- "version": "0.6.6",
+ "version": "0.6.7",
"engines": {
"node": ">=10.0.0"
},
diff --git a/server/core/ReaderWorker.js b/server/core/ReaderWorker.js
index 46b758f3..1921fcef 100644
--- a/server/core/ReaderWorker.js
+++ b/server/core/ReaderWorker.js
@@ -131,32 +131,34 @@ class ReaderWorker {
return `file://${hash}`;
}
- async periodicCleanDir(dir, maxSize, timeout) {
- const list = await fs.readdir(dir);
+ async periodicCleanDir(dir, maxSize, timeout) {
+ try {
+ const list = await fs.readdir(dir);
- let size = 0;
- let files = [];
- for (const name of list) {
- const stat = await fs.stat(`${dir}/${name}`);
- if (!stat.isDirectory()) {
- size += stat.size;
- files.push({name, stat});
+ let size = 0;
+ let files = [];
+ for (const name of list) {
+ const stat = await fs.stat(`${dir}/${name}`);
+ if (!stat.isDirectory()) {
+ size += stat.size;
+ files.push({name, stat});
+ }
}
+
+ files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
+
+ let i = 0;
+ while (i < files.length && size > maxSize) {
+ const file = files[i];
+ await fs.remove(`${dir}/${file.name}`);
+ size -= file.stat.size;
+ i++;
+ }
+ } finally {
+ setTimeout(() => {
+ this.periodicCleanDir(dir, maxSize, timeout);
+ }, timeout);
}
-
- files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
-
- let i = 0;
- while (i < files.length && size > maxSize) {
- const file = files[i];
- await fs.remove(`${dir}/${file.name}`);
- size -= file.stat.size;
- i++;
- }
-
- setTimeout(() => {
- this.periodicCleanDir(dir, maxSize, timeout);
- }, timeout);
}
}