<commit_before>var express = require('express');
var router = express.Router();
var util = require('../util/common');
var lodash = require('lodash');
var log4js = require('log4js');
var log = log4js.getLogger('api');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var modelSchema = require('../models/model');
var config  = require('../config.json').mongodb;
var connStr = 'mongodb://'+config.server+':'+config.port+'/'+config.db;
var connOpt = {};
config.user && (connOpt.user = config.user);
config.pwd && (connOpt.pass = config.pwd);
var db = mongoose.createConnection(connStr, connOpt);
var moduleFolder = './public/modules';
var distFolder = './public/dist';

var Project = db.model('projects', modelSchema.projectSchema);
var Module = db.model('modules', modelSchema.moduleSchema);

var moduleDependenciesReg = /define\s*\([^\[]*(?:\[([^\]]+)])?\s*(?:,\s*)/m;

/**
 * 获取项目列表
 */
router.get('/project/list', function (req, res, next) {
    Project.find({}, function (err, data) {
        if(err){
            log.log('ERROR',err);
            return res.json({
                code: 1,
                msg: 'server error.'
            });
        }
        res.json({
            code: 0,
            data: data
        });
    });
});

/**
 * 根据pid获取项目信息
 */
router.get('/project/view/:pid', function (req, res, next) {
    var pid = req.params['pid'];
    if(!pid){
        return res.json({
            code: 1,
            msg: 'lost the required parameter project id.'
        });
    }
    Project.findById(pid, function (err, data) {
        if(err){
            log.log('ERROR',err);
            return res.json({
                code: 2,
                msg: err.message
            });
        }
        res.json({
            code: 0,
            data: data
        });
    });
});

/**
 * 保存项目信息
 */
router.post('/project/add', function (req, res, next) {
    var body = req.body;
    var projectName = body.projectName || '';
    var userGroup = body.userGroup || '';

    if(projectName) {
        var p = new Project({
            name: projectName,
            userGroup: userGroup.split(',')
        });
        p.save(function (err) {
            if (err) {
                log.log('ERROR',err);
                return res.json({
                    code: 1,
                    msg: JSON.stringify(err)
                });
            }
            res.json({
                code: 0,
                msg: 'success'
            });
        });
    }
    else{
        res.json({
            code: 2,
            msg: 'lost required parameter projectName.'
        });
    }
});

/**
 * 根据pid获取模块
 */
router.get('/module/list/:pid', function (req, res, next) {
    var pid = req.params['pid'];
    if(!pid){
        return res.json({
            code: 1,
            msg: 'lost the required parameter project id.'
        });
    }
    Module.find({pid: pid},{_id:1, id: 1, name: 1, pid:1}, function (err, data) {
        if(err){
            log.log('ERROR',err);
            return res.json({
                code: 2,
                msg: 'server error.'
            });
        }
        res.json({
            code: 0,
            data: data
        });
    });
});

/**
 * 根据mid获取当前模块信息
 */
router.get('/module/view/:mid', function (req, res, next) {
    var mid = req.params['mid'];

    if(mid){
        Module.findById(mid, function (err, data) {
            if(err){
                log.log('ERROR',err);
                return res.json({
                    code: 2,
                    msg: err.message
                });
            }
            res.json({
                code: 0,
                data: data
            });
        });
    }
    else{
        return res.json({
            code: 1,
            msg: 'lost the required parameter mid.'
        });
    }
});

/**
 * 校验模块标识符是否合法
 */
router.get('/module/check/:id', function (req, res, next) {
    var id = req.params['id'];

    checkModuleId(id, function (result) {
        if(-2 === result){
            return res.json({
                code: -2,
                msg: 'mongo error.'
            });
        }else if(-1 === result){
            return res.json({
                code: -1,
                msg: 'file system error.'
            });
        }
        else if(0 === result){
            return res.json({
                code: 0,
                msg: 'not file and not record.'
            });
        }
        else if(1 === result){
            return res.json({
                code: 1,
                msg: 'file exist.'
            });
        }
        else if(2 === result){
            return res.json({
                code: 2,
                msg: 'module exist.'
            });
        }
    });
});

/**
 * 保存模块信息
 */
router.post('/module/save', function (req, res, next) {
    var body = req.body,
        _id = body._id,
        id = body.id,
        pid = body.pid,
        name = body.name,
        path = body.path,
        author = body.author,
        code = body.code,
        demo = body.demo,
        lastModify = body.lastModify,
        m,
        deps={},
        uses = [];

    deps.exists = [];
    deps.lostes = [];
    deps.map = {};

    var getDependenciesPromise = new Promise(function (resolve, reject) {
        // 依赖分析
        var myDeps = code.match(moduleDependenciesReg);
        if (myDeps) {
            myDepsList = (myDeps[1] && myDeps[1].split(',') || []).map(function (v) {
                return v.replace(/\s*'|\s*"/g, '');
            });
            if (myDepsList.length) {
                directive = '|'+myDepsList.join('|')+'|';
                getDependencies(myDepsList, deps, function (ret, data) {
                    if(ret) {
                        resolve(deps);
                    }
                    else{
                        reject(data.message);
                    }
                });
            }
            else {
                directive = "";
                resolve(deps);
            }
        }
        else{
            directive = "";
            resolve(deps)
        }
    });

    getDependenciesPromise.then(function (value) {
        return new Promise(function (resolve, reject) {
            Module.find({
                $or:[{'deps.exists': id},{'deps.lostes':id}]
            }, function (err, data) {
                if(err){
                    return reject(err.message);
                }
                if(data && data.length){
                    data.forEach(function (v) {
                        uses.push({
                            _id: v._id,
                            pid: v.pid,
                            id: v.id,
                            name: v.name
                        });
                    });
                    resolve(uses);
                }
                else{
                    resolve(uses);
                }
            });
        });
    }).then(save).catch(function (value) {
        log.log('ERROR',value);
        res.json({
            code: 103,
            msg: value
        });
    });

    function save(useMyList) {
        if (_id) {
            // update
            Module.update({_id: _id}, {
                name: name,
                author: author,
                code: code,
                demo: demo,
                deps: deps,
                uses: useMyList,
                lastModify: Date.now()
            }, function (err) {
                if (err) {
                    log.log('ERROR',err);
                    return res.json({
                        code: 10,
                        msg: err.message
                    });
                }

                // 写文件
                util.saveFile(moduleFolder + '/' + id + '.js', code, function (result) {
                    if (-1 === result) {
                        return res.json({
                            code: 12,
                            msg: 'async file error.'
                        });
                    }
                    else if (1 === result) {
                        return res.json({
                            code: 0,
                            msg: 'success'
                        });
                    }
                });
            });
        }
        else {
            // add
            m = new Module({
                id: id,
                pid: pid,
                name: name,
                path: path,
                author: author,
                code: code,
                demo: demo,
                deps: deps,
                uses: useMyList,
                lastModify: lastModify
            });
            m.save(function (err, data) {
                if (err) {
                    log.log('ERROR',err);
                    return res.json({
                        code: 1,
                        msg: err.message
                    });
                }
                // 写文件
                util.saveFile(moduleFolder + '/' + id + '.js', code, function (result) {
                    if (-1 === result) {
                        // 回滚
                        Module.findOneAndRemove({_id: data._id}, function () {
                        });
                        return res.json({
                            code: 2,
                            msg: '保存模块出错.'
                        });
                    }
                    else if (1 === result) {
                        return res.json({
                            code: 0,
                            msg: 'success'
                        });
                    }
                });
            });
        }

    }
});

/**
 * 加载已存在的模块文件
 */
router.post('/module/load', function (req, res, next) {
    var filename = req.body.filename;
    util.readFile(moduleFolder+'/'+filename+'.js', function (result, data) {
        if(result) {
            return res.json({
                code: 0,
                data: data
            });
        }else{
            return res.json({
                code: 1,
                msg: data.message
            });
        }

    });
});

/**
 * 模块压缩
 */
router.post('/compress', function (req, res, next) {
    var modules = req.body.modules.split(',');
    var combName = req.body.combName || '';
    var ms = [];
    if(modules.length) {
        modules.forEach(function (item) {
            if (item && '' != (item = item.trim())) {
                ms.push(moduleFolder+'/'+item+'.js');
            }
        });
        if(ms.length === 1) combName = ms[0].replace(moduleFolder, distFolder);

        util.compress(ms, combName, function (result) {
            if(-1 === result){
                log.log('INFO', 'compress module failure when save the file.');
                return res.json({
                    code: 3,
                    msg: 'save file failure.'
                });
            }
            else if( 1 === result){
                return res.json({
                    code: 0,
                    msg: 'success'
                });
            }
            else{
                return res.json({
                    code: 10,
                    msg: 'server error.'
                });
            }
        });
    }
    else{
        return res.json({
            code: 2,
            msg: 'lost required parameter modules.'
        });
    }
});

/**
 * 搜索接口
 */
router.post('/search', function (req, res, next) {
    var key = req.body.keys;
    if(key){
        Module.find({name: new RegExp('.*?'+key+'.*?')}, function (err, data) {
            if(err){
                log.log('ERROR',err);
                return res.json({
                    code: 1,
                    msg: err.message
                });
            }
            return res.json({
                code: 0,
                data: data
            });
        });
    }
});

/**
 * 模块依赖分析
 */
router.get('/module/dependencies/:mid', function (req, res, next) {
    var mid = req.params['mid'], deps={};
    deps.exists = [];
    deps.lostes = [];
    deps.map = {};
    if(mid) {
        Module.findById(mid, function (err, data) {
            if (err) {
                log.log("ERROR", err);
                return res.json({
                    code: 1,
                    msg: err.message
                });
            }
            if (data && data.code) {
                var myDeps = data.code.match(moduleDependenciesReg);
                if (myDeps) {
                    var myDepsList = (myDeps[1] && myDeps[1].split(',') || []).map(function (v) {
                        return v.replace(/\s*'|\s*"/g, '');
                    });
                    if (myDepsList.length) {
                        getDependencies(myDepsList, deps, function (ret, data) {
                            if(ret) {
                                return res.json({
                                    code: 0,
                                    data: data
                                });
                            }
                            else{
                                return res.json({
                                    code: 3,
                                    msg: data.message
                                });
                            }
                        });
                    }
                    else {
                        return res.json({
                            code: 0,
                            data: deps
                        });
                    }
                }
                else{
                    return res.json({
                        code: 0,
                        data: deps
                    });
                }
            }
            else {
                return res.json({
                    code: 2,
                    msg: 'lost the module.'
                });
            }
        });
    }
});

/**
 * 校验模块标识符是否可用
 * @param id  标识符
 * @param cb  处理函数
 */
function checkModuleId(id, cb) {
    // 查库
    Module.find({id: id}, function (err, data) {
        if (err) {
            log.log('ERROR',err);
            return cb(-2); // 出错
        }
        if (data.length) {
            cb(2); // 库里有
        }
        else {
            // 库里无，扫描文件夹
            util.fileInFolder(id + '.js', moduleFolder, cb);
        }
    });
}

/**
 * 获取模块组的依赖列表
 * @param depList  模块组
 * @param deps  依赖表 ， Ref
 * @param cb    回调函数
 */
function getDependencies(depList, deps, cb) {
    depList = depList.filter(function (dep) {
        return !(deps.exists.indexOf(dep) > -1 || deps.lostes.indexOf(dep) > -1);
    });
    if (depList.length) {
        Module.find({id: new RegExp(depList.join('|'))}, function (err, data) {
            if (err) {
                log.log('ERROR', err);
                return cb(false, err);
            }
            if (data.length) {
                var curModuleDeps = [];
                data.forEach(function (m) {
                    var mDeps = m.code.match(moduleDependenciesReg);
                    if (mDeps) {
                        var mDepList = (mDeps[1] && mDeps[1].split(',') || []).map(function (v) {
                            return v.replace(/\s*'|\s*"/g, '');
                        });
                        mDepList.length && (curModuleDeps = curModuleDeps.concat(mDepList));
                    }
                    deps.exists.push(m.id);
                    deps.map[m.id] = {
                        name: m.name,
                        mid: m._id,
                        pid: m.pid
                    };
                    depList.splice(depList.indexOf(m.id), 1);
                });
                depList.length && (deps.lostes = deps.lostes.concat(depList));
                curModuleDeps = util.uniq(curModuleDeps);
                // !deps.directive && (deps.directive = lodash.clone(deps, true));
                getDependencies(curModuleDeps, deps, cb);
            }
            else {
                deps.lostes = deps.lostes.concat(depList);
                // !deps.directive && (deps.directive = lodash.clone(deps, true));
                getDependencies([], deps, cb);
            }
        });
    }
    else {
        cb(true, deps);
    }
}

module.exports = router;<commit_msg>update<commit_after>var express = require('express');
var router = express.Router();
var util = require('../util/common');
var log4js = require('log4js');
var log = log4js.getLogger('api');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var modelSchema = require('../models/model');
var config  = require('../config.json').mongodb;
var connStr = 'mongodb://'+config.server+':'+config.port+'/'+config.db;
var connOpt = {};
config.user && (connOpt.user = config.user);
config.pwd && (connOpt.pass = config.pwd);
var db = mongoose.createConnection(connStr, connOpt);
var moduleFolder = './public/modules';
var distFolder = './public/dist';

var Project = db.model('projects', modelSchema.projectSchema);
var Module = db.model('modules', modelSchema.moduleSchema);

var moduleDependenciesReg = /define\s*\([^\[]*(?:\[([^\]]+)])?\s*(?:,\s*)/m;

/**
 * 获取项目列表
 */
router.get('/project/list', function (req, res, next) {
    Project.find({}, function (err, data) {
        if(err){
            log.log('ERROR',err);
            return res.json({
                code: 1,
                msg: 'server error.'
            });
        }
        res.json({
            code: 0,
            data: data
        });
    });
});

/**
 * 根据pid获取项目信息
 */
router.get('/project/view/:pid', function (req, res, next) {
    var pid = req.params['pid'];
    if(!pid){
        return res.json({
            code: 1,
            msg: 'lost the required parameter project id.'
        });
    }
    Project.findById(pid, function (err, data) {
        if(err){
            log.log('ERROR',err);
            return res.json({
                code: 2,
                msg: err.message
            });
        }
        res.json({
            code: 0,
            data: data
        });
    });
});

/**
 * 保存项目信息
 */
router.post('/project/add', function (req, res, next) {
    var body = req.body;
    var projectName = body.projectName || '';
    var userGroup = body.userGroup || '';

    if(projectName) {
        var p = new Project({
            name: projectName,
            userGroup: userGroup.split(',')
        });
        p.save(function (err) {
            if (err) {
                log.log('ERROR',err);
                return res.json({
                    code: 1,
                    msg: JSON.stringify(err)
                });
            }
            res.json({
                code: 0,
                msg: 'success'
            });
        });
    }
    else{
        res.json({
            code: 2,
            msg: 'lost required parameter projectName.'
        });
    }
});

/**
 * 根据pid获取模块
 */
router.get('/module/list/:pid', function (req, res, next) {
    var pid = req.params['pid'];
    if(!pid){
        return res.json({
            code: 1,
            msg: 'lost the required parameter project id.'
        });
    }
    Module.find({pid: pid},{_id:1, id: 1, name: 1, pid:1}, function (err, data) {
        if(err){
            log.log('ERROR',err);
            return res.json({
                code: 2,
                msg: 'server error.'
            });
        }
        res.json({
            code: 0,
            data: data
        });
    });
});

/**
 * 根据mid获取当前模块信息
 */
router.get('/module/view/:mid', function (req, res, next) {
    var mid = req.params['mid'];

    if(mid){
        Module.findById(mid, function (err, data) {
            if(err){
                log.log('ERROR',err);
                return res.json({
                    code: 2,
                    msg: err.message
                });
            }
            res.json({
                code: 0,
                data: data
            });
        });
    }
    else{
        return res.json({
            code: 1,
            msg: 'lost the required parameter mid.'
        });
    }
});

/**
 * 校验模块标识符是否合法
 */
router.get('/module/check/:id', function (req, res, next) {
    var id = req.params['id'];

    checkModuleId(id, function (result) {
        if(-2 === result){
            return res.json({
                code: -2,
                msg: 'mongo error.'
            });
        }else if(-1 === result){
            return res.json({
                code: -1,
                msg: 'file system error.'
            });
        }
        else if(0 === result){
            return res.json({
                code: 0,
                msg: 'not file and not record.'
            });
        }
        else if(1 === result){
            return res.json({
                code: 1,
                msg: 'file exist.'
            });
        }
        else if(2 === result){
            return res.json({
                code: 2,
                msg: 'module exist.'
            });
        }
    });
});

/**
 * 保存模块信息
 */
router.post('/module/save', function (req, res, next) {
    var body = req.body,
        _id = body._id,
        id = body.id,
        pid = body.pid,
        name = body.name,
        path = body.path,
        author = body.author,
        code = body.code,
        demo = body.demo,
        lastModify = body.lastModify,
        m,
        deps={},
        uses = [];

    deps.exists = [];
    deps.lostes = [];
    deps.map = {};

    var getDependenciesPromise = new Promise(function (resolve, reject) {
        // 依赖分析
        var myDeps = code.match(moduleDependenciesReg);
        if (myDeps) {
            myDepsList = (myDeps[1] && myDeps[1].split(',') || []).map(function (v) {
                return v.replace(/\s*'|\s*"/g, '');
            });
            if (myDepsList.length) {
                directive = '|'+myDepsList.join('|')+'|';
                getDependencies(myDepsList, deps, function (ret, data) {
                    if(ret) {
                        resolve(deps);
                    }
                    else{
                        reject(data.message);
                    }
                });
            }
            else {
                directive = "";
                resolve(deps);
            }
        }
        else{
            directive = "";
            resolve(deps)
        }
    });

    getDependenciesPromise.then(function (value) {
        return new Promise(function (resolve, reject) {
            Module.find({
                $or:[{'deps.exists': id},{'deps.lostes':id}]
            }, function (err, data) {
                if(err){
                    return reject(err.message);
                }
                if(data && data.length){
                    data.forEach(function (v) {
                        uses.push({
                            _id: v._id,
                            pid: v.pid,
                            id: v.id,
                            name: v.name
                        });
                    });
                    resolve(uses);
                }
                else{
                    resolve(uses);
                }
            });
        });
    }).then(save).catch(function (value) {
        log.log('ERROR',value);
        res.json({
            code: 103,
            msg: value
        });
    });

    function save(useMyList) {
        if (_id) {
            // update
            Module.update({_id: _id}, {
                name: name,
                author: author,
                code: code,
                demo: demo,
                deps: deps,
                uses: useMyList,
                lastModify: Date.now()
            }, function (err) {
                if (err) {
                    log.log('ERROR',err);
                    return res.json({
                        code: 10,
                        msg: err.message
                    });
                }

                // 写文件
                util.saveFile(moduleFolder + '/' + id + '.js', code, function (result) {
                    if (-1 === result) {
                        return res.json({
                            code: 12,
                            msg: 'async file error.'
                        });
                    }
                    else if (1 === result) {
                        return res.json({
                            code: 0,
                            msg: 'success'
                        });
                    }
                });
            });
        }
        else {
            // add
            m = new Module({
                id: id,
                pid: pid,
                name: name,
                path: path,
                author: author,
                code: code,
                demo: demo,
                deps: deps,
                uses: useMyList,
                lastModify: lastModify
            });
            m.save(function (err, data) {
                if (err) {
                    log.log('ERROR',err);
                    return res.json({
                        code: 1,
                        msg: err.message
                    });
                }
                // 写文件
                util.saveFile(moduleFolder + '/' + id + '.js', code, function (result) {
                    if (-1 === result) {
                        // 回滚
                        Module.findOneAndRemove({_id: data._id}, function () {
                        });
                        return res.json({
                            code: 2,
                            msg: '保存模块出错.'
                        });
                    }
                    else if (1 === result) {
                        return res.json({
                            code: 0,
                            msg: 'success'
                        });
                    }
                });
            });
        }

    }
});

/**
 * 加载已存在的模块文件
 */
router.post('/module/load', function (req, res, next) {
    var filename = req.body.filename;
    util.readFile(moduleFolder+'/'+filename+'.js', function (result, data) {
        if(result) {
            return res.json({
                code: 0,
                data: data
            });
        }else{
            return res.json({
                code: 1,
                msg: data.message
            });
        }

    });
});

/**
 * 模块压缩
 */
router.post('/compress', function (req, res, next) {
    var modules = req.body.modules.split(',');
    var combName = req.body.combName || '';
    var ms = [];
    if(modules.length) {
        modules.forEach(function (item) {
            if (item && '' != (item = item.trim())) {
                ms.push(moduleFolder+'/'+item+'.js');
            }
        });
        if(ms.length === 1) combName = ms[0].replace(moduleFolder, distFolder);

        util.compress(ms, combName, function (result) {
            if(-1 === result){
                log.log('INFO', 'compress module failure when save the file.');
                return res.json({
                    code: 3,
                    msg: 'save file failure.'
                });
            }
            else if( 1 === result){
                return res.json({
                    code: 0,
                    msg: 'success'
                });
            }
            else{
                return res.json({
                    code: 10,
                    msg: 'server error.'
                });
            }
        });
    }
    else{
        return res.json({
            code: 2,
            msg: 'lost required parameter modules.'
        });
    }
});

/**
 * 搜索接口
 */
router.post('/search', function (req, res, next) {
    var key = req.body.keys;
    if(key){
        Module.find({name: new RegExp('.*?'+key+'.*?')}, function (err, data) {
            if(err){
                log.log('ERROR',err);
                return res.json({
                    code: 1,
                    msg: err.message
                });
            }
            return res.json({
                code: 0,
                data: data
            });
        });
    }
});

/**
 * 模块依赖分析
 */
router.get('/module/dependencies/:mid', function (req, res, next) {
    var mid = req.params['mid'], deps={};
    deps.exists = [];
    deps.lostes = [];
    deps.map = {};
    if(mid) {
        Module.findById(mid, function (err, data) {
            if (err) {
                log.log("ERROR", err);
                return res.json({
                    code: 1,
                    msg: err.message
                });
            }
            if (data && data.code) {
                var myDeps = data.code.match(moduleDependenciesReg);
                if (myDeps) {
                    var myDepsList = (myDeps[1] && myDeps[1].split(',') || []).map(function (v) {
                        return v.replace(/\s*'|\s*"/g, '');
                    });
                    if (myDepsList.length) {
                        getDependencies(myDepsList, deps, function (ret, data) {
                            if(ret) {
                                return res.json({
                                    code: 0,
                                    data: data
                                });
                            }
                            else{
                                return res.json({
                                    code: 3,
                                    msg: data.message
                                });
                            }
                        });
                    }
                    else {
                        return res.json({
                            code: 0,
                            data: deps
                        });
                    }
                }
                else{
                    return res.json({
                        code: 0,
                        data: deps
                    });
                }
            }
            else {
                return res.json({
                    code: 2,
                    msg: 'lost the module.'
                });
            }
        });
    }
});

/**
 * 校验模块标识符是否可用
 * @param id  标识符
 * @param cb  处理函数
 */
function checkModuleId(id, cb) {
    // 查库
    Module.find({id: id}, function (err, data) {
        if (err) {
            log.log('ERROR',err);
            return cb(-2); // 出错
        }
        if (data.length) {
            cb(2); // 库里有
        }
        else {
            // 库里无，扫描文件夹
            util.fileInFolder(id + '.js', moduleFolder, cb);
        }
    });
}

/**
 * 获取模块组的依赖列表
 * @param depList  模块组
 * @param deps  依赖表 ， Ref
 * @param cb    回调函数
 */
function getDependencies(depList, deps, cb) {
    depList = depList.filter(function (dep) {
        return !(deps.exists.indexOf(dep) > -1 || deps.lostes.indexOf(dep) > -1);
    });
    if (depList.length) {
        Module.find({id: new RegExp(depList.join('|'))}, function (err, data) {
            if (err) {
                log.log('ERROR', err);
                return cb(false, err);
            }
            if (data.length) {
                var curModuleDeps = [];
                data.forEach(function (m) {
                    var mDeps = m.code.match(moduleDependenciesReg);
                    if (mDeps) {
                        var mDepList = (mDeps[1] && mDeps[1].split(',') || []).map(function (v) {
                            return v.replace(/\s*'|\s*"/g, '');
                        });
                        mDepList.length && (curModuleDeps = curModuleDeps.concat(mDepList));
                    }
                    deps.exists.push(m.id);
                    deps.map[m.id] = {
                        name: m.name,
                        mid: m._id,
                        pid: m.pid
                    };
                    depList.splice(depList.indexOf(m.id), 1);
                });
                depList.length && (deps.lostes = deps.lostes.concat(depList));
                curModuleDeps = util.uniq(curModuleDeps);
                // !deps.directive && (deps.directive = lodash.clone(deps, true));
                getDependencies(curModuleDeps, deps, cb);
            }
            else {
                deps.lostes = deps.lostes.concat(depList);
                // !deps.directive && (deps.directive = lodash.clone(deps, true));
                getDependencies([], deps, cb);
            }
        });
    }
    else {
        cb(true, deps);
    }
}

module.exports = router;<|endoftext|>


<commit_before>var express = require('express');
var async = require('async');
var api = express.Router();
var constants = require('../constants');
var buildMatch = require('../buildMatch');
var buildPlayer = require('../buildPlayer');
var config = require('../config');
var request = require('request');
var rc_secret = config.RECAPTCHA_SECRET_KEY;
var multer = require('multer')(
{
    inMemory: true,
    fileSize: 100 * 1024 * 1024, // no larger than 100mb
});
var utility = require('../utility');
var queue = require('../queue');
var rQueue = queue.getQueue('request');
const crypto = require('crypto');
module.exports = function(db, redis, cassandra)
{
    api.get('/items', function(req, res)
    {
        res.json(constants.items[req.query.name]);
    });
    api.get('/abilities', function(req, res)
    {
        res.json(constants.abilities[req.query.name]);
    });
    api.get('/metadata', function(req, res, cb)
    {
        async.parallel(
        {
            banner: function(cb)
            {
                redis.get("banner", cb);
            },
            cheese: function(cb)
            {
                redis.get("cheese_goal", function(err, result)
                {
                    return cb(err,
                    {
                        cheese: result,
                        goal: config.GOAL
                    });
                });
            },
            user: function(cb)
            {
                cb(null, req.user);
            },
            navbar_pages: function(cb)
            {
                cb(null, constants.navbar_pages);
            },
            player_pages: function(cb)
            {
                cb(null, constants.player_pages);
            },
            match_pages: function(cb)
            {
                cb(null, constants.match_pages);
            },
            player_fields: function(cb){
                cb(null, constants.player_fields);
            },
        }, function(err, result)
        {
            if (err)
            {
                return cb(err);
            }
            res.json(result);
        });
    });
    api.get('/matches/:match_id/:info?', function(req, res, cb)
    {
        buildMatch(
        {
            db: db,
            redis: redis,
            cassandra: cassandra,
            match_id: req.params.match_id
        }, function(err, match)
        {
            if (err)
            {
                return cb(err);
            }
            res.json(match);
        });
    });
    api.get('/players/:account_id/:info?/:subkey?', function(req, res, cb)
    {
        buildPlayer(
        {
            db: db,
            redis: redis,
            cassandra: cassandra,
            account_id: req.params.account_id,
            info: req.params.info,
            subkey: req.params.subkey,
            query: req.query
        }, function(err, player)
        {
            if (err)
            {
                return cb(err);
            }
            res.json(player);
        });
    });
    api.get('/distributions');
    api.get('/picks/:n');
    api.get('/rankings/:hero_id');
    api.get('/faq');
    api.get('/status');
    //TODO will need to figure out how to do slugs if @albertcui insists on routing with them
    api.get('/blog/:n');
    //TODO @albertcui owns mmstats
    api.get('/mmstats');
    api.get('/banner');
    api.get('/cheese', function(req, res)
    {
        //TODO implement this
        res.json(
        {
            cheese: 1,
            goal: 2
        });
    });
    api.get('/search', function(req, res, cb)
    {
        if (!req.query.q)
        {
            return cb(400);
        }

        queries.searchPlayer(db, req.query.q, function(err, result)
        {
            if (err)
            {
               return cb(err);
            }

            res.json(result);
        });
    });
    api.get('/health/:metric?', function(req, res, cb)
    {
        redis.hgetall('health', function(err, result)
        {
            if (err)
            {
                return cb(err);
            }
            for (var key in result)
            {
                result[key] = JSON.parse(result[key]);
            }
            if (!req.params.metric)
            {
                res.json(result);
            }
            else
            {
                var single = result[req.params.metric];
                var healthy = single.metric < single.threshold;
                res.status(healthy ? 200 : 500).json(single);
            }
        });
    });
    api.post('/request_job', multer.single("replay_blob"), function(req, res, next)
    {
        request.post("https://www.google.com/recaptcha/api/siteverify",
        {
            form:
            {
                secret: rc_secret,
                response: req.body.response
            }
        }, function(err, resp, body)
        {
            if (err)
            {
                return next(err);
            }
            try
            {
                body = JSON.parse(body);
            }
            catch (err)
            {
                return res.render(
                {
                    error: err
                });
            }
            var match_id = Number(req.body.match_id);
            var match;
            if (!body.success && config.ENABLE_RECAPTCHA && !req.file)
            {
                console.log('failed recaptcha');
                return res.json(
                {
                    error: "Recaptcha Failed!"
                });
            }
            else if (req.file)
            {
                console.log(req.file);
                //var key = req.file.originalname + Date.now();
                //var key = Math.random().toString(16).slice(2);
                const hash = crypto.createHash('md5');
                hash.update(req.file.buffer);
                var key = hash.digest('hex');
                redis.setex(new Buffer('upload_blob:' + key), 60 * 60, req.file.buffer);
                match = {
                    replay_blob_key: key
                };
            }
            else if (match_id && !Number.isNaN(match_id))
            {
                match = {
                    match_id: match_id
                };
            }
            if (match)
            {
                console.log(match);
                queue.addToQueue(rQueue, match,
                {
                    attempts: 1
                }, function(err, job)
                {
                    res.json(
                    {
                        error: err,
                        job:
                        {
                            jobId: job.jobId,
                            data: job.data
                        }
                    });
                });
            }
            else
            {
                res.json(
                {
                    error: "Invalid input."
                });
            }
        });
    });
    api.get('/request_job', function(req, res, cb)
    {
        rQueue.getJob(req.query.id).then(function(job)
        {
            if (job)
            {
                job.getState().then(function(state)
                {
                    return res.json(
                    {
                        jobId: job.jobId,
                        data: job.data,
                        state: state,
                        progress: job.progress()
                    });
                }).catch(cb);
            }
            else
            {
                res.json(
                {
                    state: "failed"
                });
            }
        }).catch(cb);
    });
    return api;
};
<commit_msg>fix incompetence<commit_after>var express = require('express');
var async = require('async');
var api = express.Router();
var constants = require('../constants');
var buildMatch = require('../buildMatch');
var buildPlayer = require('../buildPlayer');
var config = require('../config');
var request = require('request');
var rc_secret = config.RECAPTCHA_SECRET_KEY;
var multer = require('multer')(
{
    inMemory: true,
    fileSize: 100 * 1024 * 1024, // no larger than 100mb
});
var utility = require('../utility');
var queue = require('../queue');
var rQueue = queue.getQueue('request');
var queries = require('../queries');
const crypto = require('crypto');
module.exports = function(db, redis, cassandra)
{
    api.get('/items', function(req, res)
    {
        res.json(constants.items[req.query.name]);
    });
    api.get('/abilities', function(req, res)
    {
        res.json(constants.abilities[req.query.name]);
    });
    api.get('/metadata', function(req, res, cb)
    {
        async.parallel(
        {
            banner: function(cb)
            {
                redis.get("banner", cb);
            },
            cheese: function(cb)
            {
                redis.get("cheese_goal", function(err, result)
                {
                    return cb(err,
                    {
                        cheese: result,
                        goal: config.GOAL
                    });
                });
            },
            user: function(cb)
            {
                cb(null, req.user);
            },
            navbar_pages: function(cb)
            {
                cb(null, constants.navbar_pages);
            },
            player_pages: function(cb)
            {
                cb(null, constants.player_pages);
            },
            match_pages: function(cb)
            {
                cb(null, constants.match_pages);
            },
            player_fields: function(cb){
                cb(null, constants.player_fields);
            },
        }, function(err, result)
        {
            if (err)
            {
                return cb(err);
            }
            res.json(result);
        });
    });
    api.get('/matches/:match_id/:info?', function(req, res, cb)
    {
        buildMatch(
        {
            db: db,
            redis: redis,
            cassandra: cassandra,
            match_id: req.params.match_id
        }, function(err, match)
        {
            if (err)
            {
                return cb(err);
            }
            res.json(match);
        });
    });
    api.get('/players/:account_id/:info?/:subkey?', function(req, res, cb)
    {
        buildPlayer(
        {
            db: db,
            redis: redis,
            cassandra: cassandra,
            account_id: req.params.account_id,
            info: req.params.info,
            subkey: req.params.subkey,
            query: req.query
        }, function(err, player)
        {
            if (err)
            {
                return cb(err);
            }
            res.json(player);
        });
    });
    api.get('/distributions');
    api.get('/picks/:n');
    api.get('/rankings/:hero_id');
    api.get('/faq');
    api.get('/status');
    //TODO will need to figure out how to do slugs if @albertcui insists on routing with them
    api.get('/blog/:n');
    //TODO @albertcui owns mmstats
    api.get('/mmstats');
    api.get('/banner');
    api.get('/cheese', function(req, res)
    {
        //TODO implement this
        res.json(
        {
            cheese: 1,
            goal: 2
        });
    });
    api.get('/search', function(req, res, cb)
    {
        if (!req.query.q)
        {
            return cb(400);
        }

        queries.searchPlayer(db, req.query.q, function(err, result)
        {
            if (err)
            {
               return cb(err);
            }

            res.json(result);
        });
    });
    api.get('/health/:metric?', function(req, res, cb)
    {
        redis.hgetall('health', function(err, result)
        {
            if (err)
            {
                return cb(err);
            }
            for (var key in result)
            {
                result[key] = JSON.parse(result[key]);
            }
            if (!req.params.metric)
            {
                res.json(result);
            }
            else
            {
                var single = result[req.params.metric];
                var healthy = single.metric < single.threshold;
                res.status(healthy ? 200 : 500).json(single);
            }
        });
    });
    api.post('/request_job', multer.single("replay_blob"), function(req, res, next)
    {
        request.post("https://www.google.com/recaptcha/api/siteverify",
        {
            form:
            {
                secret: rc_secret,
                response: req.body.response
            }
        }, function(err, resp, body)
        {
            if (err)
            {
                return next(err);
            }
            try
            {
                body = JSON.parse(body);
            }
            catch (err)
            {
                return res.render(
                {
                    error: err
                });
            }
            var match_id = Number(req.body.match_id);
            var match;
            if (!body.success && config.ENABLE_RECAPTCHA && !req.file)
            {
                console.log('failed recaptcha');
                return res.json(
                {
                    error: "Recaptcha Failed!"
                });
            }
            else if (req.file)
            {
                console.log(req.file);
                //var key = req.file.originalname + Date.now();
                //var key = Math.random().toString(16).slice(2);
                const hash = crypto.createHash('md5');
                hash.update(req.file.buffer);
                var key = hash.digest('hex');
                redis.setex(new Buffer('upload_blob:' + key), 60 * 60, req.file.buffer);
                match = {
                    replay_blob_key: key
                };
            }
            else if (match_id && !Number.isNaN(match_id))
            {
                match = {
                    match_id: match_id
                };
            }
            if (match)
            {
                console.log(match);
                queue.addToQueue(rQueue, match,
                {
                    attempts: 1
                }, function(err, job)
                {
                    res.json(
                    {
                        error: err,
                        job:
                        {
                            jobId: job.jobId,
                            data: job.data
                        }
                    });
                });
            }
            else
            {
                res.json(
                {
                    error: "Invalid input."
                });
            }
        });
    });
    api.get('/request_job', function(req, res, cb)
    {
        rQueue.getJob(req.query.id).then(function(job)
        {
            if (job)
            {
                job.getState().then(function(state)
                {
                    return res.json(
                    {
                        jobId: job.jobId,
                        data: job.data,
                        state: state,
                        progress: job.progress()
                    });
                }).catch(cb);
            }
            else
            {
                res.json(
                {
                    state: "failed"
                });
            }
        }).catch(cb);
    });
    return api;
};
<|endoftext|>


<commit_before>/* vim: set ts=8 sts=2 et sw=2 tw=80 cc=80: */

/*
 * Syntax highlighting addition/removal handlers (content scripts).
 *
 * First we need to decide whether we do or undo highlight.
 *
 * To do it, we have to add a CSS stylesheet and to enclose

 blocks
 * content to highlight with  tags so that it looks like
 *
 int a = 3 + b;
 (see highlightjs doc).
 * We perform a backup of original document by putting it in a hidden div.
 *
 * Undoing highlight consists in getting saved document back from the div.
 */

/*
 * Execute this at startup
 */
var enlight = function () {
  /*
   * If there is no

 HTML block, there's nothing to work on: get
   * out of here.
   */
  if (!document.body ||
       document.body.getElementsByTagName("pre").item(0) === null) {
    self.port.emit("toggle_off", 1);
    return;
  }

  var initDocumentDiv = document.getElementById("enlightInitDocument");
  /*
   * If div is found, we already got syntax highlighting: let's undo it.
   * Else, launch highlighting.
   */
  initDocumentDiv === null ? dohl() : undohl(initDocumentDiv.firstChild);
} ();

function dohl() {
  var preList = document.getElementsByTagName("pre");
  /*
   * If self.options is undefined we shouldn't be there. Page has probably been
   * changed since a former highlight: get out as well.
   */
  if (self.options === undefined) {
    return;
  }

  /*
   * Add link to CSS stylesheet
   */
  var css = document.createElement("link");
  var style = self.options.stylesheet;
  css.setAttribute("href",  style != undefined ? style : "");
  css.setAttribute("rel",  "stylesheet");
  css.setAttribute("type", "text/css");
  css.setAttribute("id",   "enlightStylesheet");
  document.head.appendChild(css);

  /*
   * Back up initial document
   */
  var clone = document.documentElement.cloneNode(true);
  var idoc  = document.createElement("div");
  idoc.style.display = "none";
  idoc.setAttribute("id", "enlightInitDocument");
  idoc.appendChild(clone);

  /*
   * Deal with language
   */
  var setLanguage = (self.options.language != "" &&
                     self.options.language != "auto") ?
    function(element){element.setAttribute("class", self.options.language);} :
    function(element){};

  /*
   * Enclose

 blocks content in  blocks
   */
  for (var pre of preList) {
    var firstChild = pre.firstChild;
    var code = document.createElement("code");
    setLanguage(code);
    if (self.options.bgColor) {
      code.style = "padding: 0;";
    }
    code.appendChild(firstChild);
    pre.appendChild(code);
  }

  hljs.initHighlighting(); // from highlight.min.js or highlight.pack.js

  /*
   * Add line numbers if option is set
   */
  var lineNodes = self.options.lineNumbers;
  if (lineNodes) {
  for (pre of preList) {
      /*
       * Enclose each line of highlighted content into a "line" span.
       * Text has already been highlighted at this point (it's a mix of text
       * and of spans for coloring), so I can't see any easy way to do this
       * without assigning to innerHTML.
       */
      var lines = pre.firstChild.innerHTML
        .replace(/^.*?(\n|$)(?=.|\n)/gm, '$&');
      pre.firstChild.innerHTML = lines;

      /*
       * Numbering is performed with CSS. We add it to head of document. From
       * https://github.com/isagalaev/highlight.js/compare/master...line-numbers
       */
      var styleContent = " \
        pre { \
          counter-reset: lines; \
        } \
        pre .line { \
          counter-increment: lines; \
        } \
        pre .line::before { \
          -moz-user-select: none; \
          \
          content: counter(lines); text-align: right; \
          display: inline-block; min-width: 2.5em; \
          padding-right: 0.5em; margin-right: 0.5em; \
          font-weight: bold; \
          border-right: solid 1px; \
        }";
      var style = document.createElement("style");
      style.setAttribute("type", "text/css");
      var styleTextNode = document.createTextNode(styleContent);
      style.appendChild(styleTextNode);
      document.head.appendChild(style);
    }
  }

  /*
   * There's a white border remaining because of document.background.
   * If option is set, remove it.
   */
  if (self.options.bgColor) {
    setTimeout(function () { // Wait for CSS to be computed
      let codeBG = getComputedStyle(code)["background-color"];
      if (codeBG && codeBG!="white" && codeBG!="#FFFFFF" && codeBG!="#ffffff") {
          document.body.style.backgroundColor = codeBG;
      }
    }, 50);
  }

  /*
   * If we launched language auto-detection, tell main script about detected
   * language
   */
  if (self.options.language == "" || self.options.language == "auto") {
    let languageClass = document.querySelectorAll('pre code')[0].className;
    let languageId = languageClass.slice("hljs ".length);
    self.port.emit('detected_language', languageId);
  }

  /*
   * Save previous document in a hidden div to restore it on undohl()
   */
  document.body.appendChild(idoc);
}

function undohl(idoc) {
  document.replaceChild(idoc, document.documentElement);
  /*
   * Another solution:
   * window.location.reload(false);
   */
}
<commit_msg>enlightscript.js: somewhat refactor some chuncks<commit_after>/* vim: set ts=8 sts=2 et sw=2 tw=80 cc=80: */

/*
 * Syntax highlighting addition/removal handlers (content scripts).
 *
 * First we need to decide whether we do or undo highlight.
 *
 * To do it, we have to add a CSS stylesheet and to enclose

 blocks
 * content to highlight with  tags so that it looks like
 *
 int a = 3 + b;
 (see highlightjs doc).
 * We perform a backup of original document by putting it in a hidden div.
 *
 * Undoing highlight consists in getting saved document back from the div.
 */

/*****************************************************************************/

/*
 * Execute this at startup
 */
var enlight = function () {
  /*
   * If there is no

 HTML block, there's nothing to work on: get
   * out of here.
   */
  if (!document.body ||
       document.body.getElementsByTagName("pre").item(0) === null) {
    self.port.emit("toggle_off", 1);
    return;
  }

  var initDocumentDiv = document.getElementById("enlightInitDocument");
  /*
   * If div is found, we already got syntax highlighting: let's undo it.
   * Else, launch highlighting.
   */
  initDocumentDiv === null ? dohl() : undohl(initDocumentDiv.firstChild);
} ();

/*****************************************************************************/

function dohl() {
  var preList = document.getElementsByTagName("pre");
  /*
   * If self.options is undefined we shouldn't be there. Page has probably been
   * changed since a former highlight: get out as well.
   */
  if (!self.options) {
    return;
  }

  /*
   * Back up initial document
   */
  var clone = document.documentElement.cloneNode(true);
  var idoc  = document.createElement("div");
  idoc.style.display = "none";
  idoc.setAttribute("id", "enlightInitDocument");
  idoc.appendChild(clone);

  /*
   * Add link to CSS stylesheet
   */
  var css = document.createElement("link");
  var style = self.options.stylesheet;
  css.setAttribute("href",  style != undefined ? style : "");
  css.setAttribute("rel",  "stylesheet");
  css.setAttribute("type", "text/css");
  css.setAttribute("id",   "enlightStylesheet");
  document.head.appendChild(css);

  /*
   * If needed, add CSS rules for line numbering
   */
  addLineNumberStyle();

  /*
   * Deal with language
   */
  var setLanguage = (self.options.language != "" &&
                     self.options.language != "auto") ?
    function(element){element.setAttribute("class", self.options.language);} :
    function(element){};

  /*
   * Enclose

 blocks content in  blocks
   */
  for (var pre of preList) {
    var firstChild = pre.firstChild;
    var code = document.createElement("code");
    setLanguage(code);
    if (self.options.bgColor) {
      code.style = "padding: 0;";
    }
    code.appendChild(firstChild);
    pre.appendChild(code);
  }

  /*
   * Call highlighting function: hljs is defined in highlight.js library.
   */
  hljs.initHighlighting();

  /*
   * Add line numbers if needed.
   */
  var lineNodes = self.options.lineNumbers;
  if (lineNodes) {
    for (var pre of preList) {
      var code = pre.firstChild;
      addLineNumbers(code);
    }
  }

  /*
   * There's a remaining white border because of body background color.
   * If option is set, remove it.
   */
  if (self.options.bgColor) {
    setTimeout(function () { // Wait for CSS to be computed
      let codeBG = getComputedStyle(preList[0].firstChild)["background-color"];
      if (codeBG &&
          codeBG!="white" &&
          codeBG!="#FFFFFF" &&
          codeBG!="#ffffff") {
        document.body.style.backgroundColor = codeBG;
      }
    }, 50);
  }

  /*
   * If we launched language auto-detection, tell main script about detected
   * language
   */
  if (self.options.language == "" || self.options.language == "auto") {
    let languageClass = document.querySelectorAll('pre code')[0].className;
    let languageId = languageClass.slice("hljs ".length);
    self.port.emit('detected_language', languageId);
  }

  /*
   * Save previous document in a hidden div to restore it on undohl()
   */
  document.body.appendChild(idoc);
}

/*****************************************************************************/

function undohl(idoc) {
  document.replaceChild(idoc, document.documentElement);
  /*
   * Another solution:
   * window.location.reload(false);
   */
}

/*****************************************************************************/

/*
 * Add line numbers to argument code block if option is set
 */
function addLineNumbers(aCode) {
  /*
   * Enclose each line of highlighted content into a "line" span.
   * Text has already been highlighted at this point (it's a mix of text
   * and of spans for coloring), so I can't see any easy way to do this
   * without assigning to innerHTML.
   */
  var lines = aCode.innerHTML
    .replace(/^.*?(\n|$)(?=.|\n)/gm,
             '$&');
  aCode.innerHTML = lines;
}

/*****************************************************************************/

/*
 * Numbering is performed with CSS. We add it to head of document. From
 * https://github.com/isagalaev/highlight.js/compare/master...line-numbers
 */
function addLineNumberStyle() {
  var lineNodes = self.options.lineNumbers;
  if (!lineNodes) {
    return;
  }
  var styleContent = " \
    pre { \
      counter-reset: lines; \
    } \
    pre .line { \
      counter-increment: lines; \
    } \
    pre .line::before { \
      -moz-user-select: none; \
      \
      content: counter(lines); text-align: right; \
      display: inline-block; min-width: 2.5em; \
      padding-right: 0.5em; margin-right: 0.5em; \
      font-weight: bold; \
      border-right: solid 1px; \
    }";
  var style = document.createElement("style");
  style.setAttribute("type", "text/css");
  var styleTextNode = document.createTextNode(styleContent);
  style.appendChild(styleTextNode);
  document.head.appendChild(style);
}
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var path = require('path');
var shell = require('shelljs');
var config = require('../config');
var build = require('../service/build');
var origin_sync = require('../service/origin_sync');
var qiniu_sync = require('../service/qiniu-sync');
var version = require('../service/version');

module.exports = router;

router.get('/alpha/:name', function(req, res) {
  var logger = require('../logger')('log/down_gz.log', 'downgz');
  var owner = req.query.owner;
  var name = req.params.name;
  var repos_work_dir = path.resolve(config.alpha_work_path, owner, name);
  var deployed_dir = path.resolve(config.static_server.alpha, owner, name);

  if (!shell.test('-e', repos_work_dir)) {
    res.status(200).json({
      data: owner + '/' + name + '项目不存在或从未发布'
    });
  }

  var pkg = require(path.resolve(repos_work_dir, './package.json'));
  var filename = pkg.version + '.tar.gz';
  var fileurl = path.resolve(deployed_dir, filename);
  if (!shell.test('-f', fileurl)) {
    res.status(200).json({
      data: owner + '/' + name + '项目从未发布成功'
    });
  }

  res.attachment(fileurl);
  res.end('Download OK', 'UTF-8');

  // res.download(fileurl, 'name.tar.gz', function(err) {
  //   if (err) {
  //     logger.error(fileurl + '下载失败');
  //     logger.info('错误信息如下： \n' + err.message);
  //     res.status(err.status).end();

  //     return;
  //   }

  //   logger.info(fileurl + '下载成功');
  // });
});

// TODO
// 1. 工作区按 repos owner 分组
// 2. 静态服务器按 respos owner 分组
router.post('/alpha', function (req, res) {
  var repos = req.body.repository;
  var log_dir = 'log/' + repos.owner.username;
  var log_file = log_dir + '/' + repos.name + '.log';
  shell.exec('mkdir -p ' + log_dir);
  shell.exec('touch ' + log_file);
  shell.exec('> ' + log_file);
  var logger = require('../logger')(log_file, 'publish');

  logger.info('准备发布 alpha 环境...');
  logger.info('正在预处理静态资源...');
  var build_rs = build(
    req.body,
    config.alpha_work_path
  );

  if (!build_rs) {
    logger.fatal('预处理静态资源失败');
    return res.status(200).json({
      code: 500,
      data: '预处理静态资源过程中发生错误'
    });
  }

  logger.info('预处理静态资源完成');

  var pkg = require(path.resolve(build_rs.out_dir, './package.json'));
  var src = path.resolve(build_rs.out_dir, pkg.dest, './*');
  var dest_dir = path.resolve(config.static_server.alpha, repos.owner.username, pkg.name, pkg.version);

  logger.info('正在发布静态资源到服务器...');
  var origin_sync_rs = origin_sync(src, dest_dir);
  if (origin_sync_rs.code !== 0) {
    logger.fatal('静态资源发布到服务器失败');
    logger.info('错误信息:\n' + origin_sync_rs.output);

    res.status(200).json({
      code: 500,
      data: '静态资源发布到服务器失败'
    });

    return;
  }

  logger.info('正在发布静态资源到七牛服务器...');

  try {
    var qiniu_sync_rs = qiniu_sync();

    if (qiniu_sync_rs.code !== 0) {
      logger.error('上传静态资源到七牛服务器出错...');
      logger.error('错误信息:\n' + qiniu_sync_rs.output);
    }
  } catch(e) {
    // 暂不做处理，因为七牛服务器不接受 html 文件，所以导致错误
    logger.info(e);
  }

  logger.info('静态资源发布成功');

  logger.info('正在生成静态资源压缩包...');
  // TODO
  // 优化：工作区压缩，然后上传到静态服务器

  // 进入静态服务器目录
  console.log(path.dirname(dest_dir));
  shell.cd(path.dirname(dest_dir));

  var tar_gz = shell.exec('sudo tar -czvf ' + pkg.version + '.tar.gz ' + dest_dir);
  var tar_gz_tip_prefix = '生成静态资源压缩包' + path.resolve(dest_dir, pkg.version);

  if (tar_gz.code !== 0) {
    var err_tip = tar_gz_tip_prefix + '失败';

    logger.fatal(err_tip);
    logger.info('错误信息:\n' + tar_gz.output);

    res.status(200).json({
      code: 500,
      data: err_tip
    });

    return;
  }
  logger.info(tar_gz_tip_prefix + '成功');

  logger.info('正在更新版本数据库...');
  version({
    owner: build_rs.repository.owner.username,
    name: build_rs.repository.name,
    version: pkg.version,
    url: build_rs.repository.url
  }, function() {
    logger.info('版本更新成功');
    // logger.info('正在清理发布目录...');
    // shell.exec(['rm', '-rf', build_rs.out_dir].join(' '));
    // logger.info('清理发布目录完成');

    // logger.warn('other info:');
    // logger.info(log);

    res.status(200).json({
      code: 200,
      data: '项目发布成功'
    });
  });
});
<commit_msg>download<commit_after>var express = require('express');
var router = express.Router();
var path = require('path');
var shell = require('shelljs');
var config = require('../config');
var build = require('../service/build');
var origin_sync = require('../service/origin_sync');
var qiniu_sync = require('../service/qiniu-sync');
var version = require('../service/version');

module.exports = router;

router.get('/alpha/:name', function(req, res) {
  var logger = require('../logger')('log/down_gz.log', 'downgz');
  var owner = req.query.owner;
  var name = req.params.name;
  var repos_work_dir = path.resolve(config.alpha_work_path, owner, name);
  var deployed_dir = path.resolve(config.static_server.alpha, owner, name);

  if (!shell.test('-e', repos_work_dir)) {
    res.status(200).json({
      data: owner + '/' + name + '项目不存在或从未发布'
    });
  }

  var pkg = require(path.resolve(repos_work_dir, './package.json'));
  var filename = pkg.version + '.tar.gz';
  var fileurl = path.resolve(deployed_dir, filename);
  if (!shell.test('-f', fileurl)) {
    res.status(200).json({
      data: owner + '/' + name + '项目从未发布成功'
    });
  }

  res.download(fileurl, name + '.tar.gz', function(err) {
    if (err) {
      logger.error(fileurl + '下载失败');
      logger.info('错误信息如下： \n' + err.message);
      res.status(err.status).end();

      return;
    }

    logger.info(fileurl + '下载成功');
  });
});

// TODO
// 1. 工作区按 repos owner 分组
// 2. 静态服务器按 respos owner 分组
router.post('/alpha', function (req, res) {
  var repos = req.body.repository;
  var log_dir = 'log/' + repos.owner.username;
  var log_file = log_dir + '/' + repos.name + '.log';
  shell.exec('mkdir -p ' + log_dir);
  shell.exec('touch ' + log_file);
  shell.exec('> ' + log_file);
  var logger = require('../logger')(log_file, 'publish');

  logger.info('准备发布 alpha 环境...');
  logger.info('正在预处理静态资源...');
  var build_rs = build(
    req.body,
    config.alpha_work_path
  );

  if (!build_rs) {
    logger.fatal('预处理静态资源失败');
    return res.status(200).json({
      code: 500,
      data: '预处理静态资源过程中发生错误'
    });
  }

  logger.info('预处理静态资源完成');

  var pkg = require(path.resolve(build_rs.out_dir, './package.json'));
  var src = path.resolve(build_rs.out_dir, pkg.dest, './*');
  var dest_dir = path.resolve(config.static_server.alpha, repos.owner.username, pkg.name, pkg.version);

  logger.info('正在发布静态资源到服务器...');
  var origin_sync_rs = origin_sync(src, dest_dir);
  if (origin_sync_rs.code !== 0) {
    logger.fatal('静态资源发布到服务器失败');
    logger.info('错误信息:\n' + origin_sync_rs.output);

    res.status(200).json({
      code: 500,
      data: '静态资源发布到服务器失败'
    });

    return;
  }

  logger.info('正在发布静态资源到七牛服务器...');

  try {
    var qiniu_sync_rs = qiniu_sync();

    if (qiniu_sync_rs.code !== 0) {
      logger.error('上传静态资源到七牛服务器出错...');
      logger.error('错误信息:\n' + qiniu_sync_rs.output);
    }
  } catch(e) {
    // 暂不做处理，因为七牛服务器不接受 html 文件，所以导致错误
    logger.info(e);
  }

  logger.info('静态资源发布成功');

  logger.info('正在生成静态资源压缩包...');
  // TODO
  // 优化：工作区压缩，然后上传到静态服务器

  // 进入静态服务器目录
  console.log(path.dirname(dest_dir));
  shell.cd(path.dirname(dest_dir));

  var tar_gz = shell.exec('sudo tar -czvf ' + pkg.version + '.tar.gz ' + dest_dir);
  var tar_gz_tip_prefix = '生成静态资源压缩包' + path.resolve(dest_dir, pkg.version);

  if (tar_gz.code !== 0) {
    var err_tip = tar_gz_tip_prefix + '失败';

    logger.fatal(err_tip);
    logger.info('错误信息:\n' + tar_gz.output);

    res.status(200).json({
      code: 500,
      data: err_tip
    });

    return;
  }
  logger.info(tar_gz_tip_prefix + '成功');

  logger.info('正在更新版本数据库...');
  version({
    owner: build_rs.repository.owner.username,
    name: build_rs.repository.name,
    version: pkg.version,
    url: build_rs.repository.url
  }, function() {
    logger.info('版本更新成功');
    // logger.info('正在清理发布目录...');
    // shell.exec(['rm', '-rf', build_rs.out_dir].join(' '));
    // logger.info('清理发布目录完成');

    // logger.warn('other info:');
    // logger.info(log);

    res.status(200).json({
      code: 200,
      data: '项目发布成功'
    });
  });
});
<|endoftext|>


<commit_before>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe(FILL_ME_IN);
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe(FILL_ME_IN);
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe(FILL_ME_IN);
    expect(aPerson.getLastName()).toBe(FILL_ME_IN);
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

});
<commit_msg>add completed mutability code<commit_after>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe("John Smith");

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe("Smith, John");
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe("John");
    expect(aPerson.getLastName()).toBe("Smith");
    expect(aPerson.getFullName()).toBe("John Smith");

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe("Andrews, Penny");
  });

});
<|endoftext|>


<commit_before>'use strict';

var Job = require('../models/jobs_model');
var User = require('../models/user_model');

module.exports = function(app, jwtauth) {
  app.post('/jobs', jwtauth, function(req, res) {
    var newJob = new Job({
      jobDate: req.body.jobDate,
      parent: req.user._id,
      recurring: req.body.recurring,
      parentName: req.user.name,
      parentNumber: req.user.phone
    });

    newJob.save(function(err, job) {
      if (err) return res.send(err);
      User.findById(req.user._id, function(err, user) {
        if (err) return console.log('error finding user by ID for New Job Save: ' + err);
        if (user === null) return console.log('user is null during New Job save.');
        user.jobs.push(job._id);
        user.save(function(err) {
          if (err) return console.log('error saving job to user array');
          console.log('successfully saved job to user array.');
        });
      });
      res.json(job);
    });
  });
};
<commit_msg>get user jobs<commit_after>'use strict';

var Job = require('../models/jobs_model');
var User = require('../models/user_model');

module.exports = function(app, jwtauth) {
  app.post('/jobs', jwtauth, function(req, res) {
    var newJob = new Job({
      jobDate: req.body.jobDate,
      parent: req.user._id,
      recurring: req.body.recurring,
      parentName: req.user.name,
      parentNumber: req.user.phone
    });

    newJob.save(function(err, job) {
      if (err) return res.send(err);
      User.findById(req.user._id, function(err, user) {
        if (err) return console.log('error finding user by ID for New Job Save: ' + err);
        if (user === null) return console.log('user is null during New Job save.');
        user.jobs.push(job._id);
        user.save(function(err) {
          if (err) return console.log('error saving job to user array');
          console.log('successfully saved job to user array.');
        });
      });
      res.json(job);
    });
  });

  app.get('/jobs', jwtauth, function(req, res) {
    Job.find({parent:req.user._id}, function(err, jobs) {
      if (err) return res.json({msg: 'no jobs found'});
      res.json(jobs);
    });
  });
};
<|endoftext|>


<commit_before>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe(FILL_ME_IN);
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe(FILL_ME_IN);
    expect(aPerson.getLastName()).toBe(FILL_ME_IN);
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

});
<commit_msg>Made test for public and mutable added properties pass.<commit_after>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe(FILL_ME_IN);
    expect(aPerson.getLastName()).toBe(FILL_ME_IN);
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

});
<|endoftext|>


<commit_before>var express = require('express')
var router = express.Router()
var orgService = require('../service/orgService')
var logSercice = require('../service/logService')
var checkAdmin = require('../bin/middleware/checkAdmin')
const token = require('../bin/middleware/token')
router.use(token);

// 获取组织机构
router.get('/getOrgs', checkAdmin, function (req, res, next) {
  let opts = req.query
  orgService.getOrgs(opts, result => {
    res.json(result)
  })
})
// 添加组织机构
router.post('/addOrg', checkAdmin, function (req, res, next) {
  let opts = req.body
  orgService.addOrg(opts, result => {
    logSercice.log(req.userId, 'addOrg', result.status === false ? result.message : `orgName:${opts.orgname}`)
    res.json(result)
  })
})
// 更新组织机构
router.post('/editOrg', checkAdmin, function (req, res, next) {
  let opts = req.body
  orgService.editOrg(opts, result => {
    logSercice.log(req.userId, 'editOrg', result.status === false ? result.message : `orgName:${opts.orgname}`)
    res.json(result)
  })
})
// 删除组织机构
router.post('/deleteOrg', checkAdmin, function (req, res, next) {
  let opts = req.body
  orgService.deleteOrg(opts, result => {
    logSercice.log(req.userId, 'editOrg', result.status === false ? result.message : `orgName:${opts.orgname}`)
    res.json(result)
  })
})

module.exports = router<commit_msg>修改：获取组织机构不判断用户权限<commit_after>var express = require('express')
var router = express.Router()
var orgService = require('../service/orgService')
var logSercice = require('../service/logService')
var checkAdmin = require('../bin/middleware/checkAdmin')
const token = require('../bin/middleware/token')
router.use(token);

// 获取组织机构
router.get('/getOrgs', function (req, res, next) {
  let opts = req.query
  orgService.getOrgs(opts, result => {
    res.json(result)
  })
})
// 添加组织机构
router.post('/addOrg', checkAdmin, function (req, res, next) {
  let opts = req.body
  orgService.addOrg(opts, result => {
    logSercice.log(req.userId, 'addOrg', result.status === false ? result.message : `orgName:${opts.orgname}`)
    res.json(result)
  })
})
// 更新组织机构
router.post('/editOrg', checkAdmin, function (req, res, next) {
  let opts = req.body
  orgService.editOrg(opts, result => {
    logSercice.log(req.userId, 'editOrg', result.status === false ? result.message : `orgName:${opts.orgname}`)
    res.json(result)
  })
})
// 删除组织机构
router.post('/deleteOrg', checkAdmin, function (req, res, next) {
  let opts = req.body
  orgService.deleteOrg(opts, result => {
    logSercice.log(req.userId, 'editOrg', result.status === false ? result.message : `orgName:${opts.orgname}`)
    res.json(result)
  })
})

module.exports = router<|endoftext|>


<commit_before>var pact = require('../pact.js')

exports.main = function(req, res){
  var polls = new Array();
  pact.db.createReadStream({start: 'poll!',
                              end: 'poll!~'
                          })
    .on('data', function (data) {
      var title = JSON.parse(data.value).question;
      var id = data.key.split('!');
      polls.push({id: id[1], title: title});
    })
    .on('end', function() {
      res.render('all', { title: 'All',
                          polls: polls,
                          render: false
                         }
      );
    })
};
<commit_msg>need to count up the votes for every question<commit_after>var pact = require('../pact.js')

exports.main = function(req, res){
  var polls = new Array();
  pact.db.createReadStream({start: 'poll!',
                              end: 'poll!~'
                          })
    .on('data', function (data) {
      var title = JSON.parse(data.value).question;
      var id = data.key.split('!');
      pact.db.createReadStream({start: 'vote!'+pollId + '!',
                                  end: 'vote!'+pollId + '!~'
                              })
        .on('data', function (data) {
          var count;
          for (var i = 0; i<data.value.

      polls.push({id: id[1], title: title});
    })
    .on('end', function() {
      res.render('top', { title: 'Top',
                          polls: polls,
                          render: false
                         }
      );
    })
};
<|endoftext|>


<commit_before>// welcome.js

"use strict";

function welcome(message) {
  if (NODE_ENV == "development") {
    debugger;
  }

  alert(`Welcome ${message}`);
}

export { welcome };
<commit_msg>Use DEV_ENV. Add console.log for testing UglifyJS<commit_after>// welcome.js

"use strict";

function welcome(message) {
  if (NODE_ENV == DEV_ENV) {
    debugger;
  }
  console.log(`Welcome ${message}`);

  alert(`Welcome ${message}`);
}

export { welcome };
<|endoftext|>


<commit_before>import { default as React, Component } from 'react';
import { render } from 'react-dom';
import {queryObject} from './ImmutableQuery.js';
import Select from 'react-select';
var helper = require('./helper.js');

export class AppbaseSearch extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      currentValue: {}
    };
  }
  // Builds the query for the search by taking search input as query input
  // For autocomplete to work, field should be mapped to Ngram
  getQuery(input) {
    return JSON.parse(`{
      "type": "${helper.appbaseConfig.type}",
      "body": {
        "from": 0,
        "size": ${this.props.size},
        "query": {
          "multi_match": {
            "query": "${input}",
            "fields": "${this.props.fieldName}",
            "operator": "and"
          }
        }
      }
    }`);
  }
  // Fetch the items from Appbase
  getItems(input, callback) {
    var self = this;
    var requestObject = this.getQuery(input);
    var searchField = `hit._source.${this.props.fieldName}`;
    helper.appbaseRef.search(requestObject).on('data', function (data) {
      var options = [];
      // Check if this is Geo search or field tag search
      if (self.props.isGeoSearch) {
        // If it is Geo, we return the location field
        var latField = `hit._source.${self.props.latField}`;
        var lonField = `hit._source.${self.props.lonField}`;
        data.hits.hits.map(function (hit) {
          var location = {
            lat: eval(latField),
            lon: eval(lonField)
          };
          options.push({ value: location, label: eval(searchField) });
        });
      } else {
        data.hits.hits.map(function (hit) {
          options.push({ value: eval(searchField), label: eval(searchField) });
        });
      }
      options = self.removeDuplicates(options, "label");
      callback(null, {
        options: options
      });
    }).on('error', function (error) {
      console.log(error);
    });
  }
  // Search results often contain duplicate results, so display only unique values
  removeDuplicates(myArr, prop) {
    return myArr.filter((obj, pos, arr) => {
      return arr.map(mapObj => mapObj[prop]).indexOf(obj[prop]) === pos;
    });
  }
  // When user has selected a search value
  handleSearch(currentValue) {
    // If it is Geo Search, we pass the props to the parent component
    if (this.props.isGeoSearch)
      this.props.handleSearch(currentValue);
    else {
      // Remove the previous attached search value from ImmutableQuery
      if (this.state.currentValue) {
        queryObject.removeShouldClause(this.props.fieldName, this.state.currentValue.value, "Match");
      }
      // Add the new search value to the ImmutableQuery
      if (currentValue)
        queryObject.addShouldClause(this.props.fieldName, currentValue.value, "Match");
    }
    this.setState({
      currentValue: currentValue
    });
  }
  render() {
    return (
      <Select.Async
        name="appbase-search"
        value={this.state.currentValue}
        loadOptions={this.getItems.bind(this) }
        onChange={this.handleSearch.bind(this) }
        {...this.props}
        />
    );
  }
}
// Default props value
AppbaseSearch.defaultProps = {
  placeholder: "Search...",
  isGeoSearch: false,
  size: 10,
};<commit_msg>Refactor AppbaseSearch code<commit_after>import { default as React, Component } from 'react';
import { render } from 'react-dom';
import {queryObject} from './ImmutableQuery.js';
import Select from 'react-select';
var helper = require('./helper.js');

export class AppbaseSearch extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      currentValue: {}
    };
  }
  // Builds the query for the search by taking search input as query input
  // For autocomplete to work, field should be mapped to Ngram
  getQuery(input) {
    return JSON.parse(`{
      "type": "${helper.appbaseConfig.type}",
      "body": {
        "from": 0,
        "size": ${this.props.size},
        "query": {
          "multi_match": {
            "query": "${input}",
            "fields": "${this.props.fieldName}",
            "operator": "and"
          }
        }
      }
    }`);
  }
  // Fetch the items from Appbase
  getItems(input, callback) {
    let self = this;
    let requestObject = this.getQuery(input);
    let searchField = `hit._source.${this.props.fieldName}`;
    helper.appbaseRef.search(requestObject).on('data', function (data) {
      let options = [];
      // Check if this is Geo search or field tag search
      if (self.props.isGeoSearch) {
        // If it is Geo, we return the location field
        let latField = `hit._source.${self.props.latField}`;
        let lonField = `hit._source.${self.props.lonField}`;
        data.hits.hits.map(function (hit) {
          let location = {
            lat: eval(latField),
            lon: eval(lonField)
          };
          options.push({ value: location, label: eval(searchField) });
        });
      } else {
        data.hits.hits.map(function (hit) {
          options.push({ value: eval(searchField), label: eval(searchField) });
        });
      }
      options = self.removeDuplicates(options, "label");
      callback(null, {
        options: options
      });
    }).on('error', function (error) {
      console.log(error);
    });
  }
  // Search results often contain duplicate results, so display only unique values
  removeDuplicates(myArr, prop) {
    return myArr.filter((obj, pos, arr) => {
      return arr.map(mapObj => mapObj[prop]).indexOf(obj[prop]) === pos;
    });
  }
  // When user has selected a search value
  handleSearch(currentValue) {
    // If it is Geo Search, we pass the props to the parent component
    if (this.props.isGeoSearch)
      this.props.handleSearch(currentValue);
    else {
      // Remove the previous attached search value from ImmutableQuery
      if (this.state.currentValue) {
        queryObject.removeShouldClause(this.props.fieldName, this.state.currentValue.value, "Match");
      }
      // Add the new search value to the ImmutableQuery
      if (currentValue)
        queryObject.addShouldClause(this.props.fieldName, currentValue.value, "Match");
    }
    this.setState({
      currentValue: currentValue
    });
  }
  render() {
    return (
      <Select.Async
        name="appbase-search"
        value={this.state.currentValue}
        loadOptions={this.getItems.bind(this) }
        onChange={this.handleSearch.bind(this) }
        {...this.props}
        />
    );
  }
}
// Default props value
AppbaseSearch.defaultProps = {
  placeholder: "Search...",
  isGeoSearch: false,
  size: 10,
};<|endoftext|>


<commit_before>'use strict';

// import './CardComponent.css!';

import React from 'react';
import ReactDOM from 'react-dom';

export default class CardComponent extends React.Component {
  render() {
    return (

{this.props.title}

I am a very simple card.

    );
  }
}<commit_msg>Use System.import syntax for CSS<commit_after>'use strict';

System.import('./app/CardComponent.css!');

import React from 'react';
import ReactDOM from 'react-dom';

export default class CardComponent extends React.Component {
  render() {
    return (

{this.props.title}

I am a very simple card.

    );
  }
}<|endoftext|>


<commit_before>class ModuleGUI extends Phaser.Group {
  constructor(phaser, module, x, y, width) {
    super(phaser);
    this.phaser = phaser;
    this.x = x;
    this.y = y;
    this.width = width;
    this.module = module;
    this.sockets = [];
    for(var i = 0; i < this.module.sockets.length; i ++) {
      this.sockets[i] = new SocketGUI(phaser, this.module.sockets[i].label, x, 50 + y + 50 * i);
    }
  }

  draw() {
    // this.ctx.fillStyle = '#CCFFCC';
    // this.ctx.fillRect(this.x,0,this.width - 2,600);
    // for(var i = 0; i < this.module.sockets.length; i ++) {
    //   this.sockets[i].draw();
    // }
  }
}
<commit_msg>some gui stuff<commit_after>class ModuleGUI extends Phaser.Group {
  constructor(phaser, module, x, y, width) {
    super(phaser);
    //phaser.add.existing(this);
    this.phaser = phaser;
    this.x = x;
    this.y = y;
    this.width = width;
    this.module = module;
    this.sockets = [];
    for(var i = 0; i < this.module.sockets.length; i ++) {
      this.sockets[i] = new SocketGUI(phaser, this.module.sockets[i].label, x, 50 + y + 50 * i);
    }
  }

  draw() {
    // this.ctx.fillStyle = '#CCFFCC';
    // this.ctx.fillRect(this.x,0,this.width - 2,600);
    // for(var i = 0; i < this.module.sockets.length; i ++) {
    //   this.sockets[i].draw();
    // }
  }
}
<|endoftext|>


<commit_before>/* eslint-disable max-len */
const template = document.createElement('template');
template.innerHTML = `

      <slot></slot>

`;
/**
 * @class FlyingButton
 */
export class FlyingButton extends HTMLElement {
  /**
    * @function constructor
    */
  constructor () {
    super();
    // create the shadowDom and insert the template
    this._shadowRoot = this.attachShadow({mode: 'open'});
    this._shadowRoot.appendChild(template.content.cloneNode(true));
    // locate the component
    this.$open = this._shadowRoot.querySelector('.menu-button');
    this.$img = this._shadowRoot.querySelector('img');
    this.$menu = this._shadowRoot.querySelector('.menu');
    // the last element of the div is the slot
    // we retrieve all elements added in the slot (i.e. se-buttons)
    this.$elements = this.$menu.lastElementChild.assignedElements();
  }
  /**
   * @function observedAttributes
   * @returns {any} observed
   */
  static get observedAttributes () {
    return ['title', 'src', 'pressed', 'disabled'];
  }
  /**
   * @function attributeChangedCallback
   * @param {string} name
   * @param {string} oldValue
   * @param {string} newValue
   * @returns {void}
   */
  attributeChangedCallback (name, oldValue, newValue) {
    if (oldValue === newValue) return;
    switch (name) {
    case 'title':
      {
        const shortcut = this.getAttribute('shortcut');
        this.$open.setAttribute('title', `${newValue} [${shortcut}]`);
      }
      break;
    case 'src':
      this.$img.setAttribute('src', newValue);
      break;
    case 'pressed':
      if (newValue) {
        this.$div.classList.add('pressed');
      } else {
        this.$div.classList.remove('pressed');
      }
      break;
    case 'disabled':
      if (newValue) {
        this.$div.classList.add('disabled');
      } else {
        this.$div.classList.remove('disabled');
      }
      break;
    default:
      // eslint-disable-next-line no-console
      console.error(`unknown attribute: ${name}`);
      break;
    }
  }
  /**
   * @function get
   * @returns {any}
   */
  get title () {
    return this.getAttribute('title');
  }

  /**
   * @function set
   * @returns {void}
   */
  set title (value) {
    this.setAttribute('title', value);
  }
  /**
   * @function get
   * @returns {any}
   */
  get pressed () {
    return this.hasAttribute('pressed');
  }

  /**
   * @function set
   * @returns {void}
   */
  set pressed (value) {
    // boolean value => existence = true
    if (value) {
      this.setAttribute('pressed', 'true');
    } else {
      this.removeAttribute('pressed', '');
    }
  }
  /**
   * @function get
   * @returns {any}
   */
  get disabled () {
    return this.hasAttribute('disabled');
  }

  /**
   * @function set
   * @returns {void}
   */
  set disabled (value) {
    // boolean value => existence = true
    if (value) {
      this.setAttribute('disabled', 'true');
    } else {
      this.removeAttribute('disabled', '');
    }
  }
  /**
   * @function get
   * @returns {any}
   */
  get src () {
    return this.getAttribute('src');
  }

  /**
   * @function set
   * @returns {void}
   */
  set src (value) {
    this.setAttribute('src', value);
  }
}

// Register
customElements.define('se-flyingbutton', FlyingButton);
/*

    */
<commit_msg>click to toggle buttons<commit_after>/* eslint-disable max-len */
const template = document.createElement('template');
template.innerHTML = `

      <slot></slot>

`;
/**
 * @class FlyingButton
 */
export class FlyingButton extends HTMLElement {
  /**
    * @function constructor
    */
  constructor () {
    super();
    // create the shadowDom and insert the template
    this._shadowRoot = this.attachShadow({mode: 'open'});
    this._shadowRoot.appendChild(template.content.cloneNode(true));
    // locate the component
    this.$button = this._shadowRoot.querySelector('.menu-button');
    this.$img = this._shadowRoot.querySelector('img');
    this.$menu = this._shadowRoot.querySelector('.menu');
    // the last element of the div is the slot
    // we retrieve all elements added in the slot (i.e. se-buttons)
    this.$elements = this.$menu.lastElementChild.assignedElements();
  }
  /**
   * @function observedAttributes
   * @returns {any} observed
   */
  static get observedAttributes () {
    return ['title', 'src', 'pressed', 'disabled'];
  }
  /**
   * @function attributeChangedCallback
   * @param {string} name
   * @param {string} oldValue
   * @param {string} newValue
   * @returns {void}
   */
  attributeChangedCallback (name, oldValue, newValue) {
    if (oldValue === newValue) return;
    switch (name) {
    case 'title':
      {
        const shortcut = this.getAttribute('shortcut');
        this.$button.setAttribute('title', `${newValue} [${shortcut}]`);
      }
      break;
    case 'src':
      this.$img.setAttribute('src', newValue);
      break;
    case 'pressed':
      if (newValue) {
        this.$div.classList.add('pressed');
      } else {
        this.$div.classList.remove('pressed');
      }
      break;
    case 'disabled':
      if (newValue) {
        this.$div.classList.add('disabled');
      } else {
        this.$div.classList.remove('disabled');
      }
      break;
    default:
      // eslint-disable-next-line no-console
      console.error(`unknown attribute: ${name}`);
      break;
    }
  }
  /**
   * @function get
   * @returns {any}
   */
  get title () {
    return this.getAttribute('title');
  }

  /**
   * @function set
   * @returns {void}
   */
  set title (value) {
    this.setAttribute('title', value);
  }
  /**
   * @function get
   * @returns {any}
   */
  get pressed () {
    return this.hasAttribute('pressed');
  }

  /**
   * @function set
   * @returns {void}
   */
  set pressed (value) {
    // boolean value => existence = true
    if (value) {
      this.setAttribute('pressed', 'true');
    } else {
      this.removeAttribute('pressed', '');
    }
  }
  /**
   * @function get
   * @returns {any}
   */
  get disabled () {
    return this.hasAttribute('disabled');
  }

  /**
   * @function set
   * @returns {void}
   */
  set disabled (value) {
    // boolean value => existence = true
    if (value) {
      this.setAttribute('disabled', 'true');
    } else {
      this.removeAttribute('disabled', '');
    }
  }
  /**
   * @function get
   * @returns {any}
   */
  get src () {
    return this.getAttribute('src');
  }

  /**
   * @function set
   * @returns {void}
   */
  set src (value) {
    this.setAttribute('src', value);
  }
  /**
   * @function connectedCallback
   * @returns {void}
   */
  connectedCallback () {
    // capture click event
    this.$button.addEventListener('click', () => {
      // normalize key
      this.$menu.classList.toggle('open');
    });
  }
}

// Register
customElements.define('se-flyingbutton', FlyingButton);
/*

    */
<|endoftext|>