Skip to content

Commit

Permalink
rebuild with typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
swwind committed Aug 28, 2020
1 parent f14ffbb commit faafb84
Show file tree
Hide file tree
Showing 44 changed files with 983 additions and 667 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Expand Up @@ -14,6 +14,9 @@
/yarn.lock
/public/js/xepub.min.js

/app/*.js
/app/*.d.ts

# misc
.DS_Store
.env.local
Expand Down
1 change: 1 addition & 0 deletions .npmignore
Expand Up @@ -3,3 +3,4 @@
/.gitignore
/webpack.config.js
/yarn.lock
/app/*.ts
20 changes: 8 additions & 12 deletions backend/alert.js → app/alert.ts
@@ -1,45 +1,41 @@
'use strict';

require('colors');
import 'colors';

const flags = {
unstable: false,
broken: false,
debug: false,
}

const error = (message = '') => {
export const error = (message = '') => {
console.error('[ERRO]'.red, message);
}
const warn = (message = '') => {
export const warn = (message = '') => {
console.warn('[WARN]'.yellow, message);
}
const info = (message = '') => {
export const info = (message = '') => {
console.log('[INFO]'.white, message);
}
const debug = (message = '') => {
export const debug = (message = '') => {
if (flags.debug) {
console.log('[DBUG]'.green, message);
}
}
const unstable = () => {
export const unstable = () => {
if (!flags.unstable) {
warn('This book has some problems while parsing...');
warn('I can not ensure whether xepub can deal it properly or not.');
flags.unstable = true;
}
}
const broken = () => {
export const broken = () => {
if (!flags.broken) {
error('This book is almost broken!!!');
error('Xepub may crash.');
flags.broken = true;
}
}
const debugMode = () => {
export const debugMode = () => {
flags.debug = true;
}

module.exports = {
error, warn, info, unstable, broken, debug, debugMode
}
File renamed without changes.
2 changes: 1 addition & 1 deletion backend/help.txt → app/help.txt
Expand Up @@ -10,7 +10,7 @@ USAGE

-p, --port http port (default 23333, random if electron)
-o, --open open browser automaticly
-e, --electron use electron instead of browser
-e, --electron open electron automaticly
-h, --help show help document and exit
-v, --version show xepub version and exit
--debug show debug messages
Expand Down
143 changes: 143 additions & 0 deletions app/index.ts
@@ -0,0 +1,143 @@
import { promises as fsp, existsSync } from 'fs';
import opn from 'opn';
import pug from 'pug';
import * as path from 'path';
import * as http from 'http';
import * as express from 'express';
import * as alert from './alert';
import * as packages from '../package.json';
import { spawn } from 'child_process';
import options, { XepubArguments } from './options';
import parseEpub from './parse-epub';
import parseFolder from './parse-folder';
import Zip from './zip';
import { EpubInfo } from './types';
import { bindSocket } from './socket';
import { AddressInfo } from 'net';

const here = (...file: string[]) => path.resolve(__dirname, ...file);

const main = async (option: XepubArguments) => {
if (option.debug) {
alert.debugMode();
}

if (option.version) {
alert.info('Xepub v' + packages.version);
alert.info('Node ' + process.version);
process.exit(0);
}

if (option.help) {
console.log(await fsp.readFile(here('help.txt'), 'utf-8'));
process.exit(0);
}

const epubname = option._[0];
if (!epubname) {
alert.error('File name missing');
process.exit(1);
}

if (!existsSync(epubname)) {
alert.error('File or folder not found');
process.exit(1);
}

const app = express();

const lstat = await fsp.lstat(epubname);
let epub: EpubInfo = null;
const zip = new Zip();

if (lstat.isDirectory()) {

// open folder
// since v1.0.0-alpha.9

alert.info('Scanning folder...');
const dirname = path.resolve(process.cwd(), epubname);
const parseResult = await parseFolder(dirname);
epub = parseResult.epub;
alert.debug('Successfully scanned folder');

const index = pug.compile(await fsp.readFile(here('folder-index.pug'), 'utf8'));

app.use('/folder/', (req, res, next) => {
if (req.originalUrl === '/folder/') {
res.header('Content-Type', 'text/html');
res.end(index({ files: parseResult.files }));
} else {
next();
}
})
app.use('/folder', express.static(dirname));

} else if (lstat.isFile()) {

// open epub file
alert.info('Parsing EPUB file...');
await zip.initialize(epubname);
const mimetype = (await zip.readAsText('mimetype')).unwrapOr('');
if (mimetype !== 'application/epub+zip') {
alert.error('Not epub file');
alert.debug('Mimetype: ' + mimetype);
process.exit(1);
}
epub = await parseEpub(zip);
alert.debug('Successfully parsed file');
app.use(zip.middleware());
} else {

alert.error('?');
alert.error('??');
alert.error('???');
alert.error(`What is ${epubname}?`);
}

// serve public folder
app.use(express.static(here('..', 'public')));

const server = http.createServer(app);
bindSocket(server, epub);

if (option.port === -1) {
option.port = option.electron ? 0 : 23333;
}
server.listen(option.port);
const address = server.address() as AddressInfo;
const url = `http://localhost:${address.port}/`;
alert.info(`Finished, listening on ${url}`);

const terminate = async (code: number) => {
await zip.clear();
process.exit(code);
}

if (option.electron) {
const which = spawn('which', ['electron']);
which.on('close', (code) => {
if (code) {
// not found
alert.error('Electron not found in $PATH');
alert.error('Please remove -e/--electron flag');
} else {
alert.info('Opening in electron...');
const electron = spawn('electron', [ url ]);
electron.on('close', async () => {
alert.info('Electron closed.');
await terminate(0);
});
}
})
} else if (option.open) {
opn(url);
}

process.on('SIGINT', async () => {
await terminate(0);
});

}

main(options(process.argv.slice(2)));
20 changes: 13 additions & 7 deletions backend/options.js → app/options.ts
@@ -1,6 +1,6 @@
'use strict';

const { error } = require("./alert");
import { error } from './alert';

const flags = {
'p': 'port',
Expand All @@ -10,10 +10,18 @@ const flags = {
'v': 'version',
}

/**
* parse command line arguments
*/
const options = (args) => {
export interface XepubArguments {
port: number;
open: boolean;
electron: boolean;
help: boolean;
version: boolean;
debug: boolean;
_: string[],
}

export default (args: string[]): XepubArguments => {

const res = {
port: -1, // -1: default
open: false,
Expand Down Expand Up @@ -47,5 +55,3 @@ const options = (args) => {

return res;
}

module.exports = options;

0 comments on commit faafb84

Please sign in to comment.