Compare commits

...

86 Commits
0.1.0 ... 0.3.0

Author SHA1 Message Date
Book Pauk
8ddd2d6290 Merge branch 'release/0.3.0' 2019-02-17 20:16:11 +07:00
Book Pauk
f6c8666f06 Версия 0.3.0 2019-02-17 20:15:50 +07:00
Book Pauk
1bf173fcae Поправка бага 2019-02-17 20:10:25 +07:00
Book Pauk
696866f065 Merge branch 'feature/draw-page' into develop 2019-02-17 20:08:06 +07:00
Book Pauk
c82283c7f0 Поправка дефолтов 2019-02-17 20:04:28 +07:00
Book Pauk
0e62f25557 Переделки отображения needle при поиске 2019-02-17 20:02:18 +07:00
Book Pauk
e2c51f44bf Изменение drawPage - теперь не позиционирует каждое слово отдельно,
вместо этого используются возможности CSS
2019-02-17 19:35:32 +07:00
Book Pauk
d4768392a6 Мелкая поправка 2019-02-17 19:32:30 +07:00
Book Pauk
580744819d Поправил настройки по-умолчанию 2019-02-17 19:31:50 +07:00
Book Pauk
959794de10 Merge tag '0.2.2' into develop
0.2.2
2019-02-17 14:59:34 +07:00
Book Pauk
3a32c09feb Merge branch 'release/0.2.2' 2019-02-17 14:59:14 +07:00
Book Pauk
09bfce4590 Версия 0.2.2 2019-02-17 14:58:37 +07:00
Book Pauk
092697a4b2 Поправил бажок 2019-02-17 14:55:01 +07:00
Book Pauk
a36de9424e Улучшил распарсивание текста 2019-02-17 14:46:52 +07:00
Book Pauk
db4bc2afb2 Улучшена эвристика определения текста 2019-02-17 14:27:49 +07:00
Book Pauk
73bfc07082 Увеличил количество хранимых недавних до 1000 2019-02-17 13:57:12 +07:00
Book Pauk
b3cf88aac3 Поправил бажок 2019-02-17 13:33:49 +07:00
Book Pauk
69bcc61a01 Включаем yandex-метрику только на production 2019-02-17 13:30:08 +07:00
Book Pauk
bdc124052c Merge tag '0.2.1' into develop
0.2.1
2019-02-16 03:38:38 +07:00
Book Pauk
cfcee9eb99 Merge branch 'hotfix/0.2.1' 2019-02-16 03:38:24 +07:00
Book Pauk
e93c873c17 Поправил названия в списке 2019-02-16 03:37:51 +07:00
Book Pauk
2b1bb6a299 Merge tag '0.2.0' into develop
0.2.0
2019-02-16 03:20:51 +07:00
Book Pauk
3d7c039fd4 Merge branch 'release/0.2.0' 2019-02-16 03:20:41 +07:00
Book Pauk
9971f1d4bf 0.2.0 2019-02-16 03:20:22 +07:00
Book Pauk
59702d3d50 Добавлена анимация перелистывания - слева-направо, снизу-вверх 2019-02-16 02:59:13 +07:00
Book Pauk
736e6ec075 Рефакторинг 2019-02-16 00:58:28 +07:00
Book Pauk
abdd6d4142 Рефакторинг 2019-02-15 23:22:36 +07:00
Book Pauk
16edc85e39 Добавлен эффект перелистывания - Мерцание 2019-02-15 22:57:29 +07:00
Book Pauk
bbeb92a9da Мелкие доработки 2019-02-15 21:41:45 +07:00
Book Pauk
daaf9ac70b Добавлен эффект листания - Протаивание 2019-02-15 21:36:06 +07:00
Book Pauk
0805353a9e Начало работы над анимацией перелистывания 2019-02-15 19:20:50 +07:00
Book Pauk
594ff954b1 Рефакторинг 2019-02-15 19:03:05 +07:00
Book Pauk
cf5203687e Добавил зеркало 'zhurnal.lib.ru' для парсинга samlib 2019-02-15 18:22:54 +07:00
Book Pauk
55ad2d664d Улчшение парсинга samlib 2019-02-15 18:21:37 +07:00
Book Pauk
4d1485a61f Мелкая поправка 2019-02-15 18:20:29 +07:00
Book Pauk
f260378c93 Мелкая поправка 2019-02-15 03:00:16 +07:00
Book Pauk
08f9175705 Мелкие поправки 2019-02-15 02:56:58 +07:00
Book Pauk
ca7cc322d7 Добавил настройку blinkCachedLoad 2019-02-15 02:46:27 +07:00
Book Pauk
a631befdf9 Добавил инфо для поисковиков 2019-02-14 23:40:51 +07:00
Book Pauk
b7875644bc Merge tag '0.1.7' into develop
0.1.7
2019-02-14 21:52:57 +07:00
Book Pauk
9d8507a1e4 Merge branch 'hotfix/0.1.7' 2019-02-14 21:52:41 +07:00
Book Pauk
50042aa36d Убрал редирект на последнюю открытую книгу, если не задан явно url 2019-02-14 21:51:22 +07:00
Book Pauk
d21cf6286a Merge tag '0.1.6' into develop
0.1.6
2019-02-14 19:00:15 +07:00
Book Pauk
b0709abfa2 Merge branch 'hotfix/0.1.6' 2019-02-14 19:00:02 +07:00
Book Pauk
dedb729dfe Увеличил верхние границы отступов, добавил возможность сброса настроек 2019-02-14 18:59:20 +07:00
Book Pauk
27e2f26d5d Merge tag '0.1.5' into develop
0.1.5
2019-02-14 18:27:46 +07:00
Book Pauk
ae30c3865d Merge branch 'release/0.1.5' 2019-02-14 18:27:39 +07:00
Book Pauk
b3453af0fe Версия 0.1.5 2019-02-14 18:27:20 +07:00
Book Pauk
550dcbc081 Добавлена настройка addEmptyParagraphs 2019-02-14 18:25:18 +07:00
Book Pauk
5af1f81bc3 Добавил настройку cutEmptyParagraphs 2019-02-14 17:34:52 +07:00
Book Pauk
d306f972cc Добавил настройку clickControl 2019-02-14 17:10:14 +07:00
Book Pauk
0f6747f2db Увеличил граничные значения сверху 2019-02-14 16:33:47 +07:00
Book Pauk
559b96d56f Добавил реакцию на нажатие "R", мелкий рефакторинг 2019-02-13 18:30:48 +07:00
Book Pauk
69606429b8 Merge tag '0.1.4' into develop
0.1.4
2019-02-13 18:05:27 +07:00
Book Pauk
824fe68194 Merge branch 'release/0.1.4' 2019-02-13 18:05:16 +07:00
Book Pauk
b056feda59 Версия 0.1.4 2019-02-13 18:04:54 +07:00
Book Pauk
32635dedb0 Добавил сохранение нужных настроек 2019-02-13 18:02:08 +07:00
Book Pauk
835f9374f6 Добавил использование на клиенте настройки maxUploadFileSize 2019-02-13 17:58:44 +07:00
Book Pauk
edece5e17f Вынес ограничения размеров файлов и директорий в настройки 2019-02-13 17:54:41 +07:00
Book Pauk
298317d352 Подправил дефолтный конфиг 2019-02-13 17:45:22 +07:00
Book Pauk
c7637eb941 Добавил сохранение и загрузку конфига 2019-02-13 17:43:13 +07:00
Book Pauk
c8f9e0ac9d Добавил пакет minimist 2019-02-13 17:41:41 +07:00
Book Pauk
3e3f259920 Поправка бага 2019-02-13 16:41:30 +07:00
Book Pauk
c88baf3c2c Улучшение парсинга fb2 2019-02-13 14:56:54 +07:00
Book Pauk
0d27dabd62 Улучшение парсинга fb2 2019-02-13 14:49:51 +07:00
Book Pauk
5c29594b3d Добавил распознавание тега text-author 2019-02-13 14:14:34 +07:00
Book Pauk
1e71d0ae2f Merge tag '0.1.3' into develop
0.1.3
2019-02-13 13:46:07 +07:00
Book Pauk
a4c72481d1 Merge branch 'release/0.1.3' 2019-02-13 13:45:53 +07:00
Book Pauk
23ecb433fb Версия 0.1.3 2019-02-13 13:45:34 +07:00
Book Pauk
6b9ad4a947 К предыдущему 2019-02-13 13:44:34 +07:00
Book Pauk
9a44f53e5f Добавил распознавание кодировки fb2 и конвертирование в utf8 2019-02-13 13:39:53 +07:00
Book Pauk
bce31df7e6 Улучшение отображения автора и названия 2019-02-13 13:12:26 +07:00
Book Pauk
4bdd33b44f Мелкий рефакторинг 2019-02-13 13:01:41 +07:00
Book Pauk
7ab5d4e113 Добавляем в url протокол http, если не указан 2019-02-13 12:57:59 +07:00
Book Pauk
92c454b3e9 Мелкая поправка 2019-02-12 23:21:14 +07:00
Book Pauk
a7f588b724 Merge tag '0.1.2' into develop
0.1.2
2019-02-12 22:56:03 +07:00
Book Pauk
2ca7d2b7fc Merge branch 'release/0.1.2' 2019-02-12 22:55:50 +07:00
Book Pauk
fe60956362 Версия 0.1.2 2019-02-12 22:55:19 +07:00
Book Pauk
9c20df510d Улучшил поддержку текстовых файлов 2019-02-12 22:52:12 +07:00
Book Pauk
7dab3bfb1e Поправил бажок 2019-02-12 22:07:31 +07:00
Book Pauk
b281f19344 Добавил robots.txt 2019-02-12 20:25:07 +07:00
Book Pauk
d25cc64152 Merge tag 'ya-metrics' into develop
0.1.1
2019-02-12 19:53:25 +07:00
Book Pauk
a1b0ffe2c9 Merge branch 'hotfix/ya-metrics' 2019-02-12 19:53:08 +07:00
Book Pauk
17dcd9458e Версия 0.1.1 2019-02-12 19:52:38 +07:00
Book Pauk
e2d645d414 Добавил yandex-метрику для режима omnireader 2019-02-12 19:51:30 +07:00
Book Pauk
d4b7f44987 Merge tag '0.1.0' into develop
0.1.0
2019-02-12 19:32:17 +07:00
27 changed files with 996 additions and 532 deletions

View File

@@ -6,7 +6,7 @@ const api = axios.create({
class Misc {
async loadConfig() {
const response = await api.post('/config', {params: ['name', 'version', 'mode']});
const response = await api.post('/config', {params: ['name', 'version', 'mode', 'maxUploadFileSize', 'branch']});
return response.data;
}
}

View File

@@ -1,7 +1,6 @@
import axios from 'axios';
import {sleep} from '../share/utils';
const maxFileUploadSize = 50*1024*1024;
const api = axios.create({
baseURL: '/api/reader'
});
@@ -75,9 +74,11 @@ class Reader {
return await axios.get(url, options);
}
async uploadFile(file, callback) {
if (file.size > maxFileUploadSize)
throw new Error(`Размер файла превышает ${maxFileUploadSize} байт`);
async uploadFile(file, maxUploadFileSize, callback) {
if (!maxUploadFileSize)
maxUploadFileSize = 10*1024*1024;
if (file.size > maxUploadFileSize)
throw new Error(`Размер файла превышает ${maxUploadFileSize} байт`);
let formData = new FormData();
formData.append('file', file);

3
client/assets/robots.txt Normal file
View File

@@ -0,0 +1,3 @@
User-agent: *
Disallow: /?*url=
Disallow: /#/

View File

@@ -208,6 +208,22 @@ class App extends Vue {
this.$router.replace('/reader');
}
}
//yandex-метрика для omnireader
if (this.config.branch == 'production' && this.mode == 'omnireader' && !this.yaMetricsDone) {
(function(m,e,t,r,i,k,a){m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};
m[i].l=1*new Date();k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)})
(window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym");// eslint-disable-line no-unexpected-multiline
ym(52347334, "init", {// eslint-disable-line no-undef
id:52347334,
clickmap:true,
trackLinks:true,
accurateTrackBounce:true
});
this.yaMetricsDone = true;
}
}
}
//-----------------------------------------------------------------------------

View File

@@ -8,7 +8,7 @@
<li>кэширование файлов книг на клиенте и на сервере</li>
<li>открытие книг с локального диска</li>
<li>плавный скроллинг текста</li>
<li>анимация перелистывания (скоро)</li>
<li>анимация перелистывания</li>
<li>поиск по тексту и копирование фрагмента</li>
<li>запоминание недавних книг, скачивание книги из читалки в формате fb2</li>
<li>управление кликом и с клавиатуры</li>

View File

@@ -9,6 +9,7 @@
<li><b>ПКМ</b> - показать/скрыть панель управления</li>
<li><b>СКМ</b> - вкл./выкл. плавный скроллинг текста</li>
</ul>
* Для управления с помощью мыши/тачпада необходимо установить галочку "Включить управление кликом" в настройках
</div>
</template>

View File

@@ -126,8 +126,10 @@ class HistoryPage extends Vue {
updateTableData() {
let result = [];
for (let bookKey in bookManager.recent) {
const book = bookManager.recent[bookKey];
const sorted = bookManager.getSortedRecent();
const len = (sorted.length < 100 ? sorted.length : 100);
for (let i = 0; i < len; i++) {
const book = sorted[i];
let d = new Date();
d.setTime(book.touchTime);
const t = formatDate(d).split(' ');
@@ -141,17 +143,27 @@ class HistoryPage extends Vue {
}
const fb2 = (book.fb2 ? book.fb2 : {});
let title = fb2.bookTitle;
if (title)
title = `"${title}"`;
else
title = '';
let author = _.compact([
fb2.lastName,
fb2.firstName,
fb2.middleName
]).join(' ');
author = (author ? author : (fb2.bookTitle ? fb2.bookTitle : book.url));
result.push({
touchDateTime: book.touchTime,
touchDate: t[0],
touchTime: t[1],
desc: {
title: `"${fb2.bookTitle}"${perc}${textLen}`,
author: _.compact([
fb2.lastName,
fb2.firstName,
fb2.middleName
]).join(' '),
title: `${title}${perc}${textLen}`,
author,
},
url: book.url,
path: book.path,

View File

@@ -73,6 +73,7 @@ class LoaderPage extends Vue {
loadFile() {
const file = this.$refs.file.files[0];
this.$refs.file.value = '';
if (file)
this.$emit('load-file', {file});
}

View File

@@ -133,12 +133,16 @@ export default @Component({
this.loadBook({url: newValue, bookPos: this.routeParamPos});
}
},
settings: function(newValue) {
this.allowUrlParamBookPos = newValue.allowUrlParamBookPos;
this.copyFullText = newValue.copyFullText;
this.showClickMapPage = newValue.showClickMapPage;
settings: function() {
this.loadSettings();
this.updateRoute();
},
loaderActive: function(newValue) {
const recent = this.mostRecentBook();
if (!newValue && !this.loading && recent && !bookManager.hasBookParsed(recent)) {
this.loadBook(recent);
}
},
},
})
class Reader extends Vue {
@@ -168,6 +172,7 @@ class Reader extends Vue {
this.commit = this.$store.commit;
this.dispatch = this.$store.dispatch;
this.reader = this.$store.state.reader;
this.config = this.$store.state.config;
this.$root.addKeyHook(this.keyHook);
@@ -179,7 +184,7 @@ class Reader extends Vue {
this.debouncedSetRecentBook = _.debounce(async(newValue) => {
const recent = this.mostRecentBook();
if (recent && recent.bookPos != newValue) {
if (recent && (recent.bookPos != newValue || recent.bookPosSeen !== this.bookPosSeen)) {
await bookManager.setRecentBook(Object.assign({}, recent, {bookPos: newValue, bookPosSeen: this.bookPosSeen}));
if (this.actionCur < 0 || (this.actionCur >= 0 && this.actionList[this.actionCur] != newValue))
@@ -191,21 +196,17 @@ class Reader extends Vue {
this.fullScreenActive = (document.fullscreenElement !== null);
});
this.allowUrlParamBookPos = this.settings.allowUrlParamBookPos;
this.copyFullText = this.settings.copyFullText;
this.showClickMapPage = this.settings.showClickMapPage;
this.loadSettings();
}
mounted() {
(async() => {
await bookManager.init();
await bookManager.init(this.settings);
await restoreOldSettings(this.settings, bookManager, this.commit);
if (this.$root.rootRoute == '/reader') {
if (this.routeParamUrl) {
this.loadBook({url: this.routeParamUrl, bookPos: this.routeParamPos});
} else if (this.mostRecentBook()) {
this.loadBook({url: this.mostRecentBook().url});
} else {
this.loaderActive = true;
}
@@ -214,6 +215,15 @@ class Reader extends Vue {
})();
}
loadSettings() {
const settings = this.settings;
this.allowUrlParamBookPos = settings.allowUrlParamBookPos;
this.copyFullText = settings.copyFullText;
this.showClickMapPage = settings.showClickMapPage;
this.clickControl = settings.clickControl;
this.blinkCachedLoad = settings.blinkCachedLoad;
}
get routeParamPos() {
let result = undefined;
const q = this.$route.query;
@@ -438,53 +448,61 @@ class Reader extends Vue {
}
}
refreshBook() {
if (this.mostRecentBook()) {
this.loadBook({url: this.mostRecentBook().url, force: true});
}
}
buttonClick(button) {
const activeClass = this.buttonActiveClass(button);
if (!activeClass['tool-button-disabled'])
switch (button) {
case 'loader':
this.loaderToggle();
break;
case 'undoAction':
if (this.actionCur > 0) {
this.actionCur--;
this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
}
break;
case 'redoAction':
if (this.actionCur < this.actionList.length - 1) {
this.actionCur++;
this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
}
break;
case 'fullScreen':
this.fullScreenToggle();
break;
case 'setPosition':
this.setPositionToggle();
break;
case 'scrolling':
this.scrollingToggle();
break;
case 'search':
this.searchToggle();
break;
case 'copyText':
this.copyTextToggle();
break;
case 'history':
this.historyToggle();
break;
case 'refresh':
if (this.mostRecentBook()) {
this.loadBook({url: this.mostRecentBook().url, force: true});
}
break;
case 'settings':
this.settingsToggle();
break;
}
this.$refs[button].$el.blur();
if (activeClass['tool-button-disabled'])
return;
switch (button) {
case 'loader':
this.loaderToggle();
break;
case 'undoAction':
if (this.actionCur > 0) {
this.actionCur--;
this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
}
break;
case 'redoAction':
if (this.actionCur < this.actionList.length - 1) {
this.actionCur++;
this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
}
break;
case 'fullScreen':
this.fullScreenToggle();
break;
case 'setPosition':
this.setPositionToggle();
break;
case 'scrolling':
this.scrollingToggle();
break;
case 'search':
this.searchToggle();
break;
case 'copyText':
this.copyTextToggle();
break;
case 'history':
this.historyToggle();
break;
case 'refresh':
this.refreshBook();
break;
case 'settings':
this.settingsToggle();
break;
}
}
buttonActiveClass(button) {
@@ -538,8 +556,8 @@ class Reader extends Vue {
return classResult;
}
async acivateClickMapPage() {
if (this.showClickMapPage && !this.clickMapActive) {
async activateClickMapPage() {
if (this.clickControl && this.showClickMapPage && !this.clickMapActive) {
this.clickMapActive = true;
await this.$refs.clickMapPage.slowDisappear();
this.clickMapActive = false;
@@ -591,14 +609,19 @@ class Reader extends Vue {
}
loadBook(opts) {
if (!opts) {
if (!opts || !opts.url) {
this.mostRecentBook();
return;
}
let url = opts.url;
if ((url.indexOf('http://') != 0) && (url.indexOf('https://') != 0) &&
(url.indexOf('file://') != 0))
url = 'http://' + url;
// уже просматривается сейчас
const lastBook = (this.$refs.page ? this.$refs.page.lastBook : null);
if (!opts.force && lastBook && lastBook.url == opts.url && bookManager.hasBookParsed(lastBook)) {
if (!opts.force && lastBook && lastBook.url == url && bookManager.hasBookParsed(lastBook)) {
this.loaderActive = false;
return;
}
@@ -615,7 +638,7 @@ class Reader extends Vue {
progress.setState({state: 'parse'});
// есть ли среди недавних
const key = bookManager.keyFromUrl(opts.url);
const key = bookManager.keyFromUrl(url);
let wasOpened = await bookManager.getRecentBook({key});
wasOpened = (wasOpened ? wasOpened : {});
const bookPos = (opts.bookPos !== undefined ? opts.bookPos : wasOpened.bookPos);
@@ -626,7 +649,7 @@ class Reader extends Vue {
if (!opts.force) {
// пытаемся загрузить и распарсить книгу в менеджере из локального кэша
const bookParsed = await bookManager.getBook({url: opts.url}, (prog) => {
const bookParsed = await bookManager.getBook({url}, (prog) => {
progress.setState({progress: prog});
});
@@ -639,7 +662,7 @@ class Reader extends Vue {
progress.hide(); this.progressActive = false;
this.blinkCachedLoadMessage();
await this.acivateClickMapPage();
await this.activateClickMapPage();
return;
}
@@ -662,7 +685,7 @@ class Reader extends Vue {
// не удалось, скачиваем книгу полностью с конвертацией
let loadCached = true;
if (!book) {
book = await readerApi.loadBook(opts.url, (state) => {
book = await readerApi.loadBook(url, (state) => {
progress.setState(state);
});
loadCached = false;
@@ -687,7 +710,7 @@ class Reader extends Vue {
} else
this.stopBlink = true;
await this.acivateClickMapPage();
await this.activateClickMapPage();
} catch (e) {
progress.hide(); this.progressActive = false;
this.loaderActive = true;
@@ -704,7 +727,7 @@ class Reader extends Vue {
progress.show();
progress.setState({state: 'upload'});
const url = await readerApi.uploadFile(opts.file, (state) => {
const url = await readerApi.uploadFile(opts.file, this.config.maxUploadFileSize, (state) => {
progress.setState(state);
});
@@ -720,6 +743,9 @@ class Reader extends Vue {
}
blinkCachedLoadMessage() {
if (!this.blinkCachedLoad)
return;
this.blinkCount = 30;
if (!this.inBlink) {
this.inBlink = true;
@@ -780,6 +806,9 @@ class Reader extends Vue {
event.preventDefault();
event.stopPropagation();
break;
case 'KeyZ':
this.scrollingToggle();
break;
case 'KeyP':
this.setPositionToggle();
break;
@@ -797,8 +826,8 @@ class Reader extends Vue {
event.stopPropagation();
}
break;
case 'KeyZ':
this.scrollingToggle();
case 'KeyR':
this.refreshBook();
break;
case 'KeyX':
this.historyToggle();

View File

@@ -81,7 +81,7 @@
</el-form-item>
<el-form-item label="Размер">
<el-col :span="17">
<el-input-number v-model="fontSize" :min="5" :max="100"></el-input-number>
<el-input-number v-model="fontSize" :min="5" :max="200"></el-input-number>
</el-col>
<el-col :span="1">
<a href="https://fonts.google.com/?subset=cyrillic" target="_blank">Примеры</a>
@@ -112,10 +112,10 @@
<div class="partHeader">Текст</div>
<el-form-item label="Интервал">
<el-input-number v-model="lineInterval" :min="0" :max="100"></el-input-number>
<el-input-number v-model="lineInterval" :min="0" :max="200"></el-input-number>
</el-form-item>
<el-form-item label="Параграф">
<el-input-number v-model="p" :min="0" :max="200"></el-input-number>
<el-input-number v-model="p" :min="0" :max="2000"></el-input-number>
</el-form-item>
<el-form-item label="Отступ">
<el-col :span="11">
@@ -123,7 +123,7 @@
<template slot="content">
Слева/справа
</template>
<el-input-number v-model="indentLR" :min="0" :max="200"></el-input-number>
<el-input-number v-model="indentLR" :min="0" :max="2000"></el-input-number>
</el-tooltip>
</el-col>
<el-col :span="1">
@@ -134,7 +134,7 @@
<template slot="content">
Сверху/снизу
</template>
<el-input-number v-model="indentTB" :min="0" :max="200"></el-input-number>
<el-input-number v-model="indentTB" :min="0" :max="2000"></el-input-number>
</el-tooltip>
</el-col>
</el-form-item>
@@ -184,6 +184,16 @@
<el-checkbox v-model="textAlignJustify">По ширине</el-checkbox>
<el-checkbox v-model="wordWrap">Перенос по слогам</el-checkbox>
</el-form-item>
<el-form-item label="Обработка">
<el-checkbox v-model="cutEmptyParagraphs" @change="needReload">Убирать пустые параграфы</el-checkbox>
</el-form-item>
<el-form-item label="">
<el-col :span="12">
Добавлять пустые
</el-col>
<el-input-number v-model="addEmptyParagraphs" :min="0" :max="2" @change="needReload"></el-input-number>
</el-form-item>
</el-form>
<el-form :model="form" size="mini" label-width="120px" @submit.native.prevent>
@@ -194,7 +204,7 @@
<el-checkbox v-model="statusBarTop" :disabled="!showStatusBar">Вверху/внизу</el-checkbox>
</el-form-item>
<el-form-item label="Высота">
<el-input-number v-model="statusBarHeight" :min="5" :max="50" :disabled="!showStatusBar"></el-input-number>
<el-input-number v-model="statusBarHeight" :min="5" :max="100" :disabled="!showStatusBar"></el-input-number>
</el-form-item>
<el-form-item label="Прозрачность">
<el-input-number v-model="statusBarColorAlpha" :min="0" :max="1" :precision="2" :step="0.1" :disabled="!showStatusBar"></el-input-number>
@@ -208,11 +218,19 @@
<div class="partHeader">Анимация</div>
<el-form-item label="Вид">
не готово
<el-col :span="11">
<el-select v-model="pageChangeAnimation">
<el-option label="Нет" value=""></el-option>
<el-option label="Вверх-вниз" value="downShift"></el-option>
<el-option label="Вправо-влево" value="rightShift"></el-option>
<el-option label="Протаивание" value="thaw"></el-option>
<el-option label="Мерцание" value="blink"></el-option>
</el-select>
</el-col>
</el-form-item>
<el-form-item label="Скорость">
не готово
<el-input-number v-model="pageChangeAnimationSpeed" :min="0" :max="100" :disabled="pageChangeAnimation == ''"></el-input-number>
</el-form-item>
</el-form>
@@ -234,14 +252,26 @@
<!--------------------------------------------------------------------------->
<el-tab-pane label="Прочее">
<el-form :model="form" size="mini" label-width="120px" @submit.native.prevent>
<el-form-item label="Управление">
<el-checkbox v-model="clickControl">Включить управление кликом</el-checkbox>
</el-form-item>
<el-form-item label="Подсказка">
<el-tooltip :open-delay="500" effect="light">
<template slot="content">
Показывать или нет подсказку при каждой загрузке книги
</template>
<el-checkbox v-model="showClickMapPage">Показывать области управления кликом</el-checkbox>
<el-checkbox v-model="showClickMapPage" :disabled="!clickControl">Показывать области управления кликом</el-checkbox>
</el-tooltip>
</el-form-item>
</el-form-item>
<el-form-item label="Подсказка">
<el-tooltip :open-delay="500" effect="light">
<template slot="content">
Мерцать сообщением в строке статуса и на кнопке<br>
обновления при загрузке книги из кэша
</template>
<el-checkbox v-model="blinkCachedLoad">Предупреждать о загрузке из кэша</el-checkbox>
</el-tooltip>
</el-form-item>
<el-form-item label="URL">
<el-tooltip :open-delay="500" effect="light">
<template slot="content">
@@ -274,9 +304,11 @@
<el-checkbox v-model="copyFullText">Загружать весь текст</el-checkbox>
</el-tooltip>
</el-form-item>
</el-form>
</el-tab-pane>
<!--------------------------------------------------------------------------->
<el-tab-pane label="Сброс">
<el-button @click="setDefaults">Установить по-умолчанию</el-button>
</el-tab-pane>
</el-tabs>
@@ -384,10 +416,31 @@ class SettingsPage extends Vue {
];
}
needReload() {
this.$notify.warning({message: 'Необходимо обновить страницу (F5), чтобы изменения возымели эффект'});
}
close() {
this.$emit('settings-toggle');
}
async setDefaults() {
try {
if (await this.$confirm('Подтвердите установку настроек по-умолчанию', '', {
confirmButtonText: 'OK',
cancelButtonText: 'Отмена',
type: 'warning'
})) {
this.form = Object.assign({}, rstore.settingDefaults);
for (let prop in rstore.settingDefaults) {
this[prop] = this.form[prop];
}
}
} catch (e) {
//
}
}
keyHook(event) {
if (event.type == 'keydown' && event.code == 'Escape') {
this.close();

View File

@@ -1,8 +1,109 @@
import {sleep} from '../../../share/utils';
export default class DrawHelper {
fontBySize(size) {
return `${size}px ${this.fontName}`;
}
fontByStyle(style) {
return `${style.italic ? 'italic' : this.fontStyle} ${style.bold ? 'bold' : this.fontWeight} ${this.fontSize}px ${this.fontName}`;
}
measureText(text, style) {// eslint-disable-line no-unused-vars
this.context.font = this.fontByStyle(style);
return this.context.measureText(text).width;
}
measureTextFont(text, font) {// eslint-disable-line no-unused-vars
this.context.font = font;
return this.context.measureText(text).width;
}
drawPage(lines, isScrolling) {
if (!this.lastBook || this.pageLineCount < 1 || !this.book || !lines || !this.parsed.textLength)
return '';
const font = this.fontByStyle({});
const justify = (this.textAlignJustify ? 'text-align: justify; text-align-last: justify;' : '');
let out = `<div class="layout" style="width: ${this.w}px; height: ${this.h}px;` +
` position: absolute; top: ${this.fontSize*this.textShift}px; color: ${this.textColor}; font: ${font}; ${justify}` +
` line-height: ${this.lineHeight}px;">`;
let len = lines.length;
const lineCount = this.pageLineCount + (isScrolling ? 1 : 0);
len = (len > lineCount ? lineCount : len);
for (let i = 0; i < len; i++) {
const line = lines[i];
/* line:
{
begin: Number,
end: Number,
first: Boolean,
last: Boolean,
parts: array of {
style: {bold: Boolean, italic: Boolean, center: Boolean}
text: String,
}
}*/
let sel = new Set();
if (i == 0 && this.searching) {
let pureText = '';
for (const part of line.parts) {
pureText += part.text;
}
pureText = pureText.toLowerCase();
let j = 0;
while (1) {// eslint-disable-line no-constant-condition
j = pureText.indexOf(this.needle, j);
if (j >= 0) {
for (let k = 0; k < this.needle.length; k++) {
sel.add(j + k);
}
} else
break;
j++;
}
}
let lineText = '';
let center = false;
let j = 0;
for (const part of line.parts) {
let tOpen = (part.style.bold ? '<b>' : '');
tOpen += (part.style.italic ? '<i>' : '');
let tClose = (part.style.italic ? '</i>' : '');
tClose += (part.style.bold ? '</b>' : '');
let text = '';
if (i == 0 && this.searching) {
for (let k = 0; k < part.text.length; k++) {
text += (sel.has(j) ? `<ins>${part.text[k]}</ins>` : part.text[k]);
j++;
}
} else
text = part.text;
lineText += `${tOpen}${text}${tClose}`;
center = center || part.style.center;
}
const centerStyle = (center ? `text-align: center; text-align-last: center; width: ${this.w}px` : '')
if (line.first)
lineText = `<span style="display: inline-block; margin-left: ${this.p}px"></span>${lineText}`;
if (line.last || center)
lineText = `<span style="display: inline-block; ${centerStyle}">${lineText}</span>`;
out += (i > 0 ? '<br>' : '') + lineText;
}
out += '</div>';
return out;
}
drawPercentBar(x, y, w, h, font, fontSize, bookPos, textLength) {
const pad = 3;
const fh = h - 2*pad;
@@ -95,4 +196,75 @@ export default class DrawHelper {
return `<div style="position: absolute; left: ${x}px; top: ${y}px; ` +
`width: ${w}px; height: ${h}px; box-sizing: border-box; border: 1px solid ${color}"></div>`;
}
async doPageAnimationThaw(page1, page2, duration, isDown, animation1Finish) {
page1.style.animation = `page1-animation-thaw ${duration}ms ease-in 1`;
page2.style.animation = `page2-animation-thaw ${duration}ms ease-in 1`;
await animation1Finish(duration);
}
async doPageAnimationBlink(page1, page2, duration, isDown, animation1Finish, animation2Finish) {
page1.style.opacity = '0';
page2.style.opacity = '0';
page2.style.animation = `page2-animation-thaw ${duration/2}ms ease-out 1`;
await animation2Finish(duration/2);
page1.style.opacity = '1';
page1.style.animation = `page1-animation-thaw ${duration/2}ms ease-in 1`;
await animation1Finish(duration/2);
page2.style.opacity = '1';
}
async doPageAnimationRightShift(page1, page2, duration, isDown, animation1Finish) {
const s = this.w + this.fontSize;
if (isDown) {
page1.style.transform = `translateX(${s}px)`;
await sleep(30);
page1.style.transition = `${duration}ms ease-in-out`;
page1.style.transform = `translateX(0px)`;
page2.style.transition = `${duration}ms ease-in-out`;
page2.style.transform = `translateX(-${s}px)`;
await animation1Finish(duration);
} else {
page1.style.transform = `translateX(-${s}px)`;
await sleep(30);
page1.style.transition = `${duration}ms ease-in-out`;
page1.style.transform = `translateX(0px)`;
page2.style.transition = `${duration}ms ease-in-out`;
page2.style.transform = `translateX(${s}px)`;
await animation1Finish(duration);
}
}
async doPageAnimationDownShift(page1, page2, duration, isDown, animation1Finish) {
const s = this.h + this.fontSize/2;
if (isDown) {
page1.style.transform = `translateY(${s}px)`;
await sleep(30);
page1.style.transition = `${duration}ms ease-in-out`;
page1.style.transform = `translateY(0px)`;
page2.style.transition = `${duration}ms ease-in-out`;
page2.style.transform = `translateY(-${s}px)`;
await animation1Finish(duration);
} else {
page1.style.transform = `translateY(-${s}px)`;
await sleep(30);
page1.style.transition = `${duration}ms ease-in-out`;
page1.style.transform = `translateY(0px)`;
page2.style.transition = `${duration}ms ease-in-out`;
page2.style.transform = `translateY(${s}px)`;
await animation1Finish(duration);
}
}
}

View File

@@ -1,21 +1,23 @@
<template>
<div ref="main" class="main">
<div class="layout back">
<div class="layout back" @wheel.prevent.stop="onMouseWheel">
<div v-html="background"></div>
<!-- img -->
</div>
<div ref="scrollBox1" class="layout" style="overflow: hidden">
<div ref="scrollingPage" class="layout" @transitionend="onScrollingTransitionEnd">
<div ref="scrollBox1" class="layout" style="overflow: hidden" @wheel.prevent.stop="onMouseWheel">
<div ref="scrollingPage1" class="layout" @transitionend="onPage1TransitionEnd" @animationend="onPage1AnimationEnd">
<div v-html="page1"></div>
</div>
</div>
<div ref="scrollBox2" class="layout" style="overflow: hidden">
<div v-html="page2"></div>
<div ref="scrollBox2" class="layout" style="overflow: hidden" @wheel.prevent.stop="onMouseWheel">
<div ref="scrollingPage2" class="layout" @transitionend="onPage2TransitionEnd" @animationend="onPage2AnimationEnd">
<div v-html="page2"></div>
</div>
</div>
<div v-show="showStatusBar" ref="statusBar" class="layout">
<div v-html="statusBar"></div>
</div>
<div ref="layoutEvents" class="layout events" @mousedown.prevent.stop="onMouseDown" @mouseup.prevent.stop="onMouseUp"
<div v-show="clickControl" ref="layoutEvents" class="layout events" @mousedown.prevent.stop="onMouseDown" @mouseup.prevent.stop="onMouseUp"
@wheel.prevent.stop="onMouseWheel"
@touchstart.stop="onTouchStart" @touchend.stop="onTouchEnd" @touchcancel.prevent.stop="onTouchCancel"
oncontextmenu="return false;">
@@ -23,6 +25,8 @@
@click.prevent.stop="onStatusBarClick"></div>
<div v-show="fontsLoading" ref="fontsLoading"></div>
</div>
<div v-show="!clickControl && showStatusBar" class="layout" v-html="statusBarClickable" @mousedown.prevent.stop @touchstart.stop
@click.prevent.stop="onStatusBarClick"></div>
<!-- невидимым делать нельзя, вовремя не подгружаютя шрифты -->
<canvas ref="offscreenCanvas" class="layout" style="width: 0px; height: 0px"></canvas>
</div>
@@ -45,21 +49,29 @@ const minLayoutWidth = 100;
export default @Component({
watch: {
bookPos: function(newValue) {
this.$emit('book-pos-changed', {bookPos: newValue, bookPosSeen: this.bookPosSeen});
bookPos: function() {
this.$emit('book-pos-changed', {bookPos: this.bookPos, bookPosSeen: this.bookPosSeen});
this.draw();
},
bookPosSeen: function() {
this.$emit('book-pos-changed', {bookPos: this.bookPos, bookPosSeen: this.bookPosSeen});
},
settings: function() {
this.debouncedLoadSettings();
},
toggleLayout: function() {
this.updateLayout();
},
inAnimation: function() {
this.updateLayout();
},
},
})
class TextPage extends Vue {
toggleLayout = false;
showStatusBar = false;
clickControl = true;
background = null;
page1 = null;
page2 = null;
@@ -69,10 +81,14 @@ class TextPage extends Vue {
lastBook = null;
bookPos = 0;
bookPosSeen = null;
fontStyle = null;
fontSize = null;
fontName = null;
fontWeight = null;
inAnimation = false;
meta = null;
@@ -100,15 +116,20 @@ class TextPage extends Vue {
this.loadSettings();
}, 50);
this.debouncedUpdatePage = _.debounce((lines) => {
this.toggleLayout = !this.toggleLayout;
this.debouncedUpdatePage = _.debounce(async(lines) => {
if (!this.pageChangeAnimation)
this.toggleLayout = !this.toggleLayout;
else {
this.page2 = this.page1;
this.toggleLayout = true;
}
if (this.toggleLayout)
this.page1 = this.drawPage(lines);
this.page1 = this.drawHelper.drawPage(lines);
else
this.page2 = this.drawPage(lines);
this.page2 = this.drawHelper.drawPage(lines);
this.doPageTransition();
await this.doPageAnimation();
}, 10);
this.$root.$on('resize', () => {this.$nextTick(this.onResize)});
@@ -140,16 +161,39 @@ class TextPage extends Vue {
this.lineHeight = this.fontSize + this.lineInterval;
this.pageLineCount = 1 + Math.floor((this.h - this.fontSize)/this.lineHeight);
if (this.parsed) {
this.parsed.p = this.p;
this.parsed.w = this.w;// px, ширина текста
this.parsed.font = this.font;
this.parsed.wordWrap = this.wordWrap;
let t = '';
while (this.measureText(t, {}) < this.w) t += 'Щ';
this.parsed.maxWordLength = t.length - 1;
this.parsed.measureText = this.measureText;
}
this.$refs.scrollingPage1.style.width = this.w + 'px';
this.$refs.scrollingPage2.style.width = this.w + 'px';
//stuff
this.currentAnimation = '';
this.pageChangeDirectionDown = true;
this.fontShift = this.fontVertShift/100;
this.textShift = this.textVertShift/100 + this.fontShift;
//drawHelper
this.drawHelper.realWidth = this.realWidth;
this.drawHelper.realHeight = this.realHeight;
this.drawHelper.lastBook = this.lastBook;
this.drawHelper.book = this.book;
this.drawHelper.parsed = this.parsed;
this.drawHelper.pageLineCount = this.pageLineCount;
this.drawHelper.backgroundColor = this.backgroundColor;
this.drawHelper.statusBarColor = this.statusBarColor;
this.drawHelper.fontStyle = this.fontStyle;
this.drawHelper.fontWeight = this.fontWeight;
this.drawHelper.fontSize = this.fontSize;
this.drawHelper.fontName = this.fontName;
this.drawHelper.fontShift = this.fontShift;
this.drawHelper.textColor = this.textColor;
this.drawHelper.textShift = this.textShift;
this.drawHelper.p = this.p;
this.drawHelper.w = this.w;
this.drawHelper.h = this.h;
this.drawHelper.indentLR = this.indentLR;
this.drawHelper.textAlignJustify = this.textAlignJustify;
this.drawHelper.lineHeight = this.lineHeight;
this.drawHelper.context = this.context;
//сообщение "Загрузка шрифтов..."
const flText = 'Загрузка шрифта...';
@@ -158,29 +202,25 @@ class TextPage extends Vue {
fontsLoadingStyle.position = 'absolute';
fontsLoadingStyle.fontSize = this.fontSize + 'px';
fontsLoadingStyle.top = (this.realHeight/2 - 2*this.fontSize) + 'px';
fontsLoadingStyle.left = (this.realWidth - this.measureText(flText, {}))/2 + 'px';
fontsLoadingStyle.left = (this.realWidth - this.drawHelper.measureText(flText, {}))/2 + 'px';
//stuff
this.statusBarColor = this.hex2rgba(this.textColor || '#000000', this.statusBarColorAlpha);
this.currentTransition = '';
this.pageChangeDirectionDown = true;
this.fontShift = this.fontVertShift/100;
this.textShift = this.textVertShift/100 + this.fontShift;
//drawHelper
this.drawHelper.realWidth = this.realWidth;
this.drawHelper.realHeight = this.realHeight;
this.drawHelper.backgroundColor = this.backgroundColor;
this.drawHelper.statusBarColor = this.statusBarColor;
this.drawHelper.fontName = this.fontName;
this.drawHelper.fontShift = this.fontShift;
this.drawHelper.measureText = this.measureText;
this.drawHelper.measureTextFont = this.measureTextFont;
//parsed
if (this.parsed) {
this.parsed.p = this.p;
this.parsed.w = this.w;// px, ширина текста
this.parsed.font = this.font;
this.parsed.wordWrap = this.wordWrap;
let t = '';
while (this.drawHelper.measureText(t, {}) < this.w) t += 'Щ';
this.parsed.maxWordLength = t.length - 1;
this.parsed.measureText = this.drawHelper.measureText.bind(this.drawHelper);
}
//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
@@ -200,16 +240,6 @@ class TextPage extends Vue {
page2.style.left = this.indentLR + 'px';
}
measureText(text, style) {// eslint-disable-line no-unused-vars
this.context.font = this.fontByStyle(style);
return this.context.measureText(text).width;
}
measureTextFont(text, font) {// eslint-disable-line no-unused-vars
this.context.font = font;
return this.context.measureText(text).width;
}
async checkLoadedFonts() {
let loaded = await Promise.all(this.fontList.map(font => document.fonts.check(font)));
if (loaded.some(r => !r)) {
@@ -279,18 +309,12 @@ class TextPage extends Vue {
this.draw();
// шрифты хрен знает когда подгружаются, поэтому
// шрифты хрен знает когда подгружаются в div, поэтому
const parsed = this.parsed;
if (!parsed.force) {
let i = 0;
await sleep(5000);
if (this.parsed === parsed) {
parsed.force = true;
while (i < 10) {
await sleep(1000);
if (this.parsed != parsed)
break;
this.draw();
i++;
}
this.draw();
parsed.force = false;
}
}
@@ -315,7 +339,6 @@ class TextPage extends Vue {
this.linesUp = null;
this.linesDown = null;
this.searching = false;
this.statusBarMessage = '';
@@ -367,7 +390,10 @@ class TextPage extends Vue {
}
updateLayout() {
if (this.toggleLayout) {
if (this.inAnimation) {
this.$refs.scrollBox1.style.visibility = 'visible';
this.$refs.scrollBox2.style.visibility = 'visible';
} else if (this.toggleLayout) {
this.$refs.scrollBox1.style.visibility = 'visible';
this.$refs.scrollBox2.style.visibility = 'hidden';
} else {
@@ -399,34 +425,42 @@ class TextPage extends Vue {
return `${this.fontStyle} ${this.fontWeight} ${this.fontSize}px ${this.fontName}`;
}
fontByStyle(style) {
return `${style.italic ? 'italic' : this.fontStyle} ${style.bold ? 'bold' : this.fontWeight} ${this.fontSize}px ${this.fontName}`;
onPage1TransitionEnd() {
if (this.resolveTransition1Finish)
this.resolveTransition1Finish();
}
onScrollingTransitionEnd() {
if (this.resolveTransitionFinish)
this.resolveTransitionFinish();
onPage2TransitionEnd() {
if (this.resolveTransition2Finish)
this.resolveTransition2Finish();
}
startSearch(needle) {
this.needle = '';
const words = needle.split(' ');
for (const word of words) {
if (word != '') {
this.needle = word;
break;
}
}
this.searching = true;
this.drawHelper.needle = needle;
this.drawHelper.searching = true;
this.draw();
}
stopSearch() {
this.searching = false;
this.drawHelper.searching = false;
this.draw();
}
generateWaitingFunc(waitingHandlerName, stopPropertyName) {
const func = (timeout) => {
return new Promise(async(resolve) => {
this[waitingHandlerName] = resolve;
let wait = (timeout + 201)/100;
while (wait > 0 && !this[stopPropertyName]) {
wait--;
await sleep(100);
}
resolve();
});
};
return func;
}
async startTextScrolling() {
if (this.doingScrolling || !this.book || !this.parsed.textLength || !this.linesDown || this.pageLineCount < 1 ||
this.linesDown.length <= this.pageLineCount) {
@@ -434,20 +468,13 @@ class TextPage extends Vue {
return;
}
//ждем анимацию
while (this.inAnimation) await sleep(10);
this.stopScrolling = false;
this.doingScrolling = true;
const transitionFinish = (timeout) => {
return new Promise(async(resolve) => {
this.resolveTransitionFinish = resolve;
let wait = timeout/100;
while (wait > 0 && !this.stopScrolling) {
wait--;
await sleep(100);
}
resolve();
});
};
const transitionFinish = this.generateWaitingFunc('resolveTransition1Finish', 'stopScrolling');
if (!this.toggleLayout)
this.page1 = this.page2;
@@ -456,7 +483,9 @@ class TextPage extends Vue {
await sleep(50);
this.cachedPos = -1;
const page = this.$refs.scrollingPage;
this.draw();
const page = this.$refs.scrollingPage1;
let i = 0;
while (!this.stopScrolling) {
page.style.transition = `${this.scrollingDelay}ms ${this.scrollingType}`;
@@ -468,21 +497,22 @@ class TextPage extends Vue {
this.stopScrolling = true;
}
}
await transitionFinish(this.scrollingDelay + 201);
await transitionFinish(this.scrollingDelay);
page.style.transition = '';
page.style.transform = 'none';
page.offsetHeight;
i++;
}
this.resolveTransitionFinish = null;
this.resolveTransition1Finish = null;
this.doingScrolling = false;
this.$emit('stop-scrolling');
this.draw();
}
async stopTextScrolling() {
this.stopScrolling = true;
const page = this.$refs.scrollingPage;
const page = this.$refs.scrollingPage1;
page.style.transition = '';
page.style.transform = 'none';
page.offsetHeight;
@@ -491,7 +521,10 @@ class TextPage extends Vue {
}
draw() {
//scrolling
if (this.doingScrolling) {
this.currentAnimation = '';
if (this.cachedPos == this.bookPos) {
this.linesDown = this.linesCached.linesDown;
this.linesUp = this.linesCached.linesUp;
@@ -500,7 +533,7 @@ class TextPage extends Vue {
const lines = this.getLines(this.bookPos);
this.linesDown = lines.linesDown;
this.linesUp = lines.linesUp;
this.page1 = this.drawPage(lines.linesDown);
this.page1 = this.drawHelper.drawPage(lines.linesDown, true);
}
//caching next
@@ -510,7 +543,7 @@ class TextPage extends Vue {
if (this.linesDown && this.linesDown.length > this.pageLineCount && this.pageLineCount > 0) {
this.cachedPos = this.linesDown[1].begin;
this.linesCached = this.getLines(this.cachedPos);
this.pageCached = this.drawPage(this.linesCached.linesDown);
this.pageCached = this.drawHelper.drawPage(this.linesCached.linesDown, true);
}
this.cachedPageTimer = null;
}, 20);
@@ -519,6 +552,7 @@ class TextPage extends Vue {
return;
}
//check
if (this.w < minLayoutWidth) {
this.page1 = null;
this.page2 = null;
@@ -527,49 +561,97 @@ class TextPage extends Vue {
}
if (this.book && this.bookPos > 0 && this.bookPos >= this.parsed.textLength) {
this.doEnd();
this.doEnd(true);
return;
}
if (this.pageChangeDirectionDown && this.pagePrepared && this.bookPos == this.bookPosPrepared) {
//fast draw prepared
if (!this.pageChangeAnimation && this.pageChangeDirectionDown && this.pagePrepared && this.bookPos == this.bookPosPrepared) {
this.toggleLayout = !this.toggleLayout;
this.linesDown = this.linesDownNext;
this.linesUp = this.linesUpNext;
this.doPageTransition();
} else {
} else {//normal debounced draw
const lines = this.getLines(this.bookPos);
this.linesDown = lines.linesDown;
this.linesUp = lines.linesUp;
/*if (this.toggleLayout)
this.page1 = this.drawPage(lines.linesDown);
else
this.page2 = this.drawPage(lines.linesDown);*/
this.debouncedUpdatePage(lines.linesDown);
}
this.pagePrepared = false;
this.debouncedPrepareNextPage();
if (!this.pageChangeAnimation)
this.debouncedPrepareNextPage();
this.debouncedDrawStatusBar();
if (this.book && this.linesDown && this.linesDown.length < this.pageLineCount)
this.doEnd();
if (this.book && this.linesDown && this.linesDown.length < this.pageLineCount) {
this.doEnd(true);
return;
}
}
doPageTransition() {
if (this.currentTransition) {
//this.currentTransition
//this.pageChangeTransitionSpeed
//this.pageChangeDirectionDown
//curr to next transition
//пока заглушка
}
onPage1AnimationEnd() {
if (this.resolveAnimation1Finish)
this.resolveAnimation1Finish();
}
this.currentTransition = '';
this.pageChangeDirectionDown = false;//true только если PgDown
onPage2AnimationEnd() {
if (this.resolveAnimation2Finish)
this.resolveAnimation2Finish();
}
async doPageAnimation() {
if (this.currentAnimation && !this.inAnimation) {
this.inAnimation = true;
const animation1Finish = this.generateWaitingFunc('resolveAnimation1Finish', 'stopAnimation');
const animation2Finish = this.generateWaitingFunc('resolveAnimation2Finish', 'stopAnimation');
const transition1Finish = this.generateWaitingFunc('resolveTransition1Finish', 'stopAnimation');
//const transition2Finish = this.generateWaitingFunc('resolveTransition2Finish', 'stopAnimation');
const duration = Math.round(3000*(1 - this.pageChangeAnimationSpeed/100));
let page1 = this.$refs.scrollingPage1;
let page2 = this.$refs.scrollingPage2;
switch (this.currentAnimation) {
case 'thaw':
await this.drawHelper.doPageAnimationThaw(page1, page2,
duration, this.pageChangeDirectionDown, animation1Finish);
break;
case 'blink':
await this.drawHelper.doPageAnimationBlink(page1, page2,
duration, this.pageChangeDirectionDown, animation1Finish, animation2Finish);
break;
case 'rightShift':
await this.drawHelper.doPageAnimationRightShift(page1, page2,
duration, this.pageChangeDirectionDown, transition1Finish);
break;
case 'downShift':
await this.drawHelper.doPageAnimationDownShift(page1, page2,
duration, this.pageChangeDirectionDown, transition1Finish);
break;
}
this.resolveAnimation1Finish = null;
this.resolveAnimation2Finish = null;
this.resolveTransition1Finish = null;
this.resolveTransition2Finish = null;
page1.style.animation = '';
page2.style.animation = '';
page1.style.transition = '';
page1.style.transform = 'none';
page1.offsetHeight;
page2.style.transition = '';
page2.style.transform = 'none';
page2.offsetHeight;
this.currentAnimation = '';
this.pageChangeDirectionDown = false;//true только если PgDown
this.inAnimation = false;
this.stopAnimation = false;
}
}
getLines(bookPos) {
@@ -582,110 +664,6 @@ class TextPage extends Vue {
};
}
drawPage(lines) {
if (!this.lastBook || this.pageLineCount < 1 || !this.book || !lines || !this.parsed.textLength)
return '';
const spaceWidth = this.measureText(' ', {});
let out = `<div class="layout" style="width: ${this.realWidth}px; height: ${this.realHeight}px;` +
` color: ${this.textColor}">`;
let len = lines.length;
len = (len > this.pageLineCount + 1 ? this.pageLineCount + 1 : len);
let y = this.fontSize*this.textShift;
for (let i = 0; i < len; i++) {
const line = lines[i];
/* line:
{
begin: Number,
end: Number,
first: Boolean,
last: Boolean,
parts: array of {
style: {bold: Boolean, italic: Boolean, center: Boolean}
text: String,
}
}*/
let indent = line.first ? this.p : 0;
let lineText = '';
let center = false;
let centerStyle = {};
for (const part of line.parts) {
lineText += part.text;
center = center || part.style.center;
if (part.style.center)
centerStyle = part.style;
}
let filled = false;
// если выравнивание по ширине включено
if (this.textAlignJustify && !line.last && !center) {
const words = lineText.split(' ');
if (words.length > 1) {
const spaceCount = words.length - 1;
const space = (this.w - line.width + spaceWidth*spaceCount)/spaceCount;
let x = indent;
for (const part of line.parts) {
const font = this.fontByStyle(part.style);
let partWords = part.text.split(' ');
for (let j = 0; j < partWords.length; j++) {
let f = font;
let style = part.style;
let word = partWords[j];
if (i == 0 && this.searching && word.toLowerCase().indexOf(this.needle) >= 0) {
style = Object.assign({}, part.style, {bold: true});
f = this.fontByStyle(style);
}
out += this.drawHelper.fillText(word, x, y, f);
x += this.measureText(word, style) + (j < partWords.length - 1 ? space : 0);
}
}
filled = true;
}
}
// просто выводим текст
if (!filled) {
let x = indent;
x = (center ? (this.w - this.measureText(lineText, centerStyle))/2 : x);
for (const part of line.parts) {
let font = this.fontByStyle(part.style);
if (i == 0 && this.searching) {//для поиска, разбивка по словам
let partWords = part.text.split(' ');
for (let j = 0; j < partWords.length; j++) {
let f = font;
let style = part.style;
let word = partWords[j];
if (word.toLowerCase().indexOf(this.needle) >= 0) {
style = Object.assign({}, part.style, {bold: true});
f = this.fontByStyle(style);
}
out += this.drawHelper.fillText(word, x, y, f);
x += this.measureText(word, style) + (j < partWords.length - 1 ? spaceWidth : 0);
}
} else {
out += this.drawHelper.fillText(part.text, x, y, font);
x += this.measureText(part.text, part.style);
}
}
}
y += this.lineHeight;
}
out += '</div>';
return out;
}
drawStatusBar(message) {
if (this.w < minLayoutWidth) {
this.statusBar = null;
@@ -782,9 +760,9 @@ class TextPage extends Vue {
this.linesUpNext = lines.linesUp;
if (this.toggleLayout)
this.page2 = this.drawPage(lines.linesDown);//наоборот
this.page2 = this.drawHelper.drawPage(lines.linesDown);//наоборот
else
this.page1 = this.drawPage(lines.linesDown);
this.page1 = this.drawHelper.drawPage(lines.linesDown);
this.pagePrepared = true;
}
@@ -808,7 +786,7 @@ class TextPage extends Vue {
if (this.keepLastToFirst)
i--;
if (i >= 0 && this.linesDown.length >= 2*i) {
this.currentTransition = this.pageChangeTransition;
this.currentAnimation = this.pageChangeAnimation;
this.pageChangeDirectionDown = true;
this.bookPos = this.linesDown[i].begin;
} else
@@ -823,7 +801,7 @@ class TextPage extends Vue {
i--;
i = (i > this.linesUp.length - 1 ? this.linesUp.length - 1 : i);
if (i >= 0 && this.linesUp.length > i) {
this.currentTransition = this.pageChangeTransition;
this.currentAnimation = this.pageChangeAnimation;
this.pageChangeDirectionDown = false;
this.bookPos = this.linesUp[i].begin;
}
@@ -831,10 +809,12 @@ class TextPage extends Vue {
}
doHome() {
this.currentAnimation = this.pageChangeAnimation;
this.pageChangeDirectionDown = false;
this.bookPos = 0;
}
doEnd() {
doEnd(noAni) {
if (this.parsed.para.length && this.pageLineCount > 0) {
let i = this.parsed.para.length - 1;
let lastPos = this.parsed.para[i].offset + this.parsed.para[i].length - 1;
@@ -842,6 +822,9 @@ class TextPage extends Vue {
if (lines) {
i = this.pageLineCount - 1;
i = (i > lines.length - 1 ? lines.length - 1 : i);
if (!noAni)
this.currentAnimation = this.pageChangeAnimation;
this.pageChangeDirectionDown = true;
this.bookPos = lines[i].begin;
}
}
@@ -1162,4 +1145,13 @@ class TextPage extends Vue {
background: url("images/paper9.jpg");
}
@keyframes page1-animation-thaw {
0% { opacity: 0; }
100% { opacity: 1; }
}
@keyframes page2-animation-thaw {
0% { opacity: 1; }
100% { opacity: 0; }
}
</style>

View File

@@ -3,7 +3,7 @@ import sax from '../../../../server/core/BookConverter/sax';
import {sleep} from '../../../share/utils';
export default class BookParser {
constructor() {
constructor(settings) {
// defaults
this.p = 30;// px, отступ параграфа
this.w = 300;// px, ширина страницы
@@ -13,6 +13,12 @@ export default class BookParser {
this.measureText = (text, style) => {// eslint-disable-line no-unused-vars
return text.length*20;
};
//настройки
if (settings) {
this.cutEmptyParagraphs = settings.cutEmptyParagraphs;
this.addEmptyParagraphs = settings.addEmptyParagraphs;
}
}
async parse(data, callback) {
@@ -48,7 +54,14 @@ export default class BookParser {
text: String //текст параграфа (или title или epigraph и т.д) с вложенными тегами
}
*/
const newParagraph = (text, len) => {
const newParagraph = (text, len, noCut) => {
//схлопывание пустых параграфов
if (!noCut && this.cutEmptyParagraphs && paraIndex >= 0 && len == 1 && text[0] == ' ') {
let p = para[paraIndex];
if (p.length == 1 && p.text[0] == ' ')
return;
}
paraIndex++;
let p = {
index: paraIndex,
@@ -63,12 +76,23 @@ export default class BookParser {
const growParagraph = (text, len) => {
if (paraIndex < 0) {
newParagraph(text, len);
newParagraph(' ', 1);
growParagraph(text, len);
return;
}
let p = para[paraIndex];
if (p) {
//добавление пустых параграфов
if (this.addEmptyParagraphs && p.length == 1 && p.text[0] == ' ' && len > 0) {
let i = this.addEmptyParagraphs;
while (i > 0) {
newParagraph(' ', 1, true);
i--;
}
p = para[paraIndex];
}
paraOffset -= p.length;
if (p.length == 1 && p.text[0] == ' ' && len > 0) {
p.length = 0;
@@ -96,55 +120,63 @@ export default class BookParser {
tag = elemName;
path += '/' + elemName;
if ((tag == 'p' || tag == 'empty-line' || tag == 'v') && path.indexOf('/fictionbook/body/section') == 0) {
newParagraph(' ', 1);
}
if (path.indexOf('/fictionbook/body') == 0) {
if (tag == 'title') {
newParagraph(' ', 1);
bold = true;
center = true;
}
if (tag == 'emphasis' || tag == 'strong') {
growParagraph(`<${tag}>`, 0);
}
if (tag == 'emphasis' || tag == 'strong') {
growParagraph(`<${tag}>`, 0);
}
if (tag == 'title') {
newParagraph(' ', 1);
bold = true;
center = true;
}
if ((tag == 'p' || tag == 'empty-line' || tag == 'v')) {
newParagraph(' ', 1);
}
if (tag == 'subtitle') {
newParagraph(' ', 1);
bold = true;
}
if (tag == 'subtitle') {
newParagraph(' ', 1);
bold = true;
}
if (tag == 'epigraph') {
italic = true;
}
if (tag == 'epigraph') {
italic = true;
}
if (tag == 'stanza') {
newParagraph(' ', 1);
if (tag == 'poem') {
newParagraph(' ', 1);
}
if (tag == 'text-author') {
newParagraph(' <s> <s> <s> ', 4);
}
}
};
const onEndNode = (elemName) => {// eslint-disable-line no-unused-vars
if (tag == elemName) {
if (tag == 'emphasis' || tag == 'strong') {
growParagraph(`</${tag}>`, 0);
}
if (path.indexOf('/fictionbook/body') == 0) {
if (tag == 'title') {
bold = false;
center = false;
}
if (tag == 'title') {
bold = false;
center = false;
}
if (tag == 'emphasis' || tag == 'strong') {
growParagraph(`</${tag}>`, 0);
}
if (tag == 'subtitle') {
bold = false;
}
if (tag == 'subtitle') {
bold = false;
}
if (tag == 'epigraph') {
italic = false;
}
if (tag == 'epigraph') {
italic = false;
}
if (tag == 'stanza') {
newParagraph(' ', 1);
if (tag == 'stanza') {
newParagraph(' ', 1);
}
}
path = path.substr(0, path.length - tag.length - 1);
@@ -206,12 +238,12 @@ export default class BookParser {
let tOpen = (center ? '<center>' : '');
tOpen += (bold ? '<strong>' : '');
tOpen += (italic ? '<emphasis>' : '');
let tClose = (center ? '</center>' : '');
let tClose = (italic ? '</emphasis>' : '');
tClose += (bold ? '</strong>' : '');
tClose += (italic ? '</emphasis>' : '');
tClose += (center ? '</center>' : '');
if (path.indexOf('/fictionbook/body/title') == 0) {
newParagraph(`${tOpen}${text}${tClose}`, text.length, true);
growParagraph(`${tOpen}${text}${tClose}`, text.length);
}
if (path.indexOf('/fictionbook/body/section') == 0) {

View File

@@ -18,10 +18,12 @@ const bmRecentStore = localForage.createInstance({
});
class BookManager {
async init() {
async init(settings) {
this.settings = settings;
this.books = {};
this.recent = {};
this.recentChanged = true;
this.recentChanged1 = true;
this.recentChanged2 = true;
let len = await bmMetaStore.length();
for (let i = 0; i < len; i++) {
@@ -130,7 +132,7 @@ class BookManager {
async parseBook(meta, data, callback) {
if (!this.books)
await this.init();
const parsed = new BookParser();
const parsed = new BookParser(this.settings);
const parsedMeta = await parsed.parse(data, callback);
const result = Object.assign({}, meta, parsedMeta, {
@@ -169,7 +171,8 @@ class BookManager {
await bmRecentStore.setItem(result.key, result);
await this.cleanRecentBooks();
this.recentChanged = true;
this.recentChanged1 = true;
this.recentChanged2 = true;
return result;
}
@@ -185,14 +188,15 @@ class BookManager {
await bmRecentStore.removeItem(value.key);
delete this.recent[value.key];
this.recentChanged = true;
this.recentChanged1 = true;
this.recentChanged2 = true;
}
async cleanRecentBooks() {
if (!this.recent)
await this.init();
if (Object.keys(this.recent).length > 100) {
if (Object.keys(this.recent).length > 1000) {
let min = Date.now();
let found = null;
for (let key in this.recent) {
@@ -211,7 +215,7 @@ class BookManager {
}
mostRecentBook() {
if (!this.recentChanged && this.mostRecentCached) {
if (!this.recentChanged1 && this.mostRecentCached) {
return this.mostRecentCached;
}
@@ -225,10 +229,25 @@ class BookManager {
}
}
this.mostRecentCached = result;
this.recentChanged = false;
this.recentChanged1 = false;
return result;
}
getSortedRecent() {
if (!this.recentChanged2 && this.sortedRecentCached) {
return this.sortedRecentCached;
}
let result = Object.values(this.recent);
result.sort((a, b) => b.touchTime - a.touchTime);
this.sortedRecentCached = result;
this.recentChanged2 = false;
return result;
}
}
export default new BookManager();

View File

@@ -3,6 +3,8 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta name="description" content="браузерная онлайн-читалка книг из интернета и библиотека">
<meta name="keywords" content="библиотека,онлайн,читалка,книги,читать,браузер,интернет">
<title></title>
</head>
<body>

View File

@@ -6,7 +6,7 @@ const fonts = [
{name: 'Arimo', fontVertShift: 0},
{name: 'Avrile', fontVertShift: -10},
{name: 'OpenSans', fontVertShift: -5},
{name: 'Roboto', fontVertShift: 10},
{name: 'Roboto', fontVertShift: 0},
{name: 'Rubik', fontVertShift: 0},
];
@@ -152,13 +152,18 @@ const settingDefaults = {
scrollingDelay: 3000,// замедление, ms
scrollingType: 'ease-in-out', //linear, ease, ease-in, ease-out, ease-in-out
pageChangeTransition: '',// '' - нет, downShift, rightShift, thaw - протаивание, blink - мерцание
pageChangeTransitionSpeed: 50, //0-100%
pageChangeAnimation: 'blink',// '' - нет, downShift, rightShift, thaw - протаивание, blink - мерцание
pageChangeAnimationSpeed: 80, //0-100%
allowUrlParamBookPos: false,
lazyParseEnabled: false,
copyFullText: false,
showClickMapPage: true,
clickControl: true,
cutEmptyParagraphs: false,
addEmptyParagraphs: 0,
blinkCachedLoad: true,
fontShifts: {},
};

56
package-lock.json generated
View File

@@ -1,6 +1,6 @@
{
"name": "Liberama",
"version": "0.1.0",
"version": "0.2.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
@@ -4477,7 +4477,8 @@
"ansi-regex": {
"version": "2.1.1",
"bundled": true,
"dev": true
"dev": true,
"optional": true
},
"aproba": {
"version": "1.2.0",
@@ -4498,12 +4499,14 @@
"balanced-match": {
"version": "1.0.0",
"bundled": true,
"dev": true
"dev": true,
"optional": true
},
"brace-expansion": {
"version": "1.1.11",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
@@ -4518,17 +4521,20 @@
"code-point-at": {
"version": "1.1.0",
"bundled": true,
"dev": true
"dev": true,
"optional": true
},
"concat-map": {
"version": "0.0.1",
"bundled": true,
"dev": true
"dev": true,
"optional": true
},
"console-control-strings": {
"version": "1.1.0",
"bundled": true,
"dev": true
"dev": true,
"optional": true
},
"core-util-is": {
"version": "1.0.2",
@@ -4645,7 +4651,8 @@
"inherits": {
"version": "2.0.3",
"bundled": true,
"dev": true
"dev": true,
"optional": true
},
"ini": {
"version": "1.3.5",
@@ -4657,6 +4664,7 @@
"version": "1.0.0",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"number-is-nan": "^1.0.0"
}
@@ -4671,6 +4679,7 @@
"version": "3.0.4",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"brace-expansion": "^1.1.7"
}
@@ -4678,12 +4687,14 @@
"minimist": {
"version": "0.0.8",
"bundled": true,
"dev": true
"dev": true,
"optional": true
},
"minipass": {
"version": "2.2.4",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"safe-buffer": "^5.1.1",
"yallist": "^3.0.0"
@@ -4702,6 +4713,7 @@
"version": "0.5.1",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"minimist": "0.0.8"
}
@@ -4782,7 +4794,8 @@
"number-is-nan": {
"version": "1.0.1",
"bundled": true,
"dev": true
"dev": true,
"optional": true
},
"object-assign": {
"version": "4.1.1",
@@ -4794,6 +4807,7 @@
"version": "1.4.0",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"wrappy": "1"
}
@@ -4879,7 +4893,8 @@
"safe-buffer": {
"version": "5.1.1",
"bundled": true,
"dev": true
"dev": true,
"optional": true
},
"safer-buffer": {
"version": "2.1.2",
@@ -4915,6 +4930,7 @@
"version": "1.0.2",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"code-point-at": "^1.0.0",
"is-fullwidth-code-point": "^1.0.0",
@@ -4934,6 +4950,7 @@
"version": "3.0.1",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"ansi-regex": "^2.0.0"
}
@@ -4977,12 +4994,14 @@
"wrappy": {
"version": "1.0.2",
"bundled": true,
"dev": true
"dev": true,
"optional": true
},
"yallist": {
"version": "3.0.2",
"bundled": true,
"dev": true
"dev": true,
"optional": true
}
}
},
@@ -6501,9 +6520,9 @@
}
},
"minimist": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz",
"integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0="
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz",
"integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ="
},
"minipass": {
"version": "2.3.5",
@@ -6567,6 +6586,13 @@
"integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=",
"requires": {
"minimist": "0.0.8"
},
"dependencies": {
"minimist": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz",
"integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0="
}
}
},
"move-concurrently": {

View File

@@ -1,6 +1,6 @@
{
"name": "Liberama",
"version": "0.1.0",
"version": "0.3.0",
"engines": {
"node": ">=10.0.0"
},
@@ -70,6 +70,7 @@
"iconv-lite": "^0.4.24",
"localforage": "^1.7.3",
"lodash": "^4.17.11",
"minimist": "^1.2.0",
"multer": "^1.4.1",
"path-browserify": "^1.0.0",
"sql-template-strings": "^2.2.2",

View File

@@ -17,6 +17,10 @@ module.exports = {
dbFileName: 'db.sqlite',
loggingEnabled: true,
maxUploadFileSize: 50*1024*1024,//50Мб
maxTempPublicDirSize: 512*1024*1024,//512Мб
maxUploadPublicDirSize: 200*1024*1024,//100Мб
servers: [
{
serverName: '1',
@@ -24,12 +28,6 @@ module.exports = {
ip: '0.0.0.0',
port: '33080',
},
{
serverName: '2',
mode: 'omnireader',
ip: '0.0.0.0',
port: '33081',
},
],
};

View File

@@ -0,0 +1,36 @@
const fs = require('fs-extra');
const _ = require('lodash');
const propsToSave = [
'maxUploadFileSize',
'maxTempPublicDirSize',
'maxUploadPublicDirSize',
'servers',
];
async function load(config, configFilename) {
if (!configFilename) {
configFilename = `${config.dataDir}/config.json`;
if (!await fs.pathExists(configFilename)) {
save(config);
return;
}
}
const data = await fs.readFile(configFilename, 'utf8');
Object.assign(config, JSON.parse(data));
}
async function save(config) {
const configFilename = `${config.dataDir}/config.json`;
const dataToSave = _.pick(config, propsToSave);
await fs.writeFile(configFilename, JSON.stringify(dataToSave, null, 4));
}
module.exports = {
load,
save
};

View File

@@ -19,12 +19,6 @@ module.exports = Object.assign({}, base, {
ip: '0.0.0.0',
port: '44080',
},
{
serverName: '2',
mode: 'omnireader',
ip: '0.0.0.0',
port: '44081',
},
],
}

View File

@@ -1,68 +0,0 @@
function getEncoding(buf) {
const lowerCase = 3;
const upperCase = 1;
const codePage = {
'k': 'koi8-r',
'w': 'Windows-1251',
'd': 'cp866',
'i': 'ISO-8859-5',
'm': 'maccyrillic',
};
let charsets = {
'k': 0,
'w': 0,
'd': 0,
'i': 0,
'm': 0
};
const len = buf.length;
const blockSize = (len > 5*3000 ? 3000 : len);
let counter = 0;
let i = 0;
while (i < len) {
const char = buf[i];
i++;
//non-russian characters
if (char < 128 || char > 256)
continue;
//CP866
if ((char > 159 && char < 176) || (char > 223 && char < 242)) charsets['d'] += lowerCase;
if ((char > 127 && char < 160)) charsets['d'] += upperCase;
//KOI8-R
if ((char > 191 && char < 223)) charsets['k'] += lowerCase;
if ((char > 222 && char < 256)) charsets['k'] += upperCase;
//WIN-1251
if (char > 223 && char < 256) charsets['w'] += lowerCase;
if (char > 191 && char < 224) charsets['w'] += upperCase;
//MAC
if (char > 221 && char < 255) charsets['m'] += lowerCase;
if (char > 127 && char < 160) charsets['m'] += upperCase;
//ISO-8859-5
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) {
return { codePage: codePage[key], c: charsets[key] };
});
sorted.sort((a, b) => b.c - a.c);
return sorted[0].codePage;
}
module.exports = getEncoding;

View File

@@ -4,7 +4,7 @@ const iconv = require('iconv-lite');
const chardet = require('chardet');
const _ = require('lodash');
const sax = require('./sax');
const getEncoding = require('./getEncoding');
const textUtils = require('./textUtils');
const FileDetector = require('../FileDetector');
@@ -18,28 +18,37 @@ class BookConverter {
async convertToFb2(inputFile, outputFile, url, callback) {
const fileType = await this.detector.detectFile(inputFile);
if (fileType && (fileType.ext == 'html' || fileType.ext == 'xml')) {
const data = await fs.readFile(inputFile);
const data = await fs.readFile(inputFile);
callback(100);
if (data.toString().indexOf('<FictionBook') >= 0) {
await fs.writeFile(outputFile, data);
if (fileType && (fileType.ext == 'html' || fileType.ext == 'xml')) {
if (data.toString().indexOf('<FictionBook') >= 0) {
await fs.writeFile(outputFile, this.checkEncoding(data));
return;
}
const parsedUrl = new URL(url);
if (parsedUrl.hostname == 'samlib.ru' ||
parsedUrl.hostname == 'budclub.ru') {
parsedUrl.hostname == 'budclub.ru' ||
parsedUrl.hostname == 'zhurnal.lib.ru') {
await fs.writeFile(outputFile, this.convertSamlib(data));
return;
}
await fs.writeFile(outputFile, this.convertHtml(data));
callback(100);
return;
} else {
if (fileType)
throw new Error(`unknown file format: ${fileType.mime}`);
else
throw new Error(`unsupported file format: ${url}`);
throw new Error(`Этот формат файла не поддерживается: ${fileType.mime}`);
else {
//может это чистый текст?
if (textUtils.checkIfText(data)) {
await fs.writeFile(outputFile, this.convertHtml(data, true));
return;
}
throw new Error(`Не удалось определить формат файла: ${url}`);
}
}
}
@@ -55,12 +64,34 @@ class BookConverter {
}
if (selected == 'ISO-8859-5') {
selected = getEncoding(data);
selected = textUtils.getEncoding(data);
}
return iconv.decode(data, selected);
}
checkEncoding(data) {
let result = data;
const left = data.indexOf('<?xml version="1.0"');
if (left >= 0) {
const right = data.indexOf('?>', left);
if (right >= 0) {
const head = data.slice(left, right + 2).toString();
const m = head.match(/encoding="(.*)"/);
if (m) {
let encoding = m[1].toLowerCase();
if (encoding != 'utf-8') {
result = iconv.decode(data, encoding);
result = Buffer.from(result.toString().replace(m[0], 'encoding="utf-8"'));
}
}
}
}
return result;
}
convertHtml(data, isText) {
let titleInfo = {};
let desc = {_n: 'description', 'title-info': titleInfo};
@@ -136,7 +167,7 @@ class BookConverter {
titleInfo['book-title'] = title;
//подозрение на чистый текст, надо разбить на параграфы
if ((isText || pars.length < buf.length/2000) && spaceCounter.length) {
if (isText || pars.length < buf.length/2000) {
let total = 0;
for (let i = 0; i < spaceCounter.length; i++) {
total += (spaceCounter[i] ? spaceCounter[i] : 0);
@@ -145,41 +176,37 @@ class BookConverter {
let i = spaceCounter.length - 1;
while (i > 0 && (!spaceCounter[i] || spaceCounter[i] < total)) i--;
const parIndent = i;
if (parIndent > 0) {//нашли отступ параграфа
const parIndent = (i > 0 ? i : 0);
let newPars = [];
const newPar = () => {
newPars.push({_n: 'p', _t: ''});
};
let newPars = [];
const newPar = () => {
newPars.push({_n: 'p', _t: ''});
};
const growPar = (text) => {
const l = newPars.length;
if (l) {
newPars[l - 1]._t += text;
}
const growPar = (text) => {
const l = newPars.length;
if (l) {
newPars[l - 1]._t += text;
}
for (const par of pars) {
newPar();
const lines = par._t.split('\n');
for (const line of lines) {
const sp = line.split(' ');
let l = 0;
while (l < sp.length && sp[l].trim() == '') {
l++;
}
if (l >= parIndent)
newPar();
growPar(line.trim() + ' ');
}
}
body.section._a[0] = newPars;
} else {
body.section._a[0] = pars;
}
for (const par of pars) {
newPar();
const lines = par._t.split('\n');
for (const line of lines) {
const sp = line.split(' ');
let l = 0;
while (l < sp.length && sp[l].trim() == '') {
l++;
}
if (l >= parIndent)
newPar();
growPar(line.trim() + ' ');
}
}
body.section._a[0] = newPars;
} else {
body.section._a[0] = pars;
}
@@ -207,6 +234,8 @@ class BookConverter {
let node = {_a: pars};
let inPara = false;
let italic = false;
let bold = false;
const openTag = (name) => {
if (name == 'p')
@@ -219,8 +248,11 @@ class BookConverter {
const closeTag = (name) => {
if (name == 'p')
inPara = false;
if (node._n == name && node._p) {
if (node._p) {
const exact = (node._n == name);
node = node._p;
if (!exact)
closeTag(name);
}
};
@@ -252,10 +284,10 @@ class BookConverter {
openTag('p');
break;
case 'i':
openTag('emphasis');
italic = true;
break;
case 'b':
openTag('strong');
bold = true;
break;
case 'div':
if (tail.indexOf('align="center"') >= 0) {
@@ -300,10 +332,10 @@ class BookConverter {
closeTag('p');
break;
case 'i':
closeTag('emphasis');
italic = false;
break;
case 'b':
closeTag('strong');
bold = false;
break;
case 'div':
if (inSubtitle) {
@@ -351,8 +383,13 @@ class BookConverter {
return;
}
let tOpen = (bold ? '<strong>' : '');
tOpen += (italic ? '<emphasis>' : '');
let tClose = (italic ? '</emphasis>' : '');
tClose += (bold ? '</strong>' : '');
if (inText)
growParagraph(text);
growParagraph(`${tOpen}${text}${tClose}`);
};
sax.parseSync(repSpaces(this.decode(data).toString()), {

View File

@@ -0,0 +1,94 @@
function getEncoding(buf) {
const lowerCase = 3;
const upperCase = 1;
const codePage = {
'k': 'koi8-r',
'w': 'Windows-1251',
'd': 'cp866',
'i': 'ISO-8859-5',
'm': 'maccyrillic',
};
let charsets = {
'k': 0,
'w': 0,
'd': 0,
'i': 0,
'm': 0
};
const len = buf.length;
const blockSize = (len > 5*3000 ? 3000 : len);
let counter = 0;
let i = 0;
while (i < len) {
const char = buf[i];
i++;
//non-russian characters
if (char < 128 || char > 256)
continue;
//CP866
if ((char > 159 && char < 176) || (char > 223 && char < 242)) charsets['d'] += lowerCase;
if ((char > 127 && char < 160)) charsets['d'] += upperCase;
//KOI8-R
if ((char > 191 && char < 223)) charsets['k'] += lowerCase;
if ((char > 222 && char < 256)) charsets['k'] += upperCase;
//WIN-1251
if (char > 223 && char < 256) charsets['w'] += lowerCase;
if (char > 191 && char < 224) charsets['w'] += upperCase;
//MAC
if (char > 221 && char < 255) charsets['m'] += lowerCase;
if (char > 127 && char < 160) charsets['m'] += upperCase;
//ISO-8859-5
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) {
return { codePage: codePage[key], c: charsets[key] };
});
sorted.sort((a, b) => b.c - a.c);
if (sorted[0].c > 0)
return sorted[0].codePage;
else
return 'ISO-8859-5';
}
function checkIfText(buf) {
let spaceCount = 0;
let crCount = 0;
let lfCount = 0;
for (let i = 0; i < buf.length; i++) {
if (buf[i] == 32)
spaceCount++;
if (buf[i] == 13)
crCount++;
if (buf[i] == 10)
lfCount++;
}
const spaceFreq = spaceCount/(buf.length + 1);
const crFreq = crCount/(buf.length + 1);
const lfFreq = lfCount/(buf.length + 1);
return (spaceFreq > 0.1 || crFreq > 0.03 || lfFreq > 0.03);
}
module.exports = {
getEncoding,
checkIfText,
}

View File

@@ -8,8 +8,6 @@ const FileDecompressor = require('./FileDecompressor');
const BookConverter = require('./BookConverter');
const utils = require('./utils');
const maxTempPublicDirSize = 512*1024*1024;//512Мб
const maxUploadDirSize = 200*1024*1024;//100Мб
let singleCleanExecute = false;
class ReaderWorker {
@@ -27,8 +25,8 @@ class ReaderWorker {
this.bookConverter = new BookConverter();
if (!singleCleanExecute) {
this.periodicCleanDir(this.config.tempPublicDir, maxTempPublicDirSize, 60*60*1000);//1 раз в час
this.periodicCleanDir(this.config.uploadDir, maxUploadDirSize, 60*60*1000);//1 раз в час
this.periodicCleanDir(this.config.tempPublicDir, this.config.maxTempPublicDirSize, 60*60*1000);//1 раз в час
this.periodicCleanDir(this.config.uploadDir, this.config.maxUploadPublicDirSize, 60*60*1000);//1 раз в час
singleCleanExecute = true;
}
}

View File

@@ -1,9 +1,11 @@
const config = require('./config');
const {initLogger, getLog} = require('./core/getLogger');
initLogger(config);
const log = getLog();
const configSaver = require('./config/configSaver');
const argv = require('minimist')(process.argv.slice(2));
const fs = require('fs-extra');
const path = require('path');
const express = require('express');
@@ -23,15 +25,17 @@ async function init() {
await fs.remove(appDir);
await fs.move(appNewDir, appDir);
}
//загружаем конфиг из файла
await configSaver.load(config, argv.config);
}
async function main() {
const connPool = new SqliteConnectionPool(20, config);
log('Initializing');
await init();
log('Opening database');
const connPool = new SqliteConnectionPool(20, config);
await connPool.init();
//servers
@@ -42,7 +46,7 @@ async function main() {
let devModule = undefined;
if (serverConfig.branch == 'development') {
const devFileName = './dev.js'; //ignored by pkg -50Mb executable size
const devFileName = './dev.js'; //require ignored by pkg -50Mb executable size
devModule = require(devFileName);
devModule.webpackDevMiddleware(app);
}
@@ -80,4 +84,12 @@ async function main() {
}
}
main();
(async() => {
try {
await main();
} catch (e) {
console.error(e.message);
process.exit(1);
}
})();

View File

@@ -2,8 +2,6 @@ const c = require('./controllers');
const utils = require('./core/utils');
const multer = require('multer');
const maxUploadSize = 50*1024*1024;
function initRoutes(app, connPool, config) {
const misc = new c.MiscController(connPool, config);
const reader = new c.ReaderController(connPool, config);
@@ -22,7 +20,7 @@ function initRoutes(app, connPool, config) {
cb(null, utils.randomHexString(30));
}
});
const upload = multer({ storage, limits: {fileSize: maxUploadSize} });
const upload = multer({ storage, limits: {fileSize: config.maxUploadFileSize} });
//routes
const routes = [