Skip to content

Commit

Permalink
Rewrite for koa 2
Browse files Browse the repository at this point in the history
  • Loading branch information
inDream committed Aug 10, 2017
1 parent b28dd01 commit 5c7c648
Show file tree
Hide file tree
Showing 8 changed files with 244 additions and 233 deletions.
82 changes: 40 additions & 42 deletions lib/fileManager.js
Original file line number Diff line number Diff line change
@@ -1,58 +1,56 @@
var fs = require('co-fs');
var co = require('co');
var fse = require('co-fs-extra');
var path = require('path');
var JSZip = require('jszip');
const fs = require('fs-extra');
const path = require('path');
const JSZip = require('jszip');

var FileManager = {};
const FileManager = {};

FileManager.getStats = function *(p) {
var stats = yield fs.stat(p);
FileManager.getStats = async p => {
const stats = fs.statSync(p);
return {
folder: stats.isDirectory(),
size: stats.size,
mtime: stats.mtime.getTime()
}
};

FileManager.list = function *(dirPath) {
var files = yield fs.readdir(dirPath);
var stats = [];
for (var i=0; i<files.length; ++i) {
var fPath = path.join(dirPath, files[i]);
var stat = yield FileManager.getStats(fPath);
FileManager.list = async dirPath => {
const files = await fs.readdir(dirPath);
const stats = [];
for (let i = 0; i < files.length; ++i) {
const fPath = path.join(dirPath, files[i]);
const stat = await FileManager.getStats(fPath);
stat.name = files[i];
stats.push(stat);
}
return stats;
};

FileManager.remove = function *(p) {
yield fse.remove(p);
FileManager.remove = async p => {
await fs.remove(p);
};

FileManager.mkdirs = function *(dirPath) {
yield fse.mkdirs(dirPath);
FileManager.mkdirs = async dirPath => {
await fs.mkdirs(dirPath);
};

FileManager.move = function *(srcs, dest) {
for (var i=0; i<srcs.length; ++i) {
var basename = path.basename(srcs[i]);
yield fse.move(srcs[i], path.join(dest, basename));
FileManager.move = async (srcs, dest) => {
for (let i = 0; i < srcs.length; ++i) {
const basename = path.basename(srcs[i]);
await fs.move(srcs[i], path.join(dest, basename));
}
};

FileManager.rename = function *(src, dest) {
yield fse.move(src, dest);
FileManager.rename = async (src, dest) => {
await fs.move(src, dest);
};

FileManager.archive = function *(src, archive, dirPath, embedDirs) {
var zip = new JSZip();
var baseName = path.basename(archive, '.zip');
FileManager.archive = async (src, archive, dirPath, embedDirs) => {
const zip = new JSZip();
const baseName = path.basename(archive, '.zip');

function* addFile(file) {
var data = yield fs.readFile(file);
var name;
const addFile = async file => {
const data = await fs.readFile(file);
let name;
if (embedDirs) {
name = file;
if (name.indexOf(dirPath) === 0) {
Expand All @@ -65,30 +63,30 @@ FileManager.archive = function *(src, archive, dirPath, embedDirs) {
C.logger.info('Added ' + name + ' ' + data.length + ' bytes to archive ' + archive);
}

function* addDir(dir) {
var contents = yield fs.readdir(dir);
for (var file of contents) {
yield * process(path.join(dir, file));
const addDir = async dir => {
const contents = await fs.readdir(dir);
for (const file of contents) {
await process(path.join(dir, file));
}
}

function* process(fp) {
var stat = yield fs.stat(fp);
const process = async fp => {
const stat = await fs.stat(fp);
if (stat.isDirectory()) {
yield * addDir(fp);
await addDir(fp);
} else {
yield addFile(fp);
await addFile(fp);
}
}

// Add each src. For directories, do the entire recursive dir.
for (var file of src) {
yield * process(file);
for (const file of src) {
await process(file);
}

// Generate the zip and store the final.
var data = yield zip.generateAsync({type:'nodebuffer',compression:'DEFLATE'});
yield fs.writeFile(archive, data, 'binary');
const data = await zip.generateAsync({type:'nodebuffer',compression:'DEFLATE'});
await fs.writeFile(archive, data, 'binary');
};

module.exports = FileManager;
17 changes: 9 additions & 8 deletions lib/fileMap.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
var path = require('path');
const path = require('path');

var DATA_ROOT = C.data.root;
const DATA_ROOT = C.data.root;

exports.filePath = function (relPath, decodeURI) {
if (decodeURI) relPath = decodeURIComponent(relPath);
if (relPath.indexOf('..') >= 0){
var e = new Error('Do Not Contain .. in relPath!');
exports.filePath = (relPath, decodeURI) => {
if (decodeURI) {
relPath = decodeURIComponent(relPath);
}
if (relPath.indexOf('..') >= 0) {
const e = new Error('Do Not Contain .. in relPath!');
e.status = 400;
throw e;
}
else {
} else {
return path.join(DATA_ROOT, relPath);
}
};
43 changes: 21 additions & 22 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
#!/usr/bin/env node

var koa =require('koa');
var path = require('path');
var tracer = require('tracer');
var mount = require('koa-mount');
var morgan = require('koa-morgan');
var koaStatic = require('koa-static');
const path = require('path');
const koa = require('koa');
const tracer = require('tracer');
const morgan = require('koa-morgan');
const koaStatic = require('koa-static');

const dev = process.env.NODE_ENV !== 'production';

// Config
var argv = require('optimist')
const argv = require('optimist')
.usage([
'USAGE: $0 [-p <port>] [-d <directory>]']
)
Expand All @@ -27,7 +28,7 @@ var argv = require('optimist')
})
.option('help', {
alias: 'h',
description: "Display This Help Message"
description: 'Display This Help Message'
})
.argv;

Expand All @@ -50,22 +51,20 @@ global.C = {
};

// Start Server
var Tools = require('./tools');

var startServer = function (app, port) {
app.listen(port);
C.logger.info('listening on *.' + port);
};
const Tools = require('./tools');

var app = koa();
const app = new koa();
app.proxy = true;
app.use(Tools.handelError);
app.use(Tools.realIp);
app.use(morgan.middleware(C.morganFormat));
app.use(Tools.handelError);
app.use(morgan(C.morganFormat));

var IndexRouter = require('./routes');
app.use(mount('/', IndexRouter));
const router = require('./routes');
app.use(router.routes()).use(router.allowedMethods());
app.use(koaStatic(path.join(__dirname,'./public/')));

startServer(app, +argv.port);

app.listen(+argv.port, err => {
if (err) {
throw err;
}
C.logger.info('listening on *.' + argv.port);
});
43 changes: 22 additions & 21 deletions lib/public/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ FMApp.controller('FileManagerCtr', ['$scope', '$http', '$location',
var hash2paths = function (relPath) {
var paths = [];
var names = relPath.split('/');
var path = '#/';
var path = '#!/';
paths.push({name: 'Home', path: path});
for (var i=0; i<names.length; ++i) {
var name = names[i];
Expand Down Expand Up @@ -50,8 +50,8 @@ FMApp.controller('FileManagerCtr', ['$scope', '$http', '$location',

var setCurFiles = function (relPath) {
$http.get('api' + relPath)
.success(function (data) {
var files = data;
.then(function (res) {
var files = res.data;
files.forEach(function (file) {
file.relPath = relPath + encodeURIComponent(file.name);
if (file.folder) file.relPath += '/';
Expand All @@ -60,11 +60,9 @@ FMApp.controller('FileManagerCtr', ['$scope', '$http', '$location',
file.humanTime = humanTime(file.mtime);
});
FM.curFiles = files;
console.log('Current Files:');
console.log(FM.curFiles);
})
.error(function (data, status) {
alert('Error: ' + status + data);
console.log('Current Files:', FM.curFiles);
}, function (res) {
alert('Error: ' + res.status + res.data);
});
};

Expand All @@ -73,7 +71,7 @@ FMApp.controller('FileManagerCtr', ['$scope', '$http', '$location',
return $location.path('/');
}
console.log('Hash change: ' + hash);
var relPath = hash.slice(1);
var relPath = hash.slice(2);
FM.curHashPath = hash;
FM.curFolderPath = relPath;
FM.curBreadCrumbPaths = hash2paths(relPath);
Expand Down Expand Up @@ -126,12 +124,11 @@ FMApp.controller('FileManagerCtr', ['$scope', '$http', '$location',
}
console.log('request url', url);
$http(conf)
.success(function (data) {
FM.successData = data;
.then(function (res) {
FM.successData = res.data;
handleHashChange(FM.curHashPath);
})
.error(function (data, status) {
FM.errorData = ' ' + status + ': ' + data;
}, function (res) {
FM.errorData = ' ' + res.status + ': ' + res.data;
});
};

Expand Down Expand Up @@ -208,14 +205,18 @@ FMApp.controller('FileManagerCtr', ['$scope', '$http', '$location',
};

FM.upload = function () {
var folder = FM.curFolderPath;
console.log('Upload File:', FM.uploadFile);
var formData = new FormData();
formData.append('upload', FM.uploadFile);
var url = 'api' + FM.curFolderPath + encodeURI(FM.uploadFile.name);
httpRequest('POST', url, {type: 'UPLOAD_FILE'}, formData, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
});
for (var i = 0; i < FM.uploadFile.length; i++) {
var file = FM.uploadFile[i];
var formData = new FormData();
formData.append('upload', file);
var url = 'api' + folder + encodeURI(file.name);
httpRequest('POST', url, {type: 'UPLOAD_FILE'}, formData, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
});
}
};

FM.btnDisabled = function (btnName) {
Expand Down
Loading

0 comments on commit 5c7c648

Please sign in to comment.