<commit_before>var express = require('express');
var webpack = require('webpack');
var webpackConfig = require('./webpack.development');
// var https=require('https');

var webpackDevMiddleware=require('webpack-dev-middleware');
var webpackHotMiddleware=require('webpack-hot-middleware');

var app = express();
var compiler = webpack(webpackConfig);

const opn = require('opn');

var PORT=8086;

app.use(webpackDevMiddleware(compiler, {
	// publicPath: webpackConfig.output.publicPath,
  hot: true,
  historyApiFallback: false,
  compress: true,
  noInfo: true,
  stats: {
    colors: true,
  },
}));

app.use(webpackHotMiddleware(compiler));

app.use(function(req,res,next){
    console.log('test');
    next();
});

app.set('port', process.env.PORT || PORT);

//  start server
var cors=require('cors');
var logger=require('morgan');
var bodyParser=require('body-parser');  // 数据解析

app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

if(app.get('env')==='production'){
  app.use(function(req,res,next) {
    var protocol=req.get('x-forwarded-proto');
    protocol=='https'?next():res.redirect('https://'+req.hostname+req.url);
  });
}
// start post test
app.get('/test/get',function(req,res){
  res.send({test:'get'});
});
app.post('/test/post',function(req,res){
  console.log(req.body);
  res.send(req.body);
});
// end post test
//
//  end server

// 设置跨域访问，方便开发
/*app.all('*',function(req,res,next){
  res.header("Access-Control-Allow-Origin","*");
  res.header("Access-Control-Allow-Headers","X-Requested-With,accept,origin,content-type");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By","3.2.1");
  res.header("Content-Type","application/json;charset=utf-8");
  next();
});*/

//test
/*app.get('/api/test',(req,res)=>{
  var data='';
  https.get('http://localhost:3000/server/data.json',(ress)=>{
    ress.on('data',(d)=>{
      // process.stdout.write(d);
      data+=d;
    })
    .on('end',()=>{
      return res.send(data);
    });
  })
  .on('error',(e)=>{
    console.error(e);
  });
});*/

// start md2html
var fs=require('fs');
var path=require('path');
var marked=require('marked');
var hl=require('highlight.js');

marked.setOptions({
  renderer: new marked.Renderer(),
  gfm: true,
  tables: true,
  breaks: false,
  pedantic: false,
  sanitize: false,
  smartLists: true,
  smartypants: false,
  highlight: function (code) {
    return hl.highlightAuto(code).value;
  }
});

app.get('/api',function(request,response,next){
  var src=fs.readdirSync(path.join(__dirname,'doc')).filter(function (file) {
    return (file.indexOf('.') !== 0) && (file.indexOf('.md') > 0);
  });
  response.send({src:src});
});
// app.get('/api',function(request,response,next){
  fs.readdirSync(path.join(__dirname,'doc')).filter(function (file) {
    return (file.indexOf('.') !== 0) && (file.indexOf('.md') > 0);
  }).forEach(function (file) {
    // console.log(file.slice(0,-3));
    app.get('/api/'+encodeURI(file),(req,res)=>{
      fs.readFile(path.join(__dirname+'/doc',file),'utf8',(err,data)=>{ //readFileSync //同步
        if(err){
          throw err;
        }else{
          // var html=marked(data.toString());
          res.send({html:marked(data)});
        }
      });
    });
  });
// });
// end md2html

  /*
  **  20161229
  **  yiru
  **  server.js
  */

  // start mongodb
  var mongoose=require("mongoose");
  mongoose.Promise = require('bluebird');
  // 数据库名称
  var baseUrl='mongodb://localhost:27017/';
  var dataNmae='dataUI';
  var dataUrl=baseUrl+dataNmae;
  // 建立连接
  var dataCom=mongoose.createConnection(dataUrl);
  dataCom.on('error',function(err) {
    console.log('数据库连接失败！'.red);
  });
  dataCom.once('open',function(err) {
    console.log('数据库连接成功！'.green);
  });
  var t={
    name:String,
    schemaList:String,
    role:{type:Number,max:5}
  };
  var dataUISchema = new mongoose.Schema(t);
  // 创建表
  var dataUI=dataCom.model('dataUIs',dataUISchema);
  // add table
  let addTable=(name,sch)=>{
    function getType(type){
      if(type=='Boolean'){
        type=Boolean;
      }else if(type=='Number'){
        type=Number;
      }else if(type=='String'){
        type=String;
      }
      else{
        type=String;
      }
      return type;
    };
    var schema={},head=[];
    Object.keys(sch).forEach((v,k)=>{
      head.push(v);
      schema[v]=getType(sch[v]);
    });
    global[name+'Schema']=new mongoose.Schema(schema);
    !global[name]&&(global[name]=dataCom.model(name+'s',global[name+'Schema']));
    return head;
  };
  //获取数据
  app.get('/table/info',function(req,res){
    var tables=[];
    dataUI.find(function(err,data){
      if(err){
        console.log(err);
        return false;
      }
      data.forEach((v,k)=>{
        var d=JSON.parse(JSON.stringify(v));
        tables.push(d.name);
        var sl=JSON.parse(d.schemaList);
        // console.log(d);
        var head=addTable(d.name,sl);
        // global[d.name]=dataCom.model(d.name+'s',new mongoose.Schema({name:String,type:String}));
        /*global[d.name].find((err,d)=>{
          console.log(d);
        });*/
      });
      res.send(tables);
    });
  });
  //添加数据表
  app.post('/table/add',function(req,res){
    var table=req.body;
    if (!table) {
      console.log(table);
      return;
    }
    var name=table.name;
    var sch=table.schemaList;
    table.schemaList=JSON.stringify(table.schemaList);

    dataUI.findOne({name:name},function(err,data){
      if(err){
        console.log(err);
        return false;
      }
      if(data){
        return res.send({result:'该表名已存在！'});
      }else{
        var add = new dataUI(table);
        add.save(function(err){
          if (err){
            console.log('添加失败！');
            return res.send({result:'添加失败!'+err.message});
          }
          console.log('添加成功！');
          res.send({result:'添加成功！'});
        });
      }
    });
  });
  //删除数据表
  app.post('/table/delete',function(req,res){
    var name=req.body.name;
    if(name){
      global[name].remove({},function(err){
        if(err){
          console.log(err);
          return;
        }
        dataUI.remove({
          name:name
        },function(err){
          if(err){
            console.log(err);
            return;
          }
          // dataCom.disconnect();
          // dataCom.close();
          // dataCom.collections[name+'s'].drop();
          // delete dataCom.collections[name+'s'];
          // delete dataCom.base.modelSchemas[name+'s'];
          // 清空model
          delete dataCom.models[name+'s'];
          global[name]=null;

          console.log('删除成功！');
          res.send({result:'删除成功！'});
        })
      });
    }
  });
  //获取表数据
  app.get('/table/:name/info',function(req,res){
    var name=req.params.name;
    dataUI.findOne({name:name},function(err,data){
      if(err){
        console.log(err);
        return false;
      }
      var sch=JSON.parse(data.schemaList),head=[];
      Object.keys(sch).forEach((v,k)=>{
        head.push(v);
      });
      console.log('获取表成功！');
      global[name].find((err,d)=>{
        if(err){
          console.log(err);
          return;
        }
        res.send({head:head,tbody:d});
      });
    });
  });
  //添加表数据
  app.post('/table/:name/add',function(req,res){
    var name=req.params.name;
    var tbody=req.body;

    if (!tbody) {
      console.log(tbody);
      return;
    }
    var add = new (global[name])(tbody);
    add.save(function(err){
      if (err){
        console.log('添加失败！');
        return res.send({result:'添加失败!'+err.message});
      }
      console.log('添加成功！');
      // res.send({result:'添加成功！'});
      (global[name]).find((err,d)=>{
        if(err){
          console.log(err);
          return;
        }
        res.send({tbody:d});
      });
    });
  });
  //更新表数据
  app.post('/table/:name/update',function(req,res){
    var name=req.params.name;
    var data=req.body;

    if(!data){
      console.log(data);
      return;
    }

    (global[name]).update({_id:data._id},{
      $set:data.tr
    },function(err){
      if(err){
        console.log(err);
        return res.send(err.message);
      }
      console.log('更新成功！');
      // console.log(res.statusCode);
      res.status(res.statusCode).send({result:'添加成功！'});
    });
  });
  //删除表数据
  app.post('/table/:name/delete',function(req,res){
    var name=req.params.name;

    var id=req.body._id;
    if(id){
      (global[name]).remove({
        _id:id
      },function(err){
        if(err){
          console.log(err);
          return;
        }
        console.log('删除成功！');
        res.send({result:'删除成功！'});
      });
    }
  });
  // 将table导出为json文件
  app.get('/table/:name/toJson',function(req,res){
    var name=req.params.name;

    (global[name]).find(function(err,data){
      if(err){
        console.log(err);
        return false;
      }
      data=JSON.stringify(data);
      // data='export const '+name+'='+data;
      // console.log(data);
      var filename=path.join(__dirname,'../demo/models/'+name+'.json');
      fs.writeFile(filename,data,function(err){
        if(err){
          console.log(err);
          return false;
        }
        res.send({result:'OK'});
      });
    });
  });
  // end

app.listen(app.get('port'),(err)=>{
  if (err) {
    console.log(err);
    return false;
  }
  console.log('监听端口:'+ app.get('port') +', 正在构建,请稍后...');
  // opn('http://localhost:'+app.get('port'));
});
<commit_msg>add horizontal<commit_after>var express = require('express');
var webpack = require('webpack');
var webpackConfig = require('./webpack.development');
// var https=require('https');

var webpackDevMiddleware=require('webpack-dev-middleware');
var webpackHotMiddleware=require('webpack-hot-middleware');

var app = express();
var compiler = webpack(webpackConfig);

// const opn = require('opn');

var PORT=8086;

app.use(webpackDevMiddleware(compiler, {
	// publicPath: webpackConfig.output.publicPath,
  hot: true,
  historyApiFallback: false,
  compress: true,
  noInfo: true,
  stats: {
    colors: true,
  },
}));

app.use(webpackHotMiddleware(compiler));

app.use(function(req,res,next){
    console.log('test');
    next();
});

app.set('port', process.env.PORT || PORT);

//  start server
var cors=require('cors');
var logger=require('morgan');
var bodyParser=require('body-parser');  // 数据解析

app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

if(app.get('env')==='production'){
  app.use(function(req,res,next) {
    var protocol=req.get('x-forwarded-proto');
    protocol=='https'?next():res.redirect('https://'+req.hostname+req.url);
  });
}
// start post test
app.get('/test/get',function(req,res){
  res.send({test:'get'});
});
app.post('/test/post',function(req,res){
  console.log(req.body);
  res.send(req.body);
});
// end post test
//
//  end server

// 设置跨域访问，方便开发
/*app.all('*',function(req,res,next){
  res.header("Access-Control-Allow-Origin","*");
  res.header("Access-Control-Allow-Headers","X-Requested-With,accept,origin,content-type");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By","3.2.1");
  res.header("Content-Type","application/json;charset=utf-8");
  next();
});*/

//test
/*app.get('/api/test',(req,res)=>{
  var data='';
  https.get('http://localhost:3000/server/data.json',(ress)=>{
    ress.on('data',(d)=>{
      // process.stdout.write(d);
      data+=d;
    })
    .on('end',()=>{
      return res.send(data);
    });
  })
  .on('error',(e)=>{
    console.error(e);
  });
});*/

// start md2html
var fs=require('fs');
var path=require('path');
var marked=require('marked');
var hl=require('highlight.js');

marked.setOptions({
  renderer: new marked.Renderer(),
  gfm: true,
  tables: true,
  breaks: false,
  pedantic: false,
  sanitize: false,
  smartLists: true,
  smartypants: false,
  highlight: function (code) {
    return hl.highlightAuto(code).value;
  }
});

app.get('/api',function(request,response,next){
  var src=fs.readdirSync(path.join(__dirname,'doc')).filter(function (file) {
    return (file.indexOf('.') !== 0) && (file.indexOf('.md') > 0);
  });
  response.send({src:src});
});
// app.get('/api',function(request,response,next){
  fs.readdirSync(path.join(__dirname,'doc')).filter(function (file) {
    return (file.indexOf('.') !== 0) && (file.indexOf('.md') > 0);
  }).forEach(function (file) {
    // console.log(file.slice(0,-3));
    app.get('/api/'+encodeURI(file),(req,res)=>{
      fs.readFile(path.join(__dirname+'/doc',file),'utf8',(err,data)=>{ //readFileSync //同步
        if(err){
          throw err;
        }else{
          // var html=marked(data.toString());
          res.send({html:marked(data)});
        }
      });
    });
  });
// });
// end md2html

  /*
  **  20161229
  **  yiru
  **  server.js
  */

  // start mongodb
  var mongoose=require("mongoose");
  mongoose.Promise = require('bluebird');
  // 数据库名称
  var baseUrl='mongodb://localhost:27017/';
  var dataNmae='dataUI';
  var dataUrl=baseUrl+dataNmae;
  // 建立连接
  var dataCom=mongoose.createConnection(dataUrl);
  dataCom.on('error',function(err) {
    console.log('数据库连接失败！'.red);
  });
  dataCom.once('open',function(err) {
    console.log('数据库连接成功！'.green);
  });
  var t={
    name:String,
    schemaList:String,
    role:{type:Number,max:5}
  };
  var dataUISchema = new mongoose.Schema(t);
  // 创建表
  var dataUI=dataCom.model('dataUIs',dataUISchema);
  // add table
  let addTable=(name,sch)=>{
    function getType(type){
      if(type=='Boolean'){
        type=Boolean;
      }else if(type=='Number'){
        type=Number;
      }else if(type=='String'){
        type=String;
      }
      else{
        type=String;
      }
      return type;
    };
    var schema={},head=[];
    Object.keys(sch).forEach((v,k)=>{
      head.push(v);
      schema[v]=getType(sch[v]);
    });
    global[name+'Schema']=new mongoose.Schema(schema);
    !global[name]&&(global[name]=dataCom.model(name+'s',global[name+'Schema']));
    return head;
  };
  //获取数据
  app.get('/table/info',function(req,res){
    var tables=[];
    dataUI.find(function(err,data){
      if(err){
        console.log(err);
        return false;
      }
      data.forEach((v,k)=>{
        var d=JSON.parse(JSON.stringify(v));
        tables.push(d.name);
        var sl=JSON.parse(d.schemaList);
        // console.log(d);
        var head=addTable(d.name,sl);
        // global[d.name]=dataCom.model(d.name+'s',new mongoose.Schema({name:String,type:String}));
        /*global[d.name].find((err,d)=>{
          console.log(d);
        });*/
      });
      res.send(tables);
    });
  });
  //添加数据表
  app.post('/table/add',function(req,res){
    var table=req.body;
    if (!table) {
      console.log(table);
      return;
    }
    var name=table.name;
    var sch=table.schemaList;
    table.schemaList=JSON.stringify(table.schemaList);

    dataUI.findOne({name:name},function(err,data){
      if(err){
        console.log(err);
        return false;
      }
      if(data){
        return res.send({result:'该表名已存在！'});
      }else{
        var add = new dataUI(table);
        add.save(function(err){
          if (err){
            console.log('添加失败！');
            return res.send({result:'添加失败!'+err.message});
          }
          console.log('添加成功！');
          res.send({result:'添加成功！'});
        });
      }
    });
  });
  //删除数据表
  app.post('/table/delete',function(req,res){
    var name=req.body.name;
    if(name){
      global[name].remove({},function(err){
        if(err){
          console.log(err);
          return;
        }
        dataUI.remove({
          name:name
        },function(err){
          if(err){
            console.log(err);
            return;
          }
          // dataCom.disconnect();
          // dataCom.close();
          // dataCom.collections[name+'s'].drop();
          // delete dataCom.collections[name+'s'];
          // delete dataCom.base.modelSchemas[name+'s'];
          // 清空model
          delete dataCom.models[name+'s'];
          global[name]=null;

          console.log('删除成功！');
          res.send({result:'删除成功！'});
        })
      });
    }
  });
  //获取表数据
  app.get('/table/:name/info',function(req,res){
    var name=req.params.name;
    dataUI.findOne({name:name},function(err,data){
      if(err){
        console.log(err);
        return false;
      }
      var sch=JSON.parse(data.schemaList),head=[];
      Object.keys(sch).forEach((v,k)=>{
        head.push(v);
      });
      console.log('获取表成功！');
      global[name].find((err,d)=>{
        if(err){
          console.log(err);
          return;
        }
        res.send({head:head,tbody:d});
      });
    });
  });
  //添加表数据
  app.post('/table/:name/add',function(req,res){
    var name=req.params.name;
    var tbody=req.body;

    if (!tbody) {
      console.log(tbody);
      return;
    }
    var add = new (global[name])(tbody);
    add.save(function(err){
      if (err){
        console.log('添加失败！');
        return res.send({result:'添加失败!'+err.message});
      }
      console.log('添加成功！');
      // res.send({result:'添加成功！'});
      (global[name]).find((err,d)=>{
        if(err){
          console.log(err);
          return;
        }
        res.send({tbody:d});
      });
    });
  });
  //更新表数据
  app.post('/table/:name/update',function(req,res){
    var name=req.params.name;
    var data=req.body;

    if(!data){
      console.log(data);
      return;
    }

    (global[name]).update({_id:data._id},{
      $set:data.tr
    },function(err){
      if(err){
        console.log(err);
        return res.send(err.message);
      }
      console.log('更新成功！');
      // console.log(res.statusCode);
      res.status(res.statusCode).send({result:'添加成功！'});
    });
  });
  //删除表数据
  app.post('/table/:name/delete',function(req,res){
    var name=req.params.name;

    var id=req.body._id;
    if(id){
      (global[name]).remove({
        _id:id
      },function(err){
        if(err){
          console.log(err);
          return;
        }
        console.log('删除成功！');
        res.send({result:'删除成功！'});
      });
    }
  });
  // 将table导出为json文件
  app.get('/table/:name/toJson',function(req,res){
    var name=req.params.name;

    (global[name]).find(function(err,data){
      if(err){
        console.log(err);
        return false;
      }
      data=JSON.stringify(data);
      // data='export const '+name+'='+data;
      // console.log(data);
      var filename=path.join(__dirname,'../demo/models/'+name+'.json');
      fs.writeFile(filename,data,function(err){
        if(err){
          console.log(err);
          return false;
        }
        res.send({result:'OK'});
      });
    });
  });
  // end

app.listen(app.get('port'),(err)=>{
  if (err) {
    console.log(err);
    return false;
  }
  console.log('监听端口:'+ app.get('port') +', 正在构建,请稍后...');
  // opn('http://localhost:'+app.get('port'));
});
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { createStylingFromTheme, base16Themes } from './utils/createStylingFromTheme';
import shouldPureComponentUpdate from 'react-pure-render/function';
import ActionList from './ActionList';
import ActionPreview from './ActionPreview';
import getInspectedState from './utils/getInspectedState';
import DiffPatcher from './DiffPatcher';
import { getBase16Theme } from 'react-base16-styling';
import { reducer, updateMonitorState } from './redux';
import { ActionCreators } from 'redux-devtools';

const { commit, sweep, toggleAction, jumpToState } = ActionCreators;

function getLastActionId(props) {
  return props.stagedActionIds[props.stagedActionIds.length - 1];
}

function getCurrentActionId(props, monitorState) {
  return monitorState.selectedActionId === null ?
    props.stagedActionIds[props.currentStateIndex] : monitorState.selectedActionId;
}

function getFromState(actionIndex, stagedActionIds, computedStates, monitorState) {
  const { startActionId } = monitorState;
  if (startActionId === null) {
    return actionIndex > 0 ? computedStates[actionIndex - 1] : null;
  }
  let fromStateIdx = stagedActionIds.indexOf(startActionId - 1);
  if (fromStateIdx === -1) fromStateIdx = 0;
  return computedStates[fromStateIdx];
}

function createIntermediateState(props, monitorState) {
  const { supportImmutable, computedStates, stagedActionIds,
          actionsById: actions } = props;
  const { inspectedStatePath, inspectedActionPath } = monitorState;
  const currentActionId = getCurrentActionId(props, monitorState);
  const currentAction = actions[currentActionId] && actions[currentActionId].action;

  const actionIndex = stagedActionIds.indexOf(currentActionId);
  const fromState = getFromState(actionIndex, stagedActionIds, computedStates, monitorState);
  const toState = computedStates[actionIndex];
  const error = toState && toState.error;

  const fromInspectedState = !error && fromState &&
    getInspectedState(fromState.state, inspectedStatePath, supportImmutable);
  const toInspectedState =
    !error && toState && getInspectedState(toState.state, inspectedStatePath, supportImmutable);
  const delta = !error && fromState && toState && DiffPatcher.diff(
    fromInspectedState,
    toInspectedState
  );

  return {
    delta,
    nextState: toState && getInspectedState(toState.state, inspectedStatePath, false),
    action: getInspectedState(currentAction, inspectedActionPath, false),
    error
  };
}

function createThemeState(props) {
  const base16Theme = getBase16Theme(props.theme, base16Themes);
  const styling = createStylingFromTheme(props.theme, props.invertTheme);

  return { base16Theme, styling };
}

export default class DevtoolsInspector extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ...createIntermediateState(props, props.monitorState),
      isWideLayout: false,
      themeState: createThemeState(props)
    };
  }

  static propTypes = {
    dispatch: PropTypes.func,
    computedStates: PropTypes.array,
    stagedActionIds: PropTypes.array,
    actionsById: PropTypes.object,
    currentStateIndex: PropTypes.number,
    monitorState: PropTypes.shape({
      initialScrollTop: PropTypes.number
    }),
    preserveScrollTop: PropTypes.bool,
    stagedActions: PropTypes.array,
    select: PropTypes.func.isRequired,
    theme: PropTypes.oneOfType([
      PropTypes.object,
      PropTypes.string
    ]),
    supportImmutable: PropTypes.bool
  };

  static update = reducer;

  static defaultProps = {
    select: (state) => state,
    supportImmutable: false,
    theme: 'inspector',
    invertTheme: true
  };

  shouldComponentUpdate = shouldPureComponentUpdate;

  componentDidMount() {
    this.updateSizeMode();
    this.updateSizeTimeout = window.setInterval(this.updateSizeMode.bind(this), 150);
  }

  componentWillUnmount() {
    window.clearTimeout(this.updateSizeTimeout);
  }

  updateMonitorState(monitorState) {
    this.props.dispatch(updateMonitorState(monitorState));
  }

  updateSizeMode() {
    const isWideLayout = this.refs.inspector.offsetWidth > 500;

    if (isWideLayout !== this.state.isWideLayout) {
      this.setState({ isWideLayout });
    }
  }

  componentWillReceiveProps(nextProps) {
    let nextMonitorState = nextProps.monitorState;
    const monitorState = this.props.monitorState;

    if (
      getCurrentActionId(this.props, monitorState) !==
      getCurrentActionId(nextProps, nextMonitorState) ||
      monitorState.startActionId !== nextMonitorState.startActionId ||
      monitorState.inspectedStatePath !== nextMonitorState.inspectedStatePath ||
      monitorState.inspectedActionPath !== nextMonitorState.inspectedActionPath
    ) {
      this.setState(createIntermediateState(nextProps, nextMonitorState));
    }

    if (this.props.theme !== nextProps.theme ||
        this.props.invertTheme !== nextProps.invertTheme) {
      this.setState({ themeState: createThemeState(nextProps) });
    }
  }

  render() {
    const { stagedActionIds: actionIds, actionsById: actions, computedStates,
      tabs, invertTheme, skippedActionIds, currentStateIndex, monitorState } = this.props;
    const { selectedActionId, startActionId, searchValue, tabName } = monitorState;
    const inspectedPathType = tabName === 'Action' ? 'inspectedActionPath' : 'inspectedStatePath';
    const {
      themeState, isWideLayout, action, nextState, delta, error
    } = this.state;
    const { base16Theme, styling } = themeState;

    return (

        <ActionList {...{
          actions, actionIds, isWideLayout, searchValue, selectedActionId, startActionId
        }}
                    styling={styling}
                    onSearch={this.handleSearch}
                    onSelect={this.handleSelectAction}
                    onToggleAction={this.handleToggleAction}
                    onJumpToState={this.handleJumpToState}
                    onCommit={this.handleCommit}
                    onSweep={this.handleSweep}
                    skippedActionIds={skippedActionIds}
                    currentActionId={actionIds[currentStateIndex]}
                    lastActionId={getLastActionId(this.props)} />
        <ActionPreview {...{
          base16Theme, invertTheme, isWideLayout, tabs, tabName, delta, error, nextState,
          computedStates, action, actions, selectedActionId, startActionId
        }}
                       styling={styling}
                       onInspectPath={this.handleInspectPath.bind(this, inspectedPathType)}
                       inspectedPath={monitorState[inspectedPathType]}
                       onSelectTab={this.handleSelectTab} />

    );
  }

  handleToggleAction = actionId => {
    this.props.dispatch(toggleAction(actionId));
  };

  handleJumpToState = actionId => {
    const index = this.props.stagedActionIds.indexOf(actionId);
    if (index > 0) this.props.dispatch(jumpToState(index));
  };

  handleCommit = () => {
    this.props.dispatch(commit());
  };

  handleSweep = () => {
    this.props.dispatch(sweep());
  };

  handleSearch = val => {
    this.updateMonitorState({ searchValue: val });
  };

  handleSelectAction = (e, actionId) => {
    const { monitorState } = this.props;
    let startActionId;
    let selectedActionId;

    if (e.shiftKey && monitorState.selectedActionId !== null) {
      if (monitorState.startActionId !== null) {
        if (actionId >= monitorState.startActionId) {
          startActionId = Math.min(monitorState.startActionId, monitorState.selectedActionId);
          selectedActionId = actionId;
        } else {
          selectedActionId = Math.max(monitorState.startActionId, monitorState.selectedActionId);
          startActionId = actionId;
        }
      } else {
        startActionId = Math.min(actionId, monitorState.selectedActionId);
        selectedActionId = Math.max(actionId, monitorState.selectedActionId);
      }
    } else {
      startActionId = null;
      if (actionId === monitorState.selectedActionId || monitorState.startActionId !== null) {
        selectedActionId = null;
      } else {
        selectedActionId = actionId;
      }
    }

    this.updateMonitorState({ startActionId, selectedActionId });
  };

  handleInspectPath = (pathType, path) => {
    this.updateMonitorState({ [pathType]: path });
  };

  handleSelectTab = tabName => {
    this.updateMonitorState({ tabName });
  };
}
<commit_msg>Fallback for redux-devtools-instrument < 1.5<commit_after>import React, { Component, PropTypes } from 'react';
import { createStylingFromTheme, base16Themes } from './utils/createStylingFromTheme';
import shouldPureComponentUpdate from 'react-pure-render/function';
import ActionList from './ActionList';
import ActionPreview from './ActionPreview';
import getInspectedState from './utils/getInspectedState';
import DiffPatcher from './DiffPatcher';
import { getBase16Theme } from 'react-base16-styling';
import { reducer, updateMonitorState } from './redux';
import { ActionCreators } from 'redux-devtools';

const { commit, sweep, toggleAction, jumpToAction, jumpToState } = ActionCreators;

function getLastActionId(props) {
  return props.stagedActionIds[props.stagedActionIds.length - 1];
}

function getCurrentActionId(props, monitorState) {
  return monitorState.selectedActionId === null ?
    props.stagedActionIds[props.currentStateIndex] : monitorState.selectedActionId;
}

function getFromState(actionIndex, stagedActionIds, computedStates, monitorState) {
  const { startActionId } = monitorState;
  if (startActionId === null) {
    return actionIndex > 0 ? computedStates[actionIndex - 1] : null;
  }
  let fromStateIdx = stagedActionIds.indexOf(startActionId - 1);
  if (fromStateIdx === -1) fromStateIdx = 0;
  return computedStates[fromStateIdx];
}

function createIntermediateState(props, monitorState) {
  const { supportImmutable, computedStates, stagedActionIds,
          actionsById: actions } = props;
  const { inspectedStatePath, inspectedActionPath } = monitorState;
  const currentActionId = getCurrentActionId(props, monitorState);
  const currentAction = actions[currentActionId] && actions[currentActionId].action;

  const actionIndex = stagedActionIds.indexOf(currentActionId);
  const fromState = getFromState(actionIndex, stagedActionIds, computedStates, monitorState);
  const toState = computedStates[actionIndex];
  const error = toState && toState.error;

  const fromInspectedState = !error && fromState &&
    getInspectedState(fromState.state, inspectedStatePath, supportImmutable);
  const toInspectedState =
    !error && toState && getInspectedState(toState.state, inspectedStatePath, supportImmutable);
  const delta = !error && fromState && toState && DiffPatcher.diff(
    fromInspectedState,
    toInspectedState
  );

  return {
    delta,
    nextState: toState && getInspectedState(toState.state, inspectedStatePath, false),
    action: getInspectedState(currentAction, inspectedActionPath, false),
    error
  };
}

function createThemeState(props) {
  const base16Theme = getBase16Theme(props.theme, base16Themes);
  const styling = createStylingFromTheme(props.theme, props.invertTheme);

  return { base16Theme, styling };
}

export default class DevtoolsInspector extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ...createIntermediateState(props, props.monitorState),
      isWideLayout: false,
      themeState: createThemeState(props)
    };
  }

  static propTypes = {
    dispatch: PropTypes.func,
    computedStates: PropTypes.array,
    stagedActionIds: PropTypes.array,
    actionsById: PropTypes.object,
    currentStateIndex: PropTypes.number,
    monitorState: PropTypes.shape({
      initialScrollTop: PropTypes.number
    }),
    preserveScrollTop: PropTypes.bool,
    stagedActions: PropTypes.array,
    select: PropTypes.func.isRequired,
    theme: PropTypes.oneOfType([
      PropTypes.object,
      PropTypes.string
    ]),
    supportImmutable: PropTypes.bool
  };

  static update = reducer;

  static defaultProps = {
    select: (state) => state,
    supportImmutable: false,
    theme: 'inspector',
    invertTheme: true
  };

  shouldComponentUpdate = shouldPureComponentUpdate;

  componentDidMount() {
    this.updateSizeMode();
    this.updateSizeTimeout = window.setInterval(this.updateSizeMode.bind(this), 150);
  }

  componentWillUnmount() {
    window.clearTimeout(this.updateSizeTimeout);
  }

  updateMonitorState(monitorState) {
    this.props.dispatch(updateMonitorState(monitorState));
  }

  updateSizeMode() {
    const isWideLayout = this.refs.inspector.offsetWidth > 500;

    if (isWideLayout !== this.state.isWideLayout) {
      this.setState({ isWideLayout });
    }
  }

  componentWillReceiveProps(nextProps) {
    let nextMonitorState = nextProps.monitorState;
    const monitorState = this.props.monitorState;

    if (
      getCurrentActionId(this.props, monitorState) !==
      getCurrentActionId(nextProps, nextMonitorState) ||
      monitorState.startActionId !== nextMonitorState.startActionId ||
      monitorState.inspectedStatePath !== nextMonitorState.inspectedStatePath ||
      monitorState.inspectedActionPath !== nextMonitorState.inspectedActionPath
    ) {
      this.setState(createIntermediateState(nextProps, nextMonitorState));
    }

    if (this.props.theme !== nextProps.theme ||
        this.props.invertTheme !== nextProps.invertTheme) {
      this.setState({ themeState: createThemeState(nextProps) });
    }
  }

  render() {
    const { stagedActionIds: actionIds, actionsById: actions, computedStates,
      tabs, invertTheme, skippedActionIds, currentStateIndex, monitorState } = this.props;
    const { selectedActionId, startActionId, searchValue, tabName } = monitorState;
    const inspectedPathType = tabName === 'Action' ? 'inspectedActionPath' : 'inspectedStatePath';
    const {
      themeState, isWideLayout, action, nextState, delta, error
    } = this.state;
    const { base16Theme, styling } = themeState;

    return (

        <ActionList {...{
          actions, actionIds, isWideLayout, searchValue, selectedActionId, startActionId
        }}
                    styling={styling}
                    onSearch={this.handleSearch}
                    onSelect={this.handleSelectAction}
                    onToggleAction={this.handleToggleAction}
                    onJumpToState={this.handleJumpToState}
                    onCommit={this.handleCommit}
                    onSweep={this.handleSweep}
                    skippedActionIds={skippedActionIds}
                    currentActionId={actionIds[currentStateIndex]}
                    lastActionId={getLastActionId(this.props)} />
        <ActionPreview {...{
          base16Theme, invertTheme, isWideLayout, tabs, tabName, delta, error, nextState,
          computedStates, action, actions, selectedActionId, startActionId
        }}
                       styling={styling}
                       onInspectPath={this.handleInspectPath.bind(this, inspectedPathType)}
                       inspectedPath={monitorState[inspectedPathType]}
                       onSelectTab={this.handleSelectTab} />

    );
  }

  handleToggleAction = actionId => {
    this.props.dispatch(toggleAction(actionId));
  };

  handleJumpToState = actionId => {
    if (jumpToAction) {
      this.props.dispatch(jumpToAction(actionId));
    } else { // Fallback for redux-devtools-instrument < 1.5
      const index = this.props.stagedActionIds.indexOf(actionId);
      if (index !== -1) this.props.dispatch(jumpToState(index));
    }
  };

  handleCommit = () => {
    this.props.dispatch(commit());
  };

  handleSweep = () => {
    this.props.dispatch(sweep());
  };

  handleSearch = val => {
    this.updateMonitorState({ searchValue: val });
  };

  handleSelectAction = (e, actionId) => {
    const { monitorState } = this.props;
    let startActionId;
    let selectedActionId;

    if (e.shiftKey && monitorState.selectedActionId !== null) {
      if (monitorState.startActionId !== null) {
        if (actionId >= monitorState.startActionId) {
          startActionId = Math.min(monitorState.startActionId, monitorState.selectedActionId);
          selectedActionId = actionId;
        } else {
          selectedActionId = Math.max(monitorState.startActionId, monitorState.selectedActionId);
          startActionId = actionId;
        }
      } else {
        startActionId = Math.min(actionId, monitorState.selectedActionId);
        selectedActionId = Math.max(actionId, monitorState.selectedActionId);
      }
    } else {
      startActionId = null;
      if (actionId === monitorState.selectedActionId || monitorState.startActionId !== null) {
        selectedActionId = null;
      } else {
        selectedActionId = actionId;
      }
    }

    this.updateMonitorState({ startActionId, selectedActionId });
  };

  handleInspectPath = (pathType, path) => {
    this.updateMonitorState({ [pathType]: path });
  };

  handleSelectTab = tabName => {
    this.updateMonitorState({ tabName });
  };
}
<|endoftext|>


<commit_before>{
	/* Grab required dependencies */
	require('dotenv').config();
	const express 	= require('express'),
		  path 		= require('path'),
		  app 		= express(),
		  port 		= 7000;

	app.get('*', (request, response) => {
	    response.sendFile(path.join(__dirname, 'app/index.html'));
	});

	/* Listening on port */
	app.listen(process.env.PORT || port, ()=>{
	    console.log(`App listening on port ${port}`);
	})
}<commit_msg>home path modified<commit_after>{
	/* Grab required dependencies */
	require('dotenv').config();
	const express 	= require('express'),
		  path 		= require('path'),
		  app 		= express(),
		  port 		= 7000;

	app.get('/', (request, response) => {
	    response.sendFile(path.join(__dirname, 'app/index.html'));
	});

	/* Listening on port */
	app.listen(process.env.PORT || port, ()=>{
	    console.log(`App listening on port ${port}`);
	})
}<|endoftext|>


<commit_before>'use strict';

const pg = require('pg');
const express = require('express');
const requestProxy = require('express-request-proxy');
const bodyParser = require('body-parser');
const requestProxy = require('express-request-proxy');
const app = express();
const PORT = process.env.PORT || 7000;
const conString = process.env.DATABASE_URL || 'postgres://localhost:5432';
const client = new pg.Client(conString);
client.connect();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('./public'));

app.get('/', (request, response) => response.sendFile('index.html', {root: './public'}));
app.get('/new', (request, response) => response.sendFile('new.html', {root: './public'}));
app.get('/home', (request, response) => response.sendFile('index.html', {root: './public'}));
app.get('/projects', (request, response) => response.sendFile('index.html', {root: './public'}));
app.get('/github', (request, response) => response.sendFile('index.html', {root: './public'}));
app.get('/github/*', proxyGithub);

function proxyGithub(request, response) {
  console.log('Routing a Github request for ', request.params[0]);
  (requestProxy({
    url: `https://api.github.com/${request.params[0]}`,
    headers: {Authorization: `token ${process.env.GITHUB_TOKEN}`}
  }))(request, response);
}

app.get('/about', (request, response) => response.sendFile('index.html', {root: './public'}));
app.get('/contact', (request, response) => response.sendFile('index.html', {root: './public'}));

app.get('/github/*', proxyGitHub);

function proxyGitHub(request, response) {
  console.log('Routing a GitHub request for ', request.params[0]);
  (requestProxy({
    url: `https://api.github.com/${request.params[0]}`,
    headers: {Authorization: `token ${process.env.GITHUB_TOKEN}`}
  }))(request, response);
}

app.listen(PORT, function() {
  console.log(`Portfolio is being served at ${PORT}`);
});
<commit_msg>deleted duplicate requestproxy<commit_after>'use strict';

const pg = require('pg');
const express = require('express');
const requestProxy = require('express-request-proxy');
const bodyParser = require('body-parser');
const app = express();
const PORT = process.env.PORT || 7000;
const conString = process.env.DATABASE_URL || 'postgres://localhost:5432';
const client = new pg.Client(conString);
client.connect();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('./public'));

app.get('/', (request, response) => response.sendFile('index.html', {root: './public'}));
app.get('/new', (request, response) => response.sendFile('new.html', {root: './public'}));
app.get('/home', (request, response) => response.sendFile('index.html', {root: './public'}));
app.get('/projects', (request, response) => response.sendFile('index.html', {root: './public'}));
app.get('/github', (request, response) => response.sendFile('index.html', {root: './public'}));
app.get('/github/*', proxyGithub);

function proxyGithub(request, response) {
  console.log('Routing a Github request for ', request.params[0]);
  (requestProxy({
    url: `https://api.github.com/${request.params[0]}`,
    headers: {Authorization: `token ${process.env.GITHUB_TOKEN}`}
  }))(request, response);
}

app.get('/about', (request, response) => response.sendFile('index.html', {root: './public'}));
app.get('/contact', (request, response) => response.sendFile('index.html', {root: './public'}));

app.get('/github/*', proxyGitHub);

function proxyGitHub(request, response) {
  console.log('Routing a GitHub request for ', request.params[0]);
  (requestProxy({
    url: `https://api.github.com/${request.params[0]}`,
    headers: {Authorization: `token ${process.env.GITHUB_TOKEN}`}
  }))(request, response);
}

app.listen(PORT, function() {
  console.log(`Portfolio is being served at ${PORT}`);
});
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var path = require('path');

var public_folder = __dirname + '/public';

app.use(express.static(public_folder));
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
var port = process.env.OPENSHIFT_NODEJS_PORT || 3000;
app.get('/hello', function(req, res){
    res.send('hello world');
});

app.get('/assignment', function(req, res){
   res.sendfile(public_folder + '/assignment/home.html');
});

app.listen(port, ipaddress);<commit_msg>Added configuration in server.js for experiments<commit_after>var express = require('express');
var app = express();
var path = require('path');

var public_folder = __dirname + '/public';

app.use(express.static(public_folder));
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
var port = process.env.OPENSHIFT_NODEJS_PORT || 3000;
app.get('/hello', function(req, res){
    res.send('hello world');
});

app.get('/assignment', function(req, res){
   res.sendfile(public_folder + '/assignment/home.html');
});

app.get('/experiment', function(req, res){
    res.sendfile(public_folder + '/experiment/main.html');
});

app.listen(port, ipaddress);<|endoftext|>


<commit_before>var Hapi = require('hapi'),
    path = require('path'),
    port = process.env.PORT || 3000,
    server = new Hapi.Server(port),
    routes = {
        css: {
            method: 'GET',
            path: '/styles/{path*}',
            handler: createDirectoryRoute('styles')
        },
        js: {
            method: 'GET',
            path: '/scripts/{path*}',
            handler: createDirectoryRoute('scripts')
        },
        assets: {
            method: 'GET',
            path: '/assets/{path*}',
            handler: createDirectoryRoute('assets')
        },
        templates: {
            method: 'GET',
            path: '/templates/{path*}',
            handler: createDirectoryRoute('templates')
        },
        spa: {
            method: 'GET',
            path: '/{path*}',
            handler: {
                file: path.join(__dirname, '/app/pages/index.html')
            }
        }
    };

server.route([ routes.css, routes.js, routes.assets, routes.templates, routes.spa ]);

server.start( onServerStarted );

server.on('response', function (request) {
    if(request.url.path.includes('templates')) {
        console.log();
        console.log(new Date().toString() + ':  ' + request.method.toUpperCase() + ' - ' + request.url.path + ' - (' + request.response.statusCode + ')');
    }
});

function onServerStarted() {
    console.log( 'Server running on port ', port );
}

function createDirectoryRoute(directory) {
    return {
        directory: {
            path: path.join(__dirname, '/app/', directory)
        }
    };
}

module.exports = server;
<commit_msg>update path to index on server.js<commit_after>var Hapi = require('hapi'),
    path = require('path'),
    port = process.env.PORT || 3000,
    server = new Hapi.Server(port),
    routes = {
        css: {
            method: 'GET',
            path: '/styles/{path*}',
            handler: createDirectoryRoute('styles')
        },
        js: {
            method: 'GET',
            path: '/scripts/{path*}',
            handler: createDirectoryRoute('scripts')
        },
        assets: {
            method: 'GET',
            path: '/assets/{path*}',
            handler: createDirectoryRoute('assets')
        },
        templates: {
            method: 'GET',
            path: '/templates/{path*}',
            handler: createDirectoryRoute('templates')
        },
        spa: {
            method: 'GET',
            path: '/{path*}',
            handler: {
                file: path.join(__dirname, '/app/index.html')
            }
        }
    };

server.route([ routes.css, routes.js, routes.assets, routes.templates, routes.spa ]);

server.start( onServerStarted );

server.on('response', function (request) {
    if(request.url.path.includes('templates')) {
        console.log();
        console.log(new Date().toString() + ':  ' + request.method.toUpperCase() + ' - ' + request.url.path + ' - (' + request.response.statusCode + ')');
    }
});

function onServerStarted() {
    console.log( 'Server running on port ', port );
}

function createDirectoryRoute(directory) {
    return {
        directory: {
            path: path.join(__dirname, '/app/', directory)
        }
    };
}

module.exports = server;
<|endoftext|>


<commit_before>var express = require('express');
var r = require('rethinkdb');
var app = express();

// set the port of our application
// process.env.PORT lets the port be set by Heroku
var port = process.env.PORT || 8000;

// Load config for app
var config = require(__dirname+"/config.js");

// make express look in the public directory for assets (css/js/img)
app.use(express.static(__dirname+'/public'));

// set the home page route
app.get('/', function(req, res) {
  // ejs render automatically looks in the views folder
  res.sendfile('index.html');
});

app.get('/datasets/nzfapdc', function(req, res) {
  var connection = null;
  r.connect(config.rethinkdb).then(function(conn) {
    connection = conn;
    return r.table('nzfapdc').limit(20).run(connection)
  }).then(function(cursor) {
    return cursor.toArray();
  }).then(function(result) {
    res.send(JSON.stringify(result));
  }).error(handleError(res))
  .finally(function(){connection.close()});
});

app.listen(port, function() {
  console.log('Our app is running on http://localhost:' + port);
});

/*
 * Send back a 500 error
 */
function handleError(res) {
    return function(error) {
        res.send(500, {error: error.message});
    }
}
<commit_msg>Filter data by matched name<commit_after>var express = require('express');
var r = require('rethinkdb');
var app = express();

// set the port of our application
// process.env.PORT lets the port be set by Heroku
var port = process.env.PORT || 8000;

// Load config for app
var config = require(__dirname+"/config.js");

// make express look in the public directory for assets (css/js/img)
app.use(express.static(__dirname+'/public'));

// set the home page route
app.get('/', function(req, res) {
  // ejs render automatically looks in the views folder
  res.sendfile('index.html');
});

app.get('/datasets/nzfapdc/:name', function(req, res) {
  var connection = null;
  r.connect(config.rethinkdb).then(function(conn) {
    connection = conn;
    return r.table('nzfapdc').filter({"Matched Scientific Name": req.params.name}).run(connection)
  }).then(function(cursor) {
    return cursor.toArray();
  }).then(function(result) {
    res.send(JSON.stringify(result));
  }).error(handleError(res))
  .finally(function(){connection.close()});
});

app.listen(port, function() {
  console.log('Our app is running on http://localhost:' + port);
});

/*
 * Send back a 500 error
 */
function handleError(res) {
    return function(error) {
        res.send(500, {error: error.message});
    }
}
<|endoftext|>


<commit_before>/**
Validation server for json files used by the new EMU speech database management system

@author Raphael Winkelmann
*/

var sys = require('sys'),
	myHttp = require('http'),
	path = require('path'),
	fs = require('fs');

var JSONLint = require('json-lint');
var url = require("url");
var queryString = require("querystring");

var Validator = require('jsonschema').Validator;
var v = new Validator();

// global vars
var port = 9263;
var path2schemas = 'schemas/';

myHttp.createServer(function (request, response) {
	if (request.method === 'POST') {
		// the body of the POST is JSON payload.
		var queryData = url.parse(request.url, true).query;
		console.log(request.url);
		var data = '';
		request.addListener('data', function (chunk) {
			data += chunk;
		});
		request.addListener('end', function () {
			var lint = JSONLint(data);
			var mess = {};
			if (lint.error) {
				mess.type = 'ERROR';
				mess.from = 'JSLINT (means badly formated json)';
				mess.ERROR_MESSAGE = lint.error;
				mess.ERROR_LINE = lint.line;
				mess.ERROR_CHARACTER = lint.character;

				response.writeHead(200, {
					'content-type': 'text/plain'
				});
				response.end(JSON.stringify(mess, null, 2));
			} else {
				if (request.url === '/_DBconfig') {
					// console.log('Validating _DBconfig file')
					// console.log(path2schemas + 'globalDBschema.json')
					fs.readFile(path2schemas + 'globalDBschema.json', 'utf8', function (globErr, globData) {

						var validationErrs = v.validate(JSON.parse(data), JSON.parse(globData)).errors;
						if (validationErrs.length === 0) {
							mess.type = 'SUCCESS';
							response.writeHead(200, {
								'content-type': 'text/plain'
							});
							response.end(JSON.stringify(mess, null, 2));
						} else {
							// console.log('VALIDATION ERRORS:');
							// console.log(validationErrs);
							mess.type = 'ERROR';
							mess.from = 'JSONSCHEMA (means does not comply to schema)';
							mess.ERRORS = validationErrs;

							response.writeHead(200, {
								'content-type': 'text/plain'
							});
							response.end(JSON.stringify(mess, null, 2));
						}
					});
				} else if (request.url === '/_annot') {
					// console.log('Validating _DBconfig file');
					// console.log(path2schemas + 'annotationFileSchema.json');
					fs.readFile(path2schemas + 'annotationFileSchema.json', 'utf8', function (annotErr, annotData) {
						var validationErrs = v.validate(JSON.parse(data), JSON.parse(annotData)).errors;
						if (validationErrs.length === 0) {
							mess.type = 'SUCCESS';
							response.writeHead(200, {
								'content-type': 'text/plain'
							});
							response.end(JSON.stringify(mess, null, 2));
						} else {
							// console.log('VALIDATION ERRORS:');
							// console.log(validationErrs);
							mess.type = 'ERROR';
							mess.from = 'JSONSCHEMA (means does not comply to schema)';
							mess.ERRORS = validationErrs;

							response.writeHead(200, {
								'content-type': 'text/plain'
							});
							response.end(JSON.stringify(mess, null, 2));
						}
					});
				}

				// mess.type = 'SUCCESS';
				// response.writeHead(200, {
				// 	'content-type': 'text/plain'
				// });
				// response.end(JSON.stringify(mess, null, 2));
			}
		});
	}
}).listen(port);

sys.puts("Server Running @ http://localhost:" + port);<commit_msg>using tv4 + only _annot validation<commit_after>/**
Validation server for json files used by the new EMU speech database management system

@author Raphael Winkelmann
*/

var sys = require('sys'),
	myHttp = require('http'),
	path = require('path'),
	fs = require('fs');

var JSONLint = require('json-lint');
var url = require("url");
var queryString = require("querystring");

var tv4 = require('tv4');

// global vars
var port = 9263;
var path2schemas = 'schemas/';

myHttp.createServer(function (request, response) {
	if (request.method === 'GET') {
		console.log('not processing GET')
	}
	if (request.method === 'POST') {
		// the body of the POST is JSON payload.
		var queryData = url.parse(request.url, true).query;
		// console.log(request.url);
		var data = '';
		request.addListener('data', function (chunk) {
			data += chunk;
		});
		request.addListener('end', function () {
			var lint = JSONLint(data);
			var mess = {};
			if (lint.error) {
				mess.type = 'ERROR';
				mess.from = 'JSLINT (means badly formated json)';
				mess.ERROR_MESSAGE = lint.error;
				mess.ERROR_LINE = lint.line;
				mess.ERROR_CHARACTER = lint.character;

				response.writeHead(200, {
					'content-type': 'text/plain'
				});
				response.end(JSON.stringify(mess, null, 2));
			} else {
				if (request.url === '/_DBconfig') {
					// console.log('Validating _DBconfig file')
					// console.log(path2schemas + 'globalDBschema.json')
					// fs.readFile(path2schemas + 'globalDBschema.json', 'utf8', function (globErr, globData) {

					// 	var validationErrs = v.validate(JSON.parse(data), JSON.parse(globData)).errors;
					// 	if (validationErrs.length === 0) {
					// 		mess.type = 'SUCCESS';
					// 		response.writeHead(200, {
					// 			'content-type': 'text/plain'
					// 		});
					// 		response.end(JSON.stringify(mess, null, 2));
					// 	} else {
					// 		// console.log('VALIDATION ERRORS:');
					// 		// console.log(validationErrs);
					// 		mess.type = 'ERROR';
					// 		mess.from = 'JSONSCHEMA (means does not comply to schema)';
					// 		mess.ERRORS = validationErrs;

					// 		response.writeHead(200, {
					// 			'content-type': 'text/plain'
					// 		});
					// 		response.end(JSON.stringify(mess, null, 2));
					// 	}
					// });
				} else if (request.url === '/_annot') {
					console.log('Validating _annot file');
					// console.log(path2schemas + 'annotationFileSchema.json');
					fs.readFile(path2schemas + 'annotationFileSchema.json', 'utf8', function (annotSchemaErr, annotSchemaData) {

						if(annotSchemaErr){
							console.log('ERROR reading annotationFileSchema.json')
						}

						var validRes = tv4.validate(JSON.parse(data), JSON.parse(annotSchemaData))

						if (validRes) {
							console.log('SUCCESS')
							mess.type = 'SUCCESS';
							response.writeHead(200, {
								'content-type': 'text/plain'
							});
							response.end(JSON.stringify(mess, null, 2));
						} else {
							mess.type = 'ERROR';
							mess.from = 'JSONSCHEMA (means does not comply to schema)';
							mess.ERRORS = tv4.error;

							response.writeHead(200, {
								'content-type': 'text/plain'
							});
							response.end(JSON.stringify(mess, null, 2));
						}
					});
				}
			}
		});
	}
}).listen(port);

sys.puts("Server Running @ http://localhost:" + port);<|endoftext|>


<commit_before>var express = require('express'),
  requestProxy = require('express-request-proxy'),
  port = process.env.PORT || 3000,
  app = express();

var proxyGitHub = function(request, response){
  (
    requestProxy({
      url: 'https://api.github.com/' + request.param[0],
      hearder: { Authorization: 'token ' + process.env.GITHUB_TOKEN }
    })
  )(request, response);
};

app.get('/github/*', proxyGitHub);

app.use(express.static('./'));

app.get('*', function(request, response) {
  console.log('New request:', request.url);
  response.sendFile('index.html', {root: '.'});
});

app.listen(port, function(){
  console.log('Server started on port ' + port + '!');
});
<commit_msg>header update<commit_after>var express = require('express'),
  requestProxy = require('express-request-proxy'),
  port = process.env.PORT || 3000,
  app = express();

var proxyGitHub = function(request, response){
  (
    requestProxy({
      url: 'https://api.github.com/' + request.param[0],
      header: { Authorization: 'token ' + process.env.GITHUB_TOKEN }
    })
  )(request, response);
};

app.get('/github/*', proxyGitHub);

app.use(express.static('./'));

app.get('*', function(request, response) {
  console.log('New request:', request.url);
  response.sendFile('index.html', {root: '.'});
});

app.listen(port, function(){
  console.log('Server started on port ' + port + '!');
});
<|endoftext|>


<commit_before>/**
 * @file restify-based node.js-server for the wiki
 * @copyright 2013 Berne University of Applied Sciences (BUAS) -- {@link http://bfh.ch}
 * @author Pascal Mainini <pascal.mainini@bfh.ch>
 * @version 0.1.0
 *
 * ! WARNING ! WARNING ! WARNING ! WARNING ! WARNING ! WARNING !
 *
 * THIS FILE HAS NO DEFINITIVE LICENSING INFORMATION.
 * LICENSE IS SUBJECT OF CHANGE ANYTIME SOON - DO NOT DISTRIBUTE!
 *
 * ! WARNING ! WARNING ! WARNING ! WARNING ! WARNING ! WARNING !
 *
 * This is a node.js-server for the wiki based on restify.
 * It mainly implements a REST-API for CRUD-operations on a wiki-page by using the appropriate REST-verbs.
 *
 * The REST-verbs are implemented in the functions api_getPage(), api_savePage(), api_deletePage(),
 * each of these methods works with a page-"object" taking the following form:
 *
 * page {
 *  name:             {String} name of the page <-> filename without .md
 *  content:          {String} markdown-content of the page-file
 *  changeMessage:    {String} message describing the change/delete of the page
 * }
 *
 * There is no assumption made about any of the values in the page-object beeing present and the functions
 * handling these try to take care of that or at least fail gracefully.
 *
 * Internal "communication" is done entirely by passing these objects between callbacks or returning Errors
 * in case they happen.
 *
 * The REST-API currently supports three content-types: text/plain, text/html and application/json.
 * If application/json is requested, the JSON from the api_*-functions is returned "as-is".
 * Otherwise, content-formatting is done by one of the fmt_*-functions according to the requested content-type.
 */

/*jshint node:true, bitwise:true, curly:true, immed:true, indent:2, latedef:true, newcap:true, noarg: true, noempty:true, nonew:true, quotmark:single, undef:true, unused: true, trailing:true, white:false */
/*global DOCUMENT:true, HTML:true, HEAD:true, BODY:true, META:true, TITLE:true, LINK:true, SCRIPT:true, A:true, DIV:true SPAN:true */

// TODO propper NFE syntax?

/***********************************************************
 * Initialisation
 **********************************************************/

'use strict';

// TODO: make options configurable
var AUDITLOG = true;
var LISTENPORT = 8080;
var WIKIDATA = '/tmp/wikidata';
var PAGEPREFIX = '/page';

var CLIENTRESOURCES = {domo: '/node_modules/domo/lib/domo.js',
                        md_converter: '/node_modules/pagedown/Markdown.Converter.js',
                        md_sanitizer: '/node_modules/pagedown/Markdown.Sanitizer.js',
                        md_editor: '/lib/wmd-editor/Markdown.Editor.js',
                        md_styles: '/lib/wmd-editor/wmd-styles.css',
                        jquery: '/lib/jquery-1.9.0.js',
                        jquery_rest: '/lib/jquery.rest.js',
                        wikifunctions: '/static/wikifunctions.js'};

require('domo').global();

var filesystem = require('fs'),
  pagedown = require('pagedown'),
  restify = require('restify'),
  git = require('gitty'),
  mimeparse = require('mimeparse'),
  bunyan = require('bunyan');

var logger = bunyan.createLogger({    // ISSUE stuff logged with logger.debug somehow doesn't appear at all...
  name: 'wiki',
  stream: process.stdout,
  src: true
});

/***********************************************************
 * Function definitions
 **********************************************************/

//////////////////// REST-API

/**
 * Loads the contents of a wikipage (in markdown) from storage.
 *
 * @param   {restify.Request}   req   Request-object given by restify
 * @param   {restify.Response}  res   Response-object given by restify
 * @param   {Function}          next  Next callback in the chain to call
 * @returns {Object}            The return-value of the next callback in the chain or an Error if something failed.
 */
var api_getPage = function (req, res, next) {
  var pageName = req.params.name;
  var fileName = WIKIDATA + '/' + pageName + '.md';

  logger.info({fileName: fileName, page: {name: pageName}}, 'api_getPage: %s', pageName);

  filesystem.exists(fileName, function _fsExists (exists) {
    if (exists) {
      filesystem.readFile(fileName, 'utf8', function _readErr (err, file) {
        if (err) {
          logger.error({error: err, fileName: fileName, page: {name: pageName}}, 'Error occured while loading page %s : %s', pageName, err);
          return next(err);
        } else {
          return next({page: {content: file, name: req.params.name}});
        }
      });
    } else {
      logger.info({fileName: fileName, page: {name: pageName}}, 'Page %s does not exist, returning "null"-content.', pageName);
      return next({page: {content: null, name: pageName}});
    }
  });
};

/**
 * Saves the contents (markdown) of a wikipage to the storage and performs a git-commit.
 *
 * @param   {restify.Request}   req   Request-object given by restify
 * @param   {restify.Response}  res   Response-object given by restify
 * @param   {Function}          next  Next callback in the chain to call
 * @returns {Object}            Forwards to api_getPage WITHOUT returning it (api_getPage calls next callback) or an Error if something fails.
 */
var api_savePage = function (req, res, next) {
  var pageName = req.params.name;
  var page = req.params.page;
  var fileName = WIKIDATA + '/' + pageName + '.md';

  logger.info({fileName: fileName, page: {name: pageName}}, 'api_savePage: %s', pageName);

  // TODO synchronize the whole thing somehow?
  filesystem.writeFile(fileName, page.content, 'utf8', function _writeErr(err) {
    if (err) {
      logger.error({error: err, fileName: fileName, page: {name: pageName}}, 'Error occured while writing page %s : %s', pageName, err);
      return next(err);
    } else {
      var repo = new git.Repository(WIKIDATA);
      var gitFiles = [pageName + '.md'];

//      git.config('user.name', data.user.name, function _gitConfigNameErr (err) {   // BUG overrides global config
//        if (gitSuccess(err, callback)) {
//          git.config('user.email', data.user.email, function _gitConfigEMail(err) {
//            if (gitSuccess(err, callback)) {
              repo.add(gitFiles, function _gitAddErr (err) {
                if (err) {
                  logger.error({error: err, fileName: fileName, page: {name: pageName}}, 'Error occured while adding to git, trying to unstage: %s', err);
                  repo.unstage(gitFiles, function _gitUnstageErr (err) {
                      if(err) {
                        logger.error({error: err, fileName: fileName, page: {name: pageName}}, 'Error occured while unstaging: %s', err);
                        return next(err);
                      }
                    });
                  return next(err);
                } else {
                  repo.commit(page.changeMessage, function _gitCommitErr (err) {
                    if (err) {
                      logger.error({error: err, fileName: fileName, page: {name: pageName}}, 'Error occured while commiting to git, trying to unstage: %s', err);
                      repo.unstage(gitFiles, function _gitUnstageErr (err) {
                          if (err) {
                            logger.error({error: err, fileName: fileName, page: {name: pageName}}, 'Error occured while unstaging: %s', err);
                            return next(err);
                          }
                        });
                      return next(err);
                    } else {
                      logger.info({fileName: fileName, page: {name: pageName}}, 'Successfully committed page %s.', pageName);
                    }
                  });
                }
              });
//            }
//          });
//        }
//      });
    }
  });

  api_getPage(req, res, next);    // reload page from storage and give it back to caller
};

/**
 * Deletes a page from the storage and from git.
 *
 * @param   {restify.Request}   req   Request-object given by restify
 * @param   {restify.Response}  res   Response-object given by restify
 * @param   {Function}          next  Next callback in the chain to call
 * @returns {Object}            The return-value of the next callback in the chain or an Error if something failed.
 */
var api_deletePage = function (req, res, next) {
  var pageName = req.params.name;
  var page = req.params.page;
  var fileName = WIKIDATA + '/' + pageName + '.md';

  var repo = new git.Repository(WIKIDATA);
  var gitFiles = [pageName + '.md'];

  logger.info({fileName: fileName, page: {name: pageName}}, 'api_deletePage: %s', pageName);

//  git.config('user.name', data.user.name, function _gitConfigNameErr (err) {   // BUG overrides global config
//    if (gitSuccess(err, callback)) {
//      git.config('user.email', data.user.email, function _gitConfigEMailErr (err) {
//        if (gitSuccess(err, callback)) {
          repo.remove(gitFiles, function _gitRemoveErr (err) {
            if (err) {
              logger.error({error: err, fileName: fileName, page: {name: pageName}}, 'Error while removing page %s from git: %s', pageName, err);
              return next(err);
            } else {
              repo.commit(page.changeMessage, function _gitCommitErr (err) {
                if (err) {
                  logger.error({error: err, fileName: fileName, page: {name: pageName}}, 'Error while committing to git: %s', err);
                  return next(err);
                } else {
                  filesystem.unlink(fileName, function _unlinkErr (err) {
                    if (err) {
                      logger.error({error: err, fileName: fileName, page: {name: pageName}}, 'Error while deleting page %s : %s', pageName, err);
                      return next(err);
                    } else {
                      logger.info({fileName: fileName, page: {name: pageName}}, 'Successfully deleted page %s.', pageName);
                      return next({page: {content: null, name: pageName}});
                    }
                  });
                }
              });
            }
          });
//        }
//      });
//    }
//  });
};

//////////////////// output-formatters

/**
 * Formatter called by restify when requestor wants text/html.
 *
 * @param   {restify.Request}   req   Request-object given by restify
 * @param   {restify.Response}  res   Response-object given by restify
 * @param   {Object}            body  The effective wiki-page as returned by the api_*-methods as JSON.
 * @returns {String}            HTML-representation of the page (or the Error)
 */
var fmt_Html = function (req, res, body) {

  if (body instanceof Error) {

    return DOCUMENT(
      HTML({lang: 'en'},
        HEAD(
          META({charset: 'utf-8'}),
          TITLE(body.statusCode ? body.statusCode  + ': ' + body.message : body.message)
        ),
        BODY(
          DIV({id: 'wiki_error'}, (body.statusCode ? body.statusCode  + ': ' + body.message : body.message))
        )
      )
    ).outerHTML + '\n';

  } else {

    var pageContent;
    if (body.page.content) {
      pageContent = pagedown.getSanitizingConverter().makeHtml(body.page.content);   // or: new pagedown.Converter();
    } else {
      pageContent = '';
    }

    return DOCUMENT(
      HTML({lang: 'en'},
        HEAD(
          META({charset: 'utf-8'}),
          TITLE(body.page.name),
          LINK({rel: 'stylesheet', type: 'text/css', href: CLIENTRESOURCES.md_styles}),
          SCRIPT({src: CLIENTRESOURCES.domo}),
          SCRIPT({src: CLIENTRESOURCES.md_converter}),
          SCRIPT({src: CLIENTRESOURCES.md_sanitizer}),
          SCRIPT({src: CLIENTRESOURCES.md_editor}),
          SCRIPT({src: CLIENTRESOURCES.jquery}),
          SCRIPT({src: CLIENTRESOURCES.jquery_rest}),
          SCRIPT({src: CLIENTRESOURCES.wikifunctions})
        ),
        BODY(
          DIV({id: 'wiki_header'},
            DIV({id: 'wiki_title'}, body.page.name),
            DIV({id: 'wiki_navi'},
              A({id: 'wiki_button_edit', href: '#'}, 'edit'),
              SPAN({id: 'wiki_button_delete'}, ' | ', A({href: '#'}, 'delete'))
            )
          ),
          DIV({id: 'wiki_editor'}),
          DIV({id: 'wiki_content'}, '%#%PAGECONTENT%#%')
        )
      )
    ).outerHTML.replace('%#%PAGECONTENT%#%', pageContent) + '\n';   // or: new pagedown.Converter();

  }
};

/**
 * Formatter called by restify when requestor wants text/plain.
 *
 * @param   {restify.Request}   req   Request-object given by restify
 * @param   {restify.Response}  res   Response-object given by restify
 * @param   {Object}            body  The effective wiki-page as returned by the api_*-methods as JSON.
 * @returns {String}            Plaintext-representation of the page (or the Error)
 */
var fmt_Text = function (req, res, body) {
  if (body instanceof Error) {
    return 'Error!\n\n' +
      (body.statusCode ? 'Statuscode: ' + body.statusCode + '\n' : '') +
      'Message: ' + body.message + '\n';
  } else {
    return 'Title: ' + body.page.name +
      '\n------------------ START CONTENT --------------------\n' +
      body.page.content +
      '\n------------------- END CONTENT ---------------------\n';
  }
};

/***********************************************************
 * Main application
 **********************************************************/

//////////////////// setup server

var server = restify.createServer({
  formatters: {
    'text/html': fmt_Html,
    'text/plain': fmt_Text
    // application/json gets implicitly handled by restify
  }
});  // TODO SSL...

//// server: events
if (AUDITLOG) {
  server.on('after', restify.auditLogger({log: logger}));
}

// ISSUE workaround for seemingly improper accept-header-evaluation by restify...
server.pre(function _mimeFix (req, res, next) {
  req.headers.accept = mimeparse.bestMatch(['text/plain','text/html','application/json'], req.headers.accept);
  return next();
});

//// server: general handlers
server.use(restify.requestLogger());    // ISSUE requestLogger logs NOTHING!
server.use(restify.bodyParser());
server.use(restify.acceptParser(server.acceptable));

//// server: static content
server.get(/\/static\/?.*/, restify.serveStatic({directory: '.'}));   // ISSUE serveStatic doesn't emit NotFound-event...
server.get(/\/lib\/?.*/, restify.serveStatic({directory: '.'}));
server.get(/\/node_modules\/?.*/, restify.serveStatic({directory: '.'}));

//// server: page API
server.get(PAGEPREFIX + '/:name', api_getPage);   // TODO GET redirect / to a mainpage or provide a list of pages?
server.put(PAGEPREFIX + '/:name', api_savePage);
server.post(PAGEPREFIX + '/:name', api_savePage);
server.del(PAGEPREFIX + '/:name', api_deletePage);

//// start server
server.listen(LISTENPORT, function listenCallback () {
  logger.info({serverName: server.name, serverURL: server.url}, '%s listening at %s.', server.name, server.url);
});
<commit_msg>added todo<commit_after>/**
 * @file restify-based node.js-server for the wiki
 * @copyright 2013 Berne University of Applied Sciences (BUAS) -- {@link http://bfh.ch}
 * @author Pascal Mainini <pascal.mainini@bfh.ch>
 * @version 0.1.0
 *
 * ! WARNING ! WARNING ! WARNING ! WARNING ! WARNING ! WARNING !
 *
 * THIS FILE HAS NO DEFINITIVE LICENSING INFORMATION.
 * LICENSE IS SUBJECT OF CHANGE ANYTIME SOON - DO NOT DISTRIBUTE!
 *
 * ! WARNING ! WARNING ! WARNING ! WARNING ! WARNING ! WARNING !
 *
 * This is a node.js-server for the wiki based on restify.
 * It mainly implements a REST-API for CRUD-operations on a wiki-page by using the appropriate REST-verbs.
 *
 * The REST-verbs are implemented in the functions api_getPage(), api_savePage(), api_deletePage(),
 * each of these methods works with a page-"object" taking the following form:
 *
 * page {
 *  name:             {String} name of the page <-> filename without .md
 *  content:          {String} markdown-content of the page-file
 *  changeMessage:    {String} message describing the change/delete of the page
 * }
 *
 * There is no assumption made about any of the values in the page-object beeing present and the functions
 * handling these try to take care of that or at least fail gracefully.
 *
 * Internal "communication" is done entirely by passing these objects between callbacks or returning Errors
 * in case they happen.
 *
 * The REST-API currently supports three content-types: text/plain, text/html and application/json.
 * If application/json is requested, the JSON from the api_*-functions is returned "as-is".
 * Otherwise, content-formatting is done by one of the fmt_*-functions according to the requested content-type.
 */

/*jshint node:true, bitwise:true, curly:true, immed:true, indent:2, latedef:true, newcap:true, noarg: true, noempty:true, nonew:true, quotmark:single, undef:true, unused: true, trailing:true, white:false */
/*global DOCUMENT:true, HTML:true, HEAD:true, BODY:true, META:true, TITLE:true, LINK:true, SCRIPT:true, A:true, DIV:true SPAN:true */

// TODO propper NFE syntax?

/***********************************************************
 * Initialisation
 **********************************************************/

'use strict';

// TODO: make options configurable
var AUDITLOG = true;
var LISTENPORT = 8080;
var WIKIDATA = '/tmp/wikidata';
var PAGEPREFIX = '/page';

var CLIENTRESOURCES = {domo: '/node_modules/domo/lib/domo.js',
                        md_converter: '/node_modules/pagedown/Markdown.Converter.js',
                        md_sanitizer: '/node_modules/pagedown/Markdown.Sanitizer.js',
                        md_editor: '/lib/wmd-editor/Markdown.Editor.js',
                        md_styles: '/lib/wmd-editor/wmd-styles.css',
                        jquery: '/lib/jquery-1.9.0.js',
                        jquery_rest: '/lib/jquery.rest.js',
                        wikifunctions: '/static/wikifunctions.js'};

require('domo').global();

var filesystem = require('fs'),
  pagedown = require('pagedown'),
  restify = require('restify'),
  git = require('gitty'),
  mimeparse = require('mimeparse'),
  bunyan = require('bunyan');

var logger = bunyan.createLogger({    // ISSUE stuff logged with logger.debug somehow doesn't appear at all...
  name: 'wiki',
  stream: process.stdout,
  src: true
});

/***********************************************************
 * Function definitions
 **********************************************************/

//////////////////// REST-API

/**
 * Loads the contents of a wikipage (in markdown) from storage.
 *
 * @param   {restify.Request}   req   Request-object given by restify
 * @param   {restify.Response}  res   Response-object given by restify
 * @param   {Function}          next  Next callback in the chain to call
 * @returns {Object}            The return-value of the next callback in the chain or an Error if something failed.
 */
var api_getPage = function (req, res, next) {
  var pageName = req.params.name;
  var fileName = WIKIDATA + '/' + pageName + '.md';

  logger.info({fileName: fileName, page: {name: pageName}}, 'api_getPage: %s', pageName);

  filesystem.exists(fileName, function _fsExists (exists) {
    if (exists) {
      filesystem.readFile(fileName, 'utf8', function _readErr (err, file) {
        if (err) {
          logger.error({error: err, fileName: fileName, page: {name: pageName}}, 'Error occured while loading page %s : %s', pageName, err);
          return next(err);
        } else {
          return next({page: {content: file, name: req.params.name}});
        }
      });
    } else {
      logger.info({fileName: fileName, page: {name: pageName}}, 'Page %s does not exist, returning "null"-content.', pageName);
      return next({page: {content: null, name: pageName}});
    }
  });
};

/**
 * Saves the contents (markdown) of a wikipage to the storage and performs a git-commit.
 *
 * @param   {restify.Request}   req   Request-object given by restify
 * @param   {restify.Response}  res   Response-object given by restify
 * @param   {Function}          next  Next callback in the chain to call
 * @returns {Object}            Forwards to api_getPage WITHOUT returning it (api_getPage calls next callback) or an Error if something fails.
 */
var api_savePage = function (req, res, next) {
  var pageName = req.params.name;
  var page = req.params.page;
  var fileName = WIKIDATA + '/' + pageName + '.md';

  logger.info({fileName: fileName, page: {name: pageName}}, 'api_savePage: %s', pageName);

  // TODO synchronize the whole thing somehow?
  filesystem.writeFile(fileName, page.content, 'utf8', function _writeErr(err) {
    if (err) {
      logger.error({error: err, fileName: fileName, page: {name: pageName}}, 'Error occured while writing page %s : %s', pageName, err);
      return next(err);
    } else {
      var repo = new git.Repository(WIKIDATA);
      var gitFiles = [pageName + '.md'];

//      git.config('user.name', data.user.name, function _gitConfigNameErr (err) {   // BUG overrides global config
//        if (gitSuccess(err, callback)) {
//          git.config('user.email', data.user.email, function _gitConfigEMail(err) {
//            if (gitSuccess(err, callback)) {
              repo.add(gitFiles, function _gitAddErr (err) {
                if (err) {
                  logger.error({error: err, fileName: fileName, page: {name: pageName}}, 'Error occured while adding to git, trying to unstage: %s', err);
                  repo.unstage(gitFiles, function _gitUnstageErr (err) {
                      if(err) {
                        logger.error({error: err, fileName: fileName, page: {name: pageName}}, 'Error occured while unstaging: %s', err);
                        return next(err);
                      }
                    });
                  return next(err);
                } else {
                  repo.commit(page.changeMessage, function _gitCommitErr (err) {
                    if (err) {
                      logger.error({error: err, fileName: fileName, page: {name: pageName}}, 'Error occured while commiting to git, trying to unstage: %s', err);
                      repo.unstage(gitFiles, function _gitUnstageErr (err) {
                          if (err) {
                            logger.error({error: err, fileName: fileName, page: {name: pageName}}, 'Error occured while unstaging: %s', err);
                            return next(err);
                          }
                        });
                      return next(err);
                    } else {
                      logger.info({fileName: fileName, page: {name: pageName}}, 'Successfully committed page %s.', pageName);
                    }
                  });
                }
              });
//            }
//          });
//        }
//      });
    }
  });

  api_getPage(req, res, next);    // reload page from storage and give it back to caller
};

/**
 * Deletes a page from the storage and from git.
 *
 * @param   {restify.Request}   req   Request-object given by restify
 * @param   {restify.Response}  res   Response-object given by restify
 * @param   {Function}          next  Next callback in the chain to call
 * @returns {Object}            The return-value of the next callback in the chain or an Error if something failed.
 */
var api_deletePage = function (req, res, next) {
  var pageName = req.params.name;
  var page = req.params.page;
  var fileName = WIKIDATA + '/' + pageName + '.md';

  var repo = new git.Repository(WIKIDATA);
  var gitFiles = [pageName + '.md'];

  logger.info({fileName: fileName, page: {name: pageName}}, 'api_deletePage: %s', pageName);

//  git.config('user.name', data.user.name, function _gitConfigNameErr (err) {   // BUG overrides global config
//    if (gitSuccess(err, callback)) {
//      git.config('user.email', data.user.email, function _gitConfigEMailErr (err) {
//        if (gitSuccess(err, callback)) {
          repo.remove(gitFiles, function _gitRemoveErr (err) {
            if (err) {
              logger.error({error: err, fileName: fileName, page: {name: pageName}}, 'Error while removing page %s from git: %s', pageName, err);
              return next(err);
            } else {
              repo.commit(page.changeMessage, function _gitCommitErr (err) {
                if (err) {
                  logger.error({error: err, fileName: fileName, page: {name: pageName}}, 'Error while committing to git: %s', err);
                  return next(err);
                } else {
                  filesystem.unlink(fileName, function _unlinkErr (err) {
                    if (err) {
                      logger.error({error: err, fileName: fileName, page: {name: pageName}}, 'Error while deleting page %s : %s', pageName, err);
                      return next(err);
                    } else {
                      logger.info({fileName: fileName, page: {name: pageName}}, 'Successfully deleted page %s.', pageName);
                      return next({page: {content: null, name: pageName}});
                    }
                  });
                }
              });
            }
          });
//        }
//      });
//    }
//  });
};

//////////////////// output-formatters

/**
 * Formatter called by restify when requestor wants text/html.
 *
 * @param   {restify.Request}   req   Request-object given by restify
 * @param   {restify.Response}  res   Response-object given by restify
 * @param   {Object}            body  The effective wiki-page as returned by the api_*-methods as JSON.
 * @returns {String}            HTML-representation of the page (or the Error)
 */
var fmt_Html = function (req, res, body) {

  if (body instanceof Error) {

    return DOCUMENT(
      HTML({lang: 'en'},
        HEAD(
          META({charset: 'utf-8'}),
          TITLE(body.statusCode ? body.statusCode  + ': ' + body.message : body.message)
        ),
        BODY(
          DIV({id: 'wiki_error'}, (body.statusCode ? body.statusCode  + ': ' + body.message : body.message))
        )
      )
    ).outerHTML + '\n';

  } else {

    var pageContent;
    if (body.page.content) {
      pageContent = pagedown.getSanitizingConverter().makeHtml(body.page.content);   // or: new pagedown.Converter();
    } else {
      pageContent = '';
    }

    return DOCUMENT(
      HTML({lang: 'en'},
        HEAD(
          META({charset: 'utf-8'}),
          TITLE(body.page.name),
          LINK({rel: 'stylesheet', type: 'text/css', href: CLIENTRESOURCES.md_styles}),
          SCRIPT({src: CLIENTRESOURCES.domo}),
          SCRIPT({src: CLIENTRESOURCES.md_converter}),
          SCRIPT({src: CLIENTRESOURCES.md_sanitizer}),
          SCRIPT({src: CLIENTRESOURCES.md_editor}),
          SCRIPT({src: CLIENTRESOURCES.jquery}),
          SCRIPT({src: CLIENTRESOURCES.jquery_rest}),
          SCRIPT({src: CLIENTRESOURCES.wikifunctions})
        ),
        BODY(
          DIV({id: 'wiki_header'},
            DIV({id: 'wiki_title'}, body.page.name),
            DIV({id: 'wiki_navi'},
              A({id: 'wiki_button_edit', href: '#'}, 'edit'),
              SPAN({id: 'wiki_button_delete'}, ' | ', A({href: '#'}, 'delete'))
            )
          ),
          DIV({id: 'wiki_editor'}),
          DIV({id: 'wiki_content'}, '%#%PAGECONTENT%#%')
        )
      )
    ).outerHTML.replace('%#%PAGECONTENT%#%', pageContent) + '\n';   // or: new pagedown.Converter();

  }
};

/**
 * Formatter called by restify when requestor wants text/plain.
 *
 * @param   {restify.Request}   req   Request-object given by restify
 * @param   {restify.Response}  res   Response-object given by restify
 * @param   {Object}            body  The effective wiki-page as returned by the api_*-methods as JSON.
 * @returns {String}            Plaintext-representation of the page (or the Error)
 */
var fmt_Text = function (req, res, body) {
  if (body instanceof Error) {
    return 'Error!\n\n' +
      (body.statusCode ? 'Statuscode: ' + body.statusCode + '\n' : '') +
      'Message: ' + body.message + '\n';
  } else {
    return 'Title: ' + body.page.name +
      '\n------------------ START CONTENT --------------------\n' +
      body.page.content +
      '\n------------------- END CONTENT ---------------------\n';
  }
};

/***********************************************************
 * Main application
 **********************************************************/

//////////////////// setup server

var server = restify.createServer({
  formatters: {
    'text/html': fmt_Html,
    'text/plain': fmt_Text
//    'text/x-markdown': fmt_Markdown   TODO implement text/x-markdown
    // application/json gets implicitly handled by restify
  }
});  // TODO SSL...

//// server: events
if (AUDITLOG) {
  server.on('after', restify.auditLogger({log: logger}));
}

// ISSUE workaround for seemingly improper accept-header-evaluation by restify...
server.pre(function _mimeFix (req, res, next) {
  req.headers.accept = mimeparse.bestMatch(['text/plain','text/html','application/json'], req.headers.accept);
  return next();
});

//// server: general handlers
server.use(restify.requestLogger());    // ISSUE requestLogger logs NOTHING!
server.use(restify.bodyParser());
server.use(restify.acceptParser(server.acceptable));

//// server: static content
server.get(/\/static\/?.*/, restify.serveStatic({directory: '.'}));   // ISSUE serveStatic doesn't emit NotFound-event...
server.get(/\/lib\/?.*/, restify.serveStatic({directory: '.'}));
server.get(/\/node_modules\/?.*/, restify.serveStatic({directory: '.'}));

//// server: page API
server.get(PAGEPREFIX + '/:name', api_getPage);   // TODO GET redirect / to a mainpage or provide a list of pages?
server.put(PAGEPREFIX + '/:name', api_savePage);
server.post(PAGEPREFIX + '/:name', api_savePage);
server.del(PAGEPREFIX + '/:name', api_deletePage);

//// start server
server.listen(LISTENPORT, function listenCallback () {
  logger.info({serverName: server.name, serverURL: server.url}, '%s listening at %s.', server.name, server.url);
});
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const express = require('express');
const expressValidator = require('express-validator');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const config = require('./config');
const authRoute = require('./api/routes/auth.route');
const checkAuthentication = require('./api/middlewares/authentication.middleware');
const checkContentType = require('./api/middlewares/content-type.middleware');
const notFound = require('./api/middlewares/not-found.middleware');

const app = express();

mongoose.Promise = global.Promise;
mongoose.connect(`mongodb://${config.host}/${config.database}`, err => {
  if (err) {
    return console.log(`Error connecting with MongoDB: ${err}`)
  }
  console.log('MongoDB connected');
});

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(expressValidator());
app.use(checkContentType);

authRoute(app);

app.use(checkAuthentication);

app.use((req, res, next) => {
  req.checkQuery('page', "Must be an integer with '1' as min value")
    .optional().isInt({ min: 1 });
  req.checkQuery('limit', "Must be an integer with '1' as min value")
    .optional().isInt({ min: 1 });

  req.getValidationResult()
    .then(errors => {
      if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
      }
      return next();
    });
});

const routesPath = './api/routes/';
fs.readdirSync(routesPath).forEach(filename => {
  if (filename !== 'auth.route.js') {
    const route = require(routesPath + filename);
    route(app);
  }
});

app.use(notFound);

app.listen(config.port, err => {
  if (err) {
    return console.log(`Error starting REST API server: ${err}`)
  }
  console.log('REST API server started on: '
    + `${config.protocol}://${config.host}:${config.port}`);
});

module.exports = app;
<commit_msg>Move query param middleware to correct folder<commit_after>'use strict';

const fs = require('fs');
const express = require('express');
const expressValidator = require('express-validator');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const config = require('./config');
const authRoute = require('./api/routes/auth.route');
const checkAuthentication = require('./api/middlewares/authentication.middleware');
const checkContentType = require('./api/middlewares/content-type.middleware');
const checkQueryParams = require('./api/middlewares/query-param.middleware');
const notFound = require('./api/middlewares/not-found.middleware');

const app = express();

mongoose.Promise = global.Promise;
mongoose.connect(`mongodb://${config.host}/${config.database}`, err => {
  if (err) {
    return console.log(`Error connecting with MongoDB: ${err}`)
  }
  console.log('MongoDB connected');
});

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(expressValidator());
app.use(checkContentType);

authRoute(app);

app.use(checkAuthentication);
app.use(checkQueryParams);

const routesPath = './api/routes/';
fs.readdirSync(routesPath).forEach(filename => {
  if (filename !== 'auth.route.js') {
    const route = require(routesPath + filename);
    route(app);
  }
});

app.use(notFound);

app.listen(config.port, err => {
  if (err) {
    return console.log(`Error starting REST API server: ${err}`)
  }
  console.log('REST API server started on: '
    + `${config.protocol}://${config.host}:${config.port}`);
});

module.exports = app;
<|endoftext|>


<commit_before>/** hapijs default hello world **/

'use strict';

const Hapi = require('hapi');

// Create a server with a host and port
const server = new Hapi.Server();
server.connection({
    port: 8000
});

// Add the route
server.route({
    method: 'GET',
    path:'/hello',
    handler: function (request, reply) {

        return reply('hello world');
    }
});

// Start the server
server.start((err) => {

    if (err) {
        throw err;
    }
    console.log('Server running at:', server.info.uri);
});<commit_msg>set port to read $PORT assigned by heroku<commit_after>/** hapijs default hello world **/

'use strict';

const Hapi = require('hapi');

// Create a server with a host and port
const server = new Hapi.Server();
server.connection({
    port: process.env.PORT || 8000
});

// Add the route
server.route({
    method: 'GET',
    path:'/hello',
    handler: function (request, reply) {

        return reply('hello world');
    }
});

// Start the server
server.start((err) => {

    if (err) {
        throw err;
    }
    console.log('Server running at:', server.info.uri);
});<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
const conString = 'postgres://localhost:5432';
const client = new pg.Client(conString);

app.use(express.static('./'));
app.get('/', function(request, response) {
  response.sendFile('/index.html', {root: '.'});
});

app.listen(PORT, function() {
  console.log(`server up on ${PORT}`);
});<commit_msg>more fucking around..<commit_after>'use strict';

const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
const conString = 'postgres://localhost:5432';

app.use(express.static('./'));
app.get('/', function(request, response) {
  response.sendFile('/index.html', {root: '.'});
});

app.listen(PORT, function() {
  console.log(`server up on ${PORT}`);
});<|endoftext|>