<commit_before>var preContestControllers = angular.module('preContestControllers', []);

preContestControllers.controller('MainCtrl', ['$scope', '$http', '$timeout',
    function ($scope, $http, $timeout, $window) {
      function sync () {
        $http.get('api/v1/updates').success(function (data) {
          if ($scope.rawTime < parseInt(data['remaining_time'])) {
            $window.location.reload();
          }
          $scope.rawTime = data['remaining_time'];
          $scope.remainingTime = moment($scope.rawTime);
          $timeout(sync, 5000);
          for (i = 1000; i <= 4000; i += 1000) {
            $timeout(tick, i);
          }
        });
      }

      function tick () {
        $scope.rawTime -= 1;
        if ($scope.rawTime < 0) {
          $window.location.reload();
        } else {
          $scope.remainingTime = moment($scope.rawTime);
        }
      }

      sync();
    }]);

preContestControllers.controller('HomeCtrl', ['$scope', '$http',
    function ($scope, $http) {
    }]);

var contestControllers = angular.module('contestControllers', []);
var probIds = [];
var probNames = [];

contestControllers.controller('MainCtrl', ['$scope', '$http', '$interval', '$rootScope',
    function ($scope, $http, $interval, $window) {
      $http.get('api/v1/metadata').success(function (data) {
        $scope.probIds = probIds = data['prob_ids'];
        $scope.probNames = probNames = data['prob_names'];
        $scope.probContents = data['prob_contents'];
      });

      function sync () {
        $http.get('api/v1/updates').success(function (data) {
          $scope.rawTime = data['remaining_time'];
          $scope.scoreboard = data['scoreboard'];
          $scope.clarifications = data['clarifications'];
          $scope.remainingTime = moment($scope.rawTime);
          $interval(tick, 1000, 29);
        });
      }

      function tick () {
        $scope.rawTime -= 1;
        if ($scope.rawTime >= 0) {
          $scope.remainingTime = moment($scope.rawTime);
        }
      }

      sync();
      $interval(sync, 30000);
    }]);

contestControllers.controller('HomeCtrl', ['$scope', '$http',
    function ($scope, $http) {
    }]);

var whitelist = [];
var allClarifications = [];
var radioModel = 'Active';

contestControllers.controller('AdminCtrl', ['$scope', '$http', '$cookies', '$window', '$modal', '$timeout',
    function ($scope, $http, $cookies, $window, $modal, $timeout) {
      function sync () {
        $http.get('api/v1/admin/whitelist').success(function (data) {
          $scope.whitelist = data;
        });
        $http.get('api/v1/admin/clarifications').success(function (data) {
          $scope.allClarifications = data;
        });
        $http.get('api/v1/admin/frozen').success(function (data) {
          $scope.boardIsFrozen = data;
          if($scope.boardIsFrozen === "false") {
            $scope.radioModel = 'Active';
          }
          else {
            $scope.radioModel = 'Frozen';
          }
        });
        $timeout(sync, 5000);
      }
      sync();

      $scope.rejudgeProblem = function(problemId) {
        submit_url = 'api/v1/admin/rejudge';
        submit_data = { '_xsrf': $cookies._xsrf, 'probId': problemId };
        $http({
          method  : 'POST',
          url     : submit_url,
          data    : $.param(submit_data),
          headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
        }).success(function(data) {});
      }

      $scope.processAddTimeInput = function(numMin) {
        submit_url = 'api/v1/admin/add_time';
        submit_data = { '_xsrf': $cookies._xsrf, 'numMin': numMin };
        $http({
          method  : 'POST',
          url     : submit_url,
          data    : $.param(submit_data),
          headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
        }).success(function(data) {});
        $scope.addTimeTextBox = null;
      }

      $scope.processClarifResponse = function(respNum, clarifNum) {
        submit_url = 'api/v1/admin/clarifications';
        var respString = '';
        if(respNum == 2) {
          $scope.open(respNum, clarifNum)
        }
        else {
          submit_data = { '_xsrf': $cookies._xsrf, 'respNum': respNum, 'clarifNum': clarifNum, 'respString': '' };
          $http({
            method  : 'POST',
            url     : submit_url,
            data    : $.param(submit_data),
            headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
          }).success(function(data) {
            if (data) {
              $window.alert("clarif reply successfully submitted");
            }
          });
        }
      }

      $scope.processAddAdminForm = function(newAdmin) {
        submit_url = 'api/v1/admin/whitelist';
        submit_data = { '_xsrf': $cookies._xsrf, 'newAdmin': newAdmin };
        $http({
          method  : 'POST',
          url     : submit_url,
          data    : $.param(submit_data),
          headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
        }).success(function(data) {});
        $scope.addAdminTextBox = null;
      }

      $scope.changeState = function(state) {
        submit_url = 'api/v1/admin/frozen';
        submit_data = { '_xsrf': $cookies._xsrf, 'state': state };
        $http({
          method  : 'POST',
          url     : submit_url,
          data    : $.param(submit_data),
          headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
        }).success(function(data) {
          if (data) {
            $window.alert("changed state");
          }
        });
      }

      $scope.open = function(respNum, clarifNum) {
        var modalInstance = $modal.open({
          templateUrl: 'myModalContent.html',
          controller: 'ModalInstanceCtrl',
          resolve: {
            respNum: function () {
              return respNum;
            },
            clarifNum: function() {
              return clarifNum;
            }
          }
        });

        modalInstance.result.then(function (response) {
          submit_url = 'api/v1/admin/clarifications'
          response['_xsrf'] = $cookies._xsrf;
              $http({
                method  : 'POST',
                url     : submit_url,
                data    : $.param(response),
                headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
              }).success(function(data) {
                if (data) {
                  $window.alert("clarif reply successfully submitted");
                }
              });
        }, function () {
        });
      };
            var tabClasses;

      function initTabs() {
        tabClasses = ["","","",""];
      }

      $scope.getTabClass = function (tabNum) {
        return tabClasses[tabNum];
      };

      $scope.getTabPaneClass = function (tabNum) {
        return "tab-pane " + tabClasses[tabNum];
      }

      $scope.setActiveTab = function (tabNum) {
        initTabs();
        tabClasses[tabNum] = "active";
      };

      initTabs();
      $scope.setActiveTab(1);
    }]);

contestControllers.controller('ModalInstanceCtrl', function ($scope, $modalInstance, respNum, clarifNum) {

  $scope.ok = function () {
    $modalInstance.close({
      'respNum': respNum,
      'clarifNum': clarifNum,
      'response': $scope.response,
    });
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});

contestControllers.controller('ProblemCtrl', ['$scope', '$http', '$rootScope', '$window', '$cookies', '$interval',
    function ($scope, $http, $rootScope, $window, $cookies, $interval) {
      var tabClasses;

      $scope.files = {};
      $scope.files.output = [];
      $scope.files.source = [];
      i = 0;
      for (probId in probIds) {
        $scope.files.output.push("");
        $scope.files.source.push("");
      }
      if (typeof $rootScope.showSubmit == 'undefined') {
        $rootScope.showSubmit = [];
        $rootScope.ttl = [];
        $rootScope.ttlText = [];
        $rootScope.tick = [];
        for (probId in probIds) {
          $rootScope.showSubmit.push(false);
          $rootScope.ttl.push(-1);
          $rootScope.ttlText.push("");
          $rootScope.tick.push(null);
        }
      }

      function initTabs() {
        tabClasses = [];
        $scope.open = [];
        for (probId in probIds) {
          tabClasses.push("");
          $scope.open.push(false);
        }
      }

      $scope.getTabClass = function (tabNum) {
        return tabClasses[tabNum];
      };

      $scope.getTabPaneClass = function (tabNum) {
        return "tab-pane " + tabClasses[tabNum];
      };

      $scope.setActiveTab = function (tabNum) {
        initTabs();
        tabClasses[tabNum] = "active panel-primary";
        $rootScope.activeTab = tabNum;
        $scope.open[tabNum - 1] = true;
      };

      if (typeof $rootScope.activeTab == 'undefined') {
        $scope.setActiveTab(1);
      } else {
        $scope.setActiveTab($rootScope.activeTab);
      }

      $scope.clarif = {}
      $scope.processClarifForm = function (index) {
        submitUrl = 'api/v1/submit/' + probIds[index] + '/clarification';
        submitData = { '_xsrf': $cookies._xsrf, 'content': $scope.clarif[index] };
        $http({
          method  : 'POST',
          url     : submitUrl,
          data    : $.param(submitData),
          headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
        }).success(function (data) {
          if (data) {
            $window.alert("Clarification submitted successfully!");
            $scope.clarif[probId] = "";
          }
        });
        $scope.clarif[index] = null;
      };

      function tick (index) {
        $rootScope.ttl[index] -= 1;
        $rootScope.ttlText[index] = momentMinutes($rootScope.ttl[index]);
        if ($rootScope.ttl[index] <= 0) {
          $rootScope.showSubmit[index] = false;
          if ($rootScope.tick[index] != null) {
            $interval.cancel($rootScope.tick[index]);
            $rootScope.tick[index] = null;
          }
        }
      }

      $scope.getPermit = function (index) {
        permitUrl = 'api/v1/permits';
        permitData = { '_xsrf': $cookies._xsrf, 'content': probIds[index] };
        $http({
          method  : 'POST',
          url     : permitUrl,
          data    : $.param(permitData),
          headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
        }).success(function (data) {
          if ($rootScope.tick[index] != null) {
            $interval.cancel($rootScope.tick[index]);
            $rootScope.tick[index] = null;
          }
          $rootScope.showSubmit[index] = true;
          $rootScope.ttl[index] = data;
          $rootScope.ttlText[index] = momentMinutes($rootScope.ttl[index]);
          $rootScope.tick[index] = $interval(function () {
            tick(index);
          }, 1000, data);
        }).error(function (data, status, headers, config) {
          if (status == 403) {
            $window.alert("You are out of permits!");
          }
        });
      };

      $scope.processSubmitForm = function (index) {
        submitUrl = 'api/v1/submit/' + probIds[index] + '/solution';
        submitData = { '_xsrf': $cookies._xsrf,
                       'outputFile': $scope.files.output[index],
                       'sourceFile': $scope.files.source[index], };
        $rootScope.showSubmit[index] = false;
        $rootScope.ttl[index] = 0;
        if ($rootScope.tick[index] != null) {
          $interval.cancel($rootScope.tick[index]);
          $rootScope.tick[index] = null;
        }
        $http({
          method  : 'POST',
          url     : submitUrl,
          data    : $.param(submitData),
          headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
        }).success(function (data) {
          if (data) {
            $window.alert("Solution accepted!");
          } else {
            $window.alert("Solution incorrect!");
          }
        });
      };
    }]);

contestControllers.controller('ScoreboardCtrl', ['$scope', '$http',
    function ($scope, $http) {
    }]);
<commit_msg>clear clarification box AFTER successful submit; show submitted clarification right away<commit_after>var preContestControllers = angular.module('preContestControllers', []);

preContestControllers.controller('MainCtrl', ['$scope', '$http', '$timeout',
    function ($scope, $http, $timeout, $window) {
      function sync () {
        $http.get('api/v1/updates').success(function (data) {
          if ($scope.rawTime < parseInt(data['remaining_time'])) {
            $window.location.reload();
          }
          $scope.rawTime = data['remaining_time'];
          $scope.remainingTime = moment($scope.rawTime);
          $timeout(sync, 5000);
          for (i = 1000; i <= 4000; i += 1000) {
            $timeout(tick, i);
          }
        });
      }

      function tick () {
        $scope.rawTime -= 1;
        if ($scope.rawTime < 0) {
          $window.location.reload();
        } else {
          $scope.remainingTime = moment($scope.rawTime);
        }
      }

      sync();
    }]);

preContestControllers.controller('HomeCtrl', ['$scope', '$http',
    function ($scope, $http) {
    }]);

var contestControllers = angular.module('contestControllers', []);
var probIds = [];
var probNames = [];

contestControllers.controller('MainCtrl', ['$scope', '$http', '$interval', '$rootScope',
    function ($scope, $http, $interval, $window) {
      $http.get('api/v1/metadata').success(function (data) {
        $scope.probIds = probIds = data['prob_ids'];
        $scope.probNames = probNames = data['prob_names'];
        $scope.probContents = data['prob_contents'];
      });

      function sync () {
        $http.get('api/v1/updates').success(function (data) {
          $scope.rawTime = data['remaining_time'];
          $scope.scoreboard = data['scoreboard'];
          $scope.clarifications = data['clarifications'];
          $scope.remainingTime = moment($scope.rawTime);
          $interval(tick, 1000, 29);
        });
      }

      function tick () {
        $scope.rawTime -= 1;
        if ($scope.rawTime >= 0) {
          $scope.remainingTime = moment($scope.rawTime);
        }
      }

      sync();
      $interval(sync, 30000);
    }]);

contestControllers.controller('HomeCtrl', ['$scope', '$http',
    function ($scope, $http) {
    }]);

var whitelist = [];
var allClarifications = [];
var radioModel = 'Active';

contestControllers.controller('AdminCtrl', ['$scope', '$http', '$cookies', '$window', '$modal', '$timeout',
    function ($scope, $http, $cookies, $window, $modal, $timeout) {
      function sync () {
        $http.get('api/v1/admin/whitelist').success(function (data) {
          $scope.whitelist = data;
        });
        $http.get('api/v1/admin/clarifications').success(function (data) {
          $scope.allClarifications = data;
        });
        $http.get('api/v1/admin/frozen').success(function (data) {
          $scope.boardIsFrozen = data;
          if($scope.boardIsFrozen === "false") {
            $scope.radioModel = 'Active';
          }
          else {
            $scope.radioModel = 'Frozen';
          }
        });
        $timeout(sync, 5000);
      }
      sync();

      $scope.rejudgeProblem = function(problemId) {
        submit_url = 'api/v1/admin/rejudge';
        submit_data = { '_xsrf': $cookies._xsrf, 'probId': problemId };
        $http({
          method  : 'POST',
          url     : submit_url,
          data    : $.param(submit_data),
          headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
        }).success(function(data) {});
      }

      $scope.processAddTimeInput = function(numMin) {
        submit_url = 'api/v1/admin/add_time';
        submit_data = { '_xsrf': $cookies._xsrf, 'numMin': numMin };
        $http({
          method  : 'POST',
          url     : submit_url,
          data    : $.param(submit_data),
          headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
        }).success(function(data) {});
        $scope.addTimeTextBox = null;
      }

      $scope.processClarifResponse = function(respNum, clarifNum) {
        submit_url = 'api/v1/admin/clarifications';
        var respString = '';
        if(respNum == 2) {
          $scope.open(respNum, clarifNum)
        }
        else {
          submit_data = { '_xsrf': $cookies._xsrf, 'respNum': respNum, 'clarifNum': clarifNum, 'respString': '' };
          $http({
            method  : 'POST',
            url     : submit_url,
            data    : $.param(submit_data),
            headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
          }).success(function(data) {
            if (data) {
              $window.alert("clarif reply successfully submitted");
            }
          });
        }
      }

      $scope.processAddAdminForm = function(newAdmin) {
        submit_url = 'api/v1/admin/whitelist';
        submit_data = { '_xsrf': $cookies._xsrf, 'newAdmin': newAdmin };
        $http({
          method  : 'POST',
          url     : submit_url,
          data    : $.param(submit_data),
          headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
        }).success(function(data) {});
        $scope.addAdminTextBox = null;
      }

      $scope.changeState = function(state) {
        submit_url = 'api/v1/admin/frozen';
        submit_data = { '_xsrf': $cookies._xsrf, 'state': state };
        $http({
          method  : 'POST',
          url     : submit_url,
          data    : $.param(submit_data),
          headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
        }).success(function(data) {
          if (data) {
            $window.alert("changed state");
          }
        });
      }

      $scope.open = function(respNum, clarifNum) {
        var modalInstance = $modal.open({
          templateUrl: 'myModalContent.html',
          controller: 'ModalInstanceCtrl',
          resolve: {
            respNum: function () {
              return respNum;
            },
            clarifNum: function() {
              return clarifNum;
            }
          }
        });

        modalInstance.result.then(function (response) {
          submit_url = 'api/v1/admin/clarifications'
          response['_xsrf'] = $cookies._xsrf;
              $http({
                method  : 'POST',
                url     : submit_url,
                data    : $.param(response),
                headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
              }).success(function(data) {
                if (data) {
                  $window.alert("clarif reply successfully submitted");
                }
              });
        }, function () {
        });
      };
            var tabClasses;

      function initTabs() {
        tabClasses = ["","","",""];
      }

      $scope.getTabClass = function (tabNum) {
        return tabClasses[tabNum];
      };

      $scope.getTabPaneClass = function (tabNum) {
        return "tab-pane " + tabClasses[tabNum];
      }

      $scope.setActiveTab = function (tabNum) {
        initTabs();
        tabClasses[tabNum] = "active";
      };

      initTabs();
      $scope.setActiveTab(1);
    }]);

contestControllers.controller('ModalInstanceCtrl', function ($scope, $modalInstance, respNum, clarifNum) {

  $scope.ok = function () {
    $modalInstance.close({
      'respNum': respNum,
      'clarifNum': clarifNum,
      'response': $scope.response,
    });
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});

contestControllers.controller('ProblemCtrl', ['$scope', '$http', '$rootScope', '$window', '$cookies', '$interval',
    function ($scope, $http, $rootScope, $window, $cookies, $interval) {
      var tabClasses;

      $scope.files = {};
      $scope.files.output = [];
      $scope.files.source = [];
      i = 0;
      for (probId in probIds) {
        $scope.files.output.push("");
        $scope.files.source.push("");
      }
      if (typeof $rootScope.showSubmit == 'undefined') {
        $rootScope.showSubmit = [];
        $rootScope.ttl = [];
        $rootScope.ttlText = [];
        $rootScope.tick = [];
        for (probId in probIds) {
          $rootScope.showSubmit.push(false);
          $rootScope.ttl.push(-1);
          $rootScope.ttlText.push("");
          $rootScope.tick.push(null);
        }
      }

      function initTabs() {
        tabClasses = [];
        $scope.open = [];
        for (probId in probIds) {
          tabClasses.push("");
          $scope.open.push(false);
        }
      }

      $scope.getTabClass = function (tabNum) {
        return tabClasses[tabNum];
      };

      $scope.getTabPaneClass = function (tabNum) {
        return "tab-pane " + tabClasses[tabNum];
      };

      $scope.setActiveTab = function (tabNum) {
        initTabs();
        tabClasses[tabNum] = "active panel-primary";
        $rootScope.activeTab = tabNum;
        $scope.open[tabNum - 1] = true;
      };

      if (typeof $rootScope.activeTab == 'undefined') {
        $scope.setActiveTab(1);
      } else {
        $scope.setActiveTab($rootScope.activeTab);
      }

      $scope.clarif = {}
      $scope.processClarifForm = function (index) {
        submitUrl = 'api/v1/submit/' + probIds[index] + '/clarification';
        submitData = { '_xsrf': $cookies._xsrf, 'content': $scope.clarif[index] };
        $http({
          method  : 'POST',
          url     : submitUrl,
          data    : $.param(submitData),
          headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
        }).success(function (data) {
          if (data) {
            $window.alert("Clarification submitted successfully!");
            $scope.clarifications.push({
              'prob_id': probIds[index],
              'message': $scope.clarif[index],
            });
            $scope.clarif[index] = null;
          }
        });
      };

      function tick (index) {
        $rootScope.ttl[index] -= 1;
        $rootScope.ttlText[index] = momentMinutes($rootScope.ttl[index]);
        if ($rootScope.ttl[index] <= 0) {
          $rootScope.showSubmit[index] = false;
          if ($rootScope.tick[index] != null) {
            $interval.cancel($rootScope.tick[index]);
            $rootScope.tick[index] = null;
          }
        }
      }

      $scope.getPermit = function (index) {
        permitUrl = 'api/v1/permits';
        permitData = { '_xsrf': $cookies._xsrf, 'content': probIds[index] };
        $http({
          method  : 'POST',
          url     : permitUrl,
          data    : $.param(permitData),
          headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
        }).success(function (data) {
          if ($rootScope.tick[index] != null) {
            $interval.cancel($rootScope.tick[index]);
            $rootScope.tick[index] = null;
          }
          $rootScope.showSubmit[index] = true;
          $rootScope.ttl[index] = data;
          $rootScope.ttlText[index] = momentMinutes($rootScope.ttl[index]);
          $rootScope.tick[index] = $interval(function () {
            tick(index);
          }, 1000, data);
        }).error(function (data, status, headers, config) {
          if (status == 403) {
            $window.alert("You are out of permits!");
          }
        });
      };

      $scope.processSubmitForm = function (index) {
        submitUrl = 'api/v1/submit/' + probIds[index] + '/solution';
        submitData = { '_xsrf': $cookies._xsrf,
                       'outputFile': $scope.files.output[index],
                       'sourceFile': $scope.files.source[index], };
        $rootScope.showSubmit[index] = false;
        $rootScope.ttl[index] = 0;
        if ($rootScope.tick[index] != null) {
          $interval.cancel($rootScope.tick[index]);
          $rootScope.tick[index] = null;
        }
        $http({
          method  : 'POST',
          url     : submitUrl,
          data    : $.param(submitData),
          headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
        }).success(function (data) {
          if (data) {
            $window.alert("Solution accepted!");
          } else {
            $window.alert("Solution incorrect!");
          }
        });
      };
    }]);

contestControllers.controller('ScoreboardCtrl', ['$scope', '$http',
    function ($scope, $http) {
    }]);
<|endoftext|>


<commit_before>/**
 * Creation of the HTTP Server is done here
 * can be used for Middleware Attachement to request processing
 * can be used for BeforeRequestProcess Event
 */

var http = require('http');
var morgan       = require('morgan');
var fs = require("fs");

var route = require('./core/route');
var logger = require('./core/logger');
var fMiddle = require('./example-middlewares/firstMiddleWare');
var sMiddle = require('./example-middlewares/secondMiddleWare');
var config = require('./config');

var reqIntercept = new route.getRequestInterceptor();
var accessLogStream = fs.createWriteStream(__dirname + '/' +config.logpath + '/minimalweb-access.log', {flags: 'a'});

/**
 * practical use of the middleware pattern implemented in the framework
 * For example, here we have used Morgan for Request Access log
 */
route.use(morgan('combined', {stream: accessLogStream}));

/**
 * Use of the middleware pattern implemented in the framework
 * For example, here we had used our custom middlewares
 * CSRF Attack can be prevented by using custom middleware
 */
route.use(fMiddle);
route.use(sMiddle);

// Creation of the HTTP Server
var minimalWeb = function(host,port) {
	var server = http.createServer(function (req, res) {
	  route.injectSession(req,res);
	   route.route(req,res);
	}).listen(port, host);

};

/**
 * Use of Request Interceptor before processing actual request
 * Used Event Emitter Pattern here
 * Generally, we will use this event to authorise the user to use the event
 * Here,
 * 1. We can check any url directly, or
 * 2. We iterate through route collection configuration and check 'loginrequired' property
 * Point no 2 related code is currently commented out
 */

reqIntercept.on('beforeProcessRequest', function(req,res,routeCollectionconfig) {
	// If we want to directly check the URL for some business logic
	if(req.url=="/mwplain")
		{
			res.writeHead(200, {'Content-Type': 'text/plain'});
			res.end('this process requires login' + '\n');
		}

	//We can write all check on collection here
	/*for(i=0;i<routeCollectionconfig.length;i++){
		if(req.url==routeCollectionconfig[i].requestPath)
		{
			if(typeof routeCollectionconfig[i].loginrequired !=='undefined'){
				res.writeHead(200, {'Content-Type': 'text/plain'});
				res.end('this process requires login' + '\n');
			}
		}
	}*/
  });

module.exports.minimalWeb = minimalWeb;
<commit_msg>some test related changes<commit_after>/**
 * Creation of the HTTP Server is done here
 * can be used for Middleware Attachement to request processing
 * can be used for BeforeRequestProcess Event
 */

var http = require('http');
var morgan       = require('morgan');
var fs = require("fs");

var route = require('./core/route');
var logger = require('./core/logger');
var fMiddle = require('./example-middlewares/firstMiddleWare');
var sMiddle = require('./example-middlewares/secondMiddleWare');
var config = require('./config');

var reqIntercept = new route.getRequestInterceptor();
var accessLogStream = fs.createWriteStream(__dirname + '/' +config.logpath + '/minimalweb-access.log', {flags: 'a'});

/**
 * practical use of the middleware pattern implemented in the framework
 * For example, here we have used Morgan for Request Access log
 */
route.use(morgan('combined', {stream: accessLogStream}));

/**
 * Use of the middleware pattern implemented in the framework
 * For example, here we had used our custom middlewares
 * CSRF Attack can be prevented by using custom middleware
 */
route.use(fMiddle);
route.use(sMiddle);

// Creation of the HTTP Server
var minimalWeb = function(host,port) {
	var server = http.createServer(function (req, res) {
	  route.injectSession(req,res);
	   route.route(req,res);
	}).listen(port, host);

};

/**
 * Use of Request Interceptor before processing actual request
 * Used Event Emitter Pattern here
 * Generally, we will use this event to authorise the user to use the event
 * Here,
 * 1. We can check any url directly, or
 * 2. We iterate through route collection configuration and check 'loginrequired' property
 * Point no 2 related code is currently commented out
 */

reqIntercept.on('beforeProcessRequest', function(req,res,routeCollectionconfig) {
	// If we want to directly check the URL for some business logic
	if(req.url=="/mwplain")
		{
			res.writeHead(200, {'Content-Type': 'text/plain'});
			res.end('this process requires login');
		}

	//We can write all check on collection here
	/*for(i=0;i<routeCollectionconfig.length;i++){
		if(req.url==routeCollectionconfig[i].requestPath)
		{
			if(typeof routeCollectionconfig[i].loginrequired !=='undefined'){
				res.writeHead(200, {'Content-Type': 'text/plain'});
				res.end('this process requires login' + '\n');
			}
		}
	}*/
  });

module.exports.minimalWeb = minimalWeb;
<|endoftext|>


<commit_before>#!/usr/bin/env node
/*
 * Copyright (c) 2013, Vialink Informática. All rights reserved.
 *
 * This file is part of ViaCRYPT.
 *
 * ViaCRYPT is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ViaCRYPT is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with ViaCRYPT.  If not, see <http://www.gnu.org/licenses/>.
 */

// TODO Send cache headers for static files;

var connect = require('connect'),
	http = require('http'),
	express = require('express'),
	uuid = require('node-uuid'),
	nodemailer = require('nodemailer'),
	ratelimit = require('express-rate'),
	version = require('./package').version,
	config = require('./config'),
	url = require('url'),
	dateformat = require('dateformat');
	templating = require('./templating'),
	fs = require('fs');

// --------------
// --- config ---
// --------------

var _provider = config.message_provider;
if (_provider == null) {
	console.log('WARNING: unconfigured message provider, falling back to fs store.');
	_provider = 'fs';
}
var _provider_options = config[_provider + '_options'];
var store = require('./providers/' + _provider);
var provider = new store.Provider(_provider_options);
var app = express();

// -----------
// --- app ---
// -----------

var re_uuid = /^[A-Za-z0-9-]+$/;
var re_userdata = /^[A-Za-z0-9+/=]+$/;

// return message and delete it
app.get('/m/:id', function(req, res) {
	var id = req.params.id;
	res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
	if (re_uuid.test(id) === false) {
		res.statusCode = 404;
		res.send('invalid id');
	} else {
		provider.get(id, function(err, data) {
			if (err) {
				res.statusCode = 404;
				res.send('id not found');
			} else {
				data = parse(data.toString());
				res.send(data);
			}
		});
	}
});

// parses the message removing the email address header
// if necessary and verifying if an email has to be sent
function parse(data) {
	var lines = data.split('\n');
	var locale = lines[4].trim().split(' ')[1];
	var tokens = lines[5].trim().split(' ');
	var last = tokens.length - 1;
	if (tokens[last] != '') {
		var now = new Date();
		var old = new Date(lines[3].substr(16, 24).trim());
		var info = {
			mail: tokens[last],
			locale: locale,
			context : {
				now: dateformat(now, "mm-dd-yyyy HH:MM:ss"),
				date: dateformat(old, "mm-dd-yyyy HH:MM:ss")
			}
		};
		send_mail_to(info);
	}
	if (config.notification_options['hide_header'] === true) {
		lines[5] = "";
		return lines.join('\n');
	}
	return data;
}

// sends an email message using nodemailer
function send_mail_to(info) {
	templating.changelang(info.locale);
	fs.readFile(__dirname + '/template/_email.html', 'utf-8', function(err, data) {
		if(err) {
			console.log(err);
		} else {
			var template = data.split('Subject:');
			var subj = template[1].split('\n')[0];
			var body = template[1].split('\n\n')[1];
			var mail = {
				from: config.notification_options.sender,
				to: info.email,
				subject: templating.compile(subj)(info.context),
				html: templating.compile(body)(info.context)
			}
			var backend = config.notification_options.backend;
			if (backend == null)
				console.log('WARNING: unconfigured email backend, the configuration format has changed.');
			else switch (backend.type) {
				case 'smtp':
					var transport = nodemailer.createTransport("SMTP", {
							service: null,
							host: backend.smtp_server,
							port: backend.smtp_port,
							auth: {
								user: backend.username,
								pass: backend.password
							}
					});
					transport.sendMail(mail, function(err, response) {
						if (err) console.log(err);
						else console.log("Message sent:" + response.message);
					});
					transport.close();
					break;
				case 'file':
					var out = JSON.stringify(mail) + '\n';
					fs.appendFile(backend.filepath, out, function(err, data) {
						if (err) console.log(err);
					});
					break;
				default:
					console.log('WARNING: unrecognized backend type, email not sent!');
					break;
			}
		}
	});
}

var middleware = [];
if (config.ratelimit) {
	if (config.ratelimit.redis) {
		var redis = require('redis');
		var rediscfg = config.ratelimit.redis;
		var client = redis.createClient(rediscfg.port, rediscfg.host, rediscfg.options);
		var handler = new ratelimit.Redis.RedisRateHandler({client: client});
	} else {
		var handler = new ratelimit.Memory.MemoryRateHandler();
	}
	var rate_middleware = ratelimit.middleware({
		handler: handler,
		limit: config.ratelimit.limit,
		interval: config.ratelimit.interval,
		getRemoteKey: function(req) {
			return req.get('X-Forwarded-For') || req.connection.remoteAddress
		},
		onLimitReached: function(req, res, rate, limit, resetTime, next) {
			console.log('rate limit exceeded');
			res.statusCode = 429;
			res.send('Rate limit exceeded. Check headers for limit information.');
		},
		setHeadersHandler: function(req, res, rate, limit, resetTime) {
			var remaining = limit - rate;
			if (remaining < 0) {
				remaining = 0;
			}

			// follows Twitter's rate limiting scheme and header notation
			// https://dev.twitter.com/docs/rate-limiting/faq#info
			res.setHeader('X-RateLimit-Limit', limit);
			res.setHeader('X-RateLimit-Remaining', remaining);
			res.setHeader('X-RateLimit-Reset', resetTime);

			// This header allows the client to calculate the time they must
			// wait to save another message.
			res.setHeader('X-RateLimit-CurrentTime', (new Date()).getTime());
		}
	});
	middleware.push(rate_middleware);
}

// store new message
app.post('/m/', middleware, function(req, res) {
	var userdata = req.body.data;
	if (re_userdata.test(userdata) === false) {
		res.statusCode = 400;
		res.send('invalid data');
		return;
	}
	var ip = req.get('X-Forwarded-For');
	if (ip === undefined) {
		ip = req.connection.remoteAddress;
	} else {
		ip += ' (via ' + req.connection.remoteAddress + ')';
	}
	var query = url.parse(req.get('referer')).pathname;
	var message = {
		version: version,
		ip: ip,
		date: new Date(),
		notification: req.body.notify,
		email: req.body.email,
		data: userdata.match(/.{1,64}/g).join('\n'),
		locale: get_locale(query)
	};
	// in theory it's almost impossible to get ONE collision
	// but we're trying 10 times just in case
	var attempts = 0, max_attempts = 10;
	(function save() {
		var id = uuid.v4();
		provider.put(id, message, function(err) {
			if (err) {
				if (err == 'duplicate' && attempts < max_attempts) {
					attempts += 1;
					// recursion! limited to 10 times.
					save();
				} else {
					res.statusCode = 500;
					res.send('something wrong happened: ' + err);
				}
			} else {
				res.send(JSON.stringify({ id: id }));
			}
		});
	})();
});

// ------------------
// --- web server ---
// ------------------

log_fmt = ':remote-addr :req[X-Forwarded-For] - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"';

function get_locale(query) {
	var available_locales = config.locales;
	var lang = query.match(/\/?([^\/]*)\/?/)[1];
	if (available_locales.indexOf(lang) >= 0) {
		return lang;
	}
	return config.locale;
}

//function rewrite_locale(root, options) {
//    var static_enUS = connect.static(root, {maxAge: 10000, index: 'en/index.html'}),
//        static_ptBR = connect.static(root, {maxAge: 10000, index: 'pt-BR/index.html'});
//
//    return function(req, res, next) {
//        var get = req._parsedUrl['query'];
//        locale = get_locale(get);
//        if (locale == 'pt-BR') {
//            return static_ptBR(req, res, next);
//        } else {
//            return static_enUS(req, res, next);
//        }
//    };
//}

var static_dir;
if (config.serve_static) {
    static_dir = config.static_dir;
} else if (config.serve_static !== false) {
	console.log('WARNING: unconfigured parameter serve_static. Implicit "true" will be deprecated, update your config.js');
	static_dir = __dirname + '/static';
}

var con = connect()
	.use(connect.logger(log_fmt))
	.use(connect.responseTime())
	//.use(rewrite_locale(static_dir))
	.use(connect.static(static_dir, {maxAge: 10000}))
	.use(connect.limit('10mb'))
	.use(connect.bodyParser())
	.use(app)
	.listen(config.port, config.listen);

console.log('Server running at ' + config.listen + ':' + config.port);
<commit_msg>Fixing mail field.<commit_after>#!/usr/bin/env node
/*
 * Copyright (c) 2013, Vialink Informática. All rights reserved.
 *
 * This file is part of ViaCRYPT.
 *
 * ViaCRYPT is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ViaCRYPT is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with ViaCRYPT.  If not, see <http://www.gnu.org/licenses/>.
 */

// TODO Send cache headers for static files;

var connect = require('connect'),
	http = require('http'),
	express = require('express'),
	uuid = require('node-uuid'),
	nodemailer = require('nodemailer'),
	ratelimit = require('express-rate'),
	version = require('./package').version,
	config = require('./config'),
	url = require('url'),
	dateformat = require('dateformat');
	templating = require('./templating'),
	fs = require('fs');

// --------------
// --- config ---
// --------------

var _provider = config.message_provider;
if (_provider == null) {
	console.log('WARNING: unconfigured message provider, falling back to fs store.');
	_provider = 'fs';
}
var _provider_options = config[_provider + '_options'];
var store = require('./providers/' + _provider);
var provider = new store.Provider(_provider_options);
var app = express();

// -----------
// --- app ---
// -----------

var re_uuid = /^[A-Za-z0-9-]+$/;
var re_userdata = /^[A-Za-z0-9+/=]+$/;

// return message and delete it
app.get('/m/:id', function(req, res) {
	var id = req.params.id;
	res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
	if (re_uuid.test(id) === false) {
		res.statusCode = 404;
		res.send('invalid id');
	} else {
		provider.get(id, function(err, data) {
			if (err) {
				res.statusCode = 404;
				res.send('id not found');
			} else {
				data = parse(data.toString());
				res.send(data);
			}
		});
	}
});

// parses the message removing the email address header
// if necessary and verifying if an email has to be sent
function parse(data) {
	var lines = data.split('\n');
	var locale = lines[4].trim().split(' ')[1];
	var tokens = lines[5].trim().split(' ');
	var last = tokens.length - 1;
	if (tokens[last] != '') {
		var now = new Date();
		var old = new Date(lines[3].substr(16, 24).trim());
		var info = {
			email: tokens[last],
			locale: locale,
			context : {
				now: dateformat(now, "mm-dd-yyyy HH:MM:ss"),
				date: dateformat(old, "mm-dd-yyyy HH:MM:ss")
			}
		};
		send_mail_to(info);
	}
	if (config.notification_options['hide_header'] === true) {
		lines[5] = "";
		return lines.join('\n');
	}
	return data;
}

// sends an email message using nodemailer
function send_mail_to(info) {
	templating.changelang(info.locale);
	fs.readFile(__dirname + '/template/_email.html', 'utf-8', function(err, data) {
		if(err) {
			console.log(err);
		} else {
			var template = data.split('Subject:');
			var subj = template[1].split('\n')[0];
			var body = template[1].split('\n\n')[1];
			var mail = {
				from: config.notification_options.sender,
				to: info.email,
				subject: templating.compile(subj)(info.context),
				html: templating.compile(body)(info.context)
			}
			var backend = config.notification_options.backend;
			if (backend == null)
				console.log('WARNING: unconfigured email backend, the configuration format has changed.');
			else switch (backend.type) {
				case 'smtp':
					var transport = nodemailer.createTransport("SMTP", {
							service: null,
							host: backend.smtp_server,
							port: backend.smtp_port,
							auth: {
								user: backend.username,
								pass: backend.password
							}
					});
					transport.sendMail(mail, function(err, response) {
						if (err) console.log(err);
						else console.log("Message sent:" + response.message);
					});
					transport.close();
					break;
				case 'file':
					var out = JSON.stringify(mail) + '\n';
					fs.appendFile(backend.filepath, out, function(err, data) {
						if (err) console.log(err);
					});
					break;
				default:
					console.log('WARNING: unrecognized backend type, email not sent!');
					break;
			}
		}
	});
}

var middleware = [];
if (config.ratelimit) {
	if (config.ratelimit.redis) {
		var redis = require('redis');
		var rediscfg = config.ratelimit.redis;
		var client = redis.createClient(rediscfg.port, rediscfg.host, rediscfg.options);
		var handler = new ratelimit.Redis.RedisRateHandler({client: client});
	} else {
		var handler = new ratelimit.Memory.MemoryRateHandler();
	}
	var rate_middleware = ratelimit.middleware({
		handler: handler,
		limit: config.ratelimit.limit,
		interval: config.ratelimit.interval,
		getRemoteKey: function(req) {
			return req.get('X-Forwarded-For') || req.connection.remoteAddress
		},
		onLimitReached: function(req, res, rate, limit, resetTime, next) {
			console.log('rate limit exceeded');
			res.statusCode = 429;
			res.send('Rate limit exceeded. Check headers for limit information.');
		},
		setHeadersHandler: function(req, res, rate, limit, resetTime) {
			var remaining = limit - rate;
			if (remaining < 0) {
				remaining = 0;
			}

			// follows Twitter's rate limiting scheme and header notation
			// https://dev.twitter.com/docs/rate-limiting/faq#info
			res.setHeader('X-RateLimit-Limit', limit);
			res.setHeader('X-RateLimit-Remaining', remaining);
			res.setHeader('X-RateLimit-Reset', resetTime);

			// This header allows the client to calculate the time they must
			// wait to save another message.
			res.setHeader('X-RateLimit-CurrentTime', (new Date()).getTime());
		}
	});
	middleware.push(rate_middleware);
}

// store new message
app.post('/m/', middleware, function(req, res) {
	var userdata = req.body.data;
	if (re_userdata.test(userdata) === false) {
		res.statusCode = 400;
		res.send('invalid data');
		return;
	}
	var ip = req.get('X-Forwarded-For');
	if (ip === undefined) {
		ip = req.connection.remoteAddress;
	} else {
		ip += ' (via ' + req.connection.remoteAddress + ')';
	}
	var query = url.parse(req.get('referer')).pathname;
	var message = {
		version: version,
		ip: ip,
		date: new Date(),
		notification: req.body.notify,
		email: req.body.email,
		data: userdata.match(/.{1,64}/g).join('\n'),
		locale: get_locale(query)
	};
	// in theory it's almost impossible to get ONE collision
	// but we're trying 10 times just in case
	var attempts = 0, max_attempts = 10;
	(function save() {
		var id = uuid.v4();
		provider.put(id, message, function(err) {
			if (err) {
				if (err == 'duplicate' && attempts < max_attempts) {
					attempts += 1;
					// recursion! limited to 10 times.
					save();
				} else {
					res.statusCode = 500;
					res.send('something wrong happened: ' + err);
				}
			} else {
				res.send(JSON.stringify({ id: id }));
			}
		});
	})();
});

// ------------------
// --- web server ---
// ------------------

log_fmt = ':remote-addr :req[X-Forwarded-For] - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"';

function get_locale(query) {
	var available_locales = config.locales;
	var lang = query.match(/\/?([^\/]*)\/?/)[1];
	if (available_locales.indexOf(lang) >= 0) {
		return lang;
	}
	return config.locale;
}

//function rewrite_locale(root, options) {
//    var static_enUS = connect.static(root, {maxAge: 10000, index: 'en/index.html'}),
//        static_ptBR = connect.static(root, {maxAge: 10000, index: 'pt-BR/index.html'});
//
//    return function(req, res, next) {
//        var get = req._parsedUrl['query'];
//        locale = get_locale(get);
//        if (locale == 'pt-BR') {
//            return static_ptBR(req, res, next);
//        } else {
//            return static_enUS(req, res, next);
//        }
//    };
//}

var static_dir;
if (config.serve_static) {
    static_dir = config.static_dir;
} else if (config.serve_static !== false) {
	console.log('WARNING: unconfigured parameter serve_static. Implicit "true" will be deprecated, update your config.js');
	static_dir = __dirname + '/static';
}

var con = connect()
	.use(connect.logger(log_fmt))
	.use(connect.responseTime())
	//.use(rewrite_locale(static_dir))
	.use(connect.static(static_dir, {maxAge: 10000}))
	.use(connect.limit('10mb'))
	.use(connect.bodyParser())
	.use(app)
	.listen(config.port, config.listen);

console.log('Server running at ' + config.listen + ':' + config.port);
<|endoftext|>


<commit_before>#!/usr/bin/env node

var formidable = require('formidable'),
    http = require('http'),
    util = require('util'),
    os = require('os'),
    fs = require('fs'),
    crypto = require('crypto'),
    uploadDir = os.tmpDir() + "/uplodr",
    config = require('./config.js');

if (typeof config.customUploadDir !== 'undefined')
  uploadDir = config.customUploadDir;

mkdirIfNotExist(uploadDir);

http.createServer(function(req, res) {
  if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
    // current date/time of session, use UTC to avoid DST
    var date = new Date();
    var dateString = '' + date.getUTCFullYear()
              + twoDigits(date.getUTCMonth()+1)
              + twoDigits(date.getUTCDate())
              + '-'
              + twoDigits(date.getUTCHours())
              + twoDigits(date.getUTCMinutes())
              + twoDigits(date.getUTCSeconds());
    var newUploadDir = uploadDir
                     + '/' + dateString
                     + '-' + randomCharacters(5);
    mkdirIfNotExist(newUploadDir);
    // parse a file upload
    var form = new formidable.IncomingForm();
    form.uploadDir = newUploadDir;
    form.parse(req, function(err, fields, files) {
      // metadata
      var metafile = newUploadDir + '/metadata-' + randomCharacters(5) + '.txt';
      fs.appendFile(metafile,
        util.inspect({fields: fields, files: files}),
        function(err){
          if (err) throw err;
        }
      );
      console.log('uplodr: [%s] new %s', dateString, metafile);
      // files.upload, "upload" is the name of the input field
      processUpload(files.upload);
      processUpload(files.upload2);
      processUpload(files.upload3);
      processUpload(files.upload4);
      processUpload(files.upload5);
      // response to browser
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload.\n\n');
      // res.end(util.inspect({fields: fields, files: files}));
      res.end();
    });
    return;
  }

  // show a file upload form
  res.writeHead(200, {'content-type': 'text/html'});
  res.end(
    '<form action="/upload" enctype="multipart/form-data" method="post">'+
    '<input type="text" name="title">
'+
    '<input type="file" name="upload">
'+
    '<input type="file" name="upload2">
'+
    '<input type="file" name="upload3">
'+
    '<input type="file" name="upload4">
'+
    '<input type="file" name="upload5">
'+
    '<input type="submit" value="Upload">'+
    '</form>'
  );
}).listen(80);

function mkdirIfNotExist(dir) {
  if (!fs.existsSync(dir)) fs.mkdirSync(dir);
  if (!fs.existsSync(dir)) {
    return false;
  } else {
    return fs.statSync(dir).isDirectory();
  }
}

function twoDigits(num) {
  if (Number(num) < 10) {
    return '0' + Number(num);
  } else {
    return num;
  }
}

function randomCharacters (count, characters) {
  characters = characters
    || "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var result = new Array(count),
      randomByte = crypto.randomBytes(count);
  for (var i = 0; i < count; i++) {
    result[i] = characters[randomByte[i] % characters.length]
  };
  return result.join('');
}

function processUpload(inputName) {
  if (typeof inputName !== 'undefined') {
    if (inputName.size !== 0) {
      if (inputName.name.lastIndexOf('.') > 0) {
        var parts = inputName.name.split('.');
        var extension = parts.pop();
        var path = inputName.path.split('/');
        path.pop();
        var newUploadDir = path.join('/');
        // console.log('uplodr: newUploadDir %s', newUploadDir);
        if (String(extension).length > 0) {
          var safename = newUploadDir + '/'
            + parts.join().match(/[a-zA-Z0-9]+/g).join('')
            + '.' + extension;
        } else {
          var safename = newUploadDir + '/'
            + parts.join().match(/[a-zA-Z0-9]+/g).join('');
        }
        fs.rename(inputName.path, safename, function(err){
          if (err) throw err;
        });
      }
      return true;
    }
  }
  return false;
}
<commit_msg>revert last<commit_after>#!/usr/bin/env node

var formidable = require('formidable'),
    http = require('http'),
    util = require('util'),
    os = require('os'),
    fs = require('fs'),
    crypto = require('crypto'),
    uploadDir = os.tmpDir() + "/uplodr",
    config = require('./config.js');

if (typeof config.customUploadDir !== 'undefined')
  uploadDir = config.customUploadDir;

mkdirIfNotExist(uploadDir);

http.createServer(function(req, res) {
  if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
    // current date/time of session, use UTC to avoid DST
    var date = new Date();
    var dateString = '' + date.getUTCFullYear()
              + twoDigits(date.getUTCMonth()+1)
              + twoDigits(date.getUTCDate())
              + '-'
              + twoDigits(date.getUTCHours())
              + twoDigits(date.getUTCMinutes())
              + twoDigits(date.getUTCSeconds());
    var newUploadDir = uploadDir
                     + '/' + dateString
                     + '-' + randomCharacters(5);
    mkdirIfNotExist(newUploadDir);
    // parse a file upload
    var form = new formidable.IncomingForm();
    form.uploadDir = newUploadDir;
    form.parse(req, function(err, fields, files) {
      // metadata
      var metafile = newUploadDir + '/metadata-' + randomCharacters(5) + '.txt';
      fs.appendFile(metafile,
        util.inspect({fields: fields, files: files}),
        function(err){
          if (err) throw err;
        }
      );
      console.log('uplodr: new %s', metafile);
      // files.upload, "upload" is the name of the input field
      processUpload(files.upload);
      processUpload(files.upload2);
      processUpload(files.upload3);
      processUpload(files.upload4);
      processUpload(files.upload5);
      // response to browser
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload.\n\n');
      // res.end(util.inspect({fields: fields, files: files}));
      res.end();
    });
    return;
  }

  // show a file upload form
  res.writeHead(200, {'content-type': 'text/html'});
  res.end(
    '<form action="/upload" enctype="multipart/form-data" method="post">'+
    '<input type="text" name="title">
'+
    '<input type="file" name="upload">
'+
    '<input type="file" name="upload2">
'+
    '<input type="file" name="upload3">
'+
    '<input type="file" name="upload4">
'+
    '<input type="file" name="upload5">
'+
    '<input type="submit" value="Upload">'+
    '</form>'
  );
}).listen(80);

function mkdirIfNotExist(dir) {
  if (!fs.existsSync(dir)) fs.mkdirSync(dir);
  if (!fs.existsSync(dir)) {
    return false;
  } else {
    return fs.statSync(dir).isDirectory();
  }
}

function twoDigits(num) {
  if (Number(num) < 10) {
    return '0' + Number(num);
  } else {
    return num;
  }
}

function randomCharacters (count, characters) {
  characters = characters
    || "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var result = new Array(count),
      randomByte = crypto.randomBytes(count);
  for (var i = 0; i < count; i++) {
    result[i] = characters[randomByte[i] % characters.length]
  };
  return result.join('');
}

function processUpload(inputName) {
  if (typeof inputName !== 'undefined') {
    if (inputName.size !== 0) {
      if (inputName.name.lastIndexOf('.') > 0) {
        var parts = inputName.name.split('.');
        var extension = parts.pop();
        var path = inputName.path.split('/');
        path.pop();
        var newUploadDir = path.join('/');
        // console.log('uplodr: newUploadDir %s', newUploadDir);
        if (String(extension).length > 0) {
          var safename = newUploadDir + '/'
            + parts.join().match(/[a-zA-Z0-9]+/g).join('')
            + '.' + extension;
        } else {
          var safename = newUploadDir + '/'
            + parts.join().match(/[a-zA-Z0-9]+/g).join('');
        }
        fs.rename(inputName.path, safename, function(err){
          if (err) throw err;
        });
      }
      return true;
    }
  }
  return false;
}
<|endoftext|>


<commit_before>"use strict"
var pug         = require('pug');
var nodemailer  = require('nodemailer');
var settings    = require('./settings');

// Web server
var bodyParser  = require('body-parser');
var express     = require('express');
var app = express();

// Logging
var printit = require('printit');
var log = printit({
    prefix: 'SMAM',
    date: true
});

var transporter = nodemailer.createTransport(settings.mailserver);

// Serve static (JS + HTML) files
app.use(express.static('front'));
// Body parsing
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// A request on /send with user input = mail to be sent
app.post('/send', function(req, res, next) {
    // params will be used as:
    // - values for html generation from the pug template
    // - parameters for sending the mail(s)
    let params = {
        subject: req.body.subj,
        from: req.body.name + ' <' + req.body.addr + '>',
        html: req.body.text
    };

    // Replacing the mail's content with HTML from the pug template
    // Commenting the line below will bypass the generation and only user the
    // text entered by the user
    params.html = pug.renderFile('template.pug', params);

    log.info('Sending message from ' + content.from);

    // Send the email to all users
    sendMails(params, function(err, infos) {
        if(err) {
            log.error(err)
        }
        logStatus(infos);
    }, function() {
        res.header('Access-Control-Allow-Origin', '*');
        res.status(200).send();
    })
});

// Use either the default port or the one chosen by the user (PORT env variable)
var port = process.env.PORT || 1970;
// Start the server
app.listen(port, function() {
    log.info("Server started on port " + port);
});

// Send mails to the recipients specified in the JSON settings file
// content: object containing mail params
//  {
//      subject: String
//      from: String (following RFC 1036 (https://tools.ietf.org/html/rfc1036#section-2.1.1))
//      html: String
//  }
// update(next, infos): Called each time a mail is sent with the infos provided
//                      by nodemailer
// done(): Called once each mail has been sent
function sendMails(params, update, done) {
    let mails = settings.recipients.map((recipient) => {
        return new Promise((sent) => {
            params.to = recipient;

            transporter.sendMail(params, (err, infos) => {
                sent();
                if(err) {
                    return next(err, recipient);
                }
                next(null, infos);
            });
        });
    });
    Promise.all(mails).then(done);
}

// Produces log from the infos provided by nodemailer
// infos: infos provided by nodemailer
// return: nothing
function logStatus(infos) {
    if(infos.accepted.length) {
        log.info('Message sent to ' + status.accepted[0]);
    }
    if(infos.rejected.length) {
        log.info('Message failed to send to ' + status.rejected[0]);
    }
}<commit_msg>Added some doc<commit_after>"use strict"
var pug         = require('pug');
var nodemailer  = require('nodemailer');
var settings    = require('./settings');

// Web server
var bodyParser  = require('body-parser');
var express     = require('express');
var app = express();

// Logging
var printit = require('printit');
var log = printit({
    prefix: 'SMAM',
    date: true
});

var transporter = nodemailer.createTransport(settings.mailserver);

// Serve static (JS + HTML) files
app.use(express.static('front'));
// Body parsing
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// A request on /send with user input = mail to be sent
app.post('/send', function(req, res, next) {
    // params will be used as:
    // - values for html generation from the pug template
    // - parameters for sending the mail(s)
    let params = {
        subject: req.body.subj,
        from: req.body.name + ' <' + req.body.addr + '>',
        html: req.body.text
    };

    // Replacing the mail's content with HTML from the pug template
    // Commenting the line below will bypass the generation and only user the
    // text entered by the user
    params.html = pug.renderFile('template.pug', params);

    log.info('Sending message from ' + content.from);

    // Send the email to all users
    sendMails(params, function(err, infos) {
        if(err) {
            log.error(err)
        }
        logStatus(infos);
    }, function() {
        res.header('Access-Control-Allow-Origin', '*');
        res.status(200).send();
    })
});

// Use either the default port or the one chosen by the user (PORT env variable)
var port = process.env.PORT || 1970;
// Start the server
app.listen(port, function() {
    log.info("Server started on port " + port);
});

// Send mails to the recipients specified in the JSON settings file
// content: object containing mail params
//  {
//      subject: String
//      from: String (following RFC 1036 (https://tools.ietf.org/html/rfc1036#section-2.1.1))
//      html: String
//  }
// update(next, infos): Called each time a mail is sent with the infos provided
//                      by nodemailer
// done(): Called once each mail has been sent
function sendMails(params, update, done) {
    let mails = settings.recipients.map((recipient) => {
        // Promise for each recipient to send each mail asynchronously
        return new Promise((sent) => {
            params.to = recipient;
            // Send the email
            transporter.sendMail(params, (err, infos) => {
                // Promise callback
                sent();
                if(err) {
                    return next(err, recipient);
                }
                next(null, infos);
            });
        });
    });
    // Run all the promises (= send all the mails)
    Promise.all(mails).then(done);
}

// Produces log from the infos provided by nodemailer
// infos: infos provided by nodemailer
// return: nothing
function logStatus(infos) {
    if(infos.accepted.length) {
        log.info('Message sent to ' + status.accepted[0]);
    }
    if(infos.rejected.length) {
        log.info('Message failed to send to ' + status.rejected[0]);
    }
}<|endoftext|>


<commit_before>#!/usr/bin/env node
//
// Based on rpflorence's Gist @ https://gist.github.com/rpflorence/701407
//

var util = require("util"),
	http = require("http"),
	url  = require("url"),
	path = require("path"),
	fs   = require("fs"),
	conf = require("./conf/server.conf.js"),
	di   = require("./extensions/directory-indexing.js"),
	x2j  = require("./extensions/xml2json.js"),
	mime = require("mime"),
	port = process.argv[2] || 8888;

// The base level of the server, nothing allowed below this.
// Do not end this in a "/". If you want the server's root, set this to empty-string: ""
// http.DOCUMENT_ROOT = "/Users/blake/Source";

http.createServer(function(request, response) {
	var objUrl = url.parse(request.url, true),
		uri = decodeURI(path.normalize(objUrl.pathname)),
		filename = path.join(conf.DocumentRoot, uri);
	// process.cwd()

	// console.log("process.cwd()", process.cwd(), "request.url", request.url, "uri", uri);

	var writeEntireResponse = function(intStatus, strContent, objOptions) {
		if (arguments.length == 1) {
			strContent = arguments[0];
			intStatus = 200;
		}
		if (!objOptions) objOptions = {"Content-Type": conf.DefaultContentType};
		if (strContent === undefined) strContent = "";
		else if ( typeof strContent !== "string") {
			objOptions["Content-Type"] = "application/json";
			strContent = JSON.stringify(strContent);
			if (objUrl.query["callback"]) {
				objOptions["Content-Type"] = "application/javascript";
				strContent = objUrl.query["callback"] + "(" + strContent + ");";
			}
		}
		response.writeHead(intStatus, objOptions);
		response.write(strContent, "binary");
		response.end();
	};

	var serveFile = function(filename) {
		// console.log("accessing:", filename);
		var strMime = mime.lookup(filename) || conf.DefaultContentType;
		fs.readFile(filename, "binary", function(err, file) {
			if (err) {
				writeEntireResponse(500, err + "\n", {"Content-Type": "text/plain"});
				return;
			}

			writeEntireResponse(200, file, {"Content-Type": strMime});
		});
		return true;
	};

	var isServable = function(filename) {
		var fileExists = fs.existsSync(filename);
		if (!fileExists) {
			return false;
		}
		var objFileInfo = fs.statSync(filename);
		if (objFileInfo.isDirectory()) {
			return "maybe";
		}
		return true;
	};
	// var hasIndex = function(filename) {
	// 	return fs.existsSync(filename + "/" + conf.DirectoryIndex) ? filename + "/" + conf.DirectoryIndex : false;
	// };

	var bitIsServable = isServable(filename);
	if (bitIsServable) {
		if (bitIsServable === "maybe") {
			var bitHasIndex = di.hasIndex(filename);
			if (bitHasIndex) {
				serveFile(bitHasIndex);
			}
			else {
				// console.log("di.Format", di.Format);
				di.Format = (objUrl.query["f"] === "json" || objUrl.query["f"] === "html") ? objUrl.query["f"] : "";
				// console.log("di.Format", di.Format);
				var directoryIndex = di.getDirectory(filename, function(objFiles) {
					// util.puts("filename", filename);
					if ( typeof objFiles !== "string") {
						writeEntireResponse({"filesystem": [objFiles]});
					}
					else {
						writeEntireResponse(objFiles);
					}
				});
			}
		}
		else {
			if (x2j.get("Enabled") && objUrl.query["f"] === "json" ) {
				// util.puts("Attempting to convert "+ filename +" to Json.");
				x2j.convertToJson(filename, function(json) {
					writeEntireResponse(json);
				});
			}
			else {
				serveFile(filename);
			}
		}
	}
	else {
		writeEntireResponse(404, "404 Not Found\n"+uri, {"Content-Type": "text/plain"});
	}
	return;
}).listen(parseInt(conf.Listen, 10));

// console.log(" ## Noche server running ##\n  => http://localhost:" + conf.Listen + "/\n [CTRL] + [C] to shutdown");
/* server started */
util.puts(" ## Noche server running ####################################################\n  => http://localhost:" + conf.Listen + "/");
<commit_msg>Noche now supports transmitting of large files without crashing. YAY!<commit_after>#!/usr/bin/env node
//
// Based on rpflorence's Gist @ https://gist.github.com/rpflorence/701407
//

var util = require("util"),
	http = require("http"),
	url  = require("url"),
	path = require("path"),
	fs   = require("fs"),
	conf = require("./conf/server.conf.js"),
	di   = require("./extensions/directory-indexing.js"),
	x2j  = require("./extensions/xml2json.js"),
	mime = require("mime");

http.createServer(function(request, response) {
	var objUrl = url.parse(request.url, true),
		uri = decodeURI(path.normalize(objUrl.pathname)),
		filename = path.join(conf.DocumentRoot, uri);
	// process.cwd()

	// console.log("process.cwd()", process.cwd(), "request.url", request.url, "uri", uri);

	var writeEntireResponse = function(intStatus, strContent, objOptions) {
		if (arguments.length == 1) {
			strContent = arguments[0];
			intStatus = 200;
		}
		if (!objOptions) {
			objOptions = {"Content-Type": conf.DefaultContentType};
		}
		if (strContent === undefined) {
			strContent = "";
		}
		else if ( typeof strContent !== "string") {
			objOptions["Content-Type"] = "application/json";
			strContent = JSON.stringify(strContent);
			if (objUrl.query["callback"]) {
				objOptions["Content-Type"] = "application/javascript";
				strContent = objUrl.query["callback"] + "(" + strContent + ");";
			}
		}
		response.writeHead(intStatus, objOptions);
		response.write(strContent, "binary");
		response.end();
	};

	var serveFile = function(filename) {
		// console.log("accessing:", filename);
		var strMime = mime.lookup(filename) || conf.DefaultContentType;

		fs.stat(filename, function(err, stat) {
			if (err) {
				writeEntireResponse(500, err + "\n", {"Content-Type": "text/plain"});
				return;
			}
			response.writeHeader(200,{"Content-Type": strMime, "Content-Length": stat.size});
			var fReadStream = fs.createReadStream(filename);
			fReadStream.pipe(response);
		});
		return true;
	};

	var isServable = function(filename) {
		var fileExists = fs.existsSync(filename);
		if (!fileExists) {
			return false;
		}
		var objFileInfo = fs.statSync(filename);
		if (objFileInfo.isDirectory()) {
			return "maybe";
		}
		return true;
	};
	// var hasIndex = function(filename) {
		// return fs.existsSync(filename + "/" + conf.DirectoryIndex) ? filename + "/" + conf.DirectoryIndex : false;
	// };

	var bitIsServable = isServable(filename);
	if (bitIsServable) {
		if (bitIsServable === "maybe") {
			var bitHasIndex = di.hasIndex(filename);
			if (bitHasIndex) {
				serveFile(bitHasIndex);
			}
			else {
				// console.log("di.Format", di.Format);
				di.Format = (objUrl.query["f"] === "json" || objUrl.query["f"] === "html") ? objUrl.query["f"] : "";
				// console.log("di.Format", di.Format);
				di.getDirectory(filename, function(objFiles) {
					// util.puts("filename", filename);
					if ( typeof objFiles !== "string") {
						writeEntireResponse({"filesystem": [objFiles]});
					}
					else {
						writeEntireResponse(objFiles);
					}
				});
			}
		}
		else {
			if (x2j.get("Enabled") && objUrl.query["f"] === "json" ) {
				// util.puts("Attempting to convert "+ filename +" to Json.");
				x2j.convertToJson(filename, function(json) {
					writeEntireResponse(json);
				});
			}
			else {
				serveFile(filename);
			}
		}
	}
	else {
		writeEntireResponse(404, "404 Not Found\n"+uri, {"Content-Type": "text/plain"});
	}
	return;
}).listen(parseInt(conf.Listen, 10));

// console.log(" ## Noche server running ##\n  => http://localhost:" + conf.Listen + "/\n [CTRL] + [C] to shutdown");
/* server started */
util.puts(" ## Noche server running ####################################################\n  => http://localhost:" + conf.Listen + "/");
<|endoftext|>


<commit_before>var static = require('node-static');
var http = require('http');
var file = new(static.Server)();
var app = http.createServer(function (req, res) {
  file.serve(req, res);
}).listen(2014);

var io = require('socket.io').listen(app);

io.sockets.on('connection', function (socket) {

   // convenience function to log server messages on the client
	function log() {
		var array = [">>> Message from server: "];
	  for (var i = 0; i < arguments.length; i++) {
	  	array.push(arguments[i]);
	  }
	    socket.emit('log', array);
	}

  socket.on('message', function (message) {
    log('Got message: ', message);
    socket.broadcast.emit('message', message);
  });

  socket.on('create or join', function (room) {
      var numClients = io.sockets.sockets.length;
      console.log(numClients);

      log('Room ' + room + ' has ' + numClients + ' client(s)');
	    log('Request to create or join room ' + room);

      if (numClients == 1) {
        socket.join(room);
        socket.emit('created', room);
      } else if (numClients == 2) {
        io.sockets.in(room).emit('join', room);
        socket.join(room);
        socket.emit('joined', room);
      } else { // max two clients
        socket.emit('full', room);
      }

      socket.emit('emit(): client ' + socket.id + ' joined room ' + room);
	    socket.broadcast.emit('broadcast(): client ' + socket.id + ' joined room ' + room);

  });

});
<commit_msg>fixed import script<commit_after>var static = require('node-static');
var http = require('http');
var file = new(static.Server)();
var app = http.createServer(function (req, res) {
  file.serve(req, res);
}).listen(process.env.PORT || 2014);

var io = require('socket.io').listen(app);

io.sockets.on('connection', function (socket) {

   // convenience function to log server messages on the client
	function log() {
		var array = [">>> Message from server: "];
	  for (var i = 0; i < arguments.length; i++) {
	  	array.push(arguments[i]);
	  }
	    socket.emit('log', array);
	}

  socket.on('message', function (message) {
    log('Got message: ', message);
    socket.broadcast.emit('message', message);
  });

  socket.on('create or join', function (room) {
      var numClients = io.sockets.sockets.length;
      console.log(numClients);

      log('Room ' + room + ' has ' + numClients + ' client(s)');
	    log('Request to create or join room ' + room);

      if (numClients == 1) {
        socket.join(room);
        socket.emit('created', room);
      } else if (numClients == 2) {
        io.sockets.in(room).emit('join', room);
        socket.join(room);
        socket.emit('joined', room);
      } else { // max two clients
        socket.emit('full', room);
      }

      socket.emit('emit(): client ' + socket.id + ' joined room ' + room);
	    socket.broadcast.emit('broadcast(): client ' + socket.id + ' joined room ' + room);

  });

});
<|endoftext|>