Compare commits
67 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c69e9d4b69 | ||
|
|
cc66c7f5ce | ||
|
|
7b5915cdf7 | ||
|
|
5cc99366ef | ||
|
|
73289543e7 | ||
|
|
716b8b5b9a | ||
|
|
c4f6c9383c | ||
|
|
7d77d478c1 | ||
|
|
572c0d0717 | ||
|
|
b786b7b2d6 | ||
|
|
3253858c7f | ||
|
|
a5fe61078d | ||
|
|
528adae3d0 | ||
|
|
d3ff0edbff | ||
|
|
61cfee222f | ||
|
|
a96eb50784 | ||
|
|
8219e19c1b | ||
|
|
3d56a6915f | ||
|
|
4d6502f5e2 | ||
|
|
f0f245884f | ||
|
|
815f9178bf | ||
|
|
2df88f4280 | ||
|
|
156a1b4aa8 | ||
|
|
962eda7860 | ||
|
|
954ce9e85c | ||
|
|
ff27ddd442 | ||
|
|
f9cc2ad70a | ||
|
|
4bcd45a795 | ||
|
|
9e7ccd6e20 | ||
|
|
631c5930e9 | ||
|
|
0ddb182642 | ||
|
|
de2f0e74c8 | ||
|
|
ad4ee6ccc9 | ||
|
|
1670df02db | ||
|
|
0268e647cd | ||
|
|
4b9315c13c | ||
|
|
14a9948dd2 | ||
|
|
060ec98b0c | ||
|
|
9c1efe381e | ||
|
|
6a1b052d16 | ||
|
|
d6151d541e | ||
|
|
3e90277e1e | ||
|
|
641cbdfe85 | ||
|
|
c36e9b36d8 | ||
|
|
ecc3acce93 | ||
|
|
33a2ca55f0 | ||
|
|
9d0bbec4b3 | ||
|
|
4de0b3cffd | ||
|
|
06221a474b | ||
|
|
e99a42b7af | ||
|
|
37822e8409 | ||
|
|
2e477e6c99 | ||
|
|
360ee98d8d | ||
|
|
69afd7720a | ||
|
|
a75590c493 | ||
|
|
2acb65f6b3 | ||
|
|
1e1a58b58c | ||
|
|
aeadb5aeb8 | ||
|
|
3e2f01d56d | ||
|
|
cad97e639a | ||
|
|
e2632f1802 | ||
|
|
9aa0bb2bde | ||
|
|
f015d5f7ed | ||
|
|
74f8f7f9a4 | ||
|
|
2598538de9 | ||
|
|
a78a00df2b | ||
|
|
92f6beb64e |
@@ -6,7 +6,9 @@ const api = axios.create({
|
|||||||
|
|
||||||
class Misc {
|
class Misc {
|
||||||
async loadConfig() {
|
async loadConfig() {
|
||||||
const response = await api.post('/config', {params: ['name', 'version', 'mode', 'maxUploadFileSize', 'branch']});
|
const response = await api.post('/config', {params: [
|
||||||
|
'name', 'version', 'mode', 'maxUploadFileSize', 'useExternalBookConverter', 'branch',
|
||||||
|
]});
|
||||||
return response.data;
|
return response.data;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ const workerApi = axios.create({
|
|||||||
|
|
||||||
class Reader {
|
class Reader {
|
||||||
async loadBook(url, callback) {
|
async loadBook(url, callback) {
|
||||||
const refreshPause = 200;
|
const refreshPause = 300;
|
||||||
if (!callback) callback = () => {};
|
if (!callback) callback = () => {};
|
||||||
|
|
||||||
let response = await api.post('/load-book', {type: 'url', url});
|
let response = await api.post('/load-book', {type: 'url', url});
|
||||||
@@ -44,7 +44,7 @@ class Reader {
|
|||||||
await sleep(refreshPause);
|
await sleep(refreshPause);
|
||||||
|
|
||||||
i++;
|
i++;
|
||||||
if (i > 30*1000/refreshPause) {//30 сек ждем телодвижений воркера
|
if (i > 120*1000/refreshPause) {//2 мин ждем телодвижений воркера
|
||||||
throw new Error('Слишком долгое время ожидания');
|
throw new Error('Слишком долгое время ожидания');
|
||||||
}
|
}
|
||||||
//проверка воркера
|
//проверка воркера
|
||||||
|
|||||||
@@ -15,8 +15,14 @@
|
|||||||
border
|
border
|
||||||
:default-sort = "{prop: 'touchDateTime', order: 'descending'}"
|
:default-sort = "{prop: 'touchDateTime', order: 'descending'}"
|
||||||
:header-cell-style = "headerCellStyle"
|
:header-cell-style = "headerCellStyle"
|
||||||
|
:row-key = "rowKey"
|
||||||
>
|
>
|
||||||
|
|
||||||
|
<el-table-column
|
||||||
|
type="index"
|
||||||
|
width="35px"
|
||||||
|
>
|
||||||
|
</el-table-column>
|
||||||
<el-table-column
|
<el-table-column
|
||||||
prop="touchDateTime"
|
prop="touchDateTime"
|
||||||
min-width="90px"
|
min-width="90px"
|
||||||
@@ -43,6 +49,7 @@
|
|||||||
placeholder="Найти"/-->
|
placeholder="Найти"/-->
|
||||||
<div class="el-input el-input--mini">
|
<div class="el-input el-input--mini">
|
||||||
<input class="el-input__inner"
|
<input class="el-input__inner"
|
||||||
|
ref="input"
|
||||||
placeholder="Найти"
|
placeholder="Найти"
|
||||||
style="margin: 0; padding: 0; vertical-align: bottom; margin-top: 20px; padding: 0 10px 0 10px"
|
style="margin: 0; padding: 0; vertical-align: bottom; margin-top: 20px; padding: 0 10px 0 10px"
|
||||||
:value="search" @input="search = $event.target.value"
|
:value="search" @input="search = $event.target.value"
|
||||||
@@ -118,9 +125,16 @@ class HistoryPage extends Vue {
|
|||||||
created() {
|
created() {
|
||||||
}
|
}
|
||||||
|
|
||||||
mounted() {
|
init() {
|
||||||
this.updateTableData();
|
this.updateTableData();
|
||||||
this.mostRecentBook = bookManager.mostRecentBook();
|
this.mostRecentBook = bookManager.mostRecentBook();
|
||||||
|
this.$nextTick(() => {
|
||||||
|
this.$refs.input.focus();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
rowKey(row) {
|
||||||
|
return row.key;
|
||||||
}
|
}
|
||||||
|
|
||||||
updateTableData() {
|
updateTableData() {
|
||||||
@@ -172,13 +186,15 @@ class HistoryPage extends Vue {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const search = this.search;
|
const search = this.search;
|
||||||
this.tableData = result.filter(item => {
|
result = result.filter(item => {
|
||||||
return !search ||
|
return !search ||
|
||||||
item.touchTime.includes(search) ||
|
item.touchTime.includes(search) ||
|
||||||
item.touchDate.includes(search) ||
|
item.touchDate.includes(search) ||
|
||||||
item.desc.title.toLowerCase().includes(search.toLowerCase()) ||
|
item.desc.title.toLowerCase().includes(search.toLowerCase()) ||
|
||||||
item.desc.author.toLowerCase().includes(search.toLowerCase())
|
item.desc.author.toLowerCase().includes(search.toLowerCase())
|
||||||
});
|
});
|
||||||
|
|
||||||
|
this.tableData = result;
|
||||||
}
|
}
|
||||||
|
|
||||||
headerCellStyle(cell) {
|
headerCellStyle(cell) {
|
||||||
@@ -210,7 +226,8 @@ class HistoryPage extends Vue {
|
|||||||
this.updateTableData();
|
this.updateTableData();
|
||||||
|
|
||||||
const newRecent = bookManager.mostRecentBook();
|
const newRecent = bookManager.mostRecentBook();
|
||||||
if (this.mostRecentBook != newRecent)
|
|
||||||
|
if (!(this.mostRecentBook && newRecent && this.mostRecentBook.key == newRecent.key))
|
||||||
this.$emit('load-book', newRecent);
|
this.$emit('load-book', newRecent);
|
||||||
|
|
||||||
this.mostRecentBook = newRecent;
|
this.mostRecentBook = newRecent;
|
||||||
|
|||||||
@@ -3,8 +3,11 @@
|
|||||||
<div class="part">
|
<div class="part">
|
||||||
<span class="greeting bold-font">{{ title }}</span>
|
<span class="greeting bold-font">{{ title }}</span>
|
||||||
<span class="greeting">Добро пожаловать!</span>
|
<span class="greeting">Добро пожаловать!</span>
|
||||||
<span class="greeting">Поддерживаются форматы: fb2, fb2.zip, html, txt</span>
|
<span class="greeting">Поддерживаются форматы: <b>fb2, html, txt</b></span>
|
||||||
|
<span v-if="isExternalConverter" class="greeting">...а также: <b>rtf, doc, docx</b>, и вскоре: pdf, epub, mobi</span>
|
||||||
|
<span class="greeting">...и распознается сжатие: <b>zip, bz2, gz</b></span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="part center">
|
<div class="part center">
|
||||||
<el-input ref="input" placeholder="URL книги" v-model="bookUrl">
|
<el-input ref="input" placeholder="URL книги" v-model="bookUrl">
|
||||||
<el-button slot="append" icon="el-icon-check" @click="submitUrl"></el-button>
|
<el-button slot="append" icon="el-icon-check" @click="submitUrl"></el-button>
|
||||||
@@ -15,8 +18,9 @@
|
|||||||
Загрузить файл с диска
|
Загрузить файл с диска
|
||||||
</el-button>
|
</el-button>
|
||||||
<div class="space"></div>
|
<div class="space"></div>
|
||||||
<span v-if="config.mode == 'omnireader'" class="bottom-span clickable" @click="openComments">Комментарии</span>
|
<span v-if="mode == 'omnireader'" class="bottom-span clickable" @click="openComments">Комментарии</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="part bottom">
|
<div class="part bottom">
|
||||||
<span class="bottom-span clickable" @click="openHelp">Справка</span>
|
<span class="bottom-span clickable" @click="openHelp">Справка</span>
|
||||||
<span class="bottom-span clickable" @click="openDonate">Помочь проекту</span>
|
<span class="bottom-span clickable" @click="openDonate">Помочь проекту</span>
|
||||||
@@ -38,7 +42,6 @@ class LoaderPage extends Vue {
|
|||||||
|
|
||||||
created() {
|
created() {
|
||||||
this.commit = this.$store.commit;
|
this.commit = this.$store.commit;
|
||||||
this.config = this.$store.state.config;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
mounted() {
|
mounted() {
|
||||||
@@ -50,14 +53,22 @@ class LoaderPage extends Vue {
|
|||||||
}
|
}
|
||||||
|
|
||||||
get title() {
|
get title() {
|
||||||
if (this.config.mode == 'omnireader')
|
if (this.$store.state.config.mode == 'omnireader')
|
||||||
return 'Omni Reader - браузерная онлайн-читалка.';
|
return 'Omni Reader - браузерная онлайн-читалка.';
|
||||||
return 'Универсальная читалка книг и ресурсов интернета.';
|
return 'Универсальная читалка книг и ресурсов интернета.';
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get mode() {
|
||||||
|
return this.$store.state.config.mode;
|
||||||
|
}
|
||||||
|
|
||||||
get version() {
|
get version() {
|
||||||
return `v${this.config.version}`;
|
return `v${this.$store.state.config.version}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
get isExternalConverter() {
|
||||||
|
return this.$store.state.config.useExternalBookConverter;
|
||||||
}
|
}
|
||||||
|
|
||||||
submitUrl() {
|
submitUrl() {
|
||||||
|
|||||||
@@ -69,7 +69,7 @@
|
|||||||
@stop-text-search="stopTextSearch">
|
@stop-text-search="stopTextSearch">
|
||||||
</SearchPage>
|
</SearchPage>
|
||||||
<CopyTextPage v-if="copyTextActive" ref="copyTextPage" @copy-text-toggle="copyTextToggle"></CopyTextPage>
|
<CopyTextPage v-if="copyTextActive" ref="copyTextPage" @copy-text-toggle="copyTextToggle"></CopyTextPage>
|
||||||
<HistoryPage v-if="historyActive" ref="historyPage" @load-book="loadBook" @history-toggle="historyToggle"></HistoryPage>
|
<HistoryPage v-show="historyActive" ref="historyPage" @load-book="loadBook" @history-toggle="historyToggle"></HistoryPage>
|
||||||
<SettingsPage v-if="settingsActive" ref="settingsPage" @settings-toggle="settingsToggle"></SettingsPage>
|
<SettingsPage v-if="settingsActive" ref="settingsPage" @settings-toggle="settingsToggle"></SettingsPage>
|
||||||
<HelpPage v-if="helpActive" ref="helpPage" @help-toggle="helpToggle"></HelpPage>
|
<HelpPage v-if="helpActive" ref="helpPage" @help-toggle="helpToggle"></HelpPage>
|
||||||
<ClickMapPage v-show="clickMapActive" ref="clickMapPage"></ClickMapPage>
|
<ClickMapPage v-show="clickMapActive" ref="clickMapPage"></ClickMapPage>
|
||||||
@@ -415,6 +415,7 @@ class Reader extends Vue {
|
|||||||
this.historyActive = !this.historyActive;
|
this.historyActive = !this.historyActive;
|
||||||
if (this.historyActive) {
|
if (this.historyActive) {
|
||||||
this.closeAllTextPages();
|
this.closeAllTextPages();
|
||||||
|
this.$refs.historyPage.init();
|
||||||
this.historyActive = true;
|
this.historyActive = true;
|
||||||
} else {
|
} else {
|
||||||
this.historyActive = false;
|
this.historyActive = false;
|
||||||
@@ -655,7 +656,7 @@ class Reader extends Vue {
|
|||||||
|
|
||||||
// если есть в локальном кэше
|
// если есть в локальном кэше
|
||||||
if (bookParsed) {
|
if (bookParsed) {
|
||||||
await bookManager.setRecentBook(Object.assign({bookPos, bookPosSeen, bookPosPercent}, bookManager.metaOnly(bookParsed)));
|
await bookManager.setRecentBook(Object.assign({bookPos, bookPosSeen, bookPosPercent}, bookParsed));
|
||||||
this.mostRecentBook();
|
this.mostRecentBook();
|
||||||
this.addAction(bookPos);
|
this.addAction(bookPos);
|
||||||
this.loaderActive = false;
|
this.loaderActive = false;
|
||||||
@@ -698,7 +699,7 @@ class Reader extends Vue {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// добавляем в историю
|
// добавляем в историю
|
||||||
await bookManager.setRecentBook(Object.assign({bookPos, bookPosSeen, bookPosPercent}, bookManager.metaOnly(addedBook)));
|
await bookManager.setRecentBook(Object.assign({bookPos, bookPosSeen, bookPosPercent}, addedBook));
|
||||||
this.mostRecentBook();
|
this.mostRecentBook();
|
||||||
this.addAction(bookPos);
|
this.addAction(bookPos);
|
||||||
this.updateRoute(true);
|
this.updateRoute(true);
|
||||||
@@ -831,6 +832,8 @@ class Reader extends Vue {
|
|||||||
break;
|
break;
|
||||||
case 'KeyX':
|
case 'KeyX':
|
||||||
this.historyToggle();
|
this.historyToggle();
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
break;
|
break;
|
||||||
case 'KeyS':
|
case 'KeyS':
|
||||||
this.settingsToggle();
|
this.settingsToggle();
|
||||||
|
|||||||
@@ -185,7 +185,7 @@
|
|||||||
<el-checkbox v-model="wordWrap">Перенос по слогам</el-checkbox>
|
<el-checkbox v-model="wordWrap">Перенос по слогам</el-checkbox>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="Обработка">
|
<el-form-item label="Обработка">
|
||||||
<el-checkbox v-model="cutEmptyParagraphs">Убирать пустые параграфы</el-checkbox>
|
<el-checkbox v-model="cutEmptyParagraphs">Убирать пустые строки</el-checkbox>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="">
|
<el-form-item label="">
|
||||||
<el-col :span="12">
|
<el-col :span="12">
|
||||||
@@ -207,12 +207,17 @@
|
|||||||
<template slot="content">
|
<template slot="content">
|
||||||
Выносить все изображения в центр экрана
|
Выносить все изображения в центр экрана
|
||||||
</template>
|
</template>
|
||||||
<el-checkbox v-model="showInlineImagesInCenter" @change="needReload">Инлайн в центр</el-checkbox>
|
<el-checkbox v-model="showInlineImagesInCenter" @change="needReload" :disabled="!showImages">Инлайн в центр</el-checkbox>
|
||||||
</el-tooltip>
|
</el-tooltip>
|
||||||
</el-col>
|
</el-col>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="">
|
<el-form-item label="">
|
||||||
Размер изображения
|
<el-checkbox v-model="imageFitWidth" :disabled="!showImages">Ширина не более размера экрана</el-checkbox>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="">
|
||||||
|
<el-col :span="12">
|
||||||
|
Высота не более
|
||||||
|
</el-col>
|
||||||
<el-tooltip :open-delay="500" effect="light" placement="top">
|
<el-tooltip :open-delay="500" effect="light" placement="top">
|
||||||
<template slot="content">
|
<template slot="content">
|
||||||
Определяет высоту изображения количеством строк.<br>
|
Определяет высоту изображения количеством строк.<br>
|
||||||
@@ -220,7 +225,7 @@
|
|||||||
уменьшено с сохранением пропорций так, чтобы<br>
|
уменьшено с сохранением пропорций так, чтобы<br>
|
||||||
помещаться в указанное количество строк.
|
помещаться в указанное количество строк.
|
||||||
</template>
|
</template>
|
||||||
<el-input-number v-model="imageHeightLines" :min="1" :max="100"></el-input-number>
|
<el-input-number v-model="imageHeightLines" :min="1" :max="100" :disabled="!showImages"></el-input-number>
|
||||||
</el-tooltip>
|
</el-tooltip>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
</el-form>
|
</el-form>
|
||||||
@@ -437,11 +442,12 @@ class SettingsPage extends Vue {
|
|||||||
'#000000',
|
'#000000',
|
||||||
'#202020',
|
'#202020',
|
||||||
'#ebe2c9',
|
'#ebe2c9',
|
||||||
|
'#cfdc99',
|
||||||
|
'#478355',
|
||||||
|
'#a6caf0',
|
||||||
'#909080',
|
'#909080',
|
||||||
'#808080',
|
'#808080',
|
||||||
'#c8c8c8',
|
'#c8c8c8',
|
||||||
'#478355',
|
|
||||||
'#a6caf0',
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -26,9 +26,9 @@ export default class DrawHelper {
|
|||||||
const font = this.fontByStyle({});
|
const font = this.fontByStyle({});
|
||||||
const justify = (this.textAlignJustify ? 'text-align: justify; text-align-last: justify;' : '');
|
const justify = (this.textAlignJustify ? 'text-align: justify; text-align-last: justify;' : '');
|
||||||
|
|
||||||
let out = `<div style="width: ${this.w}px; height: ${this.h}px;` +
|
let out = `<div style="width: ${this.w}px; height: ${this.h + (isScrolling ? this.lineHeight : 0)}px;` +
|
||||||
` position: absolute; top: ${this.fontSize*this.textShift}px; color: ${this.textColor}; font: ${font}; ${justify}` +
|
` position: absolute; top: ${this.fontSize*this.textShift}px; color: ${this.textColor}; font: ${font}; ${justify}` +
|
||||||
` line-height: ${this.lineHeight}px;">`;
|
` line-height: ${this.lineHeight}px; white-space: nowrap; overflow: hidden;">`;
|
||||||
|
|
||||||
let imageDrawn = new Set();
|
let imageDrawn = new Set();
|
||||||
let len = lines.length;
|
let len = lines.length;
|
||||||
@@ -91,32 +91,27 @@ export default class DrawHelper {
|
|||||||
} else
|
} else
|
||||||
text = part.text;
|
text = part.text;
|
||||||
|
|
||||||
if (text.trim() == '')
|
if (text && text.trim() == '')
|
||||||
text = `<span style="white-space: pre">${text}</span>`;
|
text = `<span style="white-space: pre">${text}</span>`;
|
||||||
|
|
||||||
lineText += `${tOpen}${text}${tClose}`;
|
lineText += `${tOpen}${text}${tClose}`;
|
||||||
|
|
||||||
center = center || part.style.center;
|
center = center || part.style.center;
|
||||||
space = (part.style.space > 0 ? part.style.space : space);
|
space = (part.style.space > space ? part.style.space : space);
|
||||||
|
|
||||||
//избражения
|
//избражения
|
||||||
//image: {local: Boolean, inline: Boolean, id: String, imageLine: Number, lineCount: Number, paraIndex: Number},
|
//image: {local: Boolean, inline: Boolean, id: String, imageLine: Number, lineCount: Number, paraIndex: Number, w: Number, h: Number},
|
||||||
const img = part.image;
|
const img = part.image;
|
||||||
if (img && img.id && !img.inline && !imageDrawn.has(img.paraIndex)) {
|
if (img && img.id && !img.inline && !imageDrawn.has(img.paraIndex)) {
|
||||||
const bin = this.parsed.binary[img.id];
|
const bin = this.parsed.binary[img.id];
|
||||||
if (bin) {
|
if (bin) {
|
||||||
let imgH = img.lineCount*this.lineHeight;
|
|
||||||
imgH = (imgH <= bin.h ? imgH : bin.h);
|
|
||||||
let imgW = bin.w;
|
|
||||||
|
|
||||||
let resize = '';
|
let resize = '';
|
||||||
if (bin.h > imgH) {
|
if (bin.h > img.h) {
|
||||||
resize = `height: ${imgH}px`;
|
resize = `height: ${img.h}px`;
|
||||||
imgW = imgW*imgH/bin.h;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const left = (this.w - imgW)/2;
|
const left = (this.w - img.w)/2;
|
||||||
const top = ((img.lineCount*this.lineHeight - imgH)/2) + (i - img.imageLine)*this.lineHeight;
|
const top = ((img.lineCount*this.lineHeight - img.h)/2) + (i - img.imageLine)*this.lineHeight;
|
||||||
if (img.local) {
|
if (img.local) {
|
||||||
lineText += `<img src="data:${bin.type};base64,${bin.data}" style="position: absolute; left: ${left}px; top: ${top}px; ${resize}"/>`;
|
lineText += `<img src="data:${bin.type};base64,${bin.data}" style="position: absolute; left: ${left}px; top: ${top}px; ${resize}"/>`;
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -221,6 +221,7 @@ class TextPage extends Vue {
|
|||||||
this.parsed.showImages = this.showImages;
|
this.parsed.showImages = this.showImages;
|
||||||
this.parsed.showInlineImagesInCenter = this.showInlineImagesInCenter;
|
this.parsed.showInlineImagesInCenter = this.showInlineImagesInCenter;
|
||||||
this.parsed.imageHeightLines = this.imageHeightLines;
|
this.parsed.imageHeightLines = this.imageHeightLines;
|
||||||
|
this.parsed.imageFitWidth = this.imageFitWidth;
|
||||||
}
|
}
|
||||||
|
|
||||||
//statusBar
|
//statusBar
|
||||||
|
|||||||
@@ -45,6 +45,9 @@ export default class BookParser {
|
|||||||
let italic = false;
|
let italic = false;
|
||||||
let space = 0;
|
let space = 0;
|
||||||
let inPara = false;
|
let inPara = false;
|
||||||
|
let isFirstBody = true;
|
||||||
|
let isFirstSection = true;
|
||||||
|
let isFirstTitlePara = false;
|
||||||
|
|
||||||
this.binary = {};
|
this.binary = {};
|
||||||
let binaryId = '';
|
let binaryId = '';
|
||||||
@@ -185,7 +188,7 @@ export default class BookParser {
|
|||||||
if (attrs.href && attrs.href.value) {
|
if (attrs.href && attrs.href.value) {
|
||||||
const href = attrs.href.value;
|
const href = attrs.href.value;
|
||||||
if (href[0] == '#') {//local
|
if (href[0] == '#') {//local
|
||||||
if (inPara && !this.showInlineImagesInCenter)
|
if (inPara && !this.showInlineImagesInCenter && !center)
|
||||||
growParagraph(`<image-inline href="${href}"></image-inline>`, 0);
|
growParagraph(`<image-inline href="${href}"></image-inline>`, 0);
|
||||||
else
|
else
|
||||||
newParagraph(`<image href="${href}">${' '.repeat(maxImageLineCount)}</image>`, maxImageLineCount);
|
newParagraph(`<image href="${href}">${' '.repeat(maxImageLineCount)}</image>`, maxImageLineCount);
|
||||||
@@ -199,14 +202,23 @@ export default class BookParser {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (path.indexOf('/fictionbook/body') == 0) {
|
if (path.indexOf('/fictionbook/body') == 0) {
|
||||||
|
if (tag == 'body') {
|
||||||
|
if (!isFirstBody)
|
||||||
|
newParagraph(' ', 1);
|
||||||
|
isFirstBody = false;
|
||||||
|
}
|
||||||
|
|
||||||
if (tag == 'title') {
|
if (tag == 'title') {
|
||||||
newParagraph(' ', 1);
|
newParagraph(' ', 1);
|
||||||
|
isFirstTitlePara = true;
|
||||||
bold = true;
|
bold = true;
|
||||||
center = true;
|
center = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (tag == 'section') {
|
if (tag == 'section') {
|
||||||
newParagraph(' ', 1);
|
if (!isFirstSection)
|
||||||
|
newParagraph(' ', 1);
|
||||||
|
isFirstSection = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (tag == 'emphasis' || tag == 'strong') {
|
if (tag == 'emphasis' || tag == 'strong') {
|
||||||
@@ -214,13 +226,17 @@ export default class BookParser {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if ((tag == 'p' || tag == 'empty-line' || tag == 'v')) {
|
if ((tag == 'p' || tag == 'empty-line' || tag == 'v')) {
|
||||||
newParagraph(' ', 1);
|
if (!(tag == 'p' && isFirstTitlePara))
|
||||||
if (tag == 'p')
|
newParagraph(' ', 1);
|
||||||
|
if (tag == 'p') {
|
||||||
inPara = true;
|
inPara = true;
|
||||||
|
isFirstTitlePara = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (tag == 'subtitle') {
|
if (tag == 'subtitle') {
|
||||||
newParagraph(' ', 1);
|
newParagraph(' ', 1);
|
||||||
|
isFirstTitlePara = true;
|
||||||
bold = true;
|
bold = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -248,6 +264,7 @@ export default class BookParser {
|
|||||||
|
|
||||||
if (path.indexOf('/fictionbook/body') == 0) {
|
if (path.indexOf('/fictionbook/body') == 0) {
|
||||||
if (tag == 'title') {
|
if (tag == 'title') {
|
||||||
|
isFirstTitlePara = false;
|
||||||
bold = false;
|
bold = false;
|
||||||
center = false;
|
center = false;
|
||||||
}
|
}
|
||||||
@@ -261,6 +278,7 @@ export default class BookParser {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (tag == 'subtitle') {
|
if (tag == 'subtitle') {
|
||||||
|
isFirstTitlePara = false;
|
||||||
bold = false;
|
bold = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -293,13 +311,13 @@ export default class BookParser {
|
|||||||
text = text.replace(/>/g, '>');
|
text = text.replace(/>/g, '>');
|
||||||
text = text.replace(/</g, '<');
|
text = text.replace(/</g, '<');
|
||||||
|
|
||||||
if (text != ' ' && text.trim() == '')
|
if (text && text.trim() == '')
|
||||||
text = text.trim();
|
text = (text.indexOf(' ') >= 0 ? ' ' : '');
|
||||||
|
|
||||||
if (text == '')
|
if (!text)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
text = text.replace(/[\t\n\r]/g, ' ');
|
text = text.replace(/[\t\n\r\xa0]/g, ' ');
|
||||||
|
|
||||||
switch (path) {
|
switch (path) {
|
||||||
case '/fictionbook/description/title-info/author/first-name':
|
case '/fictionbook/description/title-info/author/first-name':
|
||||||
@@ -348,13 +366,7 @@ export default class BookParser {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (path.indexOf('/fictionbook/body/section') == 0) {
|
if (path.indexOf('/fictionbook/body/section') == 0) {
|
||||||
switch (tag) {
|
growParagraph(`${tOpen}${text}${tClose}`, text.length);
|
||||||
case 'p':
|
|
||||||
growParagraph(`${tOpen}${text}${tClose}`, text.length);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
growParagraph(`${tOpen}${text}${tClose}`, text.length);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (binaryId) {
|
if (binaryId) {
|
||||||
@@ -597,7 +609,8 @@ export default class BookParser {
|
|||||||
para.parsed.cutEmptyParagraphs === this.cutEmptyParagraphs &&
|
para.parsed.cutEmptyParagraphs === this.cutEmptyParagraphs &&
|
||||||
para.parsed.addEmptyParagraphs === this.addEmptyParagraphs &&
|
para.parsed.addEmptyParagraphs === this.addEmptyParagraphs &&
|
||||||
para.parsed.showImages === this.showImages &&
|
para.parsed.showImages === this.showImages &&
|
||||||
para.parsed.imageHeightLines === this.imageHeightLines
|
para.parsed.imageHeightLines === this.imageHeightLines &&
|
||||||
|
para.parsed.imageFitWidth === this.imageFitWidth
|
||||||
)
|
)
|
||||||
return para.parsed;
|
return para.parsed;
|
||||||
|
|
||||||
@@ -611,6 +624,7 @@ export default class BookParser {
|
|||||||
addEmptyParagraphs: this.addEmptyParagraphs,
|
addEmptyParagraphs: this.addEmptyParagraphs,
|
||||||
showImages: this.showImages,
|
showImages: this.showImages,
|
||||||
imageHeightLines: this.imageHeightLines,
|
imageHeightLines: this.imageHeightLines,
|
||||||
|
imageFitWidth: this.imageFitWidth,
|
||||||
visible: !(
|
visible: !(
|
||||||
(this.cutEmptyParagraphs && para.cut) ||
|
(this.cutEmptyParagraphs && para.cut) ||
|
||||||
(para.addIndex > this.addEmptyParagraphs)
|
(para.addIndex > this.addEmptyParagraphs)
|
||||||
@@ -626,7 +640,7 @@ export default class BookParser {
|
|||||||
last: Boolean,
|
last: Boolean,
|
||||||
parts: array of {
|
parts: array of {
|
||||||
style: {bold: Boolean, italic: Boolean, center: Boolean},
|
style: {bold: Boolean, italic: Boolean, center: Boolean},
|
||||||
image: {local: Boolean, inline: Boolean, id: String, imageLine: Number, lineCount: Number, paraIndex: Number},
|
image: {local: Boolean, inline: Boolean, id: String, imageLine: Number, lineCount: Number, paraIndex: Number, w: Number, h: Number},
|
||||||
text: String,
|
text: String,
|
||||||
}
|
}
|
||||||
}*/
|
}*/
|
||||||
@@ -641,7 +655,6 @@ export default class BookParser {
|
|||||||
let style = {};
|
let style = {};
|
||||||
let ofs = 0;//смещение от начала параграфа para.offset
|
let ofs = 0;//смещение от начала параграфа para.offset
|
||||||
let imgW = 0;
|
let imgW = 0;
|
||||||
|
|
||||||
// тут начинается самый замес, перенос по слогам и стилизация, а также изображения
|
// тут начинается самый замес, перенос по слогам и стилизация, а также изображения
|
||||||
for (const part of parts) {
|
for (const part of parts) {
|
||||||
style = part.style;
|
style = part.style;
|
||||||
@@ -651,11 +664,24 @@ export default class BookParser {
|
|||||||
parsed.visible = this.showImages;
|
parsed.visible = this.showImages;
|
||||||
let bin = this.binary[part.image.id];
|
let bin = this.binary[part.image.id];
|
||||||
if (!bin)
|
if (!bin)
|
||||||
bin = {h: 0, w: 0};
|
bin = {h: 1, w: 1};
|
||||||
|
|
||||||
let lineCount = this.imageHeightLines;
|
let lineCount = this.imageHeightLines;
|
||||||
const c = Math.ceil(bin.h/this.lineHeight);
|
let c = Math.ceil(bin.h/this.lineHeight);
|
||||||
|
|
||||||
|
const maxH = lineCount*this.lineHeight;
|
||||||
|
let maxH2 = maxH;
|
||||||
|
if (this.imageFitWidth && bin.w > this.w) {
|
||||||
|
maxH2 = bin.h*this.w/bin.w;
|
||||||
|
c = Math.ceil(maxH2/this.lineHeight);
|
||||||
|
}
|
||||||
lineCount = (c < lineCount ? c : lineCount);
|
lineCount = (c < lineCount ? c : lineCount);
|
||||||
|
|
||||||
|
let imageHeight = (maxH2 < maxH ? maxH2 : maxH);
|
||||||
|
imageHeight = (imageHeight <= bin.h ? imageHeight : bin.h);
|
||||||
|
|
||||||
|
let imageWidth = (bin.h > imageHeight ? bin.w*imageHeight/bin.h : bin.w);
|
||||||
|
|
||||||
let i = 0;
|
let i = 0;
|
||||||
for (; i < lineCount - 1; i++) {
|
for (; i < lineCount - 1; i++) {
|
||||||
line.end = para.offset + ofs;
|
line.end = para.offset + ofs;
|
||||||
@@ -667,7 +693,9 @@ export default class BookParser {
|
|||||||
id: part.image.id,
|
id: part.image.id,
|
||||||
imageLine: i,
|
imageLine: i,
|
||||||
lineCount,
|
lineCount,
|
||||||
paraIndex
|
paraIndex,
|
||||||
|
w: imageWidth,
|
||||||
|
h: imageHeight,
|
||||||
}});
|
}});
|
||||||
lines.push(line);
|
lines.push(line);
|
||||||
line = {begin: line.end + 1, parts: []};
|
line = {begin: line.end + 1, parts: []};
|
||||||
@@ -677,7 +705,9 @@ export default class BookParser {
|
|||||||
line.first = (j == 0);
|
line.first = (j == 0);
|
||||||
line.last = true;
|
line.last = true;
|
||||||
line.parts.push({style, text: ' ',
|
line.parts.push({style, text: ' ',
|
||||||
image: {local: part.image.local, inline: false, id: part.image.id, imageLine: i, lineCount, paraIndex}});
|
image: {local: part.image.local, inline: false, id: part.image.id,
|
||||||
|
imageLine: i, lineCount, paraIndex, w: imageWidth, h: imageHeight}
|
||||||
|
});
|
||||||
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,10 @@ import BookParser from './BookParser';
|
|||||||
|
|
||||||
const maxDataSize = 500*1024*1024;//chars, not bytes
|
const maxDataSize = 500*1024*1024;//chars, not bytes
|
||||||
|
|
||||||
|
const bmCacheStore = localForage.createInstance({
|
||||||
|
name: 'bmCacheStore'
|
||||||
|
});
|
||||||
|
|
||||||
const bmMetaStore = localForage.createInstance({
|
const bmMetaStore = localForage.createInstance({
|
||||||
name: 'bmMetaStore'
|
name: 'bmMetaStore'
|
||||||
});
|
});
|
||||||
@@ -20,11 +24,31 @@ const bmRecentStore = localForage.createInstance({
|
|||||||
class BookManager {
|
class BookManager {
|
||||||
async init(settings) {
|
async init(settings) {
|
||||||
this.settings = settings;
|
this.settings = settings;
|
||||||
this.books = {};
|
|
||||||
this.recent = {};
|
//this.booksCached нужен только для ускорения загрузки читалки
|
||||||
|
this.booksCached = await bmCacheStore.getItem('books');
|
||||||
|
if (!this.booksCached)
|
||||||
|
this.booksCached = {};
|
||||||
|
this.recent = await bmCacheStore.getItem('recent');
|
||||||
|
this.books = Object.assign({}, this.booksCached);
|
||||||
|
|
||||||
this.recentChanged1 = true;
|
this.recentChanged1 = true;
|
||||||
this.recentChanged2 = true;
|
this.recentChanged2 = true;
|
||||||
|
|
||||||
|
if (!this.books || !this.recent) {
|
||||||
|
this.books = {};
|
||||||
|
this.recent = {};
|
||||||
|
await this.loadMeta(true);
|
||||||
|
} else {
|
||||||
|
this.loadMeta(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async loadMeta(immediate) {
|
||||||
|
if (!immediate)
|
||||||
|
await utils.sleep(2000);
|
||||||
|
|
||||||
let len = await bmMetaStore.length();
|
let len = await bmMetaStore.length();
|
||||||
for (let i = 0; i < len; i++) {
|
for (let i = 0; i < len; i++) {
|
||||||
const key = await bmMetaStore.key(i);
|
const key = await bmMetaStore.key(i);
|
||||||
@@ -45,6 +69,12 @@ class BookManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await this.cleanBooks();
|
await this.cleanBooks();
|
||||||
|
|
||||||
|
this.booksCached = {};
|
||||||
|
for (const key in this.books) {
|
||||||
|
this.booksCached[key] = this.metaOnly(this.books[key]);
|
||||||
|
}
|
||||||
|
await bmCacheStore.setItem('books', this.booksCached);
|
||||||
}
|
}
|
||||||
|
|
||||||
async cleanBooks() {
|
async cleanBooks() {
|
||||||
@@ -80,9 +110,11 @@ class BookManager {
|
|||||||
const result = await this.parseBook(meta, newBook.data, callback);
|
const result = await this.parseBook(meta, newBook.data, callback);
|
||||||
|
|
||||||
this.books[meta.key] = result;
|
this.books[meta.key] = result;
|
||||||
|
this.booksCached[meta.key] = this.metaOnly(result);
|
||||||
|
|
||||||
await bmMetaStore.setItem(`bmMeta-${meta.key}`, this.metaOnly(result));
|
await bmMetaStore.setItem(`bmMeta-${meta.key}`, this.metaOnly(result));
|
||||||
await bmDataStore.setItem(`bmData-${meta.key}`, result.data);
|
await bmDataStore.setItem(`bmData-${meta.key}`, result.data);
|
||||||
|
await bmCacheStore.setItem('books', this.booksCached);
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -127,11 +159,15 @@ class BookManager {
|
|||||||
await bmDataStore.removeItem(`bmData-${meta.key}`);
|
await bmDataStore.removeItem(`bmData-${meta.key}`);
|
||||||
|
|
||||||
delete this.books[meta.key];
|
delete this.books[meta.key];
|
||||||
|
delete this.booksCached[meta.key];
|
||||||
|
|
||||||
|
await bmCacheStore.setItem('books', this.booksCached);
|
||||||
}
|
}
|
||||||
|
|
||||||
async parseBook(meta, data, callback) {
|
async parseBook(meta, data, callback) {
|
||||||
if (!this.books)
|
if (!this.books)
|
||||||
await this.init();
|
await this.init();
|
||||||
|
|
||||||
const parsed = new BookParser(this.settings);
|
const parsed = new BookParser(this.settings);
|
||||||
|
|
||||||
const parsedMeta = await parsed.parse(data, callback);
|
const parsedMeta = await parsed.parse(data, callback);
|
||||||
@@ -159,7 +195,7 @@ class BookManager {
|
|||||||
async setRecentBook(value, noTouch) {
|
async setRecentBook(value, noTouch) {
|
||||||
if (!this.recent)
|
if (!this.recent)
|
||||||
await this.init();
|
await this.init();
|
||||||
const result = Object.assign({}, value);
|
const result = this.metaOnly(value);
|
||||||
if (!noTouch)
|
if (!noTouch)
|
||||||
Object.assign(result, {touchTime: Date.now()});
|
Object.assign(result, {touchTime: Date.now()});
|
||||||
|
|
||||||
@@ -170,6 +206,7 @@ class BookManager {
|
|||||||
|
|
||||||
await bmRecentStore.setItem(result.key, result);
|
await bmRecentStore.setItem(result.key, result);
|
||||||
await this.cleanRecentBooks();
|
await this.cleanRecentBooks();
|
||||||
|
await bmCacheStore.setItem('recent', this.recent);
|
||||||
|
|
||||||
this.recentChanged1 = true;
|
this.recentChanged1 = true;
|
||||||
this.recentChanged2 = true;
|
this.recentChanged2 = true;
|
||||||
@@ -188,6 +225,8 @@ class BookManager {
|
|||||||
|
|
||||||
await bmRecentStore.removeItem(value.key);
|
await bmRecentStore.removeItem(value.key);
|
||||||
delete this.recent[value.key];
|
delete this.recent[value.key];
|
||||||
|
await bmCacheStore.setItem('recent', this.recent);
|
||||||
|
|
||||||
this.recentChanged1 = true;
|
this.recentChanged1 = true;
|
||||||
this.recentChanged2 = true;
|
this.recentChanged2 = true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -162,8 +162,9 @@ const settingDefaults = {
|
|||||||
addEmptyParagraphs: 0,
|
addEmptyParagraphs: 0,
|
||||||
blinkCachedLoad: true,
|
blinkCachedLoad: true,
|
||||||
showImages: true,
|
showImages: true,
|
||||||
showInlineImagesInCenter: false,
|
showInlineImagesInCenter: true,
|
||||||
imageHeightLines: 100,
|
imageHeightLines: 100,
|
||||||
|
imageFitWidth: true,
|
||||||
|
|
||||||
fontShifts: {},
|
fontShifts: {},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -15,6 +15,18 @@ chgrp www-data /home/oldreader
|
|||||||
sudo -u www-data cp -r ./old/* /home/oldreader
|
sudo -u www-data cp -r ./old/* /home/oldreader
|
||||||
###
|
###
|
||||||
|
|
||||||
|
### external converter
|
||||||
|
# calibre releases https://download.calibre-ebook.com/
|
||||||
|
# download, unpack to data/calibre
|
||||||
|
# 3.39.1
|
||||||
|
wget "https://download.calibre-ebook.com/3.39.1/calibre-3.39.1-x86_64.txz"
|
||||||
|
sudo -u www-data mkdir -p /home/liberama/data/calibre
|
||||||
|
sudo -u www-data tar xvf calibre-3.39.1-x86_64.txz -C /home/liberama/data/calibre
|
||||||
|
|
||||||
|
apt install libreoffice
|
||||||
|
apt install poppler-utils
|
||||||
|
###
|
||||||
|
|
||||||
apt install nginx
|
apt install nginx
|
||||||
|
|
||||||
cp omnireader /etc/nginx/sites-available/omnireader
|
cp omnireader /etc/nginx/sites-available/omnireader
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
sudo -u www-data /home/liberama/liberama
|
export HOME=/var/www; sudo -u www-data /home/liberama/liberama
|
||||||
7
package-lock.json
generated
7
package-lock.json
generated
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "Liberama",
|
"name": "Liberama",
|
||||||
"version": "0.3.2",
|
"version": "0.4.7",
|
||||||
"lockfileVersion": 1,
|
"lockfileVersion": 1,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -3291,11 +3291,6 @@
|
|||||||
"integrity": "sha1-8NZtA2cqglyxtzvbP+YjEMjlUrc=",
|
"integrity": "sha1-8NZtA2cqglyxtzvbP+YjEMjlUrc=",
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
"detect-file-type": {
|
|
||||||
"version": "0.2.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/detect-file-type/-/detect-file-type-0.2.0.tgz",
|
|
||||||
"integrity": "sha512-RO/pUyKObaN3KZFVAxTzq6zUIweCu45deaUj2ZpbA1wCrmHeHYHpCXT6ZMLtlMtYSgEbpGuCxzQz8a9IuwOfNw=="
|
|
||||||
},
|
|
||||||
"detect-indent": {
|
"detect-indent": {
|
||||||
"version": "4.0.0",
|
"version": "4.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-4.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-4.0.0.tgz",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "Liberama",
|
"name": "Liberama",
|
||||||
"version": "0.4.2",
|
"version": "0.5.1",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=10.0.0"
|
"node": ">=10.0.0"
|
||||||
},
|
},
|
||||||
@@ -62,7 +62,6 @@
|
|||||||
"decompress": "^4.2.0",
|
"decompress": "^4.2.0",
|
||||||
"decompress-bzip2": "^4.0.0",
|
"decompress-bzip2": "^4.0.0",
|
||||||
"decompress-gz": "0.0.1",
|
"decompress-gz": "0.0.1",
|
||||||
"detect-file-type": "^0.2.0",
|
|
||||||
"element-ui": "^2.4.11",
|
"element-ui": "^2.4.11",
|
||||||
"express": "^4.16.4",
|
"express": "^4.16.4",
|
||||||
"fg-loadcss": "^2.1.0",
|
"fg-loadcss": "^2.1.0",
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ module.exports = {
|
|||||||
maxTempPublicDirSize: 512*1024*1024,//512Мб
|
maxTempPublicDirSize: 512*1024*1024,//512Мб
|
||||||
maxUploadPublicDirSize: 200*1024*1024,//100Мб
|
maxUploadPublicDirSize: 200*1024*1024,//100Мб
|
||||||
|
|
||||||
|
useExternalBookConverter: false,
|
||||||
|
|
||||||
servers: [
|
servers: [
|
||||||
{
|
{
|
||||||
serverName: '1',
|
serverName: '1',
|
||||||
|
|||||||
@@ -5,7 +5,8 @@ const propsToSave = [
|
|||||||
'maxUploadFileSize',
|
'maxUploadFileSize',
|
||||||
'maxTempPublicDirSize',
|
'maxTempPublicDirSize',
|
||||||
'maxUploadPublicDirSize',
|
'maxUploadPublicDirSize',
|
||||||
|
'useExternalBookConverter',
|
||||||
|
|
||||||
'servers',
|
'servers',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
134
server/core/BookConverter/ConvertBase.js
Normal file
134
server/core/BookConverter/ConvertBase.js
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
const fs = require('fs-extra');
|
||||||
|
const iconv = require('iconv-lite');
|
||||||
|
const chardet = require('chardet');
|
||||||
|
|
||||||
|
const textUtils = require('./textUtils');
|
||||||
|
const utils = require('../utils');
|
||||||
|
|
||||||
|
class ConvertBase {
|
||||||
|
constructor(config) {
|
||||||
|
this.config = config;
|
||||||
|
|
||||||
|
this.calibrePath = `${config.dataDir}/calibre/ebook-convert`;
|
||||||
|
this.sofficePath = '/usr/bin/soffice';
|
||||||
|
this.pdfToHtmlPath = '/usr/bin/pdftohtml';
|
||||||
|
}
|
||||||
|
|
||||||
|
async run(data, opts) {// eslint-disable-line no-unused-vars
|
||||||
|
//override
|
||||||
|
}
|
||||||
|
|
||||||
|
async checkExternalConverterPresent() {
|
||||||
|
if (!await fs.pathExists(this.calibrePath))
|
||||||
|
throw new Error('Внешний конвертер calibre не найден');
|
||||||
|
|
||||||
|
if (!await fs.pathExists(this.sofficePath))
|
||||||
|
throw new Error('Внешний конвертер LibreOffice не найден');
|
||||||
|
|
||||||
|
if (!await fs.pathExists(this.pdfToHtmlPath))
|
||||||
|
throw new Error('Внешний конвертер pdftohtml не найден');
|
||||||
|
}
|
||||||
|
|
||||||
|
async execConverter(path, args, onData) {
|
||||||
|
try {
|
||||||
|
const result = await utils.spawnProcess(path, {args, onData});
|
||||||
|
if (result.code != 0) {
|
||||||
|
let error = result.code;
|
||||||
|
if (this.config.branch == 'development')
|
||||||
|
error = `exec: ${path}, stdout: ${result.stdout}, stderr: ${result.stderr}`;
|
||||||
|
throw new Error(`Внешний конвертер завершился с ошибкой: ${error}`);
|
||||||
|
}
|
||||||
|
} catch(e) {
|
||||||
|
if (e.status == 'killed') {
|
||||||
|
throw new Error('Слишком долгое ожидание конвертера');
|
||||||
|
} else if (e.status == 'error') {
|
||||||
|
throw new Error(e.error);
|
||||||
|
} else {
|
||||||
|
throw new Error(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
decode(data) {
|
||||||
|
let selected = textUtils.getEncoding(data);
|
||||||
|
|
||||||
|
if (selected == 'ISO-8859-5') {
|
||||||
|
const charsetAll = chardet.detectAll(data.slice(0, 20000));
|
||||||
|
for (const charset of charsetAll) {
|
||||||
|
if (charset.name.indexOf('ISO-8859') < 0) {
|
||||||
|
selected = charset.name;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (selected.toLowerCase() != 'utf-8')
|
||||||
|
return iconv.decode(data, selected);
|
||||||
|
else
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
repSpaces(text) {
|
||||||
|
return text.replace(/ |[\t\n\r]/g, ' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
formatFb2(fb2) {
|
||||||
|
let out = '<?xml version="1.0" encoding="utf-8"?>';
|
||||||
|
out += '<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">';
|
||||||
|
out += this.formatFb2Node(fb2);
|
||||||
|
out += '</FictionBook>';
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
formatFb2Node(node, name) {
|
||||||
|
let out = '';
|
||||||
|
|
||||||
|
if (Array.isArray(node)) {
|
||||||
|
for (const n of node) {
|
||||||
|
out += this.formatFb2Node(n);
|
||||||
|
}
|
||||||
|
} else if (typeof node == 'string') {
|
||||||
|
if (name)
|
||||||
|
out += `<${name}>${this.repSpaces(node)}</${name}>`;
|
||||||
|
else
|
||||||
|
out += this.repSpaces(node);
|
||||||
|
} else {
|
||||||
|
if (node._n)
|
||||||
|
name = node._n;
|
||||||
|
|
||||||
|
let attrs = '';
|
||||||
|
if (node._attrs) {
|
||||||
|
for (let attrName in node._attrs) {
|
||||||
|
attrs += ` ${attrName}="${node._attrs[attrName]}"`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let tOpen = '';
|
||||||
|
let tBody = '';
|
||||||
|
let tClose = '';
|
||||||
|
if (name)
|
||||||
|
tOpen += `<${name}${attrs}>`;
|
||||||
|
if (node.hasOwnProperty('_t'))
|
||||||
|
tBody += this.repSpaces(node._t);
|
||||||
|
|
||||||
|
for (let nodeName in node) {
|
||||||
|
if (nodeName && nodeName[0] == '_' && nodeName != '_a')
|
||||||
|
continue;
|
||||||
|
|
||||||
|
const n = node[nodeName];
|
||||||
|
tBody += this.formatFb2Node(n, nodeName);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (name)
|
||||||
|
tClose += `</${name}>`;
|
||||||
|
|
||||||
|
if (attrs == '' && name == 'p' && tBody.trim() == '')
|
||||||
|
out += '<empty-line/>'
|
||||||
|
else
|
||||||
|
out += `${tOpen}${tBody}${tClose}`;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = ConvertBase;
|
||||||
33
server/core/BookConverter/ConvertDoc.js
Normal file
33
server/core/BookConverter/ConvertDoc.js
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
const fs = require('fs-extra');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const ConvertDocX = require('./ConvertDocX');
|
||||||
|
|
||||||
|
class ConvertDoc extends ConvertDocX {
|
||||||
|
check(data, opts) {
|
||||||
|
const {inputFiles} = opts;
|
||||||
|
|
||||||
|
return this.config.useExternalBookConverter &&
|
||||||
|
inputFiles.sourceFileType && inputFiles.sourceFileType.ext == 'msi';
|
||||||
|
}
|
||||||
|
|
||||||
|
async run(data, opts) {
|
||||||
|
if (!this.check(data, opts))
|
||||||
|
return false;
|
||||||
|
await this.checkExternalConverterPresent();
|
||||||
|
|
||||||
|
const {inputFiles, callback} = opts;
|
||||||
|
|
||||||
|
const outFile = `${inputFiles.fileListDir}/${path.basename(inputFiles.sourceFile)}`;
|
||||||
|
const docFile = `${outFile}.doc`;
|
||||||
|
const docxFile = `${outFile}.docx`;
|
||||||
|
const fb2File = `${outFile}.fb2`;
|
||||||
|
|
||||||
|
await fs.copy(inputFiles.sourceFile, docFile);
|
||||||
|
await this.execConverter(this.sofficePath, ['--headless', '--convert-to', 'docx', '--outdir', inputFiles.fileListDir, docFile]);
|
||||||
|
|
||||||
|
return await super.convert(docxFile, fb2File, callback);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = ConvertDoc;
|
||||||
50
server/core/BookConverter/ConvertDocX.js
Normal file
50
server/core/BookConverter/ConvertDocX.js
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
const fs = require('fs-extra');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const ConvertBase = require('./ConvertBase');
|
||||||
|
|
||||||
|
class ConvertDocX extends ConvertBase {
|
||||||
|
check(data, opts) {
|
||||||
|
const {inputFiles} = opts;
|
||||||
|
|
||||||
|
if (this.config.useExternalBookConverter &&
|
||||||
|
inputFiles.sourceFileType && inputFiles.sourceFileType.ext == 'zip') {
|
||||||
|
//ищем файл '[Content_Types].xml'
|
||||||
|
for (const file of inputFiles.fileList) {
|
||||||
|
if (file == '[Content_Types].xml') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
async convert(docxFile, fb2File, callback) {
|
||||||
|
let perc = 0;
|
||||||
|
await this.execConverter(this.calibrePath, [docxFile, fb2File], () => {
|
||||||
|
perc = (perc < 100 ? perc + 5 : 50);
|
||||||
|
callback(perc);
|
||||||
|
});
|
||||||
|
|
||||||
|
return await fs.readFile(fb2File);
|
||||||
|
}
|
||||||
|
|
||||||
|
async run(data, opts) {
|
||||||
|
if (!this.check(data, opts))
|
||||||
|
return false;
|
||||||
|
await this.checkExternalConverterPresent();
|
||||||
|
|
||||||
|
const {inputFiles, callback} = opts;
|
||||||
|
|
||||||
|
const outFile = `${inputFiles.fileListDir}/${path.basename(inputFiles.sourceFile)}`;
|
||||||
|
const docxFile = `${outFile}.docx`;
|
||||||
|
const fb2File = `${outFile}.fb2`;
|
||||||
|
|
||||||
|
await fs.copy(inputFiles.sourceFile, docxFile);
|
||||||
|
|
||||||
|
return await this.convert(docxFile, fb2File, callback);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = ConvertDocX;
|
||||||
41
server/core/BookConverter/ConvertFb2.js
Normal file
41
server/core/BookConverter/ConvertFb2.js
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
const ConvertBase = require('./ConvertBase');
|
||||||
|
const iconv = require('iconv-lite');
|
||||||
|
|
||||||
|
class ConvertFb2 extends ConvertBase {
|
||||||
|
check(data, opts) {
|
||||||
|
const {dataType} = opts;
|
||||||
|
|
||||||
|
return (dataType && dataType.ext == 'xml' && data.toString().indexOf('<FictionBook') >= 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
async run(data, opts) {
|
||||||
|
if (!this.check(data, opts))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return this.checkEncoding(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = ConvertFb2;
|
||||||
162
server/core/BookConverter/ConvertHtml.js
Normal file
162
server/core/BookConverter/ConvertHtml.js
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
const ConvertBase = require('./ConvertBase');
|
||||||
|
const sax = require('./sax');
|
||||||
|
const textUtils = require('./textUtils');
|
||||||
|
|
||||||
|
class ConvertHtml extends ConvertBase {
|
||||||
|
check(data, opts) {
|
||||||
|
const {dataType} = opts;
|
||||||
|
|
||||||
|
if (dataType && (dataType.ext == 'html' || dataType.ext == 'xml'))
|
||||||
|
return {isText: false};
|
||||||
|
|
||||||
|
//может это чистый текст?
|
||||||
|
if (textUtils.checkIfText(data)) {
|
||||||
|
return {isText: true};
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
async run(data, opts) {
|
||||||
|
const checkResult = this.check(data, opts);
|
||||||
|
if (!checkResult)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
let {isText} = checkResult;
|
||||||
|
let titleInfo = {};
|
||||||
|
let desc = {_n: 'description', 'title-info': titleInfo};
|
||||||
|
let pars = [];
|
||||||
|
let body = {_n: 'body', section: {_a: []}};
|
||||||
|
let fb2 = [desc, body];
|
||||||
|
|
||||||
|
let title = '';
|
||||||
|
let inTitle = false;
|
||||||
|
|
||||||
|
let spaceCounter = [];
|
||||||
|
|
||||||
|
const repCrLfTab = (text) => text.replace(/[\n\r]/g, '').replace(/\t/g, ' ');
|
||||||
|
|
||||||
|
const newParagraph = () => {
|
||||||
|
pars.push({_n: 'p', _t: ''});
|
||||||
|
};
|
||||||
|
|
||||||
|
const growParagraph = (text) => {
|
||||||
|
if (!pars.length)
|
||||||
|
newParagraph();
|
||||||
|
|
||||||
|
const l = pars.length;
|
||||||
|
if (pars[l - 1]._t == '')
|
||||||
|
text = text.trimLeft();
|
||||||
|
pars[l - 1]._t += text;
|
||||||
|
|
||||||
|
//посчитаем отступы у текста, чтобы выделить потом параграфы
|
||||||
|
const lines = text.split('\n');
|
||||||
|
for (let line of lines) {
|
||||||
|
line = repCrLfTab(line)
|
||||||
|
|
||||||
|
let l = 0;
|
||||||
|
while (l < line.length && line[l] == ' ') {
|
||||||
|
l++;
|
||||||
|
}
|
||||||
|
if (!spaceCounter[l])
|
||||||
|
spaceCounter[l] = 0;
|
||||||
|
spaceCounter[l]++;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const newPara = new Set(['tr', 'br', 'br/', 'dd', 'p', 'title', '/title', 'h1', 'h2', 'h3', '/h1', '/h2', '/h3']);
|
||||||
|
|
||||||
|
const onTextNode = (text, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
|
||||||
|
if (!cutCounter) {
|
||||||
|
growParagraph(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inTitle && !title)
|
||||||
|
title = text;
|
||||||
|
};
|
||||||
|
|
||||||
|
const onStartNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
|
||||||
|
if (!cutCounter) {
|
||||||
|
if (newPara.has(tag))
|
||||||
|
newParagraph();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tag == 'title')
|
||||||
|
inTitle = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const onEndNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
|
||||||
|
if (tag == 'title')
|
||||||
|
inTitle = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
let buf = this.decode(data).toString();
|
||||||
|
|
||||||
|
sax.parseSync(buf, {
|
||||||
|
onStartNode, onEndNode, onTextNode,
|
||||||
|
innerCut: new Set(['head', 'script', 'style', 'binary'])
|
||||||
|
});
|
||||||
|
|
||||||
|
titleInfo['book-title'] = title;
|
||||||
|
|
||||||
|
//подозрение на чистый текст, надо разбить на параграфы
|
||||||
|
if (isText || pars.length < buf.length/2000) {
|
||||||
|
let total = 0;
|
||||||
|
for (let i = 0; i < spaceCounter.length; i++) {
|
||||||
|
total += (spaceCounter[i] ? spaceCounter[i] : 0);
|
||||||
|
}
|
||||||
|
total /= 10;
|
||||||
|
let i = spaceCounter.length - 1;
|
||||||
|
while (i > 0 && (!spaceCounter[i] || spaceCounter[i] < total)) i--;
|
||||||
|
|
||||||
|
const parIndent = (i > 0 ? i : 0);
|
||||||
|
|
||||||
|
let newPars = [];
|
||||||
|
const newPar = () => {
|
||||||
|
newPars.push({_n: 'p', _t: ''});
|
||||||
|
};
|
||||||
|
|
||||||
|
const growPar = (text) => {
|
||||||
|
if (!newPars.length)
|
||||||
|
newPar();
|
||||||
|
|
||||||
|
const l = newPars.length;
|
||||||
|
newPars[l - 1]._t += text;
|
||||||
|
}
|
||||||
|
|
||||||
|
i = 0;
|
||||||
|
for (const par of pars) {
|
||||||
|
if (i > 0)
|
||||||
|
newPar();
|
||||||
|
i++;
|
||||||
|
|
||||||
|
const lines = par._t.split('\n');
|
||||||
|
for (let line of lines) {
|
||||||
|
line = repCrLfTab(line);
|
||||||
|
|
||||||
|
let l = 0;
|
||||||
|
while (l < line.length && line[l] == ' ') {
|
||||||
|
l++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (l >= parIndent)
|
||||||
|
newPar();
|
||||||
|
growPar(line.trim() + ' ');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
body.section._a[0] = newPars;
|
||||||
|
} else {
|
||||||
|
body.section._a[0] = pars;
|
||||||
|
}
|
||||||
|
|
||||||
|
//убираем лишнее
|
||||||
|
for (let i = 0; i < pars.length; i++)
|
||||||
|
pars[i]._t = this.repSpaces(pars[i]._t).trim();
|
||||||
|
|
||||||
|
return this.formatFb2(fb2);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = ConvertHtml;
|
||||||
33
server/core/BookConverter/ConvertRtf.js
Normal file
33
server/core/BookConverter/ConvertRtf.js
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
const fs = require('fs-extra');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const ConvertDocX = require('./ConvertDocX');
|
||||||
|
|
||||||
|
class ConvertRtf extends ConvertDocX {
|
||||||
|
check(data, opts) {
|
||||||
|
const {inputFiles} = opts;
|
||||||
|
|
||||||
|
return this.config.useExternalBookConverter &&
|
||||||
|
inputFiles.sourceFileType && inputFiles.sourceFileType.ext == 'rtf';
|
||||||
|
}
|
||||||
|
|
||||||
|
async run(data, opts) {
|
||||||
|
if (!this.check(data, opts))
|
||||||
|
return false;
|
||||||
|
await this.checkExternalConverterPresent();
|
||||||
|
|
||||||
|
const {inputFiles, callback} = opts;
|
||||||
|
|
||||||
|
const outFile = `${inputFiles.fileListDir}/${path.basename(inputFiles.sourceFile)}`;
|
||||||
|
const rtfFile = `${outFile}.rtf`;
|
||||||
|
const docxFile = `${outFile}.docx`;
|
||||||
|
const fb2File = `${outFile}.fb2`;
|
||||||
|
|
||||||
|
await fs.copy(inputFiles.sourceFile, rtfFile);
|
||||||
|
await this.execConverter(this.sofficePath, ['--headless', '--convert-to', 'docx', '--outdir', inputFiles.fileListDir, rtfFile]);
|
||||||
|
|
||||||
|
return await super.convert(docxFile, fb2File, callback);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = ConvertRtf;
|
||||||
276
server/core/BookConverter/ConvertSamlib.js
Normal file
276
server/core/BookConverter/ConvertSamlib.js
Normal file
@@ -0,0 +1,276 @@
|
|||||||
|
const _ = require('lodash');
|
||||||
|
const URL = require('url').URL;
|
||||||
|
|
||||||
|
const sax = require('./sax');
|
||||||
|
const ConvertBase = require('./ConvertBase');
|
||||||
|
|
||||||
|
class ConvertSamlib extends ConvertBase {
|
||||||
|
check(data, opts) {
|
||||||
|
const {url, dataType} = opts;
|
||||||
|
|
||||||
|
const parsedUrl = new URL(url);
|
||||||
|
if (dataType && dataType.ext == 'html' &&
|
||||||
|
(parsedUrl.hostname == 'samlib.ru' ||
|
||||||
|
parsedUrl.hostname == 'budclub.ru' ||
|
||||||
|
parsedUrl.hostname == 'zhurnal.lib.ru')) {
|
||||||
|
return {hostname: parsedUrl.hostname};
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
async run(data, opts) {
|
||||||
|
const checkResult = this.check(data, opts);
|
||||||
|
if (!checkResult)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
const {hostname} = checkResult;
|
||||||
|
let titleInfo = {};
|
||||||
|
let desc = {_n: 'description', 'title-info': titleInfo};
|
||||||
|
let pars = [];
|
||||||
|
let body = {_n: 'body', section: {_a: pars}};
|
||||||
|
let fb2 = [desc, body];
|
||||||
|
|
||||||
|
let inSubtitle = false;
|
||||||
|
let inJustify = true;
|
||||||
|
let inImage = false;
|
||||||
|
let isFirstPara = false;
|
||||||
|
let path = '';
|
||||||
|
let tag = '';// eslint-disable-line no-unused-vars
|
||||||
|
|
||||||
|
let inText = false;
|
||||||
|
let textFound = false;
|
||||||
|
let node = {_a: pars};
|
||||||
|
|
||||||
|
let inPara = false;
|
||||||
|
let italic = false;
|
||||||
|
let bold = false;
|
||||||
|
|
||||||
|
const openTag = (name, attrs) => {
|
||||||
|
if (name == 'p')
|
||||||
|
inPara = true;
|
||||||
|
let n = {_n: name, _attrs: attrs, _a: [], _p: node};
|
||||||
|
node._a.push(n);
|
||||||
|
node = n;
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeTag = (name) => {
|
||||||
|
if (name == 'p')
|
||||||
|
inPara = false;
|
||||||
|
if (node._p) {
|
||||||
|
const exact = (node._n == name);
|
||||||
|
node = node._p;
|
||||||
|
if (!exact)
|
||||||
|
closeTag(name);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const growParagraph = (text) => {
|
||||||
|
if (!node._p) {
|
||||||
|
if (text.trim() != '')
|
||||||
|
openTag('p');
|
||||||
|
else
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (node._n == 'p' && node._a.length == 0)
|
||||||
|
text = text.trimLeft();
|
||||||
|
node._a.push({_t: text});
|
||||||
|
};
|
||||||
|
|
||||||
|
const onStartNode = (elemName, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
|
||||||
|
if (elemName == '')
|
||||||
|
return;
|
||||||
|
if (!inText) {
|
||||||
|
path += '/' + elemName;
|
||||||
|
tag = elemName;
|
||||||
|
} else {
|
||||||
|
switch (elemName) {
|
||||||
|
case 'li':
|
||||||
|
case 'p':
|
||||||
|
case 'dd':
|
||||||
|
case 'br':
|
||||||
|
if (!(inSubtitle && isFirstPara)) {
|
||||||
|
if (inPara)
|
||||||
|
closeTag('p');
|
||||||
|
openTag('p');
|
||||||
|
}
|
||||||
|
isFirstPara = false;
|
||||||
|
break;
|
||||||
|
case 'h1':
|
||||||
|
case 'h2':
|
||||||
|
case 'h3':
|
||||||
|
if (inPara)
|
||||||
|
closeTag('p');
|
||||||
|
openTag('p');
|
||||||
|
bold = true;
|
||||||
|
break;
|
||||||
|
case 'i':
|
||||||
|
case 'em':
|
||||||
|
italic = true;
|
||||||
|
break;
|
||||||
|
case 'b':
|
||||||
|
case 'strong':
|
||||||
|
bold = true;
|
||||||
|
break;
|
||||||
|
case 'div':
|
||||||
|
if (inPara)
|
||||||
|
closeTag('p');
|
||||||
|
if (tail.indexOf('align="center"') >= 0) {
|
||||||
|
openTag('subtitle');
|
||||||
|
inSubtitle = true;
|
||||||
|
isFirstPara = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tail.indexOf('align="justify"') >= 0) {
|
||||||
|
openTag('p');
|
||||||
|
inJustify = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
case 'img': {
|
||||||
|
if (inPara)
|
||||||
|
closeTag('p');
|
||||||
|
const attrs = sax.getAttrsSync(tail);
|
||||||
|
if (attrs.src && attrs.src.value) {
|
||||||
|
let href = attrs.src.value;
|
||||||
|
if (href[0] == '/')
|
||||||
|
href = `http://${hostname}${href}`;
|
||||||
|
openTag('image', {href});
|
||||||
|
inImage = true;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onEndNode = (elemName, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
|
||||||
|
if (!inText) {
|
||||||
|
const oldPath = path;
|
||||||
|
let t = '';
|
||||||
|
do {
|
||||||
|
let i = path.lastIndexOf('/');
|
||||||
|
t = path.substr(i + 1);
|
||||||
|
path = path.substr(0, i);
|
||||||
|
} while (t != elemName && path);
|
||||||
|
|
||||||
|
if (t != elemName) {
|
||||||
|
path = oldPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
let i = path.lastIndexOf('/');
|
||||||
|
tag = path.substr(i + 1);
|
||||||
|
} else {
|
||||||
|
switch (elemName) {
|
||||||
|
case 'li':
|
||||||
|
case 'p':
|
||||||
|
case 'dd':
|
||||||
|
closeTag('p');
|
||||||
|
break;
|
||||||
|
case 'h1':
|
||||||
|
case 'h2':
|
||||||
|
case 'h3':
|
||||||
|
closeTag('p');
|
||||||
|
bold = false;
|
||||||
|
break;
|
||||||
|
case 'i':
|
||||||
|
case 'em':
|
||||||
|
italic = false;
|
||||||
|
break;
|
||||||
|
case 'b':
|
||||||
|
case 'strong':
|
||||||
|
bold = false;
|
||||||
|
break;
|
||||||
|
case 'div':
|
||||||
|
if (inSubtitle) {
|
||||||
|
closeTag('subtitle');
|
||||||
|
inSubtitle = false;
|
||||||
|
isFirstPara = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inJustify) {
|
||||||
|
closeTag('p');
|
||||||
|
inJustify = false;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'img':
|
||||||
|
if (inImage)
|
||||||
|
closeTag('image');
|
||||||
|
inImage = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onComment = (text) => {// eslint-disable-line no-unused-vars
|
||||||
|
if (text == '--------- Собственно произведение -------------') {
|
||||||
|
inText = true;
|
||||||
|
textFound = true;
|
||||||
|
}
|
||||||
|
if (text == '-----------------------------------------------')
|
||||||
|
inText = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const onTextNode = (text) => {// eslint-disable-line no-unused-vars
|
||||||
|
if (text && text.trim() == '')
|
||||||
|
text = (text.indexOf(' ') >= 0 ? ' ' : '');
|
||||||
|
|
||||||
|
if (!text)
|
||||||
|
return;
|
||||||
|
|
||||||
|
switch (path) {
|
||||||
|
case '/html/body/center/h2':
|
||||||
|
titleInfo['book-title'] = text;
|
||||||
|
return;
|
||||||
|
case '/html/body/div/h3':
|
||||||
|
if (!titleInfo.author)
|
||||||
|
titleInfo.author = {};
|
||||||
|
text = text.replace(':', '').trim().split(' ');
|
||||||
|
if (text[0])
|
||||||
|
titleInfo.author['last-name'] = text[0];
|
||||||
|
if (text[1])
|
||||||
|
titleInfo.author['first-name'] = text[1];
|
||||||
|
if (text[2])
|
||||||
|
titleInfo.author['middle-name'] = text[2];
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let tOpen = (bold ? '<strong>' : '');
|
||||||
|
tOpen += (italic ? '<emphasis>' : '');
|
||||||
|
let tClose = (italic ? '</emphasis>' : '');
|
||||||
|
tClose += (bold ? '</strong>' : '');
|
||||||
|
|
||||||
|
if (inText)
|
||||||
|
growParagraph(`${tOpen}${text}${tClose}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
sax.parseSync(this.decode(data).toString().replace(/ /g, ' '), {
|
||||||
|
onStartNode, onEndNode, onTextNode, onComment,
|
||||||
|
innerCut: new Set(['head', 'script', 'style'])
|
||||||
|
});
|
||||||
|
|
||||||
|
//текст не найден на странице, обработать корректно не получилось
|
||||||
|
if (!textFound)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
const title = (titleInfo['book-title'] ? titleInfo['book-title'] : '');
|
||||||
|
let author = '';
|
||||||
|
if (titleInfo.author) {
|
||||||
|
author = _.compact([
|
||||||
|
(titleInfo.author['last-name'] ? titleInfo.author['last-name'] : ''),
|
||||||
|
(titleInfo.author['first-name'] ? titleInfo.author['first-name'] : ''),
|
||||||
|
(titleInfo.author['middle-name'] ? titleInfo.author['middle-name'] : ''),
|
||||||
|
]).join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
pars.unshift({_n: 'title', _a: [
|
||||||
|
{_n: 'p', _t: author}, {_n: 'p', _t: ''},
|
||||||
|
{_n: 'p', _t: title}, {_n: 'p', _t: ''},
|
||||||
|
]})
|
||||||
|
|
||||||
|
return this.formatFb2(fb2);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = ConvertSamlib;
|
||||||
@@ -1,496 +1,63 @@
|
|||||||
const fs = require('fs-extra');
|
const fs = require('fs-extra');
|
||||||
const URL = require('url').URL;
|
|
||||||
const iconv = require('iconv-lite');
|
|
||||||
const chardet = require('chardet');
|
|
||||||
const _ = require('lodash');
|
|
||||||
const sax = require('./sax');
|
|
||||||
const textUtils = require('./textUtils');
|
|
||||||
|
|
||||||
const FileDetector = require('../FileDetector');
|
const FileDetector = require('../FileDetector');
|
||||||
|
|
||||||
const repSpaces = (text) => text.replace(/ |[\t\n\r]/g, ' ');
|
//порядок важен
|
||||||
const repSpaces2 = (text) => text.replace(/[\n\r]/g, '');
|
const convertClassFactory = [
|
||||||
|
require('./ConvertRtf'),
|
||||||
|
require('./ConvertDocX'),
|
||||||
|
require('./ConvertDoc'),
|
||||||
|
require('./ConvertFb2'),
|
||||||
|
require('./ConvertSamlib'),
|
||||||
|
require('./ConvertHtml'),
|
||||||
|
];
|
||||||
|
|
||||||
class BookConverter {
|
class BookConverter {
|
||||||
constructor() {
|
constructor(config) {
|
||||||
this.detector = new FileDetector();
|
this.detector = new FileDetector();
|
||||||
}
|
|
||||||
|
|
||||||
async convertToFb2(inputFile, outputFile, url, callback) {
|
this.convertFactory = [];
|
||||||
const fileType = await this.detector.detectFile(inputFile);
|
for (const convertClass of convertClassFactory) {
|
||||||
|
this.convertFactory.push(new convertClass(config));
|
||||||
const data = await fs.readFile(inputFile);
|
|
||||||
callback(100);
|
|
||||||
|
|
||||||
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 == 'zhurnal.lib.ru') {
|
|
||||||
await fs.writeFile(outputFile, this.convertSamlib(data, parsedUrl.hostname));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await fs.writeFile(outputFile, this.convertHtml(data));
|
|
||||||
return;
|
|
||||||
} else {
|
|
||||||
if (fileType)
|
|
||||||
throw new Error(`Этот формат файла не поддерживается: ${fileType.mime}`);
|
|
||||||
else {
|
|
||||||
//может это чистый текст?
|
|
||||||
if (textUtils.checkIfText(data)) {
|
|
||||||
await fs.writeFile(outputFile, this.convertHtml(data, true));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(`Не удалось определить формат файла: ${url}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
decode(data) {
|
async convertToFb2(inputFiles, outputFile, url, callback) {
|
||||||
let selected = textUtils.getEncoding(data);
|
const selectedFileType = await this.detector.detectFile(inputFiles.selectedFile);
|
||||||
|
const data = await fs.readFile(inputFiles.selectedFile);
|
||||||
|
|
||||||
if (selected == 'ISO-8859-5') {
|
let selectedFileType2 = null;
|
||||||
const charsetAll = chardet.detectAll(data.slice(0, 20000));
|
let data2 = null;
|
||||||
for (const charset of charsetAll) {
|
if (inputFiles.nesting) {
|
||||||
if (charset.name.indexOf('ISO-8859') < 0) {
|
selectedFileType2 = await this.detector.detectFile(inputFiles.nesting.selectedFile);
|
||||||
selected = charset.name;
|
data2 = await fs.readFile(inputFiles.nesting.selectedFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
let result = false;
|
||||||
|
for (const convert of this.convertFactory) {
|
||||||
|
result = await convert.run(data, {inputFiles, url, callback, dataType: selectedFileType});
|
||||||
|
if (result) {
|
||||||
|
await fs.writeFile(outputFile, result);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inputFiles.nesting) {
|
||||||
|
result = await convert.run(data2, {inputFiles: inputFiles.nesting, url, callback, dataType: selectedFileType2});
|
||||||
|
if (result) {
|
||||||
|
await fs.writeFile(outputFile, result);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return iconv.decode(data, selected);
|
if (!result) {
|
||||||
}
|
if (selectedFileType)
|
||||||
|
throw new Error(`Этот формат файла не поддерживается: ${selectedFileType.mime}`);
|
||||||
checkEncoding(data) {
|
else {
|
||||||
let result = data;
|
throw new Error(`Не удалось определить формат файла: ${url}`);
|
||||||
|
|
||||||
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;
|
callback(100);
|
||||||
}
|
|
||||||
|
|
||||||
convertHtml(data, isText) {
|
|
||||||
let titleInfo = {};
|
|
||||||
let desc = {_n: 'description', 'title-info': titleInfo};
|
|
||||||
let pars = [];
|
|
||||||
let body = {_n: 'body', section: {_a: []}};
|
|
||||||
let fb2 = [desc, body];
|
|
||||||
|
|
||||||
let title = '';
|
|
||||||
let inTitle = false;
|
|
||||||
|
|
||||||
let spaceCounter = [];
|
|
||||||
|
|
||||||
const newParagraph = () => {
|
|
||||||
pars.push({_n: 'p', _t: ''});
|
|
||||||
};
|
|
||||||
|
|
||||||
const growParagraph = (text) => {
|
|
||||||
const l = pars.length;
|
|
||||||
if (l) {
|
|
||||||
if (pars[l - 1]._t == '')
|
|
||||||
text = text.trimLeft();
|
|
||||||
pars[l - 1]._t += text;
|
|
||||||
}
|
|
||||||
|
|
||||||
//посчитаем отступы у текста, чтобы выделить потом параграфы
|
|
||||||
const lines = text.split('\n');
|
|
||||||
for (const line of lines) {
|
|
||||||
const sp = line.split(' ');
|
|
||||||
let l = 0;
|
|
||||||
while (l < sp.length && sp[l].trim() == '') {
|
|
||||||
l++;
|
|
||||||
}
|
|
||||||
if (!spaceCounter[l])
|
|
||||||
spaceCounter[l] = 0;
|
|
||||||
spaceCounter[l]++;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
newParagraph();
|
|
||||||
const newPara = new Set(['tr', 'br', 'br/', 'dd', 'p', 'title', '/title', 'h1', 'h2', 'h3', '/h1', '/h2', '/h3']);
|
|
||||||
|
|
||||||
const onTextNode = (text, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
|
|
||||||
if (!cutCounter) {
|
|
||||||
growParagraph(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (inTitle && !title)
|
|
||||||
title = text;
|
|
||||||
};
|
|
||||||
|
|
||||||
const onStartNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
|
|
||||||
if (!cutCounter) {
|
|
||||||
if (newPara.has(tag))
|
|
||||||
newParagraph();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (tag == 'title')
|
|
||||||
inTitle = true;
|
|
||||||
};
|
|
||||||
|
|
||||||
const onEndNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
|
|
||||||
if (tag == 'title')
|
|
||||||
inTitle = false;
|
|
||||||
};
|
|
||||||
|
|
||||||
let buf = this.decode(data).toString();
|
|
||||||
|
|
||||||
sax.parseSync(buf, {
|
|
||||||
onStartNode, onEndNode, onTextNode,
|
|
||||||
innerCut: new Set(['head', 'script', 'style'])
|
|
||||||
});
|
|
||||||
|
|
||||||
titleInfo['book-title'] = title;
|
|
||||||
|
|
||||||
//подозрение на чистый текст, надо разбить на параграфы
|
|
||||||
if (isText || pars.length < buf.length/2000) {
|
|
||||||
let total = 0;
|
|
||||||
for (let i = 0; i < spaceCounter.length; i++) {
|
|
||||||
total += (spaceCounter[i] ? spaceCounter[i] : 0);
|
|
||||||
}
|
|
||||||
total /= 10;
|
|
||||||
let i = spaceCounter.length - 1;
|
|
||||||
while (i > 0 && (!spaceCounter[i] || spaceCounter[i] < total)) i--;
|
|
||||||
|
|
||||||
const parIndent = (i > 0 ? i : 0);
|
|
||||||
|
|
||||||
let newPars = [];
|
|
||||||
const newPar = () => {
|
|
||||||
newPars.push({_n: 'p', _t: ''});
|
|
||||||
};
|
|
||||||
|
|
||||||
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 (let i = 0; i < pars.length; i++)
|
|
||||||
pars[i]._t = repSpaces(pars[i]._t).trim();
|
|
||||||
|
|
||||||
return this.formatFb2(fb2);
|
|
||||||
}
|
|
||||||
|
|
||||||
convertSamlib(data, hostname) {
|
|
||||||
let titleInfo = {};
|
|
||||||
let desc = {_n: 'description', 'title-info': titleInfo};
|
|
||||||
let pars = [];
|
|
||||||
let body = {_n: 'body', section: {_a: pars}};
|
|
||||||
let fb2 = [desc, body];
|
|
||||||
|
|
||||||
let inSubtitle = false;
|
|
||||||
let inJustify = true;
|
|
||||||
let inImage = false;
|
|
||||||
let path = '';
|
|
||||||
let tag = '';// eslint-disable-line no-unused-vars
|
|
||||||
|
|
||||||
let inText = false;
|
|
||||||
let textFound = false;
|
|
||||||
let node = {_a: pars};
|
|
||||||
|
|
||||||
let inPara = false;
|
|
||||||
let italic = false;
|
|
||||||
let bold = false;
|
|
||||||
|
|
||||||
const openTag = (name, attrs) => {
|
|
||||||
if (name == 'p')
|
|
||||||
inPara = true;
|
|
||||||
let n = {_n: name, _attrs: attrs, _a: [], _p: node};
|
|
||||||
node._a.push(n);
|
|
||||||
node = n;
|
|
||||||
};
|
|
||||||
|
|
||||||
const closeTag = (name) => {
|
|
||||||
if (name == 'p')
|
|
||||||
inPara = false;
|
|
||||||
if (node._p) {
|
|
||||||
const exact = (node._n == name);
|
|
||||||
node = node._p;
|
|
||||||
if (!exact)
|
|
||||||
closeTag(name);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const growParagraph = (text) => {
|
|
||||||
if (node._n == 'p' && node._a.length == 0)
|
|
||||||
text = text.trimLeft();
|
|
||||||
node._a.push({_t: text});
|
|
||||||
};
|
|
||||||
|
|
||||||
openTag('p');
|
|
||||||
|
|
||||||
const onStartNode = (elemName, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
|
|
||||||
if (elemName == '')
|
|
||||||
return;
|
|
||||||
if (!inText) {
|
|
||||||
path += '/' + elemName;
|
|
||||||
tag = elemName;
|
|
||||||
} else {
|
|
||||||
if (inPara && elemName != 'i' && elemName != 'b' && elemName != 'em' && elemName != 'strong' && elemName != 'img')
|
|
||||||
closeTag('p');
|
|
||||||
|
|
||||||
switch (elemName) {
|
|
||||||
case 'li':
|
|
||||||
case 'p':
|
|
||||||
case 'dd':
|
|
||||||
case 'h1':
|
|
||||||
case 'h2':
|
|
||||||
case 'h3':
|
|
||||||
case 'br':
|
|
||||||
openTag('p');
|
|
||||||
break;
|
|
||||||
case 'i':
|
|
||||||
case 'em':
|
|
||||||
italic = true;
|
|
||||||
break;
|
|
||||||
case 'b':
|
|
||||||
case 'strong':
|
|
||||||
bold = true;
|
|
||||||
break;
|
|
||||||
case 'div':
|
|
||||||
if (tail.indexOf('align="center"') >= 0) {
|
|
||||||
openTag('subtitle');
|
|
||||||
inSubtitle = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (tail.indexOf('align="justify"') >= 0) {
|
|
||||||
openTag('p');
|
|
||||||
inJustify = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
break;
|
|
||||||
case 'img': {
|
|
||||||
const attrs = sax.getAttrsSync(tail);
|
|
||||||
if (attrs.src && attrs.src.value) {
|
|
||||||
let href = attrs.src.value;
|
|
||||||
if (href[0] == '/')
|
|
||||||
href = `http://${hostname}${href}`;
|
|
||||||
openTag('image', {href});
|
|
||||||
inImage = true;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const onEndNode = (elemName, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
|
|
||||||
if (!inText) {
|
|
||||||
const oldPath = path;
|
|
||||||
let t = '';
|
|
||||||
do {
|
|
||||||
let i = path.lastIndexOf('/');
|
|
||||||
t = path.substr(i + 1);
|
|
||||||
path = path.substr(0, i);
|
|
||||||
} while (t != elemName && path);
|
|
||||||
|
|
||||||
if (t != elemName) {
|
|
||||||
path = oldPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
let i = path.lastIndexOf('/');
|
|
||||||
tag = path.substr(i + 1);
|
|
||||||
} else {
|
|
||||||
switch (elemName) {
|
|
||||||
case 'li':
|
|
||||||
case 'p':
|
|
||||||
case 'dd':
|
|
||||||
case 'h1':
|
|
||||||
case 'h2':
|
|
||||||
case 'h3':
|
|
||||||
closeTag('p');
|
|
||||||
break;
|
|
||||||
case 'i':
|
|
||||||
case 'em':
|
|
||||||
italic = false;
|
|
||||||
break;
|
|
||||||
case 'b':
|
|
||||||
case 'strong':
|
|
||||||
bold = false;
|
|
||||||
break;
|
|
||||||
case 'div':
|
|
||||||
if (inSubtitle) {
|
|
||||||
closeTag('subtitle');
|
|
||||||
inSubtitle = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (inJustify) {
|
|
||||||
closeTag('p');
|
|
||||||
inJustify = false;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case 'img':
|
|
||||||
if (inImage)
|
|
||||||
closeTag('image');
|
|
||||||
inImage = false;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const onComment = (text) => {// eslint-disable-line no-unused-vars
|
|
||||||
if (text == '--------- Собственно произведение -------------') {
|
|
||||||
inText = true;
|
|
||||||
textFound = true;
|
|
||||||
}
|
|
||||||
if (text == '-----------------------------------------------')
|
|
||||||
inText = false;
|
|
||||||
};
|
|
||||||
|
|
||||||
const onTextNode = (text) => {// eslint-disable-line no-unused-vars
|
|
||||||
if (text != ' ' && text.trim() == '')
|
|
||||||
text = text.trim();
|
|
||||||
|
|
||||||
if (text == '')
|
|
||||||
return;
|
|
||||||
|
|
||||||
switch (path) {
|
|
||||||
case '/html/body/center/h2':
|
|
||||||
titleInfo['book-title'] = text;
|
|
||||||
return;
|
|
||||||
case '/html/body/div/h3':
|
|
||||||
if (!titleInfo.author)
|
|
||||||
titleInfo.author = {};
|
|
||||||
text = text.replace(':', '').trim().split(' ');
|
|
||||||
if (text[0])
|
|
||||||
titleInfo.author['last-name'] = text[0];
|
|
||||||
if (text[1])
|
|
||||||
titleInfo.author['first-name'] = text[1];
|
|
||||||
if (text[2])
|
|
||||||
titleInfo.author['middle-name'] = text[2];
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let tOpen = (bold ? '<strong>' : '');
|
|
||||||
tOpen += (italic ? '<emphasis>' : '');
|
|
||||||
let tClose = (italic ? '</emphasis>' : '');
|
|
||||||
tClose += (bold ? '</strong>' : '');
|
|
||||||
|
|
||||||
if (inText)
|
|
||||||
growParagraph(`${tOpen}${text}${tClose}`);
|
|
||||||
};
|
|
||||||
|
|
||||||
sax.parseSync(repSpaces(repSpaces2(this.decode(data).toString())), {
|
|
||||||
onStartNode, onEndNode, onTextNode, onComment,
|
|
||||||
innerCut: new Set(['head', 'script', 'style'])
|
|
||||||
});
|
|
||||||
|
|
||||||
//текст не найден на странице, обрабатываем как html
|
|
||||||
if (!textFound)
|
|
||||||
return this.convertHtml(data);
|
|
||||||
|
|
||||||
const title = (titleInfo['book-title'] ? titleInfo['book-title'] : '');
|
|
||||||
let author = '';
|
|
||||||
if (titleInfo.author) {
|
|
||||||
author = _.compact([
|
|
||||||
(titleInfo.author['last-name'] ? titleInfo.author['last-name'] : ''),
|
|
||||||
(titleInfo.author['first-name'] ? titleInfo.author['first-name'] : ''),
|
|
||||||
(titleInfo.author['middle-name'] ? titleInfo.author['middle-name'] : ''),
|
|
||||||
]).join(' ');
|
|
||||||
}
|
|
||||||
|
|
||||||
pars.unshift({_n: 'title', _a: [
|
|
||||||
{_n: 'p', _t: author}, {_n: 'p', _t: ''},
|
|
||||||
{_n: 'p', _t: title}, {_n: 'p', _t: ''},
|
|
||||||
]})
|
|
||||||
|
|
||||||
return this.formatFb2(fb2);
|
|
||||||
}
|
|
||||||
|
|
||||||
formatFb2(fb2) {
|
|
||||||
let out = '<?xml version="1.0" encoding="utf-8"?>';
|
|
||||||
out += '<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">';
|
|
||||||
out += this.formatFb2Node(fb2);
|
|
||||||
out += '</FictionBook>';
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
formatFb2Node(node, name) {
|
|
||||||
let out = '';
|
|
||||||
|
|
||||||
if (Array.isArray(node)) {
|
|
||||||
for (const n of node) {
|
|
||||||
out += this.formatFb2Node(n);
|
|
||||||
}
|
|
||||||
} else if (typeof node == 'string') {
|
|
||||||
if (name)
|
|
||||||
out += `<${name}>${repSpaces(node)}</${name}>`;
|
|
||||||
else
|
|
||||||
out += repSpaces(node);
|
|
||||||
} else {
|
|
||||||
if (node._n)
|
|
||||||
name = node._n;
|
|
||||||
|
|
||||||
let attrs = '';
|
|
||||||
if (node._attrs) {
|
|
||||||
for (let attrName in node._attrs) {
|
|
||||||
attrs += ` ${attrName}="${node._attrs[attrName]}"`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (name)
|
|
||||||
out += `<${name}${attrs}>`;
|
|
||||||
if (node.hasOwnProperty('_t'))
|
|
||||||
out += repSpaces(node._t);
|
|
||||||
|
|
||||||
for (let nodeName in node) {
|
|
||||||
if (nodeName && nodeName[0] == '_' && nodeName != '_a')
|
|
||||||
continue;
|
|
||||||
|
|
||||||
const n = node[nodeName];
|
|
||||||
out += this.formatFb2Node(n, nodeName);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (name)
|
|
||||||
out += `</${name}>`;
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
function getEncoding(buf) {
|
function getEncoding(buf, returnAll) {
|
||||||
const lowerCase = 3;
|
const lowerCase = 3;
|
||||||
const upperCase = 1;
|
const upperCase = 1;
|
||||||
|
|
||||||
@@ -8,6 +8,7 @@ function getEncoding(buf) {
|
|||||||
'd': 'cp866',
|
'd': 'cp866',
|
||||||
'i': 'ISO-8859-5',
|
'i': 'ISO-8859-5',
|
||||||
'm': 'maccyrillic',
|
'm': 'maccyrillic',
|
||||||
|
'u': 'utf-8',
|
||||||
};
|
};
|
||||||
|
|
||||||
let charsets = {
|
let charsets = {
|
||||||
@@ -15,38 +16,47 @@ function getEncoding(buf) {
|
|||||||
'w': 0,
|
'w': 0,
|
||||||
'd': 0,
|
'd': 0,
|
||||||
'i': 0,
|
'i': 0,
|
||||||
'm': 0
|
'm': 0,
|
||||||
|
'u': 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
const len = buf.length;
|
const len = buf.length;
|
||||||
const blockSize = (len > 5*3000 ? 3000 : len);
|
const blockSize = (len > 5*3000 ? 3000 : len);
|
||||||
let counter = 0;
|
let counter = 0;
|
||||||
let i = 0;
|
let i = 0;
|
||||||
|
let totalChecked = 0;
|
||||||
while (i < len) {
|
while (i < len) {
|
||||||
const char = buf[i];
|
const char = buf[i];
|
||||||
|
const nextChar = (i < len - 1 ? buf[i + 1] : 0);
|
||||||
|
totalChecked++;
|
||||||
i++;
|
i++;
|
||||||
//non-russian characters
|
//non-russian characters
|
||||||
if (char < 128 || char > 256)
|
if (char < 128 || char > 256)
|
||||||
continue;
|
continue;
|
||||||
//CP866
|
//UTF-8
|
||||||
if ((char > 159 && char < 176) || (char > 223 && char < 242)) charsets['d'] += lowerCase;
|
if ((char == 208 || char == 209) && nextChar >= 128 && nextChar <= 190)
|
||||||
if ((char > 127 && char < 160)) charsets['d'] += upperCase;
|
charsets['u'] += lowerCase;
|
||||||
|
else {
|
||||||
|
//CP866
|
||||||
|
if ((char > 159 && char < 176) || (char > 223 && char < 242)) charsets['d'] += lowerCase;
|
||||||
|
if ((char > 127 && char < 160)) charsets['d'] += upperCase;
|
||||||
|
|
||||||
//KOI8-R
|
//KOI8-R
|
||||||
if ((char > 191 && char < 223)) charsets['k'] += lowerCase;
|
if ((char > 191 && char < 223)) charsets['k'] += lowerCase;
|
||||||
if ((char > 222 && char < 256)) charsets['k'] += upperCase;
|
if ((char > 222 && char < 256)) charsets['k'] += upperCase;
|
||||||
|
|
||||||
//WIN-1251
|
//WIN-1251
|
||||||
if (char > 223 && char < 256) charsets['w'] += lowerCase;
|
if (char > 223 && char < 256) charsets['w'] += lowerCase;
|
||||||
if (char > 191 && char < 224) charsets['w'] += upperCase;
|
if (char > 191 && char < 224) charsets['w'] += upperCase;
|
||||||
|
|
||||||
//MAC
|
//MAC
|
||||||
if (char > 221 && char < 255) charsets['m'] += lowerCase;
|
if (char > 221 && char < 255) charsets['m'] += lowerCase;
|
||||||
if (char > 127 && char < 160) charsets['m'] += upperCase;
|
if (char > 127 && char < 160) charsets['m'] += upperCase;
|
||||||
|
|
||||||
//ISO-8859-5
|
//ISO-8859-5
|
||||||
if (char > 207 && char < 240) charsets['i'] += lowerCase;
|
if (char > 207 && char < 240) charsets['i'] += lowerCase;
|
||||||
if (char > 175 && char < 208) charsets['i'] += upperCase;
|
if (char > 175 && char < 208) charsets['i'] += upperCase;
|
||||||
|
}
|
||||||
|
|
||||||
counter++;
|
counter++;
|
||||||
|
|
||||||
@@ -57,18 +67,24 @@ function getEncoding(buf) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let sorted = Object.keys(charsets).map(function(key) {
|
let sorted = Object.keys(charsets).map(function(key) {
|
||||||
return { codePage: codePage[key], c: charsets[key] };
|
return { codePage: codePage[key], c: charsets[key], totalChecked };
|
||||||
});
|
});
|
||||||
|
|
||||||
sorted.sort((a, b) => b.c - a.c);
|
sorted.sort((a, b) => b.c - a.c);
|
||||||
|
|
||||||
if (sorted[0].c > 0)
|
if (returnAll)
|
||||||
|
return sorted;
|
||||||
|
else if (sorted[0].c > 0)
|
||||||
return sorted[0].codePage;
|
return sorted[0].codePage;
|
||||||
else
|
else
|
||||||
return 'ISO-8859-5';
|
return 'ISO-8859-5';
|
||||||
}
|
}
|
||||||
|
|
||||||
function checkIfText(buf) {
|
function checkIfText(buf) {
|
||||||
|
const enc = getEncoding(buf, true);
|
||||||
|
if (enc[0].c > enc[0].totalChecked*0.9)
|
||||||
|
return true;
|
||||||
|
|
||||||
let spaceCount = 0;
|
let spaceCount = 0;
|
||||||
let crCount = 0;
|
let crCount = 0;
|
||||||
let lfCount = 0;
|
let lfCount = 0;
|
||||||
|
|||||||
@@ -17,8 +17,17 @@ class FileDecompressor {
|
|||||||
async decompressFile(filename, outputDir) {
|
async decompressFile(filename, outputDir) {
|
||||||
const fileType = await this.detector.detectFile(filename);
|
const fileType = await this.detector.detectFile(filename);
|
||||||
|
|
||||||
if (!fileType || !(fileType.ext == 'zip' || fileType.ext == 'bz2' || fileType.ext == 'gz'))
|
let result = {
|
||||||
return filename;
|
sourceFile: filename,
|
||||||
|
sourceFileType: fileType,
|
||||||
|
selectedFile: filename,
|
||||||
|
fileListDir: outputDir,
|
||||||
|
fileList: []
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!fileType || !(fileType.ext == 'zip' || fileType.ext == 'bz2' || fileType.ext == 'gz')) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
//дурной decompress, поэтому в 2 этапа
|
//дурной decompress, поэтому в 2 этапа
|
||||||
//этап 1
|
//этап 1
|
||||||
@@ -44,20 +53,29 @@ class FileDecompressor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let result = filename;
|
let sel = filename;
|
||||||
|
let fileList = [];
|
||||||
let max = 0;
|
let max = 0;
|
||||||
if (files.length) {
|
if (files.length) {
|
||||||
//ищем файл с максимальным размером
|
//ищем файл с максимальным размером
|
||||||
for (let file of files) {
|
for (let file of files) {
|
||||||
|
fileList.push(file.path);
|
||||||
if (file.data.length > max) {
|
if (file.data.length > max) {
|
||||||
result = `${outputDir}/${file.path}`;
|
sel = `${outputDir}/${file.path}`;
|
||||||
max = file.data.length;
|
max = file.data.length;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//дурной decompress
|
//дурной decompress
|
||||||
if (result != filename)
|
if (sel != filename)
|
||||||
await fs.chmod(result, 0o664);
|
await fs.chmod(sel, 0o664);
|
||||||
|
|
||||||
|
result.selectedFile = sel;
|
||||||
|
result.fileList = fileList;
|
||||||
|
|
||||||
|
if (sel != filename) {
|
||||||
|
result.nesting = await this.decompressFile(sel, `${outputDir}/${utils.randomHexString(10)}`);
|
||||||
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,57 +0,0 @@
|
|||||||
const detect = require('detect-file-type');
|
|
||||||
|
|
||||||
//html
|
|
||||||
detect.addSignature(
|
|
||||||
{
|
|
||||||
"type": "html",
|
|
||||||
"ext": "html",
|
|
||||||
"mime": "text/html",
|
|
||||||
"rules": [
|
|
||||||
{ "type": "or", "rules":
|
|
||||||
[
|
|
||||||
{ "type": "contains", "bytes": "3c68746d6c" },
|
|
||||||
{ "type": "contains", "bytes": "3c00680074006d006c00" },
|
|
||||||
|
|
||||||
{ "type": "contains", "bytes": "3c21646f6374797065" },
|
|
||||||
{ "type": "contains", "bytes": "3c626f6479" },
|
|
||||||
{ "type": "contains", "bytes": "3c68656164" },
|
|
||||||
{ "type": "contains", "bytes": "3c696672616d65" },
|
|
||||||
{ "type": "contains", "bytes": "3c696d67" },
|
|
||||||
{ "type": "contains", "bytes": "3c6f626a656374" },
|
|
||||||
{ "type": "contains", "bytes": "3c736372697074" },
|
|
||||||
{ "type": "contains", "bytes": "3c7461626c65" },
|
|
||||||
{ "type": "contains", "bytes": "3c7469746c65" },
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
//xml 3c 3f 78 6d 6c 20 76 65 72 73 69 6f 6e 3d 22 31 2e 30 22
|
|
||||||
detect.addSignature(
|
|
||||||
{
|
|
||||||
"type": "xml",
|
|
||||||
"ext": "xml",
|
|
||||||
"mime": "application/xml",
|
|
||||||
"rules": [
|
|
||||||
{ "type": "or", "rules":
|
|
||||||
[
|
|
||||||
{ "type": "contains", "bytes": "3c3f786d6c2076657273696f6e3d22312e3022" },
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
class FileDetector {
|
|
||||||
detectFile(filename) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
detect.fromFile(filename, (err, result) => {
|
|
||||||
if (err) reject(err);
|
|
||||||
resolve(result);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = FileDetector;
|
|
||||||
274
server/core/FileDetector/index.js
Normal file
274
server/core/FileDetector/index.js
Normal file
@@ -0,0 +1,274 @@
|
|||||||
|
const fs = require('fs');
|
||||||
|
const signatures = require('./signatures.json');
|
||||||
|
|
||||||
|
class FileDetector {
|
||||||
|
detectFile(filename) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
this.fromFile(filename, 2000, (err, result) => {
|
||||||
|
if (err) reject(err);
|
||||||
|
resolve(result);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
//все, что ниже, взято здесь: https://github.com/dimapaloskin/detect-file-type
|
||||||
|
fromFile(filePath, bufferLength, callback) {
|
||||||
|
if (typeof bufferLength === 'function') {
|
||||||
|
callback = bufferLength;
|
||||||
|
bufferLength = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.getFileSize(filePath, (err, fileSize) => {
|
||||||
|
if (err) {
|
||||||
|
return callback(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.open(filePath, 'r', (err, fd) => {
|
||||||
|
if (err) {
|
||||||
|
return callback(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
let bufferSize = bufferLength;
|
||||||
|
if (!bufferSize) {
|
||||||
|
bufferSize = 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fileSize < bufferSize) {
|
||||||
|
bufferSize = fileSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
const buffer = Buffer.alloc(bufferSize);
|
||||||
|
|
||||||
|
fs.read(fd, buffer, 0, bufferSize, 0, (err) => {
|
||||||
|
fs.close(fd);
|
||||||
|
|
||||||
|
if (err) {
|
||||||
|
return callback(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.fromBuffer(buffer, callback);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fromBuffer(buffer, callback) {
|
||||||
|
let result = null;
|
||||||
|
|
||||||
|
const invalidSignaturesList = this.validateSigantures();
|
||||||
|
if (invalidSignaturesList.length) {
|
||||||
|
return callback(invalidSignaturesList);
|
||||||
|
}
|
||||||
|
|
||||||
|
signatures.every((signature) => {
|
||||||
|
if (this.detect(buffer, signature.rules)) {
|
||||||
|
result = {
|
||||||
|
ext: signature.ext,
|
||||||
|
mime: signature.mime
|
||||||
|
};
|
||||||
|
|
||||||
|
if (signature.iana)
|
||||||
|
result.iana = signature.iana;
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
callback(null, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
detect(buffer, receivedRules, type) {
|
||||||
|
if (!type) {
|
||||||
|
type = 'and';
|
||||||
|
}
|
||||||
|
|
||||||
|
const rules = [...receivedRules];
|
||||||
|
|
||||||
|
let isDetected = true;
|
||||||
|
rules.every((rule) => {
|
||||||
|
if (rule.type === 'equal') {
|
||||||
|
const slicedHex = buffer.slice(rule.start || 0, rule.end || buffer.length).toString('hex');
|
||||||
|
isDetected = (slicedHex === rule.bytes);
|
||||||
|
return this.isReturnFalse(isDetected, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rule.type === 'notEqual') {
|
||||||
|
const slicedHex = buffer.slice(rule.start || 0, rule.end || buffer.length).toString('hex');
|
||||||
|
isDetected = !(slicedHex === rule.bytes);
|
||||||
|
return this.isReturnFalse(isDetected, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rule.type === 'contains') {
|
||||||
|
const slicedHex = buffer.slice(rule.start || 0, rule.end || buffer.length).toString('hex');
|
||||||
|
if (typeof rule.bytes === 'string') {
|
||||||
|
rule.bytes = [rule.bytes];
|
||||||
|
}
|
||||||
|
|
||||||
|
rule.bytes.every((bytes) => {
|
||||||
|
isDetected = (slicedHex.indexOf(bytes) !== -1);
|
||||||
|
return isDetected;
|
||||||
|
});
|
||||||
|
|
||||||
|
return this.isReturnFalse(isDetected, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rule.type === 'notContains') {
|
||||||
|
const slicedHex = buffer.slice(rule.start || 0, rule.end || buffer.length).toString('hex');
|
||||||
|
if (typeof rule.bytes === 'string') {
|
||||||
|
rule.bytes = [rule.bytes];
|
||||||
|
}
|
||||||
|
|
||||||
|
rule.bytes.every((bytes) => {
|
||||||
|
isDetected = (slicedHex.indexOf(bytes) === -1);
|
||||||
|
return isDetected;
|
||||||
|
});
|
||||||
|
|
||||||
|
return this.isReturnFalse(isDetected, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rule.type === 'or') {
|
||||||
|
isDetected = this.detect(buffer, rule.rules, 'or');
|
||||||
|
return this.isReturnFalse(isDetected, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rule.type === 'and') {
|
||||||
|
isDetected = this.detect(buffer, rule.rules, 'and');
|
||||||
|
return this.isReturnFalse(isDetected, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
return isDetected;
|
||||||
|
}
|
||||||
|
|
||||||
|
isReturnFalse(isDetected, type) {
|
||||||
|
if (!isDetected && type === 'and') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isDetected && type === 'or') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
validateRuleType(rule) {
|
||||||
|
const types = ['or', 'and', 'contains', 'notContains', 'equal', 'notEqual'];
|
||||||
|
return (types.indexOf(rule.type) !== -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
validateSigantures() {
|
||||||
|
let invalidSignatures = signatures.map((signature) => {
|
||||||
|
return this.validateSignature(signature);
|
||||||
|
});
|
||||||
|
|
||||||
|
invalidSignatures = this.cleanArray(invalidSignatures);
|
||||||
|
|
||||||
|
if (invalidSignatures.length) {
|
||||||
|
return invalidSignatures;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
validateSignature(signature) {
|
||||||
|
if (!('type' in signature)) {
|
||||||
|
return {
|
||||||
|
message: 'signature does not contain "type" field',
|
||||||
|
signature
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!('ext' in signature)) {
|
||||||
|
return {
|
||||||
|
message: 'signature does not contain "ext" field',
|
||||||
|
signature
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!('mime' in signature)) {
|
||||||
|
return {
|
||||||
|
message: 'signature does not contain "mime" field',
|
||||||
|
signature
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!('rules' in signature)) {
|
||||||
|
return {
|
||||||
|
message: 'signature does not contain "rules" field',
|
||||||
|
signature
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const invalidRules = this.validateRules(signature.rules);
|
||||||
|
|
||||||
|
if (invalidRules && invalidRules.length) {
|
||||||
|
return {
|
||||||
|
message: 'signature has invalid rule',
|
||||||
|
signature,
|
||||||
|
rules: invalidRules
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
validateRules(rules) {
|
||||||
|
let invalidRules = rules.map((rule) => {
|
||||||
|
let isRuleTypeValid = this.validateRuleType(rule);
|
||||||
|
|
||||||
|
if (!isRuleTypeValid) {
|
||||||
|
return {
|
||||||
|
message: 'rule type does not supported',
|
||||||
|
rule
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((rule.type === 'or' || rule.type === 'and') && !('rules' in rule)) {
|
||||||
|
return {
|
||||||
|
message: 'rule should contains "rules" field',
|
||||||
|
rule
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rule.type === 'or' || rule.type === 'and') {
|
||||||
|
return this.validateRules(rule.rules);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
|
||||||
|
invalidRules = this.cleanArray(invalidRules);
|
||||||
|
|
||||||
|
if (invalidRules.length) {
|
||||||
|
return invalidRules;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanArray(actual) {
|
||||||
|
let newArray = new Array();
|
||||||
|
for (let i = 0; i < actual.length; i++) {
|
||||||
|
if (actual[i]) {
|
||||||
|
newArray.push(actual[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return newArray;
|
||||||
|
}
|
||||||
|
|
||||||
|
addSignature(signature) {
|
||||||
|
signatures.push(signature);
|
||||||
|
}
|
||||||
|
|
||||||
|
getFileSize(filePath, callback) {
|
||||||
|
fs.stat(filePath, (err, stat) => {
|
||||||
|
if (err) {
|
||||||
|
return callback(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
return callback(null, stat.size);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = FileDetector;
|
||||||
727
server/core/FileDetector/signatures.json
Normal file
727
server/core/FileDetector/signatures.json
Normal file
@@ -0,0 +1,727 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"type": "jpg",
|
||||||
|
"ext": "jpg",
|
||||||
|
"mime": "image/jpeg",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 2, "bytes": "ffd8" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "png",
|
||||||
|
"ext": "png",
|
||||||
|
"mime": "image/png",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0,"end": 4, "bytes": "89504e47" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "gif",
|
||||||
|
"ext": "gif",
|
||||||
|
"mime": "image/gif",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0,"end": 3, "bytes": "474946" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "bmp",
|
||||||
|
"ext": "bmp",
|
||||||
|
"mime": "image/bmp",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0,"end": 2, "bytes": "424d" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "webp",
|
||||||
|
"ext": "webp",
|
||||||
|
"mime": "image/webp",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 8,"end": 12, "bytes": "57454250" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "tif",
|
||||||
|
"ext": "tif",
|
||||||
|
"mime": "image/tiff",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "and", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "49492a00" },
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "4d4d002a" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{ "type": "notEqual", "start": 8, "end": 10, "bytes": "4352" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "cr2",
|
||||||
|
"ext": "cr2",
|
||||||
|
"mime": "image/x-canon-cr2",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "and", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "49492a00" },
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "4d4d002a" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{ "type": "equal", "start": 8, "end": 10, "bytes": "4352" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "jxr",
|
||||||
|
"ext": "jxr",
|
||||||
|
"mime": "image/vnd.ms-photo",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 3, "bytes": "4949bc" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "psd",
|
||||||
|
"ext": "psd",
|
||||||
|
"mime": "image/vnd.adobe.photoshop",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "38425053" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "flif",
|
||||||
|
"ext": "flif",
|
||||||
|
"mime": "image/flif",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "464c4946" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "zip",
|
||||||
|
"ext": "zip",
|
||||||
|
"mime": "application/zip",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 2, "bytes": "504b" },
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "start": 2, "end": 3, "bytes": "03" },
|
||||||
|
{ "type": "equal", "start": 2, "end": 3, "bytes": "05" },
|
||||||
|
{ "type": "equal", "start": 2, "end": 3, "bytes": "07" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "04" },
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "06" },
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "08" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{ "type": "notEqual", "start": 36, "end": 58, "bytes": "70656170706c69636174696f6e2f657075622b7a6970" },
|
||||||
|
{ "type": "notEqual", "start": 30, "end": 50, "bytes": "4d4554412d494e462f6d6f7a696c6c612e727361" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "epub",
|
||||||
|
"ext": "epub",
|
||||||
|
"mime": "application/epub+zip",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "504b0304" },
|
||||||
|
{ "type": "equal", "start": 36, "end": 58, "bytes": "70656170706c69636174696f6e2f657075622b7a6970" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "xpi",
|
||||||
|
"ext": "xpi",
|
||||||
|
"mime": "application/x-xpinstall",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "504b0304" },
|
||||||
|
{ "type": "equal", "start": 30, "end": 50, "bytes": "4d4554412d494e462f6d6f7a696c6c612e727361" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "tar",
|
||||||
|
"ext": "tar",
|
||||||
|
"mime": "application/x-tar",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 257, "end": 262, "bytes": "7573746172" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "rar",
|
||||||
|
"ext": "rar",
|
||||||
|
"mime": "application/x-rar-compressed",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 6, "bytes": "526172211a07" },
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "start": 6, "end": 7, "bytes": "00" },
|
||||||
|
{ "type": "equal", "start": 6, "end": 7, "bytes": "01" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "gz",
|
||||||
|
"ext": "gz",
|
||||||
|
"mime": "application/gzip",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 3, "bytes": "1f8b08" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "bz2",
|
||||||
|
"ext": "bz2",
|
||||||
|
"mime": "application/x-bzip2",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 3, "bytes": "425a68" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "7z",
|
||||||
|
"ext": "7z",
|
||||||
|
"mime": "application/x-7z-compressed",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 6, "bytes": "377abcaf271c" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "dmg",
|
||||||
|
"ext": "dmg",
|
||||||
|
"mime": "application/x-apple-diskimage",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 2, "bytes": "7801" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "mp4",
|
||||||
|
"ext": "mp4",
|
||||||
|
"mime": "video/mp4",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "and", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "start": 0, "end": 3, "bytes": "000000" },
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "18" },
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "20" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{ "type": "equal", "start": 4, "end": 8, "bytes": "66747970" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "33677035" },
|
||||||
|
{ "type": "and", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "start": 0, "end": 11, "bytes": "0000001c667479706d7034" },
|
||||||
|
{ "type": "equal", "start": 16, "end": 28, "bytes": "6d7034316d70343269736f6d" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{ "type": "equal", "start": 0, "end": 12, "bytes": "0000001c6674797069736f6d" },
|
||||||
|
{ "type": "equal", "start": 0, "end": 16, "bytes": "0000001c667479706d70343200000000" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "m4v",
|
||||||
|
"ext": "m4v",
|
||||||
|
"mime": "video/x-m4v",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 11, "bytes": "0000001c667479704d3456" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "mid",
|
||||||
|
"ext": "mid",
|
||||||
|
"mime": "audio/midi",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "4d546864" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "mkv",
|
||||||
|
"ext": "mkv",
|
||||||
|
"mime": "video/x-matroska",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 31, "end": 39, "bytes": "6d6174726f736b61" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "webm",
|
||||||
|
"ext": "webm",
|
||||||
|
"mime": "video/webm",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "1a45dfa3" },
|
||||||
|
{ "type": "notEqual", "start": 31, "end": 39, "bytes": "6d6174726f736b61" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "wmv",
|
||||||
|
"ext": "wmv",
|
||||||
|
"mime": "video/x-ms-wmv",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 10, "bytes": "3026b2758e66cf11a6d9" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "mpg",
|
||||||
|
"ext": "mpg",
|
||||||
|
"mime": "video/mpeg",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 3, "bytes": "000001" },
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "b0"},
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "b1"},
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "b2"},
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "b3"},
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "b4"},
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "b5"},
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "b6"},
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "b7"},
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "b8"},
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "b9"},
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "ba"},
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "bb"},
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "bc"},
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "bd"},
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "be"},
|
||||||
|
{ "type": "equal", "start": 3, "end": 4, "bytes": "bf"}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "mp3",
|
||||||
|
"ext": "mp3",
|
||||||
|
"mime": "audio/mpeg",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "start": 0, "end": 3, "bytes": "494433" },
|
||||||
|
{ "type": "equal", "start": 0, "end": 2, "bytes": "fffb" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "m4a",
|
||||||
|
"ext": "m4a",
|
||||||
|
"mime": "audio/m4a",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "start": 4, "end": 11, "bytes": "667479704d3441" },
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "4d344120" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "opus",
|
||||||
|
"ext": "opus",
|
||||||
|
"mime": "audio/opus",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 28, "end": 36, "bytes": "4f70757348656164" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "ogg",
|
||||||
|
"ext": "ogg",
|
||||||
|
"mime": "audio/ogg",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "4f676753" },
|
||||||
|
{ "type": "notEqual", "start": 28, "end": 36, "bytes": "4f70757348656164" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "flac",
|
||||||
|
"ext": "flac",
|
||||||
|
"mime": "audio/x-flac",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "664c6143" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "wav",
|
||||||
|
"ext": "wav",
|
||||||
|
"mime": "audio/x-wav",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "52494646" },
|
||||||
|
{ "type": "equal", "start": 8, "end": 12, "bytes": "57415645" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "amr",
|
||||||
|
"ext": "amr",
|
||||||
|
"mime": "audio/amr",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 6, "bytes": "2321414d520a" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "pdf",
|
||||||
|
"ext": "pdf",
|
||||||
|
"mime": "application/pdf",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "25504446" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "exe",
|
||||||
|
"ext": "exe",
|
||||||
|
"mime": "application/x-msdownload",
|
||||||
|
"iana": "application/vnd.microsoft.portable-executable",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "start": 0, "end": 2, "bytes": "4d5a" },
|
||||||
|
{ "type": "equal", "start": 0, "end": 2, "bytes": "4d7a" },
|
||||||
|
{ "type": "equal", "start": 0, "end": 2, "bytes": "6d7a" },
|
||||||
|
{ "type": "equal", "start": 0, "end": 2, "bytes": "6d5a" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "swf",
|
||||||
|
"ext": "swf",
|
||||||
|
"mime": "application/x-shockwave-flash",
|
||||||
|
"iana": "application/vnd.adobe.flash.movie",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "start": 0, "end": 1, "bytes": "43" },
|
||||||
|
{ "type": "equal", "start": 0, "end": 1, "bytes": "46" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{ "type": "equal", "start": 1, "end": 3, "bytes": "5753" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "rtf",
|
||||||
|
"ext": "rtf",
|
||||||
|
"mime": "application/rtf",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 5, "bytes": "7b5c727466" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "mov",
|
||||||
|
"ext": "mov",
|
||||||
|
"mime": "video/quicktime",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 8, "bytes": "0000001466747970" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "avi",
|
||||||
|
"ext": "avi",
|
||||||
|
"mime": "video/x-msvideo",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "52494646" },
|
||||||
|
{ "type": "equal", "start": 8, "end": 11, "bytes": "415649" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "woff",
|
||||||
|
"ext": "woff",
|
||||||
|
"mime": "application/font-woff",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "774f4646" },
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "start": 4, "end": 8, "bytes": "00010000" },
|
||||||
|
{ "type": "equal", "start": 4, "end": 8, "bytes": "4f54544f" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "woff2",
|
||||||
|
"ext": "woff2",
|
||||||
|
"mime": "application/font-woff",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "774f4632" },
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "start": 4, "end": 8, "bytes": "00010000" },
|
||||||
|
{ "type": "equal", "start": 4, "end": 8, "bytes": "4f54544f" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "eot",
|
||||||
|
"ext": "eot",
|
||||||
|
"mime": "application/octet-stream",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 34, "end": 36, "bytes": "4c50" },
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "start": 8, "end": 11, "bytes": "000001" },
|
||||||
|
{ "type": "equal", "start": 8, "end": 11, "bytes": "010002" },
|
||||||
|
{ "type": "equal", "start": 8, "end": 11, "bytes": "020002" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "ttf",
|
||||||
|
"ext": "ttf",
|
||||||
|
"mime": "application/font-sfnt",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 5, "bytes": "0001000000" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "otf",
|
||||||
|
"ext": "otf",
|
||||||
|
"mime": "application/font-sfnt",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 5, "bytes": "4f54544f00" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "ico",
|
||||||
|
"ext": "ico",
|
||||||
|
"mime": "application/x-icon",
|
||||||
|
"iana": "image/vnd.microsoft.icon",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "00000100" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "flv",
|
||||||
|
"ext": "flv",
|
||||||
|
"mime": "application/x-flv",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "464c5601" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "ps",
|
||||||
|
"ext": "ps",
|
||||||
|
"mime": "application/postscript",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 2, "bytes": "2521" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "xz",
|
||||||
|
"ext": "xz",
|
||||||
|
"mime": "application/x-xz",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 6, "bytes": "fd377a585a00" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "sqlite",
|
||||||
|
"ext": "sqlite",
|
||||||
|
"mime": "application/x-sqlite3",
|
||||||
|
"iana": "application/vnd.sqlite3",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "53514c69" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "nes",
|
||||||
|
"ext": "nes",
|
||||||
|
"mime": "application/x-nintendo-nes-rom",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "4e45531a" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "crx",
|
||||||
|
"ext": "crx",
|
||||||
|
"mime": "application/x-google-chrome-extension",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "43723234" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "cab",
|
||||||
|
"ext": "cab",
|
||||||
|
"mime": "application/vnd.ms-cab-compressed",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "4d534346" },
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "49536328" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "ar",
|
||||||
|
"ext": "ar",
|
||||||
|
"mime": "application/x-unix-archive",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 7, "bytes": "213c617263683e" },
|
||||||
|
{ "type": "notEqual", "start": 0, "end": 21, "bytes": "213c617263683e0a64656269616e2d62696e617279" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "deb",
|
||||||
|
"ext": "deb",
|
||||||
|
"mime": "application/x-deb",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 21, "bytes": "213c617263683e0a64656269616e2d62696e617279" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "rpm",
|
||||||
|
"ext": "rpm",
|
||||||
|
"mime": "application/x-rpm",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "edabeedb" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "Z",
|
||||||
|
"ext": "Z",
|
||||||
|
"mime": "application/x-compress",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "start": 0, "end": 2, "bytes": "1fa0" },
|
||||||
|
{ "type": "equal", "start": 0, "end": 2, "bytes": "1f9d" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "lz",
|
||||||
|
"ext": "lz",
|
||||||
|
"mime": "application/x-lzip",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 4, "bytes": "4c5a4950" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "msi",
|
||||||
|
"ext": "msi",
|
||||||
|
"mime": "application/x-msi",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "equal", "start": 0, "end": 8, "bytes": "d0cf11e0a1b11ae1" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "svg",
|
||||||
|
"ext": "svg",
|
||||||
|
"mime": "image/svg+xml",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "contains", "bytes": "3c737667" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "html",
|
||||||
|
"ext": "html",
|
||||||
|
"mime": "text/html",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "contains", "bytes": "3c68746d6c" },
|
||||||
|
{ "type": "contains", "bytes": "3c00680074006d006c00" },
|
||||||
|
{ "type": "equal", "end": 5, "bytes": "3c68746d6c" },
|
||||||
|
{ "type": "equal", "end": 10, "bytes": "3c00680074006d006c00" },
|
||||||
|
{ "type": "equal", "end": 9, "bytes": "3c21646f6374797065" },
|
||||||
|
{ "type": "equal", "end": 5, "bytes": "3c626f6479" },
|
||||||
|
{ "type": "equal", "end": 5, "bytes": "3c68656164" },
|
||||||
|
{ "type": "equal", "end": 7, "bytes": "3c696672616d65" },
|
||||||
|
{ "type": "equal", "end": 4, "bytes": "3c696d67" },
|
||||||
|
{ "type": "equal", "end": 7, "bytes": "3c6f626a656374" },
|
||||||
|
{ "type": "equal", "end": 7, "bytes": "3c736372697074" },
|
||||||
|
{ "type": "equal", "end": 6, "bytes": "3c7461626c65" },
|
||||||
|
{ "type": "equal", "end": 6, "bytes": "3c7469746c65" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "docx",
|
||||||
|
"ext": "docx",
|
||||||
|
"mime": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "contains", "bytes": "6170706c69636174696f6e2f766e642e6f70656e786d6c666f726d6174732d6f6666696365646f63756d656e74" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "xml",
|
||||||
|
"ext": "xml",
|
||||||
|
"mime": "application/xml",
|
||||||
|
"rules": [
|
||||||
|
{ "type": "or", "rules":
|
||||||
|
[
|
||||||
|
{ "type": "equal", "end": 19, "bytes": "3c3f786d6c2076657273696f6e3d22312e3022" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
]
|
||||||
@@ -22,7 +22,7 @@ class ReaderWorker {
|
|||||||
|
|
||||||
this.down = new FileDownloader();
|
this.down = new FileDownloader();
|
||||||
this.decomp = new FileDecompressor();
|
this.decomp = new FileDecompressor();
|
||||||
this.bookConverter = new BookConverter();
|
this.bookConverter = new BookConverter(this.config);
|
||||||
|
|
||||||
if (!singleCleanExecute) {
|
if (!singleCleanExecute) {
|
||||||
this.periodicCleanDir(this.config.tempPublicDir, this.config.maxTempPublicDirSize, 60*60*1000);//1 раз в час
|
this.periodicCleanDir(this.config.tempPublicDir, this.config.maxTempPublicDirSize, 60*60*1000);//1 раз в час
|
||||||
@@ -63,17 +63,17 @@ class ReaderWorker {
|
|||||||
//decompress
|
//decompress
|
||||||
wState.set({state: 'decompress', step: 2, progress: 0});
|
wState.set({state: 'decompress', step: 2, progress: 0});
|
||||||
decompDir = `${this.config.tempDownloadDir}/${decompDirname}`;
|
decompDir = `${this.config.tempDownloadDir}/${decompDirname}`;
|
||||||
const decompFilename = await this.decomp.decompressFile(downloadedFilename, decompDir);
|
const decompFiles = await this.decomp.decompressFile(downloadedFilename, decompDir);
|
||||||
wState.set({progress: 100});
|
wState.set({progress: 100});
|
||||||
|
|
||||||
//parse book
|
//конвертирование в fb2
|
||||||
wState.set({state: 'convert', step: 3, progress: 0});
|
wState.set({state: 'convert', step: 3, progress: 0});
|
||||||
convertFilename = `${this.config.tempDownloadDir}/${tempFilename2}`;
|
convertFilename = `${this.config.tempDownloadDir}/${tempFilename2}`;
|
||||||
await this.bookConverter.convertToFb2(decompFilename, convertFilename, url, progress => {
|
await this.bookConverter.convertToFb2(decompFiles, convertFilename, url, progress => {
|
||||||
wState.set({progress});
|
wState.set({progress});
|
||||||
});
|
});
|
||||||
|
|
||||||
//compress file to tmp dir, if not exists with the same hashname
|
//сжимаем файл в tmp, если там уже нет с тем же именем-sha256
|
||||||
const compFilename = await this.decomp.gzipFileIfNotExists(convertFilename, `${this.config.tempPublicDir}`);
|
const compFilename = await this.decomp.gzipFileIfNotExists(convertFilename, `${this.config.tempPublicDir}`);
|
||||||
|
|
||||||
wState.set({progress: 100});
|
wState.set({progress: 100});
|
||||||
@@ -83,8 +83,9 @@ class ReaderWorker {
|
|||||||
wState.finish({path: `/tmp/${finishFilename}`});
|
wState.finish({path: `/tmp/${finishFilename}`});
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
if (this.config.branch == 'development')
|
||||||
|
console.error(e);
|
||||||
wState.set({state: 'error', error: (errMes ? errMes : e.message)});
|
wState.set({state: 'error', error: (errMes ? errMes : e.message)});
|
||||||
|
|
||||||
} finally {
|
} finally {
|
||||||
//clean
|
//clean
|
||||||
if (decompDir)
|
if (decompDir)
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
const { spawn } = require('child_process');
|
||||||
const fs = require('fs-extra');
|
const fs = require('fs-extra');
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
|
|
||||||
@@ -13,8 +14,48 @@ async function touchFile(filename) {
|
|||||||
await fs.utimes(filename, Date.now()/1000, Date.now()/1000);
|
await fs.utimes(filename, Date.now()/1000, Date.now()/1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function spawnProcess(cmd, opts) {
|
||||||
|
let {args, killAfter, onData} = opts;
|
||||||
|
killAfter = (killAfter ? killAfter : 120*1000);
|
||||||
|
onData = (onData ? onData : () => {});
|
||||||
|
args = (args ? args : []);
|
||||||
|
|
||||||
|
return new Promise(async(resolve, reject) => {
|
||||||
|
let resolved = false;
|
||||||
|
const proc = spawn(cmd, args, {detached: true});
|
||||||
|
|
||||||
|
let stdout = '';
|
||||||
|
proc.stdout.on('data', (data) => {
|
||||||
|
stdout += data;
|
||||||
|
onData(data);
|
||||||
|
});
|
||||||
|
|
||||||
|
let stderr = '';
|
||||||
|
proc.stderr.on('data', (data) => {
|
||||||
|
stderr += data;
|
||||||
|
onData(data);
|
||||||
|
});
|
||||||
|
|
||||||
|
proc.on('close', (code) => {
|
||||||
|
resolved = true;
|
||||||
|
resolve({status: 'close', code, stdout, stderr});
|
||||||
|
});
|
||||||
|
|
||||||
|
proc.on('error', (error) => {
|
||||||
|
reject({status: 'error', error, stdout, stderr});
|
||||||
|
});
|
||||||
|
|
||||||
|
await sleep(killAfter);
|
||||||
|
if (!resolved) {
|
||||||
|
process.kill(proc.pid);
|
||||||
|
reject({status: 'killed', stdout, stderr});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
sleep,
|
sleep,
|
||||||
randomHexString,
|
randomHexString,
|
||||||
touchFile
|
touchFile,
|
||||||
|
spawnProcess
|
||||||
};
|
};
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
const config = require('./config');
|
const config = require('./config');
|
||||||
const {initLogger, getLog} = require('./core/getLogger');
|
const logger = require('./core/getLogger');
|
||||||
initLogger(config);
|
logger.initLogger(config);
|
||||||
const log = getLog();
|
const log = logger.getLog();
|
||||||
|
|
||||||
const configSaver = require('./config/configSaver');
|
const configSaver = require('./config/configSaver');
|
||||||
const argv = require('minimist')(process.argv.slice(2));
|
const argv = require('minimist')(process.argv.slice(2));
|
||||||
@@ -31,6 +31,7 @@ async function init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
|
log(`${config.name} v${config.version}`);
|
||||||
log('Initializing');
|
log('Initializing');
|
||||||
await init();
|
await init();
|
||||||
|
|
||||||
@@ -89,7 +90,7 @@ async function main() {
|
|||||||
try {
|
try {
|
||||||
await main();
|
await main();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e.message);
|
console.error(e);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
Reference in New Issue
Block a user