<commit_before>/**
 * @name DashboardController
 * @desc Parent controller for the dashboard views */

(function() {
    'use strict';

    angular.module('cometApp')
           .controller('DashboardController', DashboardController);

        DashboardController.$inject = ['$log',
                                       '$scope',
                                       '$state',
                                       '$stateParams',
                                       '$timeout',
                                       'ngToast',
                                       'lodash',
                                       'dashboardServiceModel',
                                       'accountService',
                                       'channelService',
                                       'notificationService',
                                       'user'];

        function DashboardController ($log,
                                      $scope,
                                      $state,
                                      $stateParams,
                                      $timeout,
                                      ngToast,
                                      lodash,
                                      dashboardServiceModel,
                                      accountService,
                                      channelService,
                                      notificationService,
                                      user) {

          var vm = this;

          vm.user = user;
          vm.project = dashboardServiceModel.getCurrentProject();

          vm.publicChannels = null;
          vm.privateChannels = null;
          vm.availableMembers = null;

          vm.membersVisible = false;
          vm.privateNotifications = false;
          vm.showMembers = showMembers;

          vm.logout = logout;

          activate();

          /**
           * @name activate
           * @desc controller activation logic
           */
          function activate() {

            // user account confirmation alert
            if (!vm.user.confirmed) {
              ngToast.warning({
                content: 'Recuerda confirmar tu dirección de correo.',
                dismissButton: true
              });
            }

            // project channels
            loadChannels(vm.project);

            // listen to project updates
            $scope.$on('currentProjectUpdated', function(event, args) {

              var previousProject = args.previous;
              if (previousProject !== null) {
                // leave the previous project room
                notificationsLeaveRoom(previousProject);
              }

              vm.project = dashboardServiceModel.getCurrentProject();
              loadChannels(vm.project);
              notificationsJoinRoom();
            });

            // listen to user updates
            $scope.$on('currentUserUpdated', function() {
              vm.user = dashboardServiceModel.getCurrentUser();
            });

            // listen to channel updates
            $scope.$on('channelsUpdated', function() {
              loadChannels(vm.project);
            });

            // notifications
            initializeNotifications();
          }

          /**
           * @name loadChannels
           * @desc loads the proyect channels
           */
          function loadChannels (project) {

            if (project === null ) {
              return;
            }

            channelService.getAll(project.id).then(function (response) {
              var channels = response.data;

              vm.privateChannels = lodash.filter(channels, function(c) {
                return c.type === 'P' && c.state !== 'C';
              });

              vm.publicChannels = lodash.filter(channels, function(c) {
                var isMember = (lodash.find(c.members, 'id', vm.user.id) !== undefined);
                return c.type === 'S' && c.state !== 'C' && isMember;
              });
            });

            // members for direct chat
            vm.availableMembers = lodash.filter(vm.project.members, function(m) {
              return (m.id !== vm.user.id);
            });
          }

          /**
           * @name initializeNotifications
           * @desc initializes the notifications socket
           */
          function initializeNotifications() {

            if (vm.project === null) {
              return;
            }

            // the server sends the channel with updates after a page load or a reconnect
            notificationService.on('channels-updates', function (data) {
              $log.log('notifications channels-updates', data);
              loadChannelsUpdates(data);
            });

            // notifications on the channels the user is member of
            notificationService.on('transient-notification', function (notification) {
              $log.log('transient-notification', notification);
              loadNotification(notification);
            });

            // join notifications room on reconnect
            notificationService.on('reconnect', function () {
              $log.log('notifications reconnect');
              notificationsJoinRoom();
            });

            notificationService.on('online-users', function (state) {
              $log.log('online-users', state);
              loadUserState(state);
            });

            notificationsJoinRoom();
            notificationsSendPing();
          }

          /**
           * @name notificationsSendPing
           * @desc sends a ping message to the server to save the
           *       user activity date.
           *        this function calls itself recursively
           */
          function notificationsSendPing() {

            if (vm.project === null) {
              return;
            }

            notificationService.emit('ping', {
              projectId: vm.project.id,
              userId: vm.user.id
            });

            $timeout(notificationsSendPing, 10 * 1000);
          }

          /**
           * @name notificationsJoinRoom
           * @desc joins the current project room
           */
          function notificationsJoinRoom() {

            $log.log('notificationsJoinRoom', vm.project);

            if (vm.project === null) {
              return;
            }

            // group channels notifications
            notificationService.emit('join-room', {
              room: getProjectRoomId(vm.project),
              projectId: vm.project.id,
              userId: vm.user.id
            });

            // direct channels notifications
            notificationService.emit('join-room', {
              room: getDirectRoomId(),
              projectId: vm.project.id,
              userId: vm.user.id
            });
          }

          /**
           * @name notificationsLeaveRoom
           * @desc leave a project notifications room
           */
          function notificationsLeaveRoom(project) {

            notificationService.emit('leave-room', {
              room: getProjectRoomId(project)
            });

            notificationService.emit('leave-room', {
              room: getDirectRoomId(user)
            });
          }

          /**
           * @name setChannelsUpdates
           * @desc marks the channels with updates
           */
          function loadChannelsUpdates(data) {

            // public and private channels
            var channelUpdatesLen = data.channels_with_updates.length;
            for (var i = 0; i < channelUpdatesLen; i++) {
              var update = data.channels_with_updates[i];
              // search in public channels
              var channel = lodash.find(vm.publicChannels, 'id', update.id);
              if (channel === undefined) {
                // search in private channels
                channel = lodash.find(vm.privateChannels, 'id', update.id);
              }
              if (channel !== undefined) {
                channel.hasNotification = true;
              }
            }

            // direct channels
            var userUpdatesLen = data.users_with_updates.length;
            for (var j = 0; j < userUpdatesLen; j++) {
              var user = data.users_with_updates[j];
              var userChannel = lodash.find(vm.availableMembers, 'id', user.id);
              if (userChannel !== undefined) {
                userChannel.hasNotification = true;
              }
            }
          }

          /**
           * @name loadNotification
           * @desc marks the channel with a (transient) notification
           */
          function loadNotification(notification) {

            // public and private channels
            if (notification.type === 'channel') {
              var channel = findChannel(notification.id);
              if (channel !== undefined) {
                channel.hasNotification = true;
              }
            }
            else {
              if (notification.type === 'direct') {
                var userChannel = findDirectChannel(notification.id);
                if (userChannel !== undefined) {
                  userChannel.hasNotification = true;
                  vm.privateNotifications = true;
                }
              } else {
                if (notification.type === 'private-channel') {
                  var privatechannel = findChannel(notification.id);
                  if (privatechannel !== undefined) {
                    privatechannel.hasNotification = true;
                  }
                }
              }
            }
          }

          /**
           * @name loadUserState
           * @desc updates the user state
           */
          function loadUserState(state) {
            var user = findDirectChannel(state.id);
            if (user !== undefined) {
              if (state.type === 'add') {
                user.isOnline = true;
              }
              else {
                if (state.type === 'remove') {
                  user.isOnline = false;
                }
              }
            }
          }

          /**
           * @name findChannel
           * @desc returns a channel searching by id
           */
          function findChannel(channelId) {
            var channel = lodash.find(vm.publicChannels, 'id', channelId);
            if (channel === undefined) {
              // search in private channels
              channel = lodash.find(vm.privateChannels, 'id', channelId);
            }
            return channel;
          }

          /**
           * @name findChannel
           * @desc returns a direct channel searching by id
           */
          function findDirectChannel(userId) {
            return lodash.find(vm.availableMembers, 'id', userId);
          }

          /**
           * @name getProjectRoomId
           * @desc returns the room id for the notifications socket
           */
          function getProjectRoomId(project) {
            return 'Project_' + project.id;
          }

          /**
           * @name getDirectRoomId
           * @desc returns the room id for the direct messages notifications socket
           */
          function getDirectRoomId() {
            return 'SELF_' + user.id;
          }

          /**
           * @name showMembers
           * @desc shows/hide the members panel
           */
          function showMembers() {
            vm.membersVisible = !vm.membersVisible;

            if(vm.privateNotifications){
              vm.privateNotifications = false;
            }

            if (vm.membersVisible) {
              $timeout(setHideMembersOnClick, 100);
            }
          }

          /**
           * @name setHideMembersOnClick
           * @desc sets a event to hide the project members panel when
           *       the user clicks on any part of the page
           */
          function setHideMembersOnClick() {
            $(document).one('click', function(event){
                var isClickedElementChildOfPopup =
                        //angular.element('.cometProjectUsers')
                        angular.element
                               .find(event.target)
                               .length > 0;

                if (isClickedElementChildOfPopup) {
                  return;
                }

                $scope.$apply(function(){
                  vm.membersVisible = false;
                });
            });
          }

          /**
           * @name logout
           * @desc logout the user and redirects to home page
           */
          function logout () {
            notificationsLeaveRoom(vm.project);
            accountService.logout();
            $state.go('home');
          }
      }
})();
<commit_msg>Fix #45<commit_after>/**
 * @name DashboardController
 * @desc Parent controller for the dashboard views */

(function() {
    'use strict';

    angular.module('cometApp')
           .controller('DashboardController', DashboardController);

        DashboardController.$inject = ['$log',
                                       '$scope',
                                       '$state',
                                       '$stateParams',
                                       '$timeout',
                                       'ngToast',
                                       'lodash',
                                       'dashboardServiceModel',
                                       'accountService',
                                       'channelService',
                                       'notificationService',
                                       'user'];

        function DashboardController ($log,
                                      $scope,
                                      $state,
                                      $stateParams,
                                      $timeout,
                                      ngToast,
                                      lodash,
                                      dashboardServiceModel,
                                      accountService,
                                      channelService,
                                      notificationService,
                                      user) {

          var vm = this;

          vm.user = user;
          vm.project = dashboardServiceModel.getCurrentProject();

          vm.publicChannels = null;
          vm.privateChannels = null;
          vm.availableMembers = null;

          vm.membersVisible = false;
          vm.privateNotifications = false;
          vm.showMembers = showMembers;

          vm.logout = logout;

          activate();

          /**
           * @name activate
           * @desc controller activation logic
           */
          function activate() {

            // user account confirmation alert
            if (!vm.user.confirmed) {
              ngToast.warning({
                content: 'Recuerda confirmar tu dirección de correo.',
                dismissButton: true
              });
            }

            // project channels
            loadChannels(vm.project);

            // listen to project updates
            $scope.$on('currentProjectUpdated', function(event, args) {

              var previousProject = args.previous;
              if (previousProject !== null) {
                // leave the previous project room
                notificationsLeaveRoom(previousProject);
              }

              vm.project = dashboardServiceModel.getCurrentProject();
              loadChannels(vm.project);
              notificationsJoinRoom();
            });

            // listen to user updates
            $scope.$on('currentUserUpdated', function() {
              vm.user = dashboardServiceModel.getCurrentUser();
            });

            // listen to channel updates
            $scope.$on('channelsUpdated', function() {
              loadChannels(vm.project);
            });

            // notifications
            initializeNotifications();
          }

          /**
           * @name loadChannels
           * @desc loads the proyect channels
           */
          function loadChannels (project) {

            if (project === null ) {
              return;
            }

            channelService.getAll(project.id).then(function (response) {
              var channels = response.data;

              vm.privateChannels = lodash.filter(channels, function(c) {
                return c.type === 'P' && c.state !== 'C';
              });

              vm.publicChannels = lodash.filter(channels, function(c) {
                var isMember = (lodash.find(c.members, 'id', vm.user.id) !== undefined);
                return c.type === 'S' && c.state !== 'C' && isMember;
              });
            });

            // members for direct chat
            vm.availableMembers = lodash.filter(vm.project.members, function(m) {
              return (m.id !== vm.user.id);
            });
          }

          /**
           * @name initializeNotifications
           * @desc initializes the notifications socket
           */
          function initializeNotifications() {

            if (vm.project === null) {
              return;
            }

            // the server sends the channel with updates after a page load or a reconnect
            notificationService.on('channels-updates', function (data) {
              $log.log('notifications channels-updates', data);
              loadChannelsUpdates(data);
            });

            // notifications on the channels the user is member of
            notificationService.on('transient-notification', function (notification) {
              $log.log('transient-notification', notification);
              loadNotification(notification);
            });

            // join notifications room on reconnect
            notificationService.on('reconnect', function () {
              $log.log('notifications reconnect');
              notificationsJoinRoom();
            });

            notificationService.on('online-users', function (state) {
              $log.log('online-users', state);
              loadUserState(state);
            });

            notificationsJoinRoom();
            notificationsSendPing();
          }

          /**
           * @name notificationsSendPing
           * @desc sends a ping message to the server to save the
           *       user activity date.
           *        this function calls itself recursively
           */
          function notificationsSendPing() {

            if (vm.project === null) {
              return;
            }

            notificationService.emit('ping', {
              projectId: vm.project.id,
              userId: vm.user.id
            });

            $timeout(notificationsSendPing, 10 * 1000);
          }

          /**
           * @name notificationsJoinRoom
           * @desc joins the current project room
           */
          function notificationsJoinRoom() {

            $log.log('notificationsJoinRoom', vm.project);

            if (vm.project === null) {
              return;
            }

            // group channels notifications
            notificationService.emit('join-room', {
              room: getProjectRoomId(vm.project),
              projectId: vm.project.id,
              userId: vm.user.id
            });

            // direct channels notifications
            notificationService.emit('join-room', {
              room: getDirectRoomId(),
              projectId: vm.project.id,
              userId: vm.user.id
            });
          }

          /**
           * @name notificationsLeaveRoom
           * @desc leave a project notifications room
           */
          function notificationsLeaveRoom(project) {

            if (project === null) {
              return;
            }

            notificationService.emit('leave-room', {
              room: getProjectRoomId(project)
            });

            notificationService.emit('leave-room', {
              room: getDirectRoomId(user)
            });
          }

          /**
           * @name setChannelsUpdates
           * @desc marks the channels with updates
           */
          function loadChannelsUpdates(data) {

            // public and private channels
            var channelUpdatesLen = data.channels_with_updates.length;
            for (var i = 0; i < channelUpdatesLen; i++) {
              var update = data.channels_with_updates[i];
              // search in public channels
              var channel = lodash.find(vm.publicChannels, 'id', update.id);
              if (channel === undefined) {
                // search in private channels
                channel = lodash.find(vm.privateChannels, 'id', update.id);
              }
              if (channel !== undefined) {
                channel.hasNotification = true;
              }
            }

            // direct channels
            var userUpdatesLen = data.users_with_updates.length;
            for (var j = 0; j < userUpdatesLen; j++) {
              var user = data.users_with_updates[j];
              var userChannel = lodash.find(vm.availableMembers, 'id', user.id);
              if (userChannel !== undefined) {
                userChannel.hasNotification = true;
              }
            }
          }

          /**
           * @name loadNotification
           * @desc marks the channel with a (transient) notification
           */
          function loadNotification(notification) {

            // public and private channels
            if (notification.type === 'channel') {
              var channel = findChannel(notification.id);
              if (channel !== undefined) {
                channel.hasNotification = true;
              }
            }
            else {
              if (notification.type === 'direct') {
                var userChannel = findDirectChannel(notification.id);
                if (userChannel !== undefined) {
                  userChannel.hasNotification = true;
                  vm.privateNotifications = true;
                }
              } else {
                if (notification.type === 'private-channel') {
                  var privatechannel = findChannel(notification.id);
                  if (privatechannel !== undefined) {
                    privatechannel.hasNotification = true;
                  }
                }
              }
            }
          }

          /**
           * @name loadUserState
           * @desc updates the user state
           */
          function loadUserState(state) {
            var user = findDirectChannel(state.id);
            if (user !== undefined) {
              if (state.type === 'add') {
                user.isOnline = true;
              }
              else {
                if (state.type === 'remove') {
                  user.isOnline = false;
                }
              }
            }
          }

          /**
           * @name findChannel
           * @desc returns a channel searching by id
           */
          function findChannel(channelId) {
            var channel = lodash.find(vm.publicChannels, 'id', channelId);
            if (channel === undefined) {
              // search in private channels
              channel = lodash.find(vm.privateChannels, 'id', channelId);
            }
            return channel;
          }

          /**
           * @name findChannel
           * @desc returns a direct channel searching by id
           */
          function findDirectChannel(userId) {
            return lodash.find(vm.availableMembers, 'id', userId);
          }

          /**
           * @name getProjectRoomId
           * @desc returns the room id for the notifications socket
           */
          function getProjectRoomId(project) {
            return 'Project_' + project.id;
          }

          /**
           * @name getDirectRoomId
           * @desc returns the room id for the direct messages notifications socket
           */
          function getDirectRoomId() {
            return 'SELF_' + user.id;
          }

          /**
           * @name showMembers
           * @desc shows/hide the members panel
           */
          function showMembers() {
            vm.membersVisible = !vm.membersVisible;

            if(vm.privateNotifications){
              vm.privateNotifications = false;
            }

            if (vm.membersVisible) {
              $timeout(setHideMembersOnClick, 100);
            }
          }

          /**
           * @name setHideMembersOnClick
           * @desc sets a event to hide the project members panel when
           *       the user clicks on any part of the page
           */
          function setHideMembersOnClick() {
            $(document).one('click', function(event){
                var isClickedElementChildOfPopup =
                        //angular.element('.cometProjectUsers')
                        angular.element
                               .find(event.target)
                               .length > 0;

                if (isClickedElementChildOfPopup) {
                  return;
                }

                $scope.$apply(function(){
                  vm.membersVisible = false;
                });
            });
          }

          /**
           * @name logout
           * @desc logout the user and redirects to home page
           */
          function logout () {
            notificationsLeaveRoom(vm.project);
            accountService.logout();
            $state.go('home');
          }
      }
})();
<|endoftext|>


<commit_before>Meteor.startup(function(){
    if (Version.find().count() > 0){
        Version.remove({});
    }
    Version.insert(JSON.parse(Assets.getText("version.json")));
})

Push.allow({
    send: function(userId, notification) {
      return true; // Allow all users to send
    }
});

Meteor.users.allow({
			remove: function(userId){
				return true;
			},
			update: function(userId){
				return true;
			},
			insert: function(userId, role){
				return true;
			}
});

Images.allow({
 		insert: function(){
 				return true;
 		},
 		update: function(){
 				return true;
 		},
 		remove: function(){
 				return true;
 		},
 		download: function(){
 			return true;
 		}
});

// server: publish all question documents
Meteor.publish("allQuestions", function () {
  return Questions.find(); // everything
});

// server: publish all answers documents
Meteor.publish("allAnswers", function () {
  return Answers.find(); // everything
});

// server: publish all images
Meteor.publish("images", function() {
  return Images.find();
});

//server: publish githooks version info
Meteor.publish('version', function () {
  return Version.find();
});

Meteor.methods({
  serverNotification: function () {
    BlindNotification.insert({
      addedAt: new Date()
    }, function (error, result) {
      if (!error) {
        Push.send({
          from: Meteor.user().username,
          title: 'you have unseen notifications',
          text: 'new Question was asked',
          payload: {
            title: 'you have unseen notifications',
            historyId: result
          },
          query: {}
        });
      }
    });
  }
});
<commit_msg>Update server.js<commit_after>Meteor.startup(function(){
    if (Version.find().count() > 0){
        Version.remove({});
    }
    Version.insert(JSON.parse(Assets.getText("version.json")));
})

Push.allow({
    send: function(userId, notification) {
      return true; // Allow all users to send
    }
});

Meteor.users.allow({
			remove: function(userId){
				return true;
			},
			update: function(userId){
				return true;
			},
			insert: function(userId, role){
				return true;
			}
});

Images.allow({
 		insert: function(){
 				return true;
 		},
 		update: function(){
 				return true;
 		},
 		remove: function(){
 				return true;
 		},
 		download: function(){
 			return true;
 		}
});

// server: publish all question documents
Meteor.publish("allQuestions", function () {
  return Questions.find(); // everything
});

// server: publish all answers documents
Meteor.publish("allAnswers", function () {
  return Answers.find(); // everything
});

// server: publish all images
Meteor.publish("images", function() {
  return Images.find();
});

//server: publish githooks version info
Meteor.publish('version', function () {
  return Version.find();
});

Meteor.publish('notFromBlind', function () {
  return BlindNotification.find();
});

Meteor.methods({
  serverNotification: function () {
    BlindNotification.insert({
      addedAt: new Date()
    }, function (error, result) {
      if (!error) {
        Push.send({
          from: Meteor.user().username,
          title: 'you have unseen notifications',
          text: 'new Question was asked',
          payload: {
            title: 'you have unseen notifications',
            historyId: result
          },
          query: {}
        });
      }
    });
  }
});
<|endoftext|>


<commit_before>/*
  eslint strict: 0
  no-console: 0
*/

'use strict';

const express = require('express');
const app = express();
const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const partials = require('express-partials');
const favicon = require('express-favicon');
const Promise = require('bluebird');
const film = require('./routes/film');
const isDeveloping = process.env.NODE_ENV !== 'production';
const port = isDeveloping ? 3000 : process.env.PORT;

app.use(partials());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(favicon(`${__dirname}/favicon.ico`));

Promise.onPossiblyUnhandledRejection((err) => {
  throw new Error(err);
});

app.use('/api/film', film);

if (isDeveloping) {
  const webpackMiddleware = require('webpack-dev-middleware');
  const webpackHotMiddleware = require('webpack-hot-middleware');
  const config = require('./webpack/webpack.config.js');

  app.set('host', 'http://localhost');
  const compiler = webpack(config);
  const middleware = webpackMiddleware(compiler, {
    publicPath: config.output.publicPath,
    contentBase: 'src',
    stats: {
      colors: true,
      hash: false,
      timings: true,
      chunks: false,
      chunkModules: false,
      modules: false,
    },
  });
  const response = (req, res) => {
    res.write(middleware.fileSystem.readFileSync(path.resolve(__dirname, 'dist/index.html')));
    res.end();
  };

  app.use(middleware);
  app.use(webpackHotMiddleware(compiler));
  app.get('*', response);
} else {
  app.use(express.static(`${__dirname}/dist`));
  app.get('*', (req, res) => {
    res.write(
      fs.readFileSync(path.resolve(__dirname, 'dist/index.html'))
    );
  });
}

const onStart = (err) => {
  if (err) {
    throw new Error(err);
  }
  console.info(
    `==> 🌎 Listening on port ${port}. ` +
    `Open up http://localhost:${port}/ in your browser.`
  );
};

if (!module.parent) {
  app.listen(port, 'localhost', onStart);
}

module.exports = app;
<commit_msg>changed host name<commit_after>/*
  eslint strict: 0
  no-console: 0
*/

'use strict';

const express = require('express');
const app = express();
const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const partials = require('express-partials');
const favicon = require('express-favicon');
const Promise = require('bluebird');
const film = require('./routes/film');
const isDeveloping = process.env.NODE_ENV !== 'production';
const port = isDeveloping ? 3000 : process.env.PORT;

app.use(partials());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(favicon(`${__dirname}/favicon.ico`));

Promise.onPossiblyUnhandledRejection((err) => {
  throw new Error(err);
});

app.use('/api/film', film);

if (isDeveloping) {
  const webpackMiddleware = require('webpack-dev-middleware');
  const webpackHotMiddleware = require('webpack-hot-middleware');
  const config = require('./webpack/webpack.config.js');

  app.set('host', 'http://localhost');
  const compiler = webpack(config);
  const middleware = webpackMiddleware(compiler, {
    publicPath: config.output.publicPath,
    contentBase: 'src',
    stats: {
      colors: true,
      hash: false,
      timings: true,
      chunks: false,
      chunkModules: false,
      modules: false,
    },
  });
  const response = (req, res) => {
    res.write(middleware.fileSystem.readFileSync(path.resolve(__dirname, 'dist/index.html')));
    res.end();
  };

  app.use(middleware);
  app.use(webpackHotMiddleware(compiler));
  app.get('*', response);
} else {
  app.use(express.static(`${__dirname}/dist`));
  app.get('*', (req, res) => {
    res.write(
      fs.readFileSync(path.resolve(__dirname, 'dist/index.html'))
    );
  });
}

const onStart = (err) => {
  if (err) {
    throw new Error(err);
  }
  console.info(
    `==> 🌎 Listening on port ${port}. ` +
    `Open up http://localhost:${port}/ in your browser.`
  );
};

if (!module.parent) {
  app.listen(port, '0.0.0.0', onStart);
}

module.exports = app;
<|endoftext|>


<commit_before>// newrelic is not working with latest npm if(process.env.NEW_RELIC_APP_NAME) require('newrelic');

import path from 'path';
import Koa from 'koa';
import mount from 'koa-mount';
import helmet from 'koa-helmet';
import koa_logger from 'koa-logger';
import prod_logger from './prod_logger';
import favicon from 'koa-favicon';
import staticCache from 'koa-static-cache';
import useRedirects from './redirects';
import useOauthLogin from './api/oauth';
import useGeneralApi from './api/general';
import useAccountRecoveryApi from './api/account_recovery';
import useNotificationsApi from './api/notifications';
import useEnterAndConfirmEmailPages from './server_pages/enter_confirm_email';
import useEnterAndConfirmMobilePages from './server_pages/enter_confirm_mobile';
import useUserJson from './json/user_json';
import isBot from 'koa-isbot';
import session from '@steem/crypto-session';
import csrf from 'koa-csrf';
import flash from 'koa-flash';
import minimist from 'minimist';
import Grant from 'grant-koa';
import config from '../config';
import {routeRegex} from 'app/ResolveRoute';
import secureRandom from 'secure-random';

const grant = new Grant(config.grant);
// import uploadImage from 'server/upload-image' //medium-editor

const app = new Koa();
app.name = 'Steemit app';
const env = process.env.NODE_ENV || 'development';
const cacheOpts = {maxAge: 86400000, gzip: true};

app.keys = [config.session_key];
const crypto_key = config.server_session_secret;
session(app, {maxAge: 1000 * 3600 * 24 * 60, crypto_key, key: config.session_cookie_key});
csrf(app);

app.use(mount(grant));
app.use(flash({key: 'flash'}));

// some redirects
app.use(function *(next) {
    // redirect to home page/feed if known account
    if (this.method === 'GET' && this.url === '/' && this.session.a) {
        this.status = 302;
        this.redirect(`/@${this.session.a}/feed`);
        return;
    }
    // normalize user name url from cased params
    if (this.method === 'GET' && routeRegex.UserProfile1.test(this.url)) {
        const p = this.originalUrl.toLowerCase();
        if(p !== this.originalUrl) {
            this.redirect(p);
            return;
        }
    }
    // // handle non-existing users endpoints with 404
    if (this.method === 'GET' && routeRegex.PostNoCategory.test(this.url)) {
        const segments = this.url.split('/');
        if(segments[2] && !routeRegex.UserEndPoints.test(segments[2])) {
            this.status = 404;
            return;
        }
    }
    // normalize top category filtering from cased params
    if (this.method === 'GET' && routeRegex.CategoryFilters.test(this.url)) {
        const p = this.originalUrl.toLowerCase();
        if(p !== this.originalUrl) {
            this.redirect(p);
            return;
        }
    }
    // start registration process if user get to create_account page and has no id in session yet
    if(this.url === '/create_account' && !this.session.user) {
        this.status = 302;
        this.redirect('/enter_email');
        return;
    }
    // remember ch, cn, r url params in the session and remove them from url
    if (this.method === 'GET' && /\?[^\w]*(ch=|cn=|r=)/.test(this.url)) {
        let redir = this.url.replace(/((ch|cn|r)=[^&]+)/gi, r => {
            const p = r.split('=');
            if (p.length === 2) this.session[p[0]] = p[1];
            return '';
        });
        redir = redir.replace(/&&&?/, '');
        redir = redir.replace(/\?&?$/, '');
        console.log(`server redirect ${this.url} -> ${redir}`);
        this.status = 302;
        this.redirect(redir);
    } else {
        yield next;
    }
});

if (env === 'production') {
    // load production middleware
    app.use(require('koa-conditional-get')());
    app.use(require('koa-etag')());
    app.use(require('koa-compressor')());
    app.use(prod_logger());
} else {
    app.use(koa_logger());
}

app.use(helmet());

app.use(mount('/static', staticCache(path.join(__dirname, '../app/assets/static'), cacheOpts)));

app.use(mount('/robots.txt', function* () {
    this.set('Cache-Control', 'public, max-age=86400000');
    this.type = 'text/plain';
    this.body = "User-agent: *\nAllow: /";
}));

// set user's uid - used to identify users in logs and some other places
app.use(function* (next) {
    const last_visit = this.session.last_visit;
    this.session.last_visit = (new Date()).getTime() / 1000 | 0;
    if (!this.session.uid) {
        this.session.uid = secureRandom.randomBuffer(13).toString('hex');
        this.session.new_visit = true;
    } else {
        this.session.new_visit = this.session.last_visit - last_visit > 1800;
    }
    yield next;
});

useRedirects(app);
useEnterAndConfirmEmailPages(app);
useEnterAndConfirmMobilePages(app);
useUserJson(app);

if (env === 'production') {
    app.use(helmet.contentSecurityPolicy(config.helmet));
}

useAccountRecoveryApi(app);
useOauthLogin(app);
useGeneralApi(app);
useNotificationsApi(app);

app.use(favicon(path.join(__dirname, '../app/assets/images/favicons/favicon.ico')));
app.use(isBot());
app.use(mount('/favicons', staticCache(path.join(__dirname, '../app/assets/images/favicons'), cacheOpts)));
app.use(mount('/images', staticCache(path.join(__dirname, '../app/assets/images'), cacheOpts)));
// Proxy asset folder to webpack development server in development mode
if (env === 'development') {
    const PORT = parseInt(process.env.PORT, 10) + 1 || 3001;
    const proxy = require('koa-proxy')({
        host: 'http://0.0.0.0:' + PORT,
        map: (filePath) => 'assets/' + filePath
    });
    app.use(mount('/assets', proxy));
} else {
    app.use(mount('/assets', staticCache(path.join(__dirname, '../dist'), cacheOpts)));
}

if (env !== 'test') {
    const appRender = require('./app_render');
    app.use(function* () {
        yield appRender(this);
        // if (app_router.dbStatus.ok) recordWebEvent(this, 'page_load');
        const bot = this.state.isBot;
        if (bot) {
            console.log(`  --> ${this.method} ${this.originalUrl} ${this.status} (BOT '${bot}')`);
        }
    });

    const argv = minimist(process.argv.slice(2));
    const port = parseInt(argv.port, 10) || parseInt(process.env.PORT, 10) || 3002;
    app.listen(port);

    // Tell parent process koa-server is started
    if (process.send) process.send('online');
    console.log(`Application started on port ${port}`);
}

module.exports = app;
<commit_msg>Tweak route settings (#890)<commit_after>// newrelic is not working with latest npm if(process.env.NEW_RELIC_APP_NAME) require('newrelic');

import path from 'path';
import Koa from 'koa';
import mount from 'koa-mount';
import helmet from 'koa-helmet';
import koa_logger from 'koa-logger';
import prod_logger from './prod_logger';
import favicon from 'koa-favicon';
import staticCache from 'koa-static-cache';
import useRedirects from './redirects';
import useOauthLogin from './api/oauth';
import useGeneralApi from './api/general';
import useAccountRecoveryApi from './api/account_recovery';
import useNotificationsApi from './api/notifications';
import useEnterAndConfirmEmailPages from './server_pages/enter_confirm_email';
import useEnterAndConfirmMobilePages from './server_pages/enter_confirm_mobile';
import useUserJson from './json/user_json';
import isBot from 'koa-isbot';
import session from '@steem/crypto-session';
import csrf from 'koa-csrf';
import flash from 'koa-flash';
import minimist from 'minimist';
import Grant from 'grant-koa';
import config from '../config';
import {routeRegex} from 'app/ResolveRoute';
import secureRandom from 'secure-random';

const grant = new Grant(config.grant);
// import uploadImage from 'server/upload-image' //medium-editor

const app = new Koa();
app.name = 'Steemit app';
const env = process.env.NODE_ENV || 'development';
const cacheOpts = {maxAge: 86400000, gzip: true};

app.keys = [config.session_key];
const crypto_key = config.server_session_secret;
session(app, {maxAge: 1000 * 3600 * 24 * 60, crypto_key, key: config.session_cookie_key});
csrf(app);

app.use(mount(grant));
app.use(flash({key: 'flash'}));

// some redirects
app.use(function *(next) {
    // redirect to home page/feed if known account
    if (this.method === 'GET' && this.url === '/' && this.session.a) {
        this.status = 302;
        this.redirect(`/@${this.session.a}/feed`);
        return;
    }
    // normalize user name url from cased params
    if (this.method === 'GET' && (routeRegex.UserProfile1.test(this.url) || routeRegex.PostNoCategory.test(this.url))) {
        const p = this.originalUrl.toLowerCase();
        if(p !== this.originalUrl) {
            this.status = 301;
            this.redirect(p);
            return;
        }
    }
    // normalize top category filtering from cased params
    if (this.method === 'GET' && routeRegex.CategoryFilters.test(this.url)) {
        const p = this.originalUrl.toLowerCase();
        if(p !== this.originalUrl) {
            this.status = 301;
            this.redirect(p);
            return;
        }
    }
    // start registration process if user get to create_account page and has no id in session yet
    if(this.url === '/create_account' && !this.session.user) {
        this.status = 302;
        this.redirect('/enter_email');
        return;
    }
    // remember ch, cn, r url params in the session and remove them from url
    if (this.method === 'GET' && /\?[^\w]*(ch=|cn=|r=)/.test(this.url)) {
        let redir = this.url.replace(/((ch|cn|r)=[^&]+)/gi, r => {
            const p = r.split('=');
            if (p.length === 2) this.session[p[0]] = p[1];
            return '';
        });
        redir = redir.replace(/&&&?/, '');
        redir = redir.replace(/\?&?$/, '');
        console.log(`server redirect ${this.url} -> ${redir}`);
        this.status = 302;
        this.redirect(redir);
    } else {
        yield next;
    }
});

if (env === 'production') {
    // load production middleware
    app.use(require('koa-conditional-get')());
    app.use(require('koa-etag')());
    app.use(require('koa-compressor')());
    app.use(prod_logger());
} else {
    app.use(koa_logger());
}

app.use(helmet());

app.use(mount('/static', staticCache(path.join(__dirname, '../app/assets/static'), cacheOpts)));

app.use(mount('/robots.txt', function* () {
    this.set('Cache-Control', 'public, max-age=86400000');
    this.type = 'text/plain';
    this.body = "User-agent: *\nAllow: /";
}));

// set user's uid - used to identify users in logs and some other places
app.use(function* (next) {
    const last_visit = this.session.last_visit;
    this.session.last_visit = (new Date()).getTime() / 1000 | 0;
    if (!this.session.uid) {
        this.session.uid = secureRandom.randomBuffer(13).toString('hex');
        this.session.new_visit = true;
    } else {
        this.session.new_visit = this.session.last_visit - last_visit > 1800;
    }
    yield next;
});

useRedirects(app);
useEnterAndConfirmEmailPages(app);
useEnterAndConfirmMobilePages(app);
useUserJson(app);

if (env === 'production') {
    app.use(helmet.contentSecurityPolicy(config.helmet));
}

useAccountRecoveryApi(app);
useOauthLogin(app);
useGeneralApi(app);
useNotificationsApi(app);

app.use(favicon(path.join(__dirname, '../app/assets/images/favicons/favicon.ico')));
app.use(isBot());
app.use(mount('/favicons', staticCache(path.join(__dirname, '../app/assets/images/favicons'), cacheOpts)));
app.use(mount('/images', staticCache(path.join(__dirname, '../app/assets/images'), cacheOpts)));
// Proxy asset folder to webpack development server in development mode
if (env === 'development') {
    const PORT = parseInt(process.env.PORT, 10) + 1 || 3001;
    const proxy = require('koa-proxy')({
        host: 'http://0.0.0.0:' + PORT,
        map: (filePath) => 'assets/' + filePath
    });
    app.use(mount('/assets', proxy));
} else {
    app.use(mount('/assets', staticCache(path.join(__dirname, '../dist'), cacheOpts)));
}

if (env !== 'test') {
    const appRender = require('./app_render');
    app.use(function* () {
        yield appRender(this);
        // if (app_router.dbStatus.ok) recordWebEvent(this, 'page_load');
        const bot = this.state.isBot;
        if (bot) {
            console.log(`  --> ${this.method} ${this.originalUrl} ${this.status} (BOT '${bot}')`);
        }
    });

    const argv = minimist(process.argv.slice(2));
    const port = parseInt(argv.port, 10) || parseInt(process.env.PORT, 10) || 3002;
    app.listen(port);

    // Tell parent process koa-server is started
    if (process.send) process.send('online');
    console.log(`Application started on port ${port}`);
}

module.exports = app;
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
//var reqLogger= require('morgan');
var log4js = require('log4js');
/*
log4js.configure({
  appenders: [
    {type: 'console'},
    {type: 'file', filename: 'logs/app.log', category: 'app'}
  ]
});
*/

var bodyParser = require('body-parser');

var app = express();
var log = log4js.getLogger('app');
console.log('app.get("env"): ' + app.get('env'));
console.log('process.argv[2]: ' + process.argv[2]);
var environment = process.argv[2] || app.get('env') || 'development';
var serverConfig = require('./env.json')[ environment ];

console.log('Stringify environment: ' + JSON.stringify(serverConfig));

// view engine setup
/*
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'jade');
*/
//app.use(reqLogger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', express.static('./client/'));
app.use('/', express.static('./'));

var model = require('./model/model.js');
model = model(log4js, serverConfig.dbFile);
model.connect();

var notify = require('./notify/notify.js');
notify = notify(log4js, model);

/**
 * set api routes up
 */
var api = require('./api/api.js');
api = api(log4js, express, model, notify);
app.use(api);

/**
 *
 * Status Codes
 *
 */

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

/**
 *
 * Error Handlers
 *
 */
/*
if (environment === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    log.error(err.message);
    log.error(err.stack);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  log.error(err.message);
  log.error(err.stack);
  res.render('error', {
    message: err.message,
    error: {}
  });
});
*/
var server = app.listen(serverConfig.port, function () {
  log.info('lwefd listening on port '+ serverConfig.port)
});

module.exports = app;
<commit_msg>removing irrelevant debugging statements<commit_after>var express = require('express');
var path = require('path');
//var reqLogger= require('morgan');
var log4js = require('log4js');
/*
log4js.configure({
  appenders: [
    {type: 'console'},
    {type: 'file', filename: 'logs/app.log', category: 'app'}
  ]
});
*/

var bodyParser = require('body-parser');

var app = express();
var log = log4js.getLogger('app');
var environment = process.argv[2] || app.get('env') || 'development';
var serverConfig = require('./env.json')[ environment ];

// view engine setup
/*
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'jade');
*/
//app.use(reqLogger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', express.static('./client/'));
app.use('/', express.static('./'));

var model = require('./model/model.js');
model = model(log4js, serverConfig.dbFile);
model.connect();

var notify = require('./notify/notify.js');
notify = notify(log4js, model);

/**
 * set api routes up
 */
var api = require('./api/api.js');
api = api(log4js, express, model, notify);
app.use(api);

/**
 *
 * Status Codes
 *
 */

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

/**
 *
 * Error Handlers
 *
 */
/*
if (environment === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    log.error(err.message);
    log.error(err.stack);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  log.error(err.message);
  log.error(err.stack);
  res.render('error', {
    message: err.message,
    error: {}
  });
});
*/
var server = app.listen(serverConfig.port, function () {
  log.info('lwefd listening on port '+ serverConfig.port)
});

module.exports = app;
<|endoftext|>


<commit_before>const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
var path = require('path');

const app = express();

app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, '../')));

const port = process.env.PORT || 3000;
app.listen(port);
console.log(`Listening on port: ${port}`);
<commit_msg>Add request-handler file connection<commit_after>const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
var path = require('path');

const app = express();

// Middleware
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, '../')));

// Routes
require('./routes.js')(app);

const port = process.env.PORT || 3000;
app.listen(port);
console.log(`Listening on port: ${port}`);
<|endoftext|>


<commit_before>/**
 * Created by garie on 12/10/2015.
 */
Slingshot.createDirective("myFileUploads", Slingshot.S3Storage, {
    bucket: Meteor.settings.bucket,
    acl: Meteor.settings.acl,
    AWSAccessKeyId: Meteor.settings.AWSAccessKeyId,
    AWSSecretAccessKey: Meteor.settings.AWSSecretAccessKey,
    region: Meteor.settings.region,

    authorize: function () {
        //Deny uploads if user is not logged in.
        //if (!this.userId) {
        //    var message = "Please login before posting files";
        //    throw new Meteor.Error("Login Required", message);
        //}
        console.log('authorized');
        return true;
    },

    key: function (file) {
        //Store file into a directory by the user's username.
        //var user = Meteor.users.findOne(this.userId);
        //var wish = Meteor.wishes._id;
        //console.log(wish);
        return Date.now().toString();
    }
});

SearchSource.defineSource('channels', function(searchText, options) {
    //var options = {limit: 20};

    if(searchText) {
        var regExp = buildRegExp(searchText);
        var selector = {name: regExp};

        //console.log(Channels.find(selector).fetch());

        return Channels.find(selector).fetch();
    } else {

        return Channels.find({}).fetch();
    }
});

function buildRegExp(searchText) {
    // this is a dumb implementation
    var parts = searchText.trim().split(/[ \-\:]+/);
    var newRegEx = new RegExp("(" + parts.join('|') + ")", "ig");

    return new RegExp("(" + parts.join('|') + ")", "ig");
}<commit_msg>fixed server.js<commit_after>/**
 * Created by garie on 12/10/2015.
 */
if (Meteor.isServer) {
    Slingshot.createDirective("myFileUploads", Slingshot.S3Storage, {
    bucket: Meteor.settings.bucket,
    acl: Meteor.settings.acl,
    AWSAccessKeyId: Meteor.settings.AWSAccessKeyId,
    AWSSecretAccessKey: Meteor.settings.AWSSecretAccessKey,
    region: Meteor.settings.region,

    authorize: function () {
        //Deny uploads if user is not logged in.
        //if (!this.userId) {
        //    var message = "Please login before posting files";
        //    throw new Meteor.Error("Login Required", message);
        //}
        console.log('authorized');
        return true;
    },

    key: function (file) {
        //Store file into a directory by the user's username.
        //var user = Meteor.users.findOne(this.userId);
        //var wish = Meteor.wishes._id;
        //console.log(wish);
        return Date.now().toString();
    }
});

SearchSource.defineSource('channels', function(searchText, options) {
    //var options = {limit: 20};

    if(searchText) {
        var regExp = buildRegExp(searchText);
        var selector = {name: regExp};

        //console.log(Channels.find(selector).fetch());

        return Channels.find(selector).fetch();
    } else {

        return Channels.find({}).fetch();
    }
});

function buildRegExp(searchText) {
    // this is a dumb implementation
    var parts = searchText.trim().split(/[ \-\:]+/);
    var newRegEx = new RegExp("(" + parts.join('|') + ")", "ig");

    return new RegExp("(" + parts.join('|') + ")", "ig");
}
}<|endoftext|>


<commit_before>if (Meteor.isServer) {
  self= this;

  markers = new Meteor.Collection("markers");

  markers._ensureIndex({ loc : "2d" });

  users = new Meteor.Collection("user");

  agencies = new Meteor.Collection("agencies");

    Meteor.publish("myMarkers"),function(agency_id,group_id,vis){
  //      console.log(this);
//        var agency = agencies.find({_id:agency_id},{});
        // eventually get agency id..
        return markers.find();

    }

  Meteor.startup(function () {
    // theres no org..

 });

   Meteor.methods({

    isLoggedIn : function(uid){

    },

    isAdmin : function(uid){
        // do we have session here?
        console.log(Session);
        return true;
    },

    newAgency : function(title,type){
        // figure out user id??? how???
        var user_id = '', timestamp = 212930212;
      //  agencies.insert({"title": title,"type":type,"owner":user_id,"created":timestamp});

    },

    findAgencies : function(agency_id){
        //

    },

    findMarker : function(x,y){
        console.log(x);
        console.log(y);
         markers._ensureIndex({ loc : "2d" });
         var theCenter = [[x,y],.1];
         // returns everything
         var r = markers.find({ loc : { "$geoWithin" : { "$center" : theCenter }}}).fetch();
         console.log(r.length);
        return r;
    },
    findMarkers : function(){
        console.log('finding markers');
        return markers.find({},{}).fetch();
    },
    markersIndex : function(){
        console.log('finding markers index');
        var c = markers.find({},{}).fetch(),r=[];
        c.filter(function(arr){
            console.log(arr);
            var x = {}
            // use underscore for this..
            x._id = arr._id;
            x.marker_name = arr.marker_name;
            r.push(x);
        });
        return r;
    }
  });
}<commit_msg>fixed typo in server.js for publish<commit_after>if (Meteor.isServer) {
  self= this;

  markers = new Meteor.Collection("markers");

  markers._ensureIndex({ loc : "2d" });

  users = new Meteor.Collection("user");

  agencies = new Meteor.Collection("agencies");

  Meteor.publish("myMarkers", function(agency_id,group_id,vis){
  //      console.log(this);
//        var agency = agencies.find({_id:agency_id},{});
        // eventually get agency id..
        return markers.find();

    });

  Meteor.startup(function () {
    // theres no org..

 });

   Meteor.methods({

    isLoggedIn : function(uid){

    },

    isAdmin : function(uid){
        // do we have session here?
        console.log(Session);
        return true;
    },

    newAgency : function(title,type){
        // figure out user id??? how???
        var user_id = '', timestamp = 212930212;
      //  agencies.insert({"title": title,"type":type,"owner":user_id,"created":timestamp});

    },

    findAgencies : function(agency_id){
        //

    },

    findMarker : function(x,y){
        console.log(x);
        console.log(y);
         markers._ensureIndex({ loc : "2d" });
         var theCenter = [[x,y],.1];
         // returns everything
         var r = markers.find({ loc : { "$geoWithin" : { "$center" : theCenter }}}).fetch();
         console.log(r.length);
        return r;
    },
    findMarkers : function(){
        console.log('finding markers');
        return markers.find({},{}).fetch();
    },
    markersIndex : function(){
        console.log('finding markers index');
        var c = markers.find({},{}).fetch(),r=[];
        c.filter(function(arr){
            console.log(arr);
            var x = {}
            // use underscore for this..
            x._id = arr._id;
            x.marker_name = arr.marker_name;
            r.push(x);
        });
        return r;
    }
  });
}<|endoftext|>


<commit_before>// DEPENDENCIES
// ============

var Config =  global.Config = require('./config/config').config,
    express = require("express"),
    require('./newrelic');
    bcrypt = require("bcrypt-nodejs"),
    _ = require("underscore"),
    http =    require("http"),
    exphbs = require('express3-handlebars'),
    path = require('path'),
    port =    ( process.env.PORT || Config.listenPort ),
    mongoose =     require('mongoose'),
    server =  module.exports = express();
    // API =     require('./routes/API');
    // API =     require('./routes/API');

// DATABASE CONFIGURATION
// ======================

// Connect to Database
mongoose.connect(Config.database.mongohq_url);
// mongoose.connect('mongodb://' + Config.database.IP + ':' + Config.database.port + '/' + Config.database.name);

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'DB connection error:'));
db.once('open', function callback () {
  console.log('Connected to ' + Config.database.name);
});

// // DATABASE SCHEMAS
// // ================

// var schema = require('./schemas/schema');

// SERVER CONFIGURATION
// ====================

server.enable('trust proxy');

server.configure('local', function(){
    server.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
server.configure('development', function(){
    server.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
server.configure('production', function(){
    server.use(express.errorHandler());
});

server.configure(function() {

  server.set('views', path.join(__dirname, '/views'));

  server.engine('handlebars', exphbs({
    defaultLayout:'main',
    layoutsDir: server.get('views') + '/layouts'
  }));

  server.set('view engine', 'handlebars');

  server.use('/', express.static(path.join(__dirname + "./../public")));
  server.use('/tests', express.static(path.join(__dirname + "./../public")));

  server.use(express.errorHandler({

    dumpExceptions: true,

    showStack: true

  }));

  server.use( express.compress() );

  server.use( express.urlencoded() );            // Needed to parse POST data sent as JSON payload

  server.use( express.json() );

  server.use(express.bodyParser());

  server.use(express.methodOverride());

  // server.use(express.cookieParser());

  // server.use(express.session({ secret: Config.sessionSecret }));

  server.use( express.cookieParser( Config.cookieSecret ) );           // populates req.signedCookies
  server.use( express.cookieSession( Config.sessionSecret ) );

  server.use(server.router);

});

// API
// ===

// API.api(server);
require('./routes/api')(server);
require('./routes/blog')(server);
require('./routes/blog_admin')(server);
require('./routes/comments')(server);
require('./routes/index')(server);
require('./routes/tests')(server);
require('./routes/trivia')(server);
require('./routes/users')(server);

// Start Node.js Server
http.createServer(server).listen(port);

console.log('\n\nWelcome to Stacked!\n\nPlease go to http://localhost:' + port + ' to start using Require.js and Backbone.js\n\n');
<commit_msg>syntax error<commit_after>// DEPENDENCIES
// ============

require('./newrelic');
var Config =  global.Config = require('./config/config').config,
    express = require("express"),
    bcrypt = require("bcrypt-nodejs"),
    _ = require("underscore"),
    http =    require("http"),
    exphbs = require('express3-handlebars'),
    path = require('path'),
    port =    ( process.env.PORT || Config.listenPort ),
    mongoose =     require('mongoose'),
    server =  module.exports = express();
    // API =     require('./routes/API');
    // API =     require('./routes/API');

// DATABASE CONFIGURATION
// ======================

// Connect to Database
mongoose.connect(Config.database.mongohq_url);
// mongoose.connect('mongodb://' + Config.database.IP + ':' + Config.database.port + '/' + Config.database.name);

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'DB connection error:'));
db.once('open', function callback () {
  console.log('Connected to ' + Config.database.name);
});

// // DATABASE SCHEMAS
// // ================

// var schema = require('./schemas/schema');

// SERVER CONFIGURATION
// ====================

server.enable('trust proxy');

server.configure('local', function(){
    server.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
server.configure('development', function(){
    server.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
server.configure('production', function(){
    server.use(express.errorHandler());
});

server.configure(function() {

  server.set('views', path.join(__dirname, '/views'));

  server.engine('handlebars', exphbs({
    defaultLayout:'main',
    layoutsDir: server.get('views') + '/layouts'
  }));

  server.set('view engine', 'handlebars');

  server.use('/', express.static(path.join(__dirname + "./../public")));
  server.use('/tests', express.static(path.join(__dirname + "./../public")));

  server.use(express.errorHandler({

    dumpExceptions: true,

    showStack: true

  }));

  server.use( express.compress() );

  server.use( express.urlencoded() );            // Needed to parse POST data sent as JSON payload

  server.use( express.json() );

  server.use(express.bodyParser());

  server.use(express.methodOverride());

  // server.use(express.cookieParser());

  // server.use(express.session({ secret: Config.sessionSecret }));

  server.use( express.cookieParser( Config.cookieSecret ) );           // populates req.signedCookies
  server.use( express.cookieSession( Config.sessionSecret ) );

  server.use(server.router);

});

// API
// ===

// API.api(server);
require('./routes/api')(server);
require('./routes/blog')(server);
require('./routes/blog_admin')(server);
require('./routes/comments')(server);
require('./routes/index')(server);
require('./routes/tests')(server);
require('./routes/trivia')(server);
require('./routes/users')(server);

// Start Node.js Server
http.createServer(server).listen(port);

console.log('\n\nWelcome to Stacked!\n\nPlease go to http://localhost:' + port + ' to start using Require.js and Backbone.js\n\n');
<|endoftext|>


<commit_before>// Copyright 2014 Endless Mobile, Inc.

const Endless = imports.gi.Endless;
const EosKnowledge = imports.gi.EosKnowledge;
const GObject = imports.gi.GObject;
const Gtk = imports.gi.Gtk;
const Lang = imports.lang;

const HomePage = imports.homePage;
const Config = imports.config;

/**
 * Class: HomePageB
 *
 * This represents the home page for template B of the knowledge apps.
 * It extends <HomePage> and has a title image and list of article cards to show.
 * The list of cards only accepts 4, 6 or 8 cards.
 *
 */
const HomePageB = new Lang.Class({
    Name: 'HomePageB',
    GTypeName: 'EknHomePageB',
    Extends: HomePage.HomePage,

    _init: function (props) {
        this._card_container = new Gtk.Grid({
            column_homogeneous: true,
            row_homogeneous: true,
            hexpand: true
        });

        this.parent(props);

        this.get_style_context().add_class(EosKnowledge.STYLE_CLASS_HOME_PAGE_B);
    },

    pack_widgets: function (title_image, search_box) {
        title_image.vexpand = true;
        search_box.halign = Gtk.Align.CENTER;
        search_box.width_chars = 40;

        let card_container_frame = new Gtk.Frame();
        card_container_frame.get_style_context().add_class(EosKnowledge.STYLE_CLASS_CARD_CONTAINER);
        card_container_frame.add(this._card_container);

        this.attach(title_image, 0, 0, 1, 1);
        this.attach(search_box, 1, 0, 1, 1);
        this.attach(card_container_frame, 0, 1, 2, 1);
    },

    pack_cards: function (cards) {
        let _allowed_card_numbers = [4, 6, 8];
        if (_allowed_card_numbers.indexOf(cards.length) < 0)
            printerr('Should only set 4, 6 or 8 cards in template B. ' + cards.length);

        for (let card of this._card_container.get_children()) {
            this._card_container.remove(card);
        }
        // FIXME: For now we're always showing two rows of cards.
        // An alternative would be to show 1 row for 4 cards, and 2 rows otherwise
        // let columns = this._cards.length === 6 ? 3 : 4;
        let columns = cards.length / 2;
        let i = 0;
        for (let card of cards) {
            let col = i % columns;
            let row = Math.floor(i / columns);
            this._card_container.attach(card, col, row, 1, 1);
            i++;
        }
    }
});
<commit_msg>Cards take up two thirds of screen size on template B<commit_after>// Copyright 2014 Endless Mobile, Inc.

const Endless = imports.gi.Endless;
const EosKnowledge = imports.gi.EosKnowledge;
const GObject = imports.gi.GObject;
const Gtk = imports.gi.Gtk;
const Lang = imports.lang;

const HomePage = imports.homePage;
const Config = imports.config;

/**
 * Class: HomePageB
 *
 * This represents the home page for template B of the knowledge apps.
 * It extends <HomePage> and has a title image and list of article cards to show.
 * The list of cards only accepts 4, 6 or 8 cards.
 *
 */
const HomePageB = new Lang.Class({
    Name: 'HomePageB',
    GTypeName: 'EknHomePageB',
    Extends: HomePage.HomePage,

    _init: function (props) {
        this._card_container = new Gtk.Grid({
            column_homogeneous: true,
            row_homogeneous: true,
            hexpand: true
        });

        this.parent(props);

        this.get_style_context().add_class(EosKnowledge.STYLE_CLASS_HOME_PAGE_B);
    },

    pack_widgets: function (title_image, search_box) {
        title_image.vexpand = true;
        search_box.halign = Gtk.Align.CENTER;
        search_box.width_chars = 40;

        let card_container_frame = new Gtk.Frame();
        card_container_frame.get_style_context().add_class(EosKnowledge.STYLE_CLASS_CARD_CONTAINER);
        card_container_frame.add(this._card_container);

        this.row_homogeneous = true;
        this.attach(title_image, 0, 0, 1, 1);
        this.attach(search_box, 1, 0, 1, 1);
        this.attach(card_container_frame, 0, 1, 2, 2);
    },

    pack_cards: function (cards) {
        let _allowed_card_numbers = [4, 6, 8];
        if (_allowed_card_numbers.indexOf(cards.length) < 0)
            printerr('Should only set 4, 6 or 8 cards in template B. ' + cards.length);

        for (let card of this._card_container.get_children()) {
            this._card_container.remove(card);
        }
        // FIXME: For now we're always showing two rows of cards.
        // An alternative would be to show 1 row for 4 cards, and 2 rows otherwise
        // let columns = this._cards.length === 6 ? 3 : 4;
        let columns = cards.length / 2;
        let i = 0;
        for (let card of cards) {
            let col = i % columns;
            let row = Math.floor(i / columns);
            this._card_container.attach(card, col, row, 1, 1);
            i++;
        }
    }
});
<|endoftext|>


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

var app = express();

app.get('/cars', function (req, res) {
        res.send([
            {
                make: 'BMW',
                model: '4 series',
                year: 2014
            },
            {
                make: 'BMW',
                model: '3 series',
                year: 2011
            },
            {
                make: 'BMW',
                model: '7 series',
                year: 2013
            },
            {
                make: 'Mercedes',
                model: 'C-Class',
                year: 2012
            },
            {
                make: 'Mercedes',
                model: 'S-Class',
                year: 2010
            },
            {
                make: 'Audi',
                model: 'A4',
                year: 2015
            },
            {
                make: 'Audi',
                model: 'A5',
                year: 2012
            },
            {
                make: 'Ford',
                model: 'Fusion',
                year: 2011
            }
        ]);
});

var server = app.listen(8081, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log("Example app listening at http://%s:%s", host, port);
});<commit_msg>Fixed server response<commit_after>var express = require('express');

var app = express();

app.get('/cars', function (req, res) {
    res.send({
        data: [
            {
                make: 'BMW',
                model: '4 series',
                year: 2014
            },
            {
                make: 'BMW',
                model: '3 series',
                year: 2011
            },
            {
                make: 'BMW',
                model: '7 series',
                year: 2013
            },
            {
                make: 'Mercedes',
                model: 'C-Class',
                year: 2012
            },
            {
                make: 'Mercedes',
                model: 'S-Class',
                year: 2010
            },
            {
                make: 'Audi',
                model: 'A4',
                year: 2015
            },
            {
                make: 'Audi',
                model: 'A5',
                year: 2012
            },
            {
                make: 'Ford',
                model: 'Fusion',
                year: 2011
            }
        ]
    });
});

var server = app.listen(8081, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log("Example app listening at http://%s:%s", host, port);
});<|endoftext|>


<commit_before>var router = require('./router');
var viewEngine = require('./view_engine');
var env = require('../config/environments/env');
var assetCompiler = require('./lib/assetCompiler');

exports.dataAdapter = null;

// ===== VIEWS =====

exports.viewConfig =  {
  engineName: 'coffee',
  engine: viewEngine.engine,
  viewDir: env.paths.viewDir,
  publicDir: env.paths.publicDir,
  apiPath:'/api'
};

// ===== ROUTES =====

exports.routes = function() {
  return router.routes();
};

// ===== MIDDLEWARE =====

var createAppInstance = function() {
  return function(req, res, next) {
    var App = require(env.paths.entryPath + "/app");  // moweb/app/app.coffee
    req.rendrApp = new App;
    next();
  };
};

exports.middleware = function() {
  return [ createAppInstance() ];
};

// ===== LIBRARIES =====

/**
  - options
    - logger
    - dataAdapter
*/
exports.initLibs = function(options, callback) {
  if (!options) options = {};

  // pass down stashError and stashPerf to router
  router.init(options);

  exports.dataAdapter = options.dataAdapter;

  if (env.current.assetCompiler && env.current.assetCompiler.enabled) {
    assetCompiler.init(env.current.assetCompiler, options.logger, function(err) {
      if (err) return callback(err);
      assetCompiler.compile(callback);
    });
  } else {
    callback();
  }
};

exports.closeLibs = function(callback) {
  callback();
};

<commit_msg>don't compile assets at init<commit_after>var router = require('./router');
var viewEngine = require('./view_engine');
var env = require('../config/environments/env');
//var assetCompiler = require('./lib/assetCompiler');

exports.dataAdapter = null;

// ===== VIEWS =====

exports.viewConfig =  {
  engineName: 'coffee',
  engine: viewEngine.engine,
  viewDir: env.paths.viewDir,
  publicDir: env.paths.publicDir,
  apiPath:'/api'
};

// ===== ROUTES =====

exports.routes = function() {
  return router.routes();
};

// ===== MIDDLEWARE =====

var createAppInstance = function() {
  return function(req, res, next) {
    var App = require(env.paths.entryPath + "/app");  // moweb/app/app.coffee
    req.rendrApp = new App;
    next();
  };
};

exports.middleware = function() {
  return [ createAppInstance() ];
};

// ===== LIBRARIES =====

/**
  - options
    - logger
    - dataAdapter
*/
exports.initLibs = function(options, callback) {
  if (!options) options = {};

  // pass down stashError and stashPerf to router
  router.init(options);

  exports.dataAdapter = options.dataAdapter;

  callback();
  // if (env.current.assetCompiler && env.current.assetCompiler.enabled) {
  //   assetCompiler.init(env.current.assetCompiler, options.logger, function(err) {
  //     if (err) return callback(err);
  //     assetCompiler.compile(callback);
  //   });
  // } else {
  //   callback();
  // }
};

exports.closeLibs = function(callback) {
  callback();
};

<|endoftext|>


<commit_before>console.log('Hello world!');<commit_msg>Add basic server functionality<commit_after>var express     = require('express');
var server      = express();
var port        = process.env.PORT || 4000;
var bodyParser  = require('body-parser');
var router      = express.Router();

server.listen(port);
console.log('The Butler Server is running on port: ' + port);<|endoftext|>


<commit_before>import path from 'path';
import Koa from 'koa';
import mount from 'koa-mount';
import helmet from 'koa-helmet';
import koa_logger from 'koa-logger';
import prod_logger from './prod_logger';
import favicon from 'koa-favicon';
import staticCache from 'koa-static-cache';
import useRedirects from './redirects';
import useOauthLogin from './api/oauth';
import useGeneralApi from './api/general';
import useIcoApi from './api/ico';
import useAccountRecoveryApi from './api/account_recovery';
import useEnterAndConfirmEmailPages from './server_pages/enter_confirm_email';
import isBot from 'koa-isbot';
import session from 'koa-session';
import csrf from 'koa-csrf';
import flash from 'koa-flash';
import minimist from 'minimist';
import Grant from 'grant-koa';
import config from '../config';

import {githash} from 'config/last-build';

const grant = new Grant(config.grant);
// import uploadImage from 'server/upload-image' //medium-editor

const app = new Koa();
app.name = 'Голос';

const env = process.env.NODE_ENV || 'development';
const cacheOpts = {maxAge: 86400000, gzip: true};

app.keys = [config.session_key];
app.use(session({maxAge: 1000 * 3600 * 24 * 7}, app));
csrf(app);
app.use(mount(grant));
app.use(flash({key: 'flash'}));

// redirect to home page if known account
// remember ch, cn, r url params in the session and remove them from url
app.use(function *(next) {
    if (this.method === 'GET' && this.url === '/' && this.session.a) {
        this.status = 301;
        this.redirect('/ico'); // LANDING this.redirect(`/@${this.session.a}/feed`);
        return;
    }
    if (this.method === 'GET' && /\?[^\w]*(ch=|cn=|r=)/.test(this.url)) {
        let redir = this.url.replace(/((ch|cn|r)=[^&]+)/gi, r => {
            const p = r.split('=');
            if (p.length === 2) this.session[p[0]] = p[1];
            return '';
        });
        redir = redir.replace(/&&&?/, '');
        redir = redir.replace(/\?&?$/, '');
        console.log(`server redirect ${this.url} -> ${redir}`);
        this.status = 301;
        this.redirect(redir);
    } else {
        yield next;
    }
});

if (env === 'production') {
    // load production middleware
    app.use(require('koa-conditional-get')());
    app.use(require('koa-etag')());
    app.use(require('koa-compressor')());
    app.use(prod_logger());
} else {
    app.use(koa_logger());
}

app.use(helmet());

app.use(mount('/static', staticCache(path.join(__dirname, '../app/assets/static'), cacheOpts)));

app.use(mount('/robots.txt', function* () {
    this.set('Cache-Control', 'public, max-age=86400000');
    this.type = 'text/plain';
    this.body = "User-agent: *\nAllow: /";
}));

useRedirects(app);
useEnterAndConfirmEmailPages(app);

if (env === 'production') {
    app.use(helmet.contentSecurityPolicy(config.helmet));
}

useAccountRecoveryApi(app);
useOauthLogin(app);
useGeneralApi(app);
useIcoApi(app);

app.use(favicon(path.join(__dirname, '../app/assets/images/favicons/favicon.ico')));
app.use(isBot());
app.use(mount('/favicons', staticCache(path.join(__dirname, '../app/assets/images/favicons'), cacheOpts)));
app.use(mount('/images', staticCache(path.join(__dirname, '../app/assets/images'), cacheOpts)));
app.use(mount('/legal', staticCache(path.join(__dirname, '../app/assets/legal'), cacheOpts)));
// Proxy asset folder to webpack development server in development mode
console.log (env)

if (env === 'development') {
    const PORT = parseInt(process.env.PORT, 10) + 1 || 3001;
    const proxy = require('koa-proxy')({
        host: 'http://0.0.0.0:' + PORT,
        map: (filePath) => 'assets/' + filePath
    });
    app.use(mount('/assets', proxy));
} else {
    app.use(mount('/assets', staticCache(path.join(__dirname, '../dist'), cacheOpts)));
}

if (env !== 'test') {
    const appRender = require('./app_render');
    app.use(function* () {
        this.first_visit = false;
        this.last_visit = this.session.last_visit;
        this.session.last_visit = (new Date()).getTime() / 1000 | 0;
        if (!this.session.uid) {
            this.session.uid = Math.random().toString(36).slice(2);
            this.first_visit = true;
            this.session.new_visit = true;
        } else {
            this.session.new_visit = this.session.last_visit - this.last_visit > 1800;
        }
        yield appRender(this);
        // if (app_router.dbStatus.ok) recordWebEvent(this, 'page_load');
        const bot = this.state.isBot;
        if (bot) {
            console.log(`  --> ${this.method} ${this.originalUrl} ${this.status} (BOT '${bot}')`);
        }
    });

    const argv = minimist(process.argv.slice(2));
    const port = parseInt(argv.port, 10) || parseInt(process.env.PORT, 10) || 3002;
    app.listen(port);

    // Tell parent process koa-server is started
    if (process.send) process.send('online');
    console.log(`Application started on port ${port}`);
}

module.exports = app;
<commit_msg>(IMPORTANT) change default app port to 4002<commit_after>import path from 'path';
import Koa from 'koa';
import mount from 'koa-mount';
import helmet from 'koa-helmet';
import koa_logger from 'koa-logger';
import prod_logger from './prod_logger';
import favicon from 'koa-favicon';
import staticCache from 'koa-static-cache';
import useRedirects from './redirects';
import useOauthLogin from './api/oauth';
import useGeneralApi from './api/general';
import useIcoApi from './api/ico';
import useAccountRecoveryApi from './api/account_recovery';
import useEnterAndConfirmEmailPages from './server_pages/enter_confirm_email';
import isBot from 'koa-isbot';
import session from 'koa-session';
import csrf from 'koa-csrf';
import flash from 'koa-flash';
import minimist from 'minimist';
import Grant from 'grant-koa';
import config from '../config';

import {githash} from 'config/last-build';

const grant = new Grant(config.grant);
// import uploadImage from 'server/upload-image' //medium-editor

const app = new Koa();
app.name = 'Голос';

const env = process.env.NODE_ENV || 'development';
const cacheOpts = {maxAge: 86400000, gzip: true};

app.keys = [config.session_key];
app.use(session({maxAge: 1000 * 3600 * 24 * 7}, app));
csrf(app);
app.use(mount(grant));
app.use(flash({key: 'flash'}));

// redirect to home page if known account
// remember ch, cn, r url params in the session and remove them from url
app.use(function *(next) {
    if (this.method === 'GET' && this.url === '/' && this.session.a) {
        this.status = 301;
        this.redirect('/ico'); // LANDING this.redirect(`/@${this.session.a}/feed`);
        return;
    }
    if (this.method === 'GET' && /\?[^\w]*(ch=|cn=|r=)/.test(this.url)) {
        let redir = this.url.replace(/((ch|cn|r)=[^&]+)/gi, r => {
            const p = r.split('=');
            if (p.length === 2) this.session[p[0]] = p[1];
            return '';
        });
        redir = redir.replace(/&&&?/, '');
        redir = redir.replace(/\?&?$/, '');
        console.log(`server redirect ${this.url} -> ${redir}`);
        this.status = 301;
        this.redirect(redir);
    } else {
        yield next;
    }
});

if (env === 'production') {
    // load production middleware
    app.use(require('koa-conditional-get')());
    app.use(require('koa-etag')());
    app.use(require('koa-compressor')());
    app.use(prod_logger());
} else {
    app.use(koa_logger());
}

app.use(helmet());

app.use(mount('/static', staticCache(path.join(__dirname, '../app/assets/static'), cacheOpts)));

app.use(mount('/robots.txt', function* () {
    this.set('Cache-Control', 'public, max-age=86400000');
    this.type = 'text/plain';
    this.body = "User-agent: *\nAllow: /";
}));

useRedirects(app);
useEnterAndConfirmEmailPages(app);

if (env === 'production') {
    app.use(helmet.contentSecurityPolicy(config.helmet));
}

useAccountRecoveryApi(app);
useOauthLogin(app);
useGeneralApi(app);
useIcoApi(app);

app.use(favicon(path.join(__dirname, '../app/assets/images/favicons/favicon.ico')));
app.use(isBot());
app.use(mount('/favicons', staticCache(path.join(__dirname, '../app/assets/images/favicons'), cacheOpts)));
app.use(mount('/images', staticCache(path.join(__dirname, '../app/assets/images'), cacheOpts)));
app.use(mount('/legal', staticCache(path.join(__dirname, '../app/assets/legal'), cacheOpts)));
// Proxy asset folder to webpack development server in development mode
console.log (env)

if (env === 'development') {
    const PORT = parseInt(process.env.PORT, 10) + 1 || 3001;
    const proxy = require('koa-proxy')({
        host: 'http://0.0.0.0:' + PORT,
        map: (filePath) => 'assets/' + filePath
    });
    app.use(mount('/assets', proxy));
} else {
    app.use(mount('/assets', staticCache(path.join(__dirname, '../dist'), cacheOpts)));
}

if (env !== 'test') {
    const appRender = require('./app_render');
    app.use(function* () {
        this.first_visit = false;
        this.last_visit = this.session.last_visit;
        this.session.last_visit = (new Date()).getTime() / 1000 | 0;
        if (!this.session.uid) {
            this.session.uid = Math.random().toString(36).slice(2);
            this.first_visit = true;
            this.session.new_visit = true;
        } else {
            this.session.new_visit = this.session.last_visit - this.last_visit > 1800;
        }
        yield appRender(this);
        // if (app_router.dbStatus.ok) recordWebEvent(this, 'page_load');
        const bot = this.state.isBot;
        if (bot) {
            console.log(`  --> ${this.method} ${this.originalUrl} ${this.status} (BOT '${bot}')`);
        }
    });

    const argv = minimist(process.argv.slice(2));
    const port = parseInt(argv.port, 10) || parseInt(process.env.PORT, 10) || 4002;
    app.listen(port);

    // Tell parent process koa-server is started
    if (process.send) process.send('online');
    console.log(`Application started on port ${port}`);
}

module.exports = app;
<|endoftext|>


<commit_before>var express = require('express');
var downldr = require('./lib/downloader.js');
var fs      = require('fs');
var exec    = require('child_process').exec;
var path    = require('path');

var app = express.createServer();
var filePath = "./files/";

app.get('/channel.js', function(req, res) {
        res.header('Content-Type', 'text/javascript');
        res.send('function _bulkr_download(data) { '+
                'if(data.error == false) { ' +
                	          'var txtLink = document.getElementById("txtBulkZipLink");' +
                	          'txtLink.value = txtLink.getAttribute("endpoint") + "/set/" + data.id;' +
                	          'document.getElementById("bulkTip").style.display = "block"; ' +
                '} else { alert("Error processing bulkr request:\\n "+data.error); } }');
});

app.get(/\/set\/?(?:([\d]{13}_[\d\._]+))/, function(req, res) {
	var file = filePath + req.params[0] + ".zip";
	path.exists(file, function(exists) {
		if(exists) {
			fs.readFile(file, function(error, content) {
				if (error) {
                    res.writeHead(500);
                    res.end();
                }
                else {
                    res.writeHead(200, { 'Content-Type': 'application/zip','Content-disposition': 'attachment' });
                    res.end(content, 'utf-8');
                }

			});
		} else {
			res.writeHead(404);
            res.end();
		}
	});
});

app.get('/', function(req, res) {
        res.header('Access-Control-Allow-Origin','*');
        res.header('Content-Type','text/javascript');

        var photos  = req.query.photos.split(",");
        var error   = false;
        var baseuri = "http://farm1.static.flickr.com/";
        var id        = (parseInt(new Date().getTime())) + "_" + (Math.random() * 1000);
        var savepath  = "/tmp/bulkr/" + id;
        var zip_savepath = filePath;
        var completed = 0;

        var onComplete = function() {
            completed++;

            if(completed == photos.length) {
                var zip   = exec('zip -9 ' + zip_savepath + id + ' ' + savepath + "/*", function(aError, stdout, stderr) {
                	// Do some cleaning...
                	for(var i = 0; i < photos.length; i++) {
	        			var local_file  = savepath+"/"+(i+1)+".jpg";
	                	fs.unlink(local_file);
	                }
                	fs.unlink(savepath);

                	// Send error or successful id of the zip.
                    if(aError !== null) {
                		error = aError;
                		res.send("_bulkr_download("+JSON.stringify({"id":"", "error": error})+")");
                	} else {
                		res.send("_bulkr_download("+JSON.stringify({"id": id, "error": false})+")");
                	}
                });

            }
        };

        fs.mkdir(savepath, 0777, function() {

	        for(var i = 0; i < photos.length; i++) {
	                var remote_file = baseuri + photos[i] + "_b.jpg";
	                var local_file  = savepath+"/"+(i+1)+".jpg";

	                var dl = new downldr.Downloader(remote_file, local_file);
	                dl.on("completed", onComplete);
	                dl.run();
	        }

        });

});

app.listen('8080','127.0.0.1');
<commit_msg>Corrected file download regex<commit_after>var express = require('express');
var downldr = require('./lib/downloader.js');
var fs      = require('fs');
var exec    = require('child_process').exec;
var path    = require('path');

var app = express.createServer();
var filePath = "./files/";

app.get('/channel.js', function(req, res) {
        res.header('Content-Type', 'text/javascript');
        res.send('function _bulkr_download(data) { '+
                'if(data.error == false) { ' +
                	          'var txtLink = document.getElementById("txtBulkZipLink");' +
                	          'txtLink.value = txtLink.getAttribute("endpoint") + "/set/" + data.id + ".zip";' +
                	          'document.getElementById("bulkTip").style.display = "block"; ' +
                '} else { alert("Error processing bulkr request:\\n "+data.error); } }');
});

app.get(/\/set\/?(?:([\d]{13}_[\d\._]+)).zip/, function(req, res) {
	var file = filePath + req.params[0];
	path.exists(file, function(exists) {
		if(exists) {
			fs.readFile(file, function(error, content) {
				if (error) {
                    res.writeHead(500);
                    res.end();
                }
                else {
                    res.writeHead(200, { 'Content-Type': 'application/zip','Content-disposition': 'attachment' });
                    res.end(content, 'utf-8');
                }

			});
		} else {
			res.writeHead(404);
            res.end();
		}
	});
});

app.get('/', function(req, res) {
        res.header('Access-Control-Allow-Origin','*');
        res.header('Content-Type','text/javascript');

        var photos  = req.query.photos.split(",");
        var error   = false;
        var baseuri = "http://farm1.static.flickr.com/";
        var id        = (parseInt(new Date().getTime())) + "_" + (Math.random() * 1000);
        var savepath  = "/tmp/bulkr/" + id;
        var zip_savepath = filePath;
        var completed = 0;

        var onComplete = function() {
            completed++;

            if(completed == photos.length) {
                var zip   = exec('zip -9 ' + zip_savepath + id + ' ' + savepath + "/*", function(aError, stdout, stderr) {
                	// Do some cleaning...
                	for(var i = 0; i < photos.length; i++) {
	        			var local_file  = savepath+"/"+(i+1)+".jpg";
	                	fs.unlink(local_file);
	                }
                	fs.unlink(savepath);

                	// Send error or successful id of the zip.
                    if(aError !== null) {
                		error = aError;
                		res.send("_bulkr_download("+JSON.stringify({"id":"", "error": error})+")");
                	} else {
                		res.send("_bulkr_download("+JSON.stringify({"id": id, "error": false})+")");
                	}
                });

            }
        };

        fs.mkdir(savepath, 0777, function() {

	        for(var i = 0; i < photos.length; i++) {
	                var remote_file = baseuri + photos[i] + "_b.jpg";
	                var local_file  = savepath+"/"+(i+1)+".jpg";

	                var dl = new downldr.Downloader(remote_file, local_file);
	                dl.on("completed", onComplete);
	                dl.run();
	        }

        });

});

app.listen('8080','127.0.0.1');
<|endoftext|>


<commit_before>'use strict';

var loopback = require('loopback');
var boot = require('loopback-boot');
var path = require('path');
var app = module.exports = loopback();
var env = require('get-env')();

/*
 * body-parser is a piece of express middleware that
 *   reads a form's input and stores it as a javascript
 *   object accessible through `req.body`
 *
 */
var bodyParser = require('body-parser');

// Passport configurators..
var loopbackPassport = require('loopback-component-passport');

var PassportConfigurator = loopbackPassport.PassportConfigurator;
var passportConfigurator = new PassportConfigurator(app);

//app.use(function(req, res, next) {
//  res.setHeader('X-Powered-By', 'Loopback Admin');
//  res.removeHeader('Vary');
//  next();
//});

// Set up the /favicon.ico
app.use(loopback.favicon());

// request pre-processing middleware
app.use(loopback.compress());

// -- Add your pre-processing middleware here --

var ds = loopback.createDataSource({
  connector: require('loopback-component-storage'),
  provider: 'filesystem',
  root: path.join(__dirname, '../', 'storage')
});
var container = ds.createModel('container');

app.model(container);

// boot scripts mount components like REST API
boot(app, __dirname);

// to support JSON-encoded bodies
app.use(bodyParser.json());
// to support URL-encoded bodies
app.use(bodyParser.urlencoded({
  extended: true
}));

// The access token is only available after boot
app.use(loopback.token({
  model: app.models.accessToken
}));

// Enable http session
//app.use(loopback.cookieParser(app.get('cookieSecret')));
app.use(loopback.session({
  secret: 'kitty',
  saveUninitialized: true,
  resave: true
}));

// Load the provider configurations
var config = {};
try {
  config = require('../providers.json');
} catch (err) {
  console.error('Please configure your passport strategy in `providers.json`.');
  console.error('Copy `providers.json.template` to `providers.json` and replace the clientID/clientSecret values with your own.');
  process.exit(1);
}
// Initialize passport
passportConfigurator.init();

// Set up related models
passportConfigurator.setupModels({
  userModel: app.models.user,
  userIdentityModel: app.models.userIdentity,
  userCredentialModel: app.models.userCredential
});
// Configure passport strategies for third party auth providers
for (var s in config) {
  var c = config[s];
  c.session = c.session !== false;
  passportConfigurator.configureProvider(s, c);
}

var ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn;

app.get('/auth/account', ensureLoggedIn('/login.html'), function (req, res, next) {
  res.render('pages/loginProfiles', {
    user: req.user,
    url: req.url
  });
});

app.get('/link/account', ensureLoggedIn('/login.html'), function (req, res, next) {
  res.render('pages/linkedAccounts', {
    user: req.user,
    url: req.url
  });
});

app.get('/auth/logout', function (req, res, next) {
  req.logout();
  res.redirect('/');
});

// -- Mount static files here--
// All static middleware should be registered at the end, as all requests
// passing the static middleware are hitting the file system
// Example:

var staticPath = null;

if (env === 'prod') {
  staticPath = path.resolve(__dirname, '../dist/');
}
else {
  staticPath = path.resolve(__dirname, '../client/app');
}

console.log("staticPath", staticPath);
app.use(loopback.static(staticPath));

// Requests that get this far won't be handled
// by any middleware. Convert them into a 404 error
// that will be handled later down the chain.
app.use(loopback.urlNotFound());

// The ultimate error handler.
app.use(loopback.errorHandler());

app.start = function () {
  // start the web server
  return app.listen(function () {
    app.emit('started');
    console.log('Web server listening at: %s', app.get('url'));
  });
};

// start the server if `$ node server.js`
if (require.main === module) {
  app.start();
}
<commit_msg>Negate enviroment variable check<commit_after>'use strict';

var loopback = require('loopback');
var boot = require('loopback-boot');
var path = require('path');
var app = module.exports = loopback();
var env = require('get-env')();

/*
 * body-parser is a piece of express middleware that
 *   reads a form's input and stores it as a javascript
 *   object accessible through `req.body`
 *
 */
var bodyParser = require('body-parser');

// Passport configurators..
var loopbackPassport = require('loopback-component-passport');

var PassportConfigurator = loopbackPassport.PassportConfigurator;
var passportConfigurator = new PassportConfigurator(app);

//app.use(function(req, res, next) {
//  res.setHeader('X-Powered-By', 'Loopback Admin');
//  res.removeHeader('Vary');
//  next();
//});

// Set up the /favicon.ico
app.use(loopback.favicon());

// request pre-processing middleware
app.use(loopback.compress());

// -- Add your pre-processing middleware here --

var ds = loopback.createDataSource({
  connector: require('loopback-component-storage'),
  provider: 'filesystem',
  root: path.join(__dirname, '../', 'storage')
});
var container = ds.createModel('container');

app.model(container);

// boot scripts mount components like REST API
boot(app, __dirname);

// to support JSON-encoded bodies
app.use(bodyParser.json());
// to support URL-encoded bodies
app.use(bodyParser.urlencoded({
  extended: true
}));

// The access token is only available after boot
app.use(loopback.token({
  model: app.models.accessToken
}));

// Enable http session
//app.use(loopback.cookieParser(app.get('cookieSecret')));
app.use(loopback.session({
  secret: 'kitty',
  saveUninitialized: true,
  resave: true
}));

// Load the provider configurations
var config = {};
try {
  config = require('../providers.json');
} catch (err) {
  console.error('Please configure your passport strategy in `providers.json`.');
  console.error('Copy `providers.json.template` to `providers.json` and replace the clientID/clientSecret values with your own.');
  process.exit(1);
}
// Initialize passport
passportConfigurator.init();

// Set up related models
passportConfigurator.setupModels({
  userModel: app.models.user,
  userIdentityModel: app.models.userIdentity,
  userCredentialModel: app.models.userCredential
});
// Configure passport strategies for third party auth providers
for (var s in config) {
  var c = config[s];
  c.session = c.session !== false;
  passportConfigurator.configureProvider(s, c);
}

var ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn;

app.get('/auth/account', ensureLoggedIn('/login.html'), function (req, res, next) {
  res.render('pages/loginProfiles', {
    user: req.user,
    url: req.url
  });
});

app.get('/link/account', ensureLoggedIn('/login.html'), function (req, res, next) {
  res.render('pages/linkedAccounts', {
    user: req.user,
    url: req.url
  });
});

app.get('/auth/logout', function (req, res, next) {
  req.logout();
  res.redirect('/');
});

// -- Mount static files here--
// All static middleware should be registered at the end, as all requests
// passing the static middleware are hitting the file system
// Example:

var staticPath = null;

if (env !== 'prod') {
  staticPath = path.resolve(__dirname, '../client/app');
} else {
  staticPath = path.resolve(__dirname, '../dist/');
}

console.log("staticPath", staticPath);
app.use(loopback.static(staticPath));

// Requests that get this far won't be handled
// by any middleware. Convert them into a 404 error
// that will be handled later down the chain.
app.use(loopback.urlNotFound());

// The ultimate error handler.
app.use(loopback.errorHandler());

app.start = function () {
  // start the web server
  return app.listen(function () {
    app.emit('started');
    console.log('Web server listening at: %s', app.get('url'));
  });
};

// start the server if `$ node server.js`
if (require.main === module) {
  app.start();
}
<|endoftext|>