<commit_before>// ***********************************************//
//                 Router
// ***********************************************//
require('akvo-flow/core-common');

FLOW.Router = Ember.Router.extend({
  enableLogging: true,
  loggedIn: false,
  location: 'none',
  //'hash'or 'none' for URLs

  resetState: function () {
    FLOW.selectedControl.set('selectedQuestionGroup', null);
    FLOW.selectedControl.set('selectedSurveyGroup', null);
    FLOW.selectedControl.set('selectedSurvey', null);
    FLOW.selectedControl.set('selectedQuestion', null);
    FLOW.surveyControl.set('content', null);
    FLOW.questionControl.set('OPTIONcontent', null);
  },

  root: Ember.Route.extend({
    doNavSurveys: function (router, context) {
      router.transitionTo('navSurveys.index');
    },
    doNavDevices: function (router, context) {
      router.transitionTo('navDevices.index');
    },
    doNavData: function (router, context) {
      router.transitionTo('navData.index');
    },
    doNavReports: function (router, context) {
      router.transitionTo('navReports.index');
    },
    doNavMaps: function (router, context) {
      router.transitionTo('navMaps');
    },
    doNavUsers: function (router, context) {
      router.transitionTo('navUsers');
    },
    doNavMessages: function (router, context) {
      router.transitionTo('navMessages');
    },
    // not used at the moment
    doNavAdmin: function (router, context) {
      router.transitionTo('navAdmin');
    },

    // non-working code for transitioning to navHome at first entry of the app
    //    setup: function(router){
    //      router.send("goHome");
    //    },
    //    goHome:function(router){
    //      router.transitionTo('navHome');
    //    },
    index: Ember.Route.extend({
      route: '/',
      redirectsTo: 'navSurveys.index'
    }),

    // ******************* SURVEYS ROUTER ********************
    navSurveys: Ember.Route.extend({
      route: '/surveys',
      connectOutlets: function (router, event) {
        router.get('applicationController').connectOutlet('navSurveys');
        router.set('navigationController.selected', 'navSurveys');
      },

      doNewSurvey: function (router, event) {
        router.transitionTo('navSurveys.navSurveysNew');
      },

      doEditSurvey: function (router, event) {
        FLOW.selectedControl.set('selectedSurvey', event.context);
        router.transitionTo('navSurveys.navSurveysEdit.index');
      },

      doSurveysMain: function (router, event) {
        FLOW.selectedControl.set('selectedQuestion', null);
        router.transitionTo('navSurveys.navSurveysMain');
      },

      index: Ember.Route.extend({
        route: '/',
        redirectsTo: 'navSurveysMain'
      }),

      navSurveysMain: Ember.Route.extend({
        route: '/main',
        connectOutlets: function (router, event) {
          router.get('navSurveysController').connectOutlet({
            name: 'navSurveysMain'
          });
          FLOW.surveyGroupControl.populate();
          FLOW.selectedControl.set('selectedQuestionGroup', null);
          FLOW.selectedControl.set('selectedSurvey', null);
          FLOW.selectedControl.set('selectedQuestion', null);
          FLOW.questionControl.set('OPTIONcontent', null);

        }
      }),

      navSurveysNew: Ember.Route.extend({
        route: '/new',
        connectOutlets: function (router, event) {
          var newSurvey;

          newSurvey = FLOW.store.createRecord(FLOW.Survey, {
            "name": "",
            "defaultLanguageCode": "en",
            "requireApproval": false,
            "status": "NOT_PUBLISHED",
            "surveyGroupId": FLOW.selectedControl.selectedSurveyGroup.get('keyId')
          });

          FLOW.selectedControl.set('selectedSurvey', newSurvey);
          router.transitionTo('navSurveys.navSurveysEdit.index');
        }
      }),

      navSurveysEdit: Ember.Route.extend({
        route: '/edit',
        connectOutlets: function (router, event) {
          router.get('navSurveysController').connectOutlet({
            name: 'navSurveysEdit'
          });
          // all questions should be closed when we enter
          FLOW.selectedControl.set('selectedQuestion', null);
          FLOW.attributeControl.populate();
        },

        doEditQuestions: function (router, event) {
          router.transitionTo('navSurveys.navSurveysEdit.editQuestions');
        },

        index: Ember.Route.extend({
          route: '/',
          redirectsTo: 'editQuestions'
        }),

        manageNotifications: Ember.Route.extend({
          route: '/notifications',
          connectOutlets: function (router, event) {
            router.get('navSurveysEditController').connectOutlet({
              name: 'manageNotifications'
            });
            FLOW.notificationControl.populate();
          }
        }),

        manageTranslations: Ember.Route.extend({
          route: '/translations',
          connectOutlets: function (router, event) {
            router.get('navSurveysEditController').connectOutlet({
              name: 'manageTranslations'
            });
            FLOW.translationControl.populate();
          }
        }),

        editQuestions: Ember.Route.extend({
          route: '/questions',
          connectOutlets: function (router, event) {
            router.get('navSurveysEditController').connectOutlet({
              name: 'editQuestions'
            });

          }
        })
      })
    }),

    //********************** DEVICES ROUTER *******************
    navDevices: Ember.Route.extend({
      route: '/devices',
      connectOutlets: function (router, event) {
        router.get('applicationController').connectOutlet('navDevices');
        router.set('navigationController.selected', 'navDevices');
      },

      doCurrentDevices: function (router, event) {
        router.transitionTo('navDevices.currentDevices');
      },

      doAssignSurveysOverview: function (router, event) {
        router.transitionTo('navDevices.assignSurveysOverview');
      },

      doEditSurveysAssignment: function (router, event) {
        router.transitionTo('navDevices.editSurveysAssignment');
      },

      doSurveyBootstrap: function (router, event) {
        router.transitionTo('navDevices.surveyBootstrap');
      },

      index: Ember.Route.extend({
        route: '/',
        redirectsTo: 'currentDevices'
      }),

      currentDevices: Ember.Route.extend({
        route: '/current-devices',
        connectOutlets: function (router, context) {
          router.get('navDevicesController').connectOutlet('currentDevices');
          FLOW.deviceGroupControl.populate();
          FLOW.deviceControl.populate();
          FLOW.surveyAssignmentControl.populate();
          router.resetState();
          router.set('devicesSubnavController.selected', 'currentDevices');
        }
      }),

      assignSurveysOverview: Ember.Route.extend({
        route: '/assign-surveys',
        connectOutlets: function (router, context) {
          router.get('navDevicesController').connectOutlet('assignSurveysOverview');
          router.set('devicesSubnavController.selected', 'assignSurveys');
        }
      }),

      editSurveysAssignment: Ember.Route.extend({
        route: '/assign-surveys',
        connectOutlets: function (router, context) {
          router.get('navDevicesController').connectOutlet('editSurveyAssignment');
          router.set('devicesSubnavController.selected', 'assignSurveys');
        }
      }),

      surveyBootstrap: Ember.Route.extend({
        route: '/manual-transfer',
        connectOutlets: function (router, context) {
          router.get('navDevicesController').connectOutlet('surveyBootstrap');
          router.set('devicesSubnavController.selected', 'surveyBootstrap');
        }
      })
    }),

    // ******************* DATA ROUTER ***********************
    navData: Ember.Route.extend({
      route: '/data',
      connectOutlets: function (router, event) {
        router.get('applicationController').connectOutlet('navData');
        router.set('navigationController.selected', 'navData');
      },

      doInspectData: function (router, event) {
        router.transitionTo('navData.inspectData');
      },
      doManageAttributes: function (router, event) {
        router.transitionTo('navData.manageAttributes');
      },
      doBulkUpload: function (router, event) {
        router.transitionTo('navData.bulkUpload');
      },
      doDataCleaning: function (router, event) {
        router.transitionTo('navData.dataCleaning');
      },
      doMonitoringData: function (router, event) {
        router.transitionTo('navData.monitoringData');
      },

      index: Ember.Route.extend({
        route: '/',
        redirectsTo: 'inspectData'
      }),

      inspectData: Ember.Route.extend({
        route: '/inspectdata',
        connectOutlets: function (router, context) {
          router.get('navDataController').connectOutlet('inspectData');
          router.set('datasubnavController.selected', 'inspectData');
          router.resetState();
          FLOW.surveyGroupControl.populate();
          FLOW.surveyInstanceControl.populate();
        }
      }),

      manageAttributes: Ember.Route.extend({
        route: '/manageattributes',
        connectOutlets: function (router, context) {
          router.get('navDataController').connectOutlet('manageAttributes');
          router.set('datasubnavController.selected', 'manageAttributes');
          FLOW.attributeControl.populate();
        }
      }),

      bulkUpload: Ember.Route.extend({
        route: '/bulkupload',
        connectOutlets: function (router, context) {
          router.get('navDataController').connectOutlet('bulkUpload');
          router.set('datasubnavController.selected', 'bulkUpload');
        }
      }),

      dataCleaning: Ember.Route.extend({
        route: '/datacleaning',
        connectOutlets: function (router, context) {
          router.get('navDataController').connectOutlet('dataCleaning');
          router.set('datasubnavController.selected', 'dataCleaning');
        }
      }),

      monitoringData: Ember.Route.extend({
        route: '/monitoringdata',
        connectOutlets: function (router, context) {
          router.get('navDataController').connectOutlet('monitoringData');
          router.set('datasubnavController.selected', 'monitoringData');
          FLOW.surveyGroupControl.populate(function (item) {
                 return item.get('monitoringGroup');
          });
        }
      }),
    }),

    // ************************** REPORTS ROUTER **********************************
    navReports: Ember.Route.extend({
      route: '/reports',
      connectOutlets: function (router, context) {
        router.get('applicationController').connectOutlet('navReports');
        FLOW.surveyGroupControl.populate();
        router.resetState();
        router.set('navigationController.selected', 'navReports');
      },

      doExportReports: function (router, event) {
        router.transitionTo('navReports.exportReports');
      },

      doChartReports: function (router, event) {
        router.transitionTo('navReports.chartReports');
      },

      doStatistics: function(router, event) {
        router.transitionTo('navReports.statistics');
      },

      index: Ember.Route.extend({
        route: '/',
        redirectsTo: 'chartReports'
      }),

      exportReports: Ember.Route.extend({
        route: '/exportreports',
        connectOutlets: function (router, context) {
          router.get('navReportsController').connectOutlet('exportReports');
          router.set('reportsSubnavController.selected', 'exportReports');
          router.resetState();
        }
      }),

      chartReports: Ember.Route.extend({
        route: '/chartreports',
        connectOutlets: function (router, context) {
          router.get('navReportsController').connectOutlet('chartReports');
          router.set('reportsSubnavController.selected', 'chartReports');
          FLOW.surveyGroupControl.populate();
        }
      }),
      statistics: Ember.Route.extend({
        route: '/statistics',
        connectOutlets: function(router, context) {
          router.resetState();
          router.get('navReportsController').connectOutlet('statistics');
          router.set('reportsSubnavController.selected', 'statistics');
          FLOW.surveyGroupControl.populate();
        }
      })
    }),

    // ************************** MAPS ROUTER **********************************
    navMaps: Ember.Route.extend({
      route: '/maps',
      connectOutlets: function (router, context) {
        router.get('applicationController').connectOutlet('navMaps');
        router.set('navigationController.selected', 'navMaps');
      }
    }),

    // ************************** USERS ROUTER **********************************
    navUsers: Ember.Route.extend({
      route: '/users',
      connectOutlets: function (router, context) {
        router.get('applicationController').connectOutlet('navUsers');
        router.set('navigationController.selected', 'navUsers');
        FLOW.userControl.populate();
      }
    }),

    // ************************** MESSAGES ROUTER **********************************
    navMessages: Ember.Route.extend({
      route: '/users',
      connectOutlets: function (router, context) {
        router.get('applicationController').connectOutlet('navMessages');
        router.set('navigationController.selected', 'navMessages');
        FLOW.messageControl.populate();
        router.resetState();
      }
    }),

    // ************************** ADMIN ROUTER **********************************
    // not used at the moment
    navAdmin: Ember.Route.extend({
      route: '/admin',
      connectOutlets: function (router, context) {
        router.get('applicationController').connectOutlet('navAdmin');
        router.set('navigationController.selected', 'navAdmin');
      }
    })
  })
});
<commit_msg>[#629] List all survey groups in assignment list<commit_after>// ***********************************************//
//                 Router
// ***********************************************//
require('akvo-flow/core-common');

FLOW.Router = Ember.Router.extend({
  enableLogging: true,
  loggedIn: false,
  location: 'none',
  //'hash'or 'none' for URLs

  resetState: function () {
    FLOW.selectedControl.set('selectedQuestionGroup', null);
    FLOW.selectedControl.set('selectedSurveyGroup', null);
    FLOW.selectedControl.set('selectedSurvey', null);
    FLOW.selectedControl.set('selectedQuestion', null);
    FLOW.surveyControl.set('content', null);
    FLOW.questionControl.set('OPTIONcontent', null);
  },

  root: Ember.Route.extend({
    doNavSurveys: function (router, context) {
      router.transitionTo('navSurveys.index');
    },
    doNavDevices: function (router, context) {
      router.transitionTo('navDevices.index');
    },
    doNavData: function (router, context) {
      router.transitionTo('navData.index');
    },
    doNavReports: function (router, context) {
      router.transitionTo('navReports.index');
    },
    doNavMaps: function (router, context) {
      router.transitionTo('navMaps');
    },
    doNavUsers: function (router, context) {
      router.transitionTo('navUsers');
    },
    doNavMessages: function (router, context) {
      router.transitionTo('navMessages');
    },
    // not used at the moment
    doNavAdmin: function (router, context) {
      router.transitionTo('navAdmin');
    },

    // non-working code for transitioning to navHome at first entry of the app
    //    setup: function(router){
    //      router.send("goHome");
    //    },
    //    goHome:function(router){
    //      router.transitionTo('navHome');
    //    },
    index: Ember.Route.extend({
      route: '/',
      redirectsTo: 'navSurveys.index'
    }),

    // ******************* SURVEYS ROUTER ********************
    navSurveys: Ember.Route.extend({
      route: '/surveys',
      connectOutlets: function (router, event) {
        router.get('applicationController').connectOutlet('navSurveys');
        router.set('navigationController.selected', 'navSurveys');
      },

      doNewSurvey: function (router, event) {
        router.transitionTo('navSurveys.navSurveysNew');
      },

      doEditSurvey: function (router, event) {
        FLOW.selectedControl.set('selectedSurvey', event.context);
        router.transitionTo('navSurveys.navSurveysEdit.index');
      },

      doSurveysMain: function (router, event) {
        FLOW.selectedControl.set('selectedQuestion', null);
        router.transitionTo('navSurveys.navSurveysMain');
      },

      index: Ember.Route.extend({
        route: '/',
        redirectsTo: 'navSurveysMain'
      }),

      navSurveysMain: Ember.Route.extend({
        route: '/main',
        connectOutlets: function (router, event) {
          router.get('navSurveysController').connectOutlet({
            name: 'navSurveysMain'
          });
          FLOW.surveyGroupControl.populate();
          FLOW.selectedControl.set('selectedQuestionGroup', null);
          FLOW.selectedControl.set('selectedSurvey', null);
          FLOW.selectedControl.set('selectedQuestion', null);
          FLOW.questionControl.set('OPTIONcontent', null);

        }
      }),

      navSurveysNew: Ember.Route.extend({
        route: '/new',
        connectOutlets: function (router, event) {
          var newSurvey;

          newSurvey = FLOW.store.createRecord(FLOW.Survey, {
            "name": "",
            "defaultLanguageCode": "en",
            "requireApproval": false,
            "status": "NOT_PUBLISHED",
            "surveyGroupId": FLOW.selectedControl.selectedSurveyGroup.get('keyId')
          });

          FLOW.selectedControl.set('selectedSurvey', newSurvey);
          router.transitionTo('navSurveys.navSurveysEdit.index');
        }
      }),

      navSurveysEdit: Ember.Route.extend({
        route: '/edit',
        connectOutlets: function (router, event) {
          router.get('navSurveysController').connectOutlet({
            name: 'navSurveysEdit'
          });
          // all questions should be closed when we enter
          FLOW.selectedControl.set('selectedQuestion', null);
          FLOW.attributeControl.populate();
        },

        doEditQuestions: function (router, event) {
          router.transitionTo('navSurveys.navSurveysEdit.editQuestions');
        },

        index: Ember.Route.extend({
          route: '/',
          redirectsTo: 'editQuestions'
        }),

        manageNotifications: Ember.Route.extend({
          route: '/notifications',
          connectOutlets: function (router, event) {
            router.get('navSurveysEditController').connectOutlet({
              name: 'manageNotifications'
            });
            FLOW.notificationControl.populate();
          }
        }),

        manageTranslations: Ember.Route.extend({
          route: '/translations',
          connectOutlets: function (router, event) {
            router.get('navSurveysEditController').connectOutlet({
              name: 'manageTranslations'
            });
            FLOW.translationControl.populate();
          }
        }),

        editQuestions: Ember.Route.extend({
          route: '/questions',
          connectOutlets: function (router, event) {
            router.get('navSurveysEditController').connectOutlet({
              name: 'editQuestions'
            });

          }
        })
      })
    }),

    //********************** DEVICES ROUTER *******************
    navDevices: Ember.Route.extend({
      route: '/devices',
      connectOutlets: function (router, event) {
        router.get('applicationController').connectOutlet('navDevices');
        router.set('navigationController.selected', 'navDevices');
      },

      doCurrentDevices: function (router, event) {
        router.transitionTo('navDevices.currentDevices');
      },

      doAssignSurveysOverview: function (router, event) {
        router.transitionTo('navDevices.assignSurveysOverview');
      },

      doEditSurveysAssignment: function (router, event) {
        router.transitionTo('navDevices.editSurveysAssignment');
      },

      doSurveyBootstrap: function (router, event) {
        router.transitionTo('navDevices.surveyBootstrap');
      },

      index: Ember.Route.extend({
        route: '/',
        redirectsTo: 'currentDevices'
      }),

      currentDevices: Ember.Route.extend({
        route: '/current-devices',
        connectOutlets: function (router, context) {
          router.get('navDevicesController').connectOutlet('currentDevices');
          FLOW.deviceGroupControl.populate();
          FLOW.deviceControl.populate();
          FLOW.surveyAssignmentControl.populate();
          FLOW.surveyGroupControl.populate();
          router.resetState();
          router.set('devicesSubnavController.selected', 'currentDevices');
        }
      }),

      assignSurveysOverview: Ember.Route.extend({
        route: '/assign-surveys',
        connectOutlets: function (router, context) {
          router.get('navDevicesController').connectOutlet('assignSurveysOverview');
          router.set('devicesSubnavController.selected', 'assignSurveys');
        }
      }),

      editSurveysAssignment: Ember.Route.extend({
        route: '/assign-surveys',
        connectOutlets: function (router, context) {
          router.get('navDevicesController').connectOutlet('editSurveyAssignment');
          router.set('devicesSubnavController.selected', 'assignSurveys');
        }
      }),

      surveyBootstrap: Ember.Route.extend({
        route: '/manual-transfer',
        connectOutlets: function (router, context) {
          router.get('navDevicesController').connectOutlet('surveyBootstrap');
          router.set('devicesSubnavController.selected', 'surveyBootstrap');
        }
      })
    }),

    // ******************* DATA ROUTER ***********************
    navData: Ember.Route.extend({
      route: '/data',
      connectOutlets: function (router, event) {
        router.get('applicationController').connectOutlet('navData');
        router.set('navigationController.selected', 'navData');
      },

      doInspectData: function (router, event) {
        router.transitionTo('navData.inspectData');
      },
      doManageAttributes: function (router, event) {
        router.transitionTo('navData.manageAttributes');
      },
      doBulkUpload: function (router, event) {
        router.transitionTo('navData.bulkUpload');
      },
      doDataCleaning: function (router, event) {
        router.transitionTo('navData.dataCleaning');
      },
      doMonitoringData: function (router, event) {
        router.transitionTo('navData.monitoringData');
      },

      index: Ember.Route.extend({
        route: '/',
        redirectsTo: 'inspectData'
      }),

      inspectData: Ember.Route.extend({
        route: '/inspectdata',
        connectOutlets: function (router, context) {
          router.get('navDataController').connectOutlet('inspectData');
          router.set('datasubnavController.selected', 'inspectData');
          router.resetState();
          FLOW.surveyGroupControl.populate();
          FLOW.surveyInstanceControl.populate();
        }
      }),

      manageAttributes: Ember.Route.extend({
        route: '/manageattributes',
        connectOutlets: function (router, context) {
          router.get('navDataController').connectOutlet('manageAttributes');
          router.set('datasubnavController.selected', 'manageAttributes');
          FLOW.attributeControl.populate();
        }
      }),

      bulkUpload: Ember.Route.extend({
        route: '/bulkupload',
        connectOutlets: function (router, context) {
          router.get('navDataController').connectOutlet('bulkUpload');
          router.set('datasubnavController.selected', 'bulkUpload');
        }
      }),

      dataCleaning: Ember.Route.extend({
        route: '/datacleaning',
        connectOutlets: function (router, context) {
          router.get('navDataController').connectOutlet('dataCleaning');
          router.set('datasubnavController.selected', 'dataCleaning');
        }
      }),

      monitoringData: Ember.Route.extend({
        route: '/monitoringdata',
        connectOutlets: function (router, context) {
          router.get('navDataController').connectOutlet('monitoringData');
          router.set('datasubnavController.selected', 'monitoringData');
          FLOW.surveyGroupControl.populate(function (item) {
                 return item.get('monitoringGroup');
          });
        }
      }),
    }),

    // ************************** REPORTS ROUTER **********************************
    navReports: Ember.Route.extend({
      route: '/reports',
      connectOutlets: function (router, context) {
        router.get('applicationController').connectOutlet('navReports');
        FLOW.surveyGroupControl.populate();
        router.resetState();
        router.set('navigationController.selected', 'navReports');
      },

      doExportReports: function (router, event) {
        router.transitionTo('navReports.exportReports');
      },

      doChartReports: function (router, event) {
        router.transitionTo('navReports.chartReports');
      },

      doStatistics: function(router, event) {
        router.transitionTo('navReports.statistics');
      },

      index: Ember.Route.extend({
        route: '/',
        redirectsTo: 'chartReports'
      }),

      exportReports: Ember.Route.extend({
        route: '/exportreports',
        connectOutlets: function (router, context) {
          router.get('navReportsController').connectOutlet('exportReports');
          router.set('reportsSubnavController.selected', 'exportReports');
          router.resetState();
        }
      }),

      chartReports: Ember.Route.extend({
        route: '/chartreports',
        connectOutlets: function (router, context) {
          router.get('navReportsController').connectOutlet('chartReports');
          router.set('reportsSubnavController.selected', 'chartReports');
          FLOW.surveyGroupControl.populate();
        }
      }),
      statistics: Ember.Route.extend({
        route: '/statistics',
        connectOutlets: function(router, context) {
          router.resetState();
          router.get('navReportsController').connectOutlet('statistics');
          router.set('reportsSubnavController.selected', 'statistics');
          FLOW.surveyGroupControl.populate();
        }
      })
    }),

    // ************************** MAPS ROUTER **********************************
    navMaps: Ember.Route.extend({
      route: '/maps',
      connectOutlets: function (router, context) {
        router.get('applicationController').connectOutlet('navMaps');
        router.set('navigationController.selected', 'navMaps');
      }
    }),

    // ************************** USERS ROUTER **********************************
    navUsers: Ember.Route.extend({
      route: '/users',
      connectOutlets: function (router, context) {
        router.get('applicationController').connectOutlet('navUsers');
        router.set('navigationController.selected', 'navUsers');
        FLOW.userControl.populate();
      }
    }),

    // ************************** MESSAGES ROUTER **********************************
    navMessages: Ember.Route.extend({
      route: '/users',
      connectOutlets: function (router, context) {
        router.get('applicationController').connectOutlet('navMessages');
        router.set('navigationController.selected', 'navMessages');
        FLOW.messageControl.populate();
        router.resetState();
      }
    }),

    // ************************** ADMIN ROUTER **********************************
    // not used at the moment
    navAdmin: Ember.Route.extend({
      route: '/admin',
      connectOutlets: function (router, context) {
        router.get('applicationController').connectOutlet('navAdmin');
        router.set('navigationController.selected', 'navAdmin');
      }
    })
  })
});
<|endoftext|>


<commit_before>import Webpack from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';

import APP_CONFIG from '../app.config';
import APP_PATHS from '../app.paths';
import PACKAGE from '../../package';

import {
  AUTH0_DOMAIN,
  AUTH0_CLIENT_ID
} from '../auth/auth0.config';

import {
  isDev,
  isProd
} from '../env';

export const BANNER_PLUGIN = new Webpack.BannerPlugin({
  banner: APP_CONFIG.BANNER,
  entryOnly: true
});

export const DEFINE_PLUGIN = new Webpack.DefinePlugin({
  __DEV__: JSON.stringify(isDev),
  __PROD__: JSON.stringify(isProd),
  __VERSION__: JSON.stringify(`v${PACKAGE.version}`),
  __AUTH0_CLIENT_ID__: JSON.stringify(AUTH0_CLIENT_ID),
  __AUTH0_DOMAIN__: JSON.stringify(AUTH0_DOMAIN)
});

export const EXTRACT_TEXT_PLUGIN = new ExtractTextPlugin(`${APP_PATHS.REL.STATIC_CSS}/${APP_CONFIG.APP_CSS}`);
<commit_msg>use hash as part of the app css filename<commit_after>import Webpack from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';

import APP_CONFIG from '../app.config';
import APP_PATHS from '../app.paths';
import PACKAGE from '../../package';

import {
  AUTH0_DOMAIN,
  AUTH0_CLIENT_ID
} from '../auth/auth0.config';

import {
  isDev,
  isProd
} from '../env';

export const BANNER_PLUGIN = new Webpack.BannerPlugin({
  banner: APP_CONFIG.BANNER,
  entryOnly: true
});

export const DEFINE_PLUGIN = new Webpack.DefinePlugin({
  __DEV__: JSON.stringify(isDev),
  __PROD__: JSON.stringify(isProd),
  __VERSION__: JSON.stringify(`v${PACKAGE.version}`),
  __AUTH0_CLIENT_ID__: JSON.stringify(AUTH0_CLIENT_ID),
  __AUTH0_DOMAIN__: JSON.stringify(AUTH0_DOMAIN)
});

export const EXTRACT_TEXT_PLUGIN = new ExtractTextPlugin(`${APP_PATHS.REL.STATIC_CSS}/app.[hash:8].css`);
<|endoftext|>


<commit_before>var http = require( 'http' );
var server = http.createServer( function( req, res ) {
  var from = '';

  if ( req.connection.remoteAddress === '127.0.0.1' || req.connection.remoteAddress === 'localhost' ) {
    from = req.headers['x-forwarded-for'];
  } else {
    from = req.connection.remoteAddress;
  }

  res.end( from + "\n" );
}).listen( 3013 );
<commit_msg>geo working - need spatial stuff now<commit_after>var http = require( 'http' ),
geoip = require( 'geoip-lite' ),
server = http.createServer( function( req, res ) {
  var from = '', geo;

  if ( req.connection.remoteAddress === '127.0.0.1' || req.connection.remoteAddress === 'localhost' ) {
    from = req.headers['x-forwarded-for'] || '127.0.0.1';
  } else {
    from = req.connection.remoteAddress;
  }

  if ( req.url === '/geo' ) {
    geo = geoip.lookup( from ) || {};
    geo.ip = from;
    res.end( JSON.stringify(geo) );
  } else if ( req.url === '/mirror' ) {
    geo = geoip.lookup( from ) || {};
    // lookup in the mirror db
  } else {
    res.end( from + "\n" );
  }

}).listen( 3013 );
<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const app = express();
const port = process.env.PORT || 8080;
const morgan = require('morgan');

app.use(morgan('dev'));
app.use(express.static(`${__dirname}/build`));

app.listen(port, function(){
  console.log('server up on', port);
});
<commit_msg>removed morgan<commit_after>'use strict';

const express = require('express');
const app = express();
const port = process.env.PORT || 8080;

app.use(express.static(`${__dirname}/build`));

app.listen(port, function(){
  console.log('server up on', port);
});
<|endoftext|>


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

var User = require('./db/models/User')
var Bracket = require('./db/models/Bracket')

var app = express()

// app.get('/', function(res, req) {
//   res.send('hello express')
// })
//
// app.listen(3000, function() {
//   console.log('shits listening on 3000')
// })

mongoose.connect("mongodb://localhost:27017/brackets")
var db = mongoose.connection

db.on('error', console.error.bind(console, 'connection error: '))
db.once('open', function() {
  console.log('connected')

  var leif = new User({
    created_at: new Date(),
    name: 'Leif',
    email: 'leify@blah.com',
    gamesPlayed: 100,
    wins: 92
  })

  leif.save()

  var bracketTest = new Bracket({
    created_at: new Date(),
    name: 'Testing 1 2',
    created_by: leif._id,
    admins: leif._id,
    users: leif._id,
  })

  //bracketTest.save()

  Bracket.find().populate('users').exec(function(err, brackets) {
    if (err)
      console.log(err)
    else
      console.log('popped')
      console.log(brackets[0])
  })

  console.log('done')

})
<commit_msg>go away...<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node
/**
 * Fairly generic cluster-based web service runner. Starts several instances
 * of a worker module (in this case the restface module), and manages restart
 * and graceful shutdown. The worker module can also be started independently,
 * which is especially useful for debugging.
 */
"use strict";

var cluster = require('cluster'),
    path = require('path'),
    // process arguments
    opts = require( "yargs" )
        .usage( "Usage: $0 [-h|-v] [--param[=val]]" )
        .default({

            // Start a few more workers than there are cpus visible to the OS,
            // so that we get some degree of parallelism even on single-core
            // systems. A single long-running request would otherwise hold up
            // all concurrent short requests.
            n: require( "os" ).cpus().length,
            c: __dirname + '/localsettings.js',

            v: false,
            h: false

        })
        .boolean( [ "h", "v" ] )
        .alias( "h", "help" )
        .alias( "v", "version" )
        .alias( "c", "config" )
        .alias( "n", "num-workers" ),
    argv = opts.argv;

// Disable cluster RR balancing; direct socket sharing has better throughput /
// lower overhead.
cluster.schedulingPolicy = cluster.SCHED_NONE;

if (cluster.isMaster && argv.n > 0) {
    var fs = require( "fs" ),
        path = require( "path" ),
        meta = require( path.join( __dirname, "./package.json" ) );

    // help
    if ( argv.h ) {
        opts.showHelp();
        process.exit( 0 );
    }

    // version
    if ( argv.v ) {
        console.log( meta.name + " " + meta.version );
        process.exit( 0 );
    }

    // Fork workers.
    console.log('master(' + process.pid + ') initializing ' +
                argv.n + ' workers');
    for (var i = 0; i < argv.n; i++) {
        cluster.fork();
    }

    cluster.on('exit', function(worker, code, signal) {
        if (!worker.suicide) {
            var exitCode = worker.process.exitCode;
            console.log('worker', worker.process.pid,
                'died ('+exitCode+'), restarting.');
            cluster.fork();
        }
    });

    var shutdown_master = function() {
        console.log('master shutting down, killing workers');
        cluster.disconnect(function() {
            console.log('Exiting master');
            process.exit(0);
        });
    };

    process.on('SIGINT', shutdown_master);
    process.on('SIGTERM', shutdown_master);

} else {
    // Worker.
    process.on('SIGTERM', function() {
        console.log('Worker ' + process.pid + ' shutting down');
        process.exit(0);
    });

    // Enable heap dumps in /tmp on kill -USR2.
    // See https://github.com/bnoordhuis/node-heapdump/
    // For node 0.6/0.8: npm install heapdump@0.1.0
    // For 0.10: npm install heapdump
    process.on('SIGUSR2', function() {
        var heapdump = require('heapdump');
        console.error('SIGUSR2 received! Writing snapshot.');
        process.chdir('/tmp');
        heapdump.writeSnapshot();
    });

    var worker = require('./restface.js');
    worker();
}
<commit_msg>Add note about somaxconn tuning<commit_after>#!/usr/bin/env node
/**
 * Fairly generic cluster-based web service runner. Starts several instances
 * of a worker module (in this case the restface module), and manages restart
 * and graceful shutdown. The worker module can also be started independently,
 * which is especially useful for debugging.
 */
"use strict";

var cluster = require('cluster'),
    path = require('path'),
    // process arguments
    opts = require( "yargs" )
        .usage( "Usage: $0 [-h|-v] [--param[=val]]" )
        .default({

            // Start a few more workers than there are cpus visible to the OS,
            // so that we get some degree of parallelism even on single-core
            // systems. A single long-running request would otherwise hold up
            // all concurrent short requests.
            n: require( "os" ).cpus().length,
            c: __dirname + '/localsettings.js',

            v: false,
            h: false

        })
        .boolean( [ "h", "v" ] )
        .alias( "h", "help" )
        .alias( "v", "version" )
        .alias( "c", "config" )
        .alias( "n", "num-workers" ),
    argv = opts.argv;

// Disable cluster RR balancing; direct socket sharing has better throughput /
// lower overhead. Also bump up somaxconn with this command:
// sudo sysctl -w net.core.somaxconn=4096
cluster.schedulingPolicy = cluster.SCHED_NONE;

if (cluster.isMaster && argv.n > 0) {
    var fs = require( "fs" ),
        path = require( "path" ),
        meta = require( path.join( __dirname, "./package.json" ) );

    // help
    if ( argv.h ) {
        opts.showHelp();
        process.exit( 0 );
    }

    // version
    if ( argv.v ) {
        console.log( meta.name + " " + meta.version );
        process.exit( 0 );
    }

    // Fork workers.
    console.log('master(' + process.pid + ') initializing ' +
                argv.n + ' workers');
    for (var i = 0; i < argv.n; i++) {
        cluster.fork();
    }

    cluster.on('exit', function(worker, code, signal) {
        if (!worker.suicide) {
            var exitCode = worker.process.exitCode;
            console.log('worker', worker.process.pid,
                'died ('+exitCode+'), restarting.');
            cluster.fork();
        }
    });

    var shutdown_master = function() {
        console.log('master shutting down, killing workers');
        cluster.disconnect(function() {
            console.log('Exiting master');
            process.exit(0);
        });
    };

    process.on('SIGINT', shutdown_master);
    process.on('SIGTERM', shutdown_master);

} else {
    // Worker.
    process.on('SIGTERM', function() {
        console.log('Worker ' + process.pid + ' shutting down');
        process.exit(0);
    });

    // Enable heap dumps in /tmp on kill -USR2.
    // See https://github.com/bnoordhuis/node-heapdump/
    // For node 0.6/0.8: npm install heapdump@0.1.0
    // For 0.10: npm install heapdump
    process.on('SIGUSR2', function() {
        var heapdump = require('heapdump');
        console.error('SIGUSR2 received! Writing snapshot.');
        process.chdir('/tmp');
        heapdump.writeSnapshot();
    });

    var worker = require('./restface.js');
    worker();
}
<|endoftext|>


<commit_before>var path = require("path");
var express = require("express");
var elasticsearch = require("elasticsearch")
var bodyParser = require("body-parser")
var methodOverride = require("method-override")
var compression = require("compression")
var _ = require("lodash")
var cors = require('cors')
var SearchkitExpress = require("searchkit-express")

module.exports = {
  start: function(prodMode) {

    var env = {
      production: process.env.NODE_ENV === 'production'
    };

    var express = require('express');
    var app = express();
    app.use(compression())
    app.use("/images", express.static('images'))
    app.set('view engine', 'ejs');
    app.set('views', __dirname + '/server/views');
    app.use(bodyParser.urlencoded({ extended: false }))
    app.use(bodyParser.json())
    app.use(methodOverride())

    var port = Number(process.env.PORT || 3000);

    if (!env.production) {
      var webpack = require("webpack");
      var webpackMiddleware = require("webpack-dev-middleware");
      var webpackHotMiddleware = require('webpack-hot-middleware');
      var config = require("./webpack.dev.config.js");
      var compiler = webpack(config);

      app.use(webpackMiddleware(compiler, {
        publicPath: config.output.publicPath,
        contentBase: 'src',
        stats: {
          colors: true,
          hash: false,
          timings: true,
          chunks: false,
          chunkModules: false,
          modules: false
        }
      }));

      app.use(webpackHotMiddleware(compiler));

    } else {
      app.use("/static", express.static(__dirname + '/dist'));
    }

    var host = process.env.ES_URL || "http://localhost:9200"

    app.use("/api", cors({
      origin:"*",
      maxAge:20*24*60*60 //20 days like elastic
    }))
    app.use("/api/movies", SearchkitExpress.createRouter({
      host, index:"movies"
    }))

    app.use("/api/crimes", SearchkitExpress.createRouter({
      host, index:"crimes"
    }))

    app.use("/api/taxonomy", SearchkitExpress.createRouter({
      host, index:"taxonomynested"
    }))

    app.get('*', function(req, res) {
      res.render('index');
    });

    app.listen(port, function () {
      console.log('server running at localhost:3000, go refresh and see magic');
    });
  }
}
<commit_msg>Server.js cleanup<commit_after>var path = require("path");
var express = require("express");
var elasticsearch = require("elasticsearch")
var bodyParser = require("body-parser")
var methodOverride = require("method-override")
var compression = require("compression")
var _ = require("lodash")
var cors = require('cors')
var SearchkitExpress = require("searchkit-express")

module.exports = {
  start: function(prodMode) {

    var env = {
      production: process.env.NODE_ENV === 'production'
    };

    var express = require('express');
    var app = express();
    app.use(compression())
    app.use("/images", express.static('images'))
    app.set('view engine', 'ejs');
    app.set('views', __dirname + '/server/views');
    app.use(bodyParser.urlencoded({ extended: false }))
    app.use(bodyParser.json())
    app.use(methodOverride())

    var port = Number(process.env.PORT || 3000);

    if (!env.production) {
      var webpack = require("webpack");
      var webpackMiddleware = require("webpack-dev-middleware");
      var webpackHotMiddleware = require('webpack-hot-middleware');
      var config = require("./webpack.dev.config.js");
      var compiler = webpack(config);

      app.use(webpackMiddleware(compiler, {
        publicPath: config.output.publicPath,
        contentBase: 'src',
        stats: {
          colors: true,
          hash: false,
          timings: true,
          chunks: false,
          chunkModules: false,
          modules: false
        }
      }));

      app.use(webpackHotMiddleware(compiler));

    } else {
      app.use("/static", express.static(__dirname + '/dist'));
    }

    var host = process.env.ES_URL || "http://localhost:9200"

    app.use("/api", cors({
      origin:"*",
      maxAge:20*24*60*60 //20 days like elastic
    }))

    app.get('*', function(req, res) {
      res.render('index');
    });

    app.listen(port, function () {
      console.log('server running at localhost:3000, go refresh and see magic');
    });
  }
}
<|endoftext|>


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

financeControllers.controller('StocksController', function ($scope, $http) {
	$scope.title = 'Stock Market';
	$http.get('data.json').success(function (data) {
		$scope.stocks = data;
	});
	$scope.orderProp = '-value';
});<commit_msg>added list and detail controllers for stock<commit_after>
var financeControllers = angular.module('financeControllers', []);

financeControllers.controller('StocksController', ['$scope', '$http',
	function ($scope, $http) {
		$http.get('data.json').success(function (data){
			$scope.stocks = data;
		});
		$scope.orderProp = '-value';
	}
]);

financeControllers.controller('StockController', ['$scope' '$routeParams',
	function ($scope, $routeParams) {
		$scope.stockId = $routeParams.stockId;
	}
]);<|endoftext|>


<commit_before>// Require Modules
var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');

// Array of Mime Types
var mimeTypes = {
	"bmp" : "image/bmp",
	"css" : "text/css",
	"htm" : "text/html",
	"html" : "text/html",
	"htmls" : "text/html",
	"js" : "application/javascript",
	"jpeg" : "image/jpeg",
	"jpg" : "image/jpeg"
};

// Create Server
http.createServer(function(req, res){
	//Resouce loader
	var uri = url.parse(req.url).pathname;
	var fileName = path.join(process.cwd(),unescape(uri));
	console.log('Resource loader: Loading '+ uri);
	var stats;

	try{
		stats = fs.lstatSync(fileName);
	} catch(e) {
		res.writeHead(404, {'Content-type': 'text/plain'});
		res.write('404 Not Found\n');
		res.end();
		return;
	}

	// Check if file/directory
	if(stats.isFile()){
		var mimeType = mimeTypes[path.extname(fileName).split(".").reverse()[0]];
		console.log("stats.isFile: mimetype will be: " + mimeType);
		res.writeHead(200, {'Content-type': mimeType});

		var fileStream = fs.createReadStream(fileName);
		fileStream.pipe(res);

	} else if(stats.isDirectory()){
  		res.writeHead(302,{'Location' : 'index.html'});
		res.end();
	} else {
		res.writeHead(500, {'Content-Type' : 'text/plain'});
		res.write('500 Internal Error\n');
		res.end();
	}

  //POST handler
	if(req.method === 'POST'){
		    console.log('POST handler: Begin POST transaction');
	     	var fullBody = '';
		    req.on('data', function(chunk) {
		      // append the current chunk of data to the fullBody variable
		      fullBody += chunk;
		    });

    req.on('end', function() {
			console.log("POST handler: " + uri);
			var wstream = fs.createWriteStream(fileName);
			wstream.write(fullBody);
			wstream.end();
      console.log('POST handler: End POST transaction');
    });

	}
}).listen(5397, console.log("Node Server running..."));
<commit_msg>added json MIME type<commit_after>// Require Modules
var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');

// Array of Mime Types
var mimeTypes = {
	"bmp" : "image/bmp",
	"css" : "text/css",
	"htm" : "text/html",
	"html" : "text/html",
	"htmls" : "text/html",
	"js" : "application/javascript",
	"jpeg" : "image/jpeg",
	"jpg" : "image/jpeg",
	"json" : "application/json"
};

// Create Server
http.createServer(function(req, res){
	//Resouce loader
	var uri = url.parse(req.url).pathname;
	var fileName = path.join(process.cwd(),unescape(uri));
	console.log('Resource loader: Loading '+ uri);
	var stats;

	try{
		stats = fs.lstatSync(fileName);
	} catch(e) {
		res.writeHead(404, {'Content-type': 'text/plain'});
		res.write('404 Not Found\n');
		res.end();
		return;
	}

	// Check if file/directory
	if(stats.isFile()){
		var mimeType = mimeTypes[path.extname(fileName).split(".").reverse()[0]];
		console.log("Check if file/directory: mimetype will be: " + mimeType);
		res.writeHead(200, {'Content-type': mimeType});

		var fileStream = fs.createReadStream(fileName);
		fileStream.pipe(res);

	} else if(stats.isDirectory()){
  		res.writeHead(302,{'Location' : 'index.html'});
		res.end();
	} else {
		res.writeHead(500, {'Content-Type' : 'text/plain'});
		res.write('500 Internal Error\n');
		res.end();
	}

  //POST handler
	if(req.method === 'POST'){
		    console.log('POST handler: Begin POST transaction');
	     	var fullBody = '';
		    req.on('data', function(chunk) {
		      // append the current chunk of data to the fullBody variable
		      fullBody += chunk;
		    });

    req.on('end', function() {
			console.log("POST handler: " + uri);
			var wstream = fs.createWriteStream(fileName);
			wstream.write(fullBody);
			wstream.end();
      console.log('POST handler: End POST transaction');
    });

	}
}).listen(5397, console.log("Node Server running..."));
<|endoftext|>


<commit_before>'use strict';

var statik = require('statik');
var server = statik.createServer('.');
server.listen();
<commit_msg>Serving app in app dir<commit_after>'use strict';

var statik = require('statik');
var server = statik.createServer('./app');
server.listen();
<|endoftext|>


<commit_before>var http = require('http');
var rangeParser = require('range-parser');
var mime = require('mime');
var partFile = require('part-file');
var Readable = require('readable-stream');
var piece = require('./piece');

var pipeline = function(inp, out) {
	inp.pipe(out);
	out.on('close', function() {
		inp.destroy();
	});
};

module.exports = function(torrent, file, destination) {
	var PieceStream = function(range) {
		Readable.call(this);
		range = range || {start:0, end:file.length-1};
		this.position = ((range.start + file.offset) / torrent.pieceLength) | 0;
		this.remaining = range.end - range.start + 1;
		this.skip = (range.start + file.offset) % torrent.pieceLength;
		this.destroyed = false;
		this._onreadable = null;
	};

	PieceStream.prototype.__proto__ = Readable.prototype;

	PieceStream.prototype._read = function() {
		if (!this.remaining) return this.push(null);

		var self = this;
		var onread = function(err, data) {
			if (err) return self.emit('error', err);
			if (self.skip) data = data.slice(self.skip);
			if (data.length > self.remaining) data = data.slice(0, self.remaining);
			self.skip = 0;
			self.remaining -= data.length;
			if (!self.destroyed) self.push(data);
		};

		if (dest.readable(this.position)) return dest.read(this.position++, onread);

		this._onreadable = function(index) {
			if (index !== self.position) return;
			dest.removeListener('readable', self._onreadable);
			dest.read(self.position++, onread);
		};

		dest.on('readable', this._onreadable);
	};

	PieceStream.prototype.destroy = function() {
		this.destroyed = true;
		if (this._onreadable) dest.removeListener('readable', this._onreadable);
		this.emit('close');
	};

	var missing = [];

	var start = (file.offset / torrent.pieceLength) | 0;
	var end = ((file.offset + file.length + 1) / torrent.pieceLength) | 0;
	var dest = partFile(destination, torrent.pieceLength, torrent.pieces.slice(start, end+1));

	var prioritize = function(i) {
		missing.sort(function(a, b) {
			if (a >= i && b < i) return -1;
			if (b >= i && a < i) return 1;
			return a - b;
		});
	};

	var stream = function(range) {
		var s = new PieceStream(range);
		prioritize(s.position);
		return s;
	};

	var pieces = torrent.pieces.map(function(_, i) {
		if (i < start) return;
		if (i > end) return;

		missing.push(i);

		if (i === torrent.pieces.length-1) return piece(((file.length + file.offset) % torrent.pieceLength) || torrent.pieceLength);
		return piece(torrent.pieceLength);
	});

	var server = http.createServer(function(request, response) {
		var range = request.headers.range;

		response.setHeader('Accept-Ranges', 'bytes');
		response.setHeader('Content-Type', mime.lookup(file.name));

		range = range && rangeParser(file.length, range)[0];

		if (!range) {
			response.setHeader('Content-Length', file.length);
			if (request.method === 'HEAD') return response.end();
			pipeline(stream(), response);
			return;
		}

		response.statusCode = 206;
		response.setHeader('Content-Length', range.end - range.start + 1);
		response.setHeader('Content-Range', 'bytes '+range.start+'-'+range.end+'/'+file.length);

		if (request.method === 'HEAD') return response.end();
		pipeline(stream(range), response);
	});

	dest.on('readable', function(index) {
		index += start;
		var i = missing.indexOf(index);
		pieces[index] = null;
		if (i > -1) missing.splice(i, 1);
		server.emit('readable', index);
	});

	prioritize(0);
	server.missing = missing;
	server.filename = file.name;
	server.destination = destination;

	server.sizeof = function(index, offset) {
		var p = pieces[index];
		return p ? p.sizeof(offset) : 0;
	};

	server.select = function(index) {
		var p = pieces[index];
		return p ? p.select() : -1;
	};

	server.deselect = function(index, offset) {
		var p = pieces[index];
		if (p) p.deselect(offset);
	};

	server.write = function(index, offset, block) {
		var p = pieces[index];
		if (!p) return;

		var buffer = p.write(offset, block);
		if (!buffer) return;

		dest.write(index - start, buffer, function(err) {
			if (err) return p.reset();
		});
	};

	server.read = function(index, offset, length, callback) {
		dest.read(index - start, function(err, buffer) {
			if (err) return callback(err);
			callback(null, buffer.slice(offset, offset+length));
		});
	};

	return server;
};
<commit_msg>fixed last piece issue<commit_after>var http = require('http');
var rangeParser = require('range-parser');
var mime = require('mime');
var partFile = require('part-file');
var Readable = require('readable-stream');
var piece = require('./piece');

var pipeline = function(inp, out) {
	inp.pipe(out);
	out.on('close', function() {
		inp.destroy();
	});
};

module.exports = function(torrent, file, destination) {
	var PieceStream = function(range) {
		Readable.call(this);
		range = range || {start:0, end:file.length-1};
		this.position = ((range.start + file.offset) / torrent.pieceLength) | 0;
		this.remaining = range.end - range.start + 1;
		this.skip = (range.start + file.offset) % torrent.pieceLength;
		this.destroyed = false;
		this._onreadable = null;
	};

	PieceStream.prototype.__proto__ = Readable.prototype;

	PieceStream.prototype._read = function() {
		if (!this.remaining) return this.push(null);

		var self = this;
		var onread = function(err, data) {
			if (err) return self.emit('error', err);
			if (self.skip) data = data.slice(self.skip);
			if (data.length > self.remaining) data = data.slice(0, self.remaining);
			self.skip = 0;
			self.remaining -= data.length;
			if (!self.destroyed) self.push(data);
		};

		if (dest.readable(this.position)) return dest.read(this.position++, onread);

		this._onreadable = function(index) {
			if (index !== self.position) return;
			dest.removeListener('readable', self._onreadable);
			dest.read(self.position++, onread);
		};

		dest.on('readable', this._onreadable);
	};

	PieceStream.prototype.destroy = function() {
		this.destroyed = true;
		if (this._onreadable) dest.removeListener('readable', this._onreadable);
		this.emit('close');
	};

	var missing = [];

	var start = (file.offset / torrent.pieceLength) | 0;
	var end = ((file.offset + file.length + 1) / torrent.pieceLength) | 0;
	var dest = partFile(destination, torrent.pieceLength, torrent.pieces.slice(start, end+1));

	var prioritize = function(i) {
		missing.sort(function(a, b) {
			if (a >= i && b < i) return -1;
			if (b >= i && a < i) return 1;
			return a - b;
		});
	};

	var stream = function(range) {
		var s = new PieceStream(range);
		prioritize(s.position);
		return s;
	};

	var lastFile = torrent.files[torrent.files.length-1];
	var pieces = torrent.pieces.map(function(_, i) {
		if (i < start) return;
		if (i > end) return;

		missing.push(i);

		if (i === torrent.pieces.length-1) return piece(((lastFile.length + lastFile.offset) % torrent.pieceLength) || torrent.pieceLength);
		return piece(torrent.pieceLength);
	});

	var server = http.createServer(function(request, response) {
		var range = request.headers.range;

		response.setHeader('Accept-Ranges', 'bytes');
		response.setHeader('Content-Type', mime.lookup(file.name));

		range = range && rangeParser(file.length, range)[0];

		if (!range) {
			response.setHeader('Content-Length', file.length);
			if (request.method === 'HEAD') return response.end();
			pipeline(stream(), response);
			return;
		}

		response.statusCode = 206;
		response.setHeader('Content-Length', range.end - range.start + 1);
		response.setHeader('Content-Range', 'bytes '+range.start+'-'+range.end+'/'+file.length);

		if (request.method === 'HEAD') return response.end();
		pipeline(stream(range), response);
	});

	dest.on('readable', function(index) {
		index += start;
		var i = missing.indexOf(index);
		pieces[index] = null;
		if (i > -1) missing.splice(i, 1);
		server.emit('readable', index);
	});

	prioritize(0);
	server.missing = missing;
	server.filename = file.name;
	server.destination = destination;

	server.sizeof = function(index, offset) {
		var p = pieces[index];
		return p ? p.sizeof(offset) : 0;
	};

	server.select = function(index) {
		var p = pieces[index];
		return p ? p.select() : -1;
	};

	server.deselect = function(index, offset) {
		var p = pieces[index];
		if (p) p.deselect(offset);
	};

	server.write = function(index, offset, block) {
		var p = pieces[index];
		if (!p) return;

		var buffer = p.write(offset, block);
		if (!buffer) return;

		dest.write(index - start, buffer, function(err) {
			if (err) return p.reset();
		});
	};

	server.read = function(index, offset, length, callback) {
		dest.read(index - start, function(err, buffer) {
			if (err) return callback(err);
			callback(null, buffer.slice(offset, offset+length));
		});
	};

	return server;
};
<|endoftext|>


<commit_before>/* eslint-disable no-console */
const express = require('express');
const next = require('next');
const compression = require('compression');
const LRUCache = require('lru-cache');
const path = require('path');
const fs = require('fs');
const cors = require('cors');
const helmet = require('helmet');
const dotenv = require('dotenv');

dotenv.config();

const router = require('./routes');
const logger = require('./server/logger');

const isDev = process.env.NODE_ENV !== 'production';
const isProd = !isDev;
const ngrok = isDev && process.env.ENABLE_TUNNEL ? require('ngrok') : null;

const customHost = process.env.HOST;
const host = customHost || null;
const prettyHost = customHost || 'localhost';
const port = parseInt(process.env.PORT, 10) || 3000;
const publicEnvFilename = 'public.env';

const app = next({ dev: isDev });
const handle = app.getRequestHandler();

const ssrCache = new LRUCache({
  max: 100,
  maxAge: 3600 // 1 hour
});

// share public env variables (if not already set)
try {
  if (fs.existsSync(path.resolve(__dirname, publicEnvFilename))) {
    const publicEnv = dotenv.parse(
      fs.readFileSync(path.resolve(__dirname, publicEnvFilename))
    );
    Object.keys(publicEnv).forEach(key => {
      if (!process.env[key]) {
        process.env[key] = publicEnv[key];
      }
    });
  }
} catch (err) {
  // silence is golden
}

const buildStats = isProd
  ? JSON.parse(fs.readFileSync('./.next/build-stats.json', 'utf8').toString())
  : null;

const buildId = isProd
  ? fs.readFileSync('./.next/BUILD_ID', 'utf8').toString()
  : null;

/*
 * NB: make sure to modify this to take into account anything that should trigger
 * an immediate page change (e.g a locale stored in req.session)
 */
const getCacheKey = function getCacheKey(req) {
  return `${req.url}`;
};

const renderAndCache = function renderAndCache(
  req,
  res,
  pagePath,
  queryParams
) {
  const key = getCacheKey(req);

  if (ssrCache.has(key) && !isDev) {
    console.log(`CACHE HIT: ${key}`);
    res.send(ssrCache.get(key));
    return;
  }

  app
    .renderToHTML(req, res, pagePath, queryParams)
    .then(html => {
      // Let's cache this page
      if (!isDev) {
        console.log(`CACHE MISS: ${key}`);
        ssrCache.set(key, html);
      }

      res.send(html);
    })
    .catch(err => {
      app.renderError(err, req, res, pagePath, queryParams);
    });
};

const routerHandler = router.getRequestHandler(
  app,
  ({ req, res, route, query }) => {
    renderAndCache(req, res, route.page, query);
  }
);

app.prepare().then(() => {
  const server = express();

  server.use(compression({ threshold: 0 }));
  server.use(
    cors({
      origin:
        prettyHost.indexOf('http') !== -1 ? prettyHost : `http://${prettyHost}`,
      credentials: true
    })
  );
  server.use(helmet());
  server.use(routerHandler);

  server.get(`/favicon.ico`, (req, res) =>
    app.serveStatic(req, res, path.resolve('./static/icons/favicon.ico'))
  );

  server.get('/sw.js', (req, res) =>
    app.serveStatic(req, res, path.resolve('./.next/sw.js'))
  );

  server.get('/manifest.html', (req, res) =>
    app.serveStatic(req, res, path.resolve('./.next/manifest.html'))
  );

  server.get('/manifest.appcache', (req, res) =>
    app.serveStatic(req, res, path.resolve('./.next/manifest.appcache'))
  );

  if (isProd) {
    server.get('/_next/-/app.js', (req, res) =>
      app.serveStatic(req, res, path.resolve('./.next/app.js'))
    );

    const hash = buildStats['app.js'] ? buildStats['app.js'].hash : buildId;

    server.get(`/_next/${hash}/app.js`, (req, res) =>
      app.serveStatic(req, res, path.resolve('./.next/app.js'))
    );
  }

  server.get('*', (req, res) => handle(req, res));

  server.listen(port, host, err => {
    if (err) {
      return logger.error(err.message);
    }

    if (ngrok) {
      ngrok.connect(port, (innerErr, url) => {
        if (innerErr) {
          return logger.error(innerErr);
        }

        logger.appStarted(port, prettyHost, url);
      });
    } else {
      logger.appStarted(port, prettyHost);
    }
  });
});
<commit_msg>fix(server): cache 1 hour<commit_after>/* eslint-disable no-console */
const express = require('express');
const next = require('next');
const compression = require('compression');
const LRUCache = require('lru-cache');
const path = require('path');
const fs = require('fs');
const cors = require('cors');
const helmet = require('helmet');
const dotenv = require('dotenv');

dotenv.config();

const router = require('./routes');
const logger = require('./server/logger');

const isDev = process.env.NODE_ENV !== 'production';
const isProd = !isDev;
const ngrok = isDev && process.env.ENABLE_TUNNEL ? require('ngrok') : null;

const customHost = process.env.HOST;
const host = customHost || null;
const prettyHost = customHost || 'localhost';
const port = parseInt(process.env.PORT, 10) || 3000;
const publicEnvFilename = 'public.env';

const app = next({ dev: isDev });
const handle = app.getRequestHandler();

const ssrCache = new LRUCache({
  max: 100,
  maxAge: 1000 * 60 * 60 // 1hour
});

// share public env variables (if not already set)
try {
  if (fs.existsSync(path.resolve(__dirname, publicEnvFilename))) {
    const publicEnv = dotenv.parse(
      fs.readFileSync(path.resolve(__dirname, publicEnvFilename))
    );
    Object.keys(publicEnv).forEach(key => {
      if (!process.env[key]) {
        process.env[key] = publicEnv[key];
      }
    });
  }
} catch (err) {
  // silence is golden
}

const buildStats = isProd
  ? JSON.parse(fs.readFileSync('./.next/build-stats.json', 'utf8').toString())
  : null;

const buildId = isProd
  ? fs.readFileSync('./.next/BUILD_ID', 'utf8').toString()
  : null;

/*
 * NB: make sure to modify this to take into account anything that should trigger
 * an immediate page change (e.g a locale stored in req.session)
 */
const getCacheKey = function getCacheKey(req) {
  return `${req.url}`;
};

const renderAndCache = function renderAndCache(
  req,
  res,
  pagePath,
  queryParams
) {
  const key = getCacheKey(req);

  if (ssrCache.has(key) && !isDev) {
    console.log(`CACHE HIT: ${key}`);
    res.send(ssrCache.get(key));
    return;
  }

  app
    .renderToHTML(req, res, pagePath, queryParams)
    .then(html => {
      // Let's cache this page
      if (!isDev) {
        console.log(`CACHE MISS: ${key}`);
        ssrCache.set(key, html);
      }

      res.send(html);
    })
    .catch(err => {
      app.renderError(err, req, res, pagePath, queryParams);
    });
};

const routerHandler = router.getRequestHandler(
  app,
  ({ req, res, route, query }) => {
    renderAndCache(req, res, route.page, query);
  }
);

app.prepare().then(() => {
  const server = express();

  server.use(compression({ threshold: 0 }));
  server.use(
    cors({
      origin:
        prettyHost.indexOf('http') !== -1 ? prettyHost : `http://${prettyHost}`,
      credentials: true
    })
  );
  server.use(helmet());
  server.use(routerHandler);

  server.get(`/favicon.ico`, (req, res) =>
    app.serveStatic(req, res, path.resolve('./static/icons/favicon.ico'))
  );

  server.get('/sw.js', (req, res) =>
    app.serveStatic(req, res, path.resolve('./.next/sw.js'))
  );

  server.get('/manifest.html', (req, res) =>
    app.serveStatic(req, res, path.resolve('./.next/manifest.html'))
  );

  server.get('/manifest.appcache', (req, res) =>
    app.serveStatic(req, res, path.resolve('./.next/manifest.appcache'))
  );

  if (isProd) {
    server.get('/_next/-/app.js', (req, res) =>
      app.serveStatic(req, res, path.resolve('./.next/app.js'))
    );

    const hash = buildStats['app.js'] ? buildStats['app.js'].hash : buildId;

    server.get(`/_next/${hash}/app.js`, (req, res) =>
      app.serveStatic(req, res, path.resolve('./.next/app.js'))
    );
  }

  server.get('*', (req, res) => handle(req, res));

  server.listen(port, host, err => {
    if (err) {
      return logger.error(err.message);
    }

    if (ngrok) {
      ngrok.connect(port, (innerErr, url) => {
        if (innerErr) {
          return logger.error(innerErr);
        }

        logger.appStarted(port, prettyHost, url);
      });
    } else {
      logger.appStarted(port, prettyHost);
    }
  });
});
<|endoftext|>


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

var logger = app.logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({
      level: 'debug'
    })
  ]
});

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

app.use(function (req, res, next) {
  logger.debug(req.path);
  next();
});

app.listen(process.env.PORT || 4000, function (err, connection) {
  if (err) throw err;
  logger.info('Up and running');
  require('./server/db').init(app);
});
<commit_msg>update port<commit_after>
var express = require('express');
var winston = require('winston');
var app = express();

var logger = app.logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({
      level: 'debug'
    })
  ]
});

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

app.use(function (req, res, next) {
  logger.debug(req.path);
  next();
});

app.listen(process.env.PORT || 5000, function (err, connection) {
  if (err) throw err;
  logger.info('Up and running');
  require('./server/db').init(app);
});
<|endoftext|>


<commit_before>var restify = require("restify");
var fs = require("fs");

//setup cors

var server = restify.createServer();
var https_options = {
  key: fs.readFileSync('./self-signed/localhost.key'),
  certificate: fs.readFileSync('./self-signed/localhost.crt')
};
var https_server =  restify.createServer(https_options);

https_server.use(restify.acceptParser(server.acceptable));
https_server.use(restify.authorizationParser());
https_server.use(restify.dateParser());
https_server.use(restify.queryParser());
https_server.use(restify.jsonp());
https_server.use(restify.gzipResponse());
https_server.use(restify.bodyParser());
https_server.use(restify.CORS());
https_server.use(restify.fullResponse());
https_server.opts(/.*/, function (req,res,next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", req.header("Access-Control-Request-Method"));
    res.header("Access-Control-Allow-Headers", req.header("Access-Control-Request-Headers"));
    res.send(200);
    return next();
});

var server = restify.createServer();
server.use(restify.acceptParser(server.acceptable));
server.use(restify.authorizationParser());
server.use(restify.dateParser());
server.use(restify.queryParser());
server.use(restify.jsonp());
server.use(restify.gzipResponse());
server.use(restify.bodyParser());
server.use(restify.CORS());
server.use(restify.fullResponse());
server.opts(/.*/, function (req,res,next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", req.header("Access-Control-Request-Method"));
    res.header("Access-Control-Allow-Headers", req.header("Access-Control-Request-Headers"));
    res.send(200);
    return next();
});
server.get(/(.*)/,restify.serveStatic({
  directory: './public',
  default: 'index.html'
}));

var port = process.env.PORT || 8080;
server.listen(port,function(){
	console.log("Server Started. Press Ctrl+c to quit server")
})

https_server.get(/(.*)/,restify.serveStatic({
  directory: './public',
  default: 'index.html'
}));

https_server.listen(443, function() {
   console.log('%s listening at %s', https_server.name, https_server.url);
});<commit_msg>removed ssl and fs from server.js<commit_after>var restify = require("restify");

//setup cors
var server = restify.createServer();
server.use(restify.acceptParser(server.acceptable));
server.use(restify.authorizationParser());
server.use(restify.dateParser());
server.use(restify.queryParser());
server.use(restify.jsonp());
server.use(restify.gzipResponse());
server.use(restify.bodyParser());
server.use(restify.CORS());
server.use(restify.fullResponse());
//setup cors
server.opts(/.*/, function (req,res,next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", req.header("Access-Control-Request-Method"));
    res.header("Access-Control-Allow-Headers", req.header("Access-Control-Request-Headers"));
    res.send(200);
    return next();
});
server.get(/(.*)/,restify.serveStatic({
  directory: './public',
  default: 'index.html'
}));

var port = process.env.PORT || 8080;
server.listen(port, function () {
  console.log("Server Started. Press Ctrl+c to quit server")
});<|endoftext|>


<commit_before>'use strict';

var express = require('express'),
    cip = require('./lib/services/natmus-cip'),
    cipCategories = require('./lib/cip-categories'),
    es = require('./lib/services/elasticsearch');

process.env.NODE_ENV = process.env.NODE_ENV || 'development';

var config = require('./lib/config/config');
var app = express();
require('./lib/config/express')(app);
app.locals.config = config;

app.set('siteTitle', config.siteTitle);
// Trust the X-Forwarded-* headers from the Nginx reverse proxy infront of
// the app (See http://expressjs.com/api.html#app.set)
app.set('trust proxy', 'loopback');

require('./lib/routes')(app);
require('./lib/errors')(app);

es.count({
  index: config.esAssetsIndex
}).then(function(response) {
  console.log('Connecting to the Elasticsearch host', config.esHost);
  console.log('The assets index is created and contains',
              response.count, 'documents.');
  console.log('Loading categories...');
}, function() {
  console.log('Could not connect to the Elasticsearch host', config.esHost);
  // We have an error in the communication with the Elasticsearch server
  // I is probably not started.
  console.error('Is the elasticsearch service started?');
  process.exit(1);
});

var categories = {};

cipCategories.loadCategories().then(function(result) {
  for (var i = 0; i < result.length; ++i) {
    if (result[i] && result[i].id) {
      categories[result[i].id] = result[i];
    } else {
      console.error(result);
      throw new Error('Could not read id from the result of loadCategories');
    }
  }
  // Fetch the number of assets in the category.
  return cipCategories.fetchCategoryCounts(es, categories)
  .then(function(categoriesWithCounts) {
    app.set('categories', categoriesWithCounts);
  });
}).then(function() {
  return cip.getCatalogs().then(function(catalogs) {
    app.set('catalogs', catalogs);
  });
}).then(function() {
  // Start server
  app.listen(config.port, config.ip, function() {
    console.log('Express server listening on %s:%d, in %s mode',
                config.ip, config.port, app.get('env'));
  });
}, function(err) {
  console.error('Error when starting the app: ', err.stack);
});

// Expose app
exports = module.exports = app;
<commit_msg>We need an initialized session to fetch categories and catalogs.<commit_after>'use strict';

var express = require('express'),
    cip = require('./lib/services/natmus-cip'),
    cipCategories = require('./lib/cip-categories'),
    es = require('./lib/services/elasticsearch');

process.env.NODE_ENV = process.env.NODE_ENV || 'development';

var config = require('./lib/config/config');
var app = express();
require('./lib/config/express')(app);
app.locals.config = config;

app.set('siteTitle', config.siteTitle);
// Trust the X-Forwarded-* headers from the Nginx reverse proxy infront of
// the app (See http://expressjs.com/api.html#app.set)
app.set('trust proxy', 'loopback');

require('./lib/routes')(app);
require('./lib/errors')(app);

es.count({
  index: config.esAssetsIndex
}).then(function(response) {
  console.log('Connecting to the Elasticsearch host', config.esHost);
  console.log('The assets index is created and contains',
              response.count, 'documents.');
  console.log('Loading categories...');
}, function() {
  console.log('Could not connect to the Elasticsearch host', config.esHost);
  // We have an error in the communication with the Elasticsearch server
  // I is probably not started.
  console.error('Is the elasticsearch service started?');
  process.exit(1);
});

var categories = {};

cip.initSession().then(function() {
  return cipCategories.loadCategories().then(function(result) {
    for (var i = 0; i < result.length; ++i) {
      if (result[i] && result[i].id) {
        categories[result[i].id] = result[i];
      } else {
        console.error(result);
        throw new Error('Could not read id from the result of loadCategories');
      }
    }
    // Fetch the number of assets in the category.
    return cipCategories.fetchCategoryCounts(es, categories)
    .then(function(categoriesWithCounts) {
      app.set('categories', categoriesWithCounts);
    });
  }).then(function() {
    return cip.getCatalogs().then(function(catalogs) {
      app.set('catalogs', catalogs);
    });
  });
}).then(function() {
  // Start server
  app.listen(config.port, config.ip, function() {
    console.log('Express server listening on %s:%d, in %s mode',
                config.ip, config.port, app.get('env'));
  });
}, function(err) {
  console.error('Error when starting the app: ', err.stack);
});

// Expose app
exports = module.exports = app;
<|endoftext|>


<commit_before>// Load dependencies
var express = require('express');
var webpack = require('webpack');
var webpackConfig = require('./webpack.config');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var webpackCompiler = webpack(webpackConfig);

// Create the express app
var app = express();

// Attach webpack-dev-middleware and webpack-hot-middleware
app.use(webpackDevMiddleware(webpackCompiler));
app.use(webpackHotMiddleware(webpackCompiler));

// Create static directories
app.use(express.static(__dirname + '/public'));
app.use('/dist', express.static(__dirname + '/dist'));

// Set the address/port
var address = process.env.DOCKER_HOST || 'localhost';
var port = process.env.PORT || 4000

// Listen to the port
var server = app.listen(port, function(err, result) {
    if (err) {
        console.log(err);
    }
  console.log('Running on http://%s:%s', address, port);
});
<commit_msg>don't display info<commit_after>// Load dependencies
var express = require('express');
var webpack = require('webpack');
var webpackConfig = require('./webpack.config');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var webpackCompiler = webpack(webpackConfig);

// Create the express app
var app = express();

// Attach webpack-dev-middleware and webpack-hot-middleware
app.use(webpackDevMiddleware(webpackCompiler, {
    noInfo: true
}));
app.use(webpackHotMiddleware(webpackCompiler));

// Create static directories
app.use(express.static(__dirname + '/public'));
app.use('/dist', express.static(__dirname + '/dist'));

// Set the address/port
var address = process.env.DOCKER_HOST || 'localhost';
var port = process.env.PORT || 4000

// Listen to the port
var server = app.listen(port, function(err, result) {
    if (err) {
        console.log(err);
    }
  console.log('Running on http://%s:%s', address, port);
});
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var fs = require('fs'),
	http = require('http'),
	express = require('express'),
	app = express(),
	favicon = require('serve-favicon'),
	path = require('path'),
	passport = require('passport'),
	errorHandler = require('errorhandler'),
	/*sio = require('socket.io'),*/
	/*socketio_jwt = require('socketio-jwt'),*/
	configs = require('./server/config/config'),
	auth = require('./server/middlewares/auth'),
	jwt = require('./server/middlewares/jwt')(configs);

// Bootstrap db connection
var db = require('./server/config/db')(configs);

// Bootstrap models
var modelsPath = path.join(configs.serverPath+ '/models');
fs.readdirSync(modelsPath).forEach(function (file) {
	require(modelsPath + '/' + file);
});

require(configs.serverPath+'/config/passport')(passport);

// We are going to protect /api routes with JWT
//app.use('/api', expressJwt({secret: configs.apiSecret}));

require(configs.serverPath+'/config/express')(configs,app,passport,db);

 if (app.get('env') === 'development') {
 	app.disable('etag');
	app.use(require('connect-livereload')());
}
app.set('port', process.env.PORT || 3000);

app.use(favicon(path.join(configs.rootPath,configs.releasePath,'favicon.ico')));
app.use(express.static( path.join(configs.rootPath, configs.releasePath)));

/*
var router = express.Router();

router.use(function(req, res, next) {
	res.header('Access-Control-Allow-Origin', '*');
    	res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    	res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
            // intercept OPTIONS method
	if ('OPTIONS' == req.method) {
	      return res.sendStatus(200);
	}
   	next();
});
app.use('/api', router);
*/
// Routes
require(configs.serverPath+'/routers/auth')(app, auth, configs, jwt, passport);
require(configs.serverPath+'/routers/users')(app, auth);

app.use(function(err, req, res, next) {
	// If the error object doesn't exists
	if (!err){
		return next();
	}
	// Log it
	console.error(err.stack);
	//For /api
	if (err.constructor.name === 'UnauthorizedError') {
    		res.status(401).send('Unauthorized');
  	}
  	if (err.status === 405) {
    		res.status(405).send('Method Not Allowed');
  	}
  	res.status(500).send('Internal Server Error');
});

// Assume 404 since no middleware responded
app.use(function(req, res) {
	// Log it
	console.error(req.url);
	if(configs.niceErrorPage){
		return res.status(404).render('404');
	}
	res.status(404).send('Not Found');
});

if (app.get('env') === 'development') {
	app.use(errorHandler());
}
var server = http.createServer(app);
//var io = sio(server);

/*io.use(socketio_jwt.authorize({
  secret: configs.apiSecret,
  handshake: true
}));*/

//io.on('connection', require(configs.serverPath+'/routers/chat')(io));

server.listen(app.get('port'), function () {
	console.log( 'Express started on http://'  + configs.hostname + ':' +
		app.get('port') + ' env: ' + app.get('env') +  '; press Ctrl-C to terminate.' );
});

exports = module.exports = app;
<commit_msg>set up<commit_after>'use strict';

/**
 * Module dependencies.
 */
var fs = require('fs'),
	http = require('http'),
	express = require('express'),
	app = express(),
	favicon = require('serve-favicon'),
	path = require('path'),
	passport = require('passport'),
	errorHandler = require('errorhandler'),
	/*sio = require('socket.io'),*/
	/*socketio_jwt = require('socketio-jwt'),*/
	configs = require('./server/config/config'),
	auth = require('./server/middlewares/auth'),
	jwt = require('./server/middlewares/jwt')(configs);

// Bootstrap db connection
var db = require('./server/config/db')(configs);

// Bootstrap models
var modelsPath = path.join(configs.serverPath+ '/models');
fs.readdirSync(modelsPath).forEach(function (file) {
	require(modelsPath + '/' + file);
});

require(configs.serverPath+'/config/passport')(passport);

// We are going to protect /api routes with JWT
//app.use('/api', expressJwt({secret: configs.apiSecret}));

require(configs.serverPath+'/config/express')(configs,app,passport,db);

 if (app.get('env') === 'development') {
 	app.disable('etag');
	app.use(require('connect-livereload')());
}
app.set('port', process.env.PORT || 3000);
app.use(favicon(path.join(__dirname,configs.releasePath,'favicon.ico')));
app.use(express.static( path.join(configs.rootPath, configs.releasePath)));

/*
var router = express.Router();

router.use(function(req, res, next) {
	res.header('Access-Control-Allow-Origin', '*');
    	res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    	res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
            // intercept OPTIONS method
	if ('OPTIONS' == req.method) {
	      return res.sendStatus(200);
	}
   	next();
});
app.use('/api', router);
*/
// Routes
require(configs.serverPath+'/routers/auth')(app, auth, configs, jwt, passport);
require(configs.serverPath+'/routers/users')(app, auth);

app.use(function(err, req, res, next) {
	// If the error object doesn't exists
	if (!err){
		return next();
	}
	// Log it
	console.error(err.stack);
	//For /api
	if (err.constructor.name === 'UnauthorizedError') {
    		res.status(401).send('Unauthorized');
  	}
  	if (err.status === 405) {
    		res.status(405).send('Method Not Allowed');
  	}
  	res.status(500).send('Internal Server Error');
});

// Assume 404 since no middleware responded
app.use(function(req, res) {
	// Log it
	console.error(req.url);
	if(configs.niceErrorPage){
		return res.status(404).render('404');
	}
	res.status(404).send('Not Found');
});

if (app.get('env') === 'development') {
	app.use(errorHandler());
}
var server = http.createServer(app);
//var io = sio(server);

/*io.use(socketio_jwt.authorize({
  secret: configs.apiSecret,
  handshake: true
}));*/

//io.on('connection', require(configs.serverPath+'/routers/chat')(io));

server.listen(app.get('port'), function () {
	console.log( 'Express started on http://'  + configs.hostname + ':' +
		app.get('port') + ' env: ' + app.get('env') +  '; press Ctrl-C to terminate.' );
});

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


<commit_before>var config = require('./config.js');
var Slack = require('slack-client');
var token = config.slackApiKey;
var slack = new Slack(token, true, true);
var chrono = require('chrono-node');
var m = require('moment');
var tz = require('moment-timezone');

slack.on('message', function(message) {
    var user = slack.getUserByID(message.user);
    var channel = slack.getChannelGroupOrDMByID(message.channel);
    var results = chrono.parse(message.text);

    if (results.length > 0 && message.type === 'message' && channel.name === 'bottesting') {
    	results.forEach(function(result) {
    		var start = m(result.start.date());
    		channel.send(start.format('MMMM Do YYYY, h:mm a ZZ'));
    		console.log(start.format('MMMM Do YYYY, h:mm a ZZ'));

    		if (result.end) {
    			var end = m(result.end.date());
    			channel.send(end.format('MMMM Do YYYY, h:mm a ZZ'));
    			console.log(end.format('MMMM Do YYYY, h:mm a ZZ'));
    		}
    	});
    }

    // var regex = /([0-9]{1,2}):([0-9]{2})(am|pm)?/gi;
    // var match = regex.exec(message);
    // if (match && message.type === 'message' && channel.name === 'bottesting') {

        // var time = new Date();

        // var hour = parseInt(match[1], 10);
        // var mins = parseInt(match[2], 10);

        // if (match[3] && match[3].toLowerCase() === 'pm') {
        //     hour = hour + 12;
        // }

        // time.setHours(hour);
        // time.setMinutes(mins);

        // channel.send(time);

        // User.findOne({uuid: message.user}, function(err, user) {

        //     if(err) {
        //         return;
        //     }

        //     if(!user.timezone) {
        //         // ask user for timezone
        //         return;
        //     }

        //     channel.users.forEach(function (user) {

        //         User.findOne({uuid: user.id}, function(err, user) {

        //             if(!err && user.timezone) {
        //                 channel.sendDM(time, user.id);
        //             }

        //         });

        //     });

        // });

    // }
});

slack.login();<commit_msg>Add simple server to make heroku happy<commit_after>var config = require('./config.js');
var Slack = require('slack-client');
var token = config.slackApiKey;
var slack = new Slack(token, true, true);
var chrono = require('chrono-node');
var m = require('moment');
var tz = require('moment-timezone');
var http = require('http');

var server = http.createServer(function(req, res) {
    res.end('Welcome to fathertime.');
});

server.listen(process.env.PORT || 5000);

slack.on('message', function(message) {
    var user = slack.getUserByID(message.user);
    var channel = slack.getChannelGroupOrDMByID(message.channel);
    var results = chrono.parse(message.text);

    if (results.length > 0 && message.type === 'message' && channel.name === 'bottesting') {
    	results.forEach(function(result) {
    		var start = m(result.start.date());
    		channel.send(start.format('MMMM Do YYYY, h:mm a ZZ'));
    		console.log(start.format('MMMM Do YYYY, h:mm a ZZ'));

    		if (result.end) {
    			var end = m(result.end.date());
    			channel.send(end.format('MMMM Do YYYY, h:mm a ZZ'));
    			console.log(end.format('MMMM Do YYYY, h:mm a ZZ'));
    		}
    	});
    }

    // var regex = /([0-9]{1,2}):([0-9]{2})(am|pm)?/gi;
    // var match = regex.exec(message);
    // if (match && message.type === 'message' && channel.name === 'bottesting') {

        // var time = new Date();

        // var hour = parseInt(match[1], 10);
        // var mins = parseInt(match[2], 10);

        // if (match[3] && match[3].toLowerCase() === 'pm') {
        //     hour = hour + 12;
        // }

        // time.setHours(hour);
        // time.setMinutes(mins);

        // channel.send(time);

        // User.findOne({uuid: message.user}, function(err, user) {

        //     if(err) {
        //         return;
        //     }

        //     if(!user.timezone) {
        //         // ask user for timezone
        //         return;
        //     }

        //     channel.users.forEach(function (user) {

        //         User.findOne({uuid: user.id}, function(err, user) {

        //             if(!err && user.timezone) {
        //                 channel.sendDM(time, user.id);
        //             }

        //         });

        //     });

        // });

    // }
});

slack.login();<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const pg = require('pg');
const PORT = process.env.PORT || 3000;
// const connString = 'postgres://localhost:5432/yourtube';
const connString = process.env.PG_PASSWORD;
const client = new pg.Client(connString);
client.connect();

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

// put from model
app.put('/setGenres', (req, res) => {
  client.query(`INSERT INTO genres (genre) VALUES ($1) ON CONFLICT DO NOTHING;`,
  [req.body.genre])
  .then(() => {
    res.send('insert genres complete')
  })
  .catch((err) => {
    console.error(err);
  });
});

app.post('/newUser', function(req, res) {
  client.query(
      `INSERT INTO users (username, name) VALUES ($1, $2) RETURNING *;`, [
        req.body.username,
        req.body.name
      ]
    )
    .then(function(result) {
      res.send(result.rows[0]);
    })
    .catch(function(err) {
      console.error(err);
      res.send(err);
    });
});

app.put('/updateUser', function(req, res) {
  client.query(
      `UPDATE users SET name=$1, genres=$2, days=$3, times=$4 WHERE user_id=$5 RETURNING *;`, [
        req.body.name,
        req.body.genres,
        req.body.days,
        req.body.times,
        req.body.user_id
      ]
    )
    .then(function(result) {
      res.send(result.rows[0]);
    })
    .catch(function(err) {
      console.log(req.body)
      console.error(err)
      res.send(err);
    });
});

app.get('/getUser', function(req, res) {
  console.log(req.query.user_id);
  client.query(
      `SELECT * FROM users WHERE user_id=$1;`, [req.query.user_id]
    )
    .then(function(result) {
      console.log('Inside server GET success: ')
      console.log(result)
      res.send(result.rows[0]);
    })
    .catch(function(err) {
      console.log('Inside server GET error: ')
      console.error(err);
      res.send(err);
    });
});

app.get('/getUsers', function(req, res) {
  client.query(
      `SELECT * FROM users;`
    )
    .then(function(result) {
      console.log('Inside server GET success: ')
      console.log(result)
      res.send(result.rows[0]);
    })
    .catch(function(err) {
      console.log('Inside server GET error: ')
      console.error(err);
      res.send(err);
    });
});

// get data from tables

app.get('/getGenres', (req, res) => {
  client.query(
      `SELECT genre FROM genres;`
    )
    .then( (result) => {
      res.send(result.rows);
    })
    .catch( (err) => {
      res.send(err);
    });
});

app.get('/getDays', (req, res) => {
  client.query(
      `SELECT day FROM days;`
    )
    .then( (result) => {
      res.send(result.rows);
    })
    .catch( (err) => {
      res.send(err);
    });
});

app.get('/getTimes', (req, res) => {
  client.query(
      `SELECT time FROM times;`
    )
    .then((result) => {
      res.send(result.rows);
    })
    .catch((err) => {
      res.send(err);
    });
});

loadDB();

function loadDB() {

  //TODO: do this as a check
  client.query('DROP TABLE days, times, genres, users');

  const DAY_ARRAY = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
  const TIME_ARRAY = ['morning', 'afternoon', 'evening'];
  // const GENRE_ARRAY = [];

  createUsersTable();
  createGenresTable();
  createDaysTable();
  createTimesTable();

  // TODO: DRY refactor needed
  function createUsersTable() {
    client.query(`CREATE TABLE IF NOT EXISTS users (
      user_id SERIAL PRIMARY KEY,
      username VARCHAR NOT NULL,
      name VARCHAR);`)
  }

  // create tables for genre
  function createGenresTable() {
    client.query(`CREATE TABLE IF NOT EXISTS genres (
      genre_id SERIAL PRIMARY KEY,
      genre VARCHAR
    );`).then(function() {
      console.info('Created genres table');
    });
  }

  // function insertGenresData(thisGenre) {
  //   client.query(`INSERT INTO genres (genre) VALUES ($1) ON CONFLICT DO NOTHING RETURNING *;`, [thisGenre]);
  // }

  // create days table
  function createDaysTable() {
    client.query(`CREATE TABLE IF NOT EXISTS days (
    day_id SERIAL PRIMARY KEY,
    day VARCHAR
  );`).then(function() {
    console.info('Created days table');
    DAY_ARRAY.forEach(function(day) {
      insertDaysData(day);
    });
  });
  }

  function insertDaysData(thisDay) {
    client.query(`INSERT INTO days (day) VALUES ($1) ON CONFLICT DO NOTHING RETURNING *;`, [thisDay]);
  };

  // create times table
  function createTimesTable() {
    client.query(`CREATE TABLE IF NOT EXISTS times (
    time_id SERIAL PRIMARY KEY,
    time VARCHAR
  );`).then(function() {
    console.info('Created times table');
    TIME_ARRAY.forEach(function(time) {
      insertTimesData(time);
    });
  });
  }

  function insertTimesData(thisTime) {
    client.query(`INSERT INTO times (time) VALUES ($1) ON CONFLICT DO NOTHING RETURNING *;`, [thisTime]);
  }
}

app.listen(PORT, function() {
  console.info('Listening on port: ' + PORT);
})
<commit_msg>investigated genres duplicate<commit_after>'use strict';

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const pg = require('pg');
const PORT = process.env.PORT || 3000;
// const connString = 'postgres://localhost:5432/yourtube';
const connString = process.env.PG_PASSWORD;
const client = new pg.Client(connString);
client.connect();

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

loadDB();

// put from model
app.put('/setGenres', (req, res) => {
  client.query(`INSERT INTO genres (genre) VALUES ($1) ON CONFLICT DO NOTHING;`,
  [req.body.genre])
  .then(() => {
    res.send('insert genres complete')
  })
  .catch((err) => {
    console.error(err);
  });
});

app.post('/newUser', function(req, res) {
  client.query(
      `INSERT INTO users (username, name) VALUES ($1, $2) RETURNING *;`, [
        req.body.username,
        req.body.name
      ]
    )
    .then(function(result) {
      res.send(result.rows[0]);
    })
    .catch(function(err) {
      console.error(err);
      res.send(err);
    });
});

app.put('/updateUser', function(req, res) {
  client.query(
      `UPDATE users SET name=$1, genres=$2, days=$3, times=$4 WHERE user_id=$5 RETURNING *;`, [
        req.body.name,
        req.body.genres,
        req.body.days,
        req.body.times,
        req.body.user_id
      ]
    )
    .then(function(result) {
      res.send(result.rows[0]);
    })
    .catch(function(err) {
      console.log(req.body)
      console.error(err)
      res.send(err);
    });
});

app.get('/getUser', function(req, res) {
  console.log(req.query.user_id);
  client.query(
      `SELECT * FROM users WHERE user_id=$1;`, [req.query.user_id]
    )
    .then(function(result) {
      console.log('Inside server GET success: ')
      console.log(result)
      res.send(result.rows[0]);
    })
    .catch(function(err) {
      console.log('Inside server GET error: ')
      console.error(err);
      res.send(err);
    });
});

app.get('/getUsers', function(req, res) {
  client.query(
      `SELECT * FROM users;`
    )
    .then(function(result) {
      console.log('Inside server GET success: ')
      console.log(result)
      res.send(result.rows[0]);
    })
    .catch(function(err) {
      console.log('Inside server GET error: ')
      console.error(err);
      res.send(err);
    });
});

// get data from tables

app.get('/getGenres', (req, res) => {
  client.query(
      `SELECT genre FROM genres;`
    )
    .then( (result) => {
      res.send(result.rows);
    })
    .catch( (err) => {
      res.send(err);
    });
});

app.get('/getDays', (req, res) => {
  client.query(
      `SELECT day FROM days;`
    )
    .then( (result) => {
      res.send(result.rows);
    })
    .catch( (err) => {
      res.send(err);
    });
});

app.get('/getTimes', (req, res) => {
  client.query(
      `SELECT time FROM times;`
    )
    .then((result) => {
      res.send(result.rows);
    })
    .catch((err) => {
      res.send(err);
    });
});

function loadDB() {

  //TODO: do this as a check
  client.query('DROP TABLE days, times, genres, users');

  const DAY_ARRAY = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
  const TIME_ARRAY = ['morning', 'afternoon', 'evening'];
  // const GENRE_ARRAY = [];

  createUsersTable();
  createGenresTable();
  createDaysTable();
  createTimesTable();

  // TODO: DRY refactor needed
  function createUsersTable() {
    client.query(`CREATE TABLE IF NOT EXISTS users (
      user_id SERIAL PRIMARY KEY,
      username VARCHAR NOT NULL,
      name VARCHAR);`)
  }

  // create tables for genre
  function createGenresTable() {
    client.query(`CREATE TABLE IF NOT EXISTS genres (
      genre_id SERIAL PRIMARY KEY,
      genre VARCHAR
    );`).then(function() {
      console.info('Created genres table');
    });
  }

  // function insertGenresData(thisGenre) {
  //   client.query(`INSERT INTO genres (genre) VALUES ($1) ON CONFLICT DO NOTHING RETURNING *;`, [thisGenre]);
  // }

  // create days table
  function createDaysTable() {
    client.query(`CREATE TABLE IF NOT EXISTS days (
    day_id SERIAL PRIMARY KEY,
    day VARCHAR
  );`).then(function() {
    console.info('Created days table');
    DAY_ARRAY.forEach(function(day) {
      insertDaysData(day);
    });
  });
  }

  function insertDaysData(thisDay) {
    client.query(`INSERT INTO days (day) VALUES ($1) ON CONFLICT DO NOTHING RETURNING *;`, [thisDay]);
  };

  // create times table
  function createTimesTable() {
    client.query(`CREATE TABLE IF NOT EXISTS times (
    time_id SERIAL PRIMARY KEY,
    time VARCHAR
  );`).then(function() {
    console.info('Created times table');
    TIME_ARRAY.forEach(function(time) {
      insertTimesData(time);
    });
  });
  }

  function insertTimesData(thisTime) {
    client.query(`INSERT INTO times (time) VALUES ($1) ON CONFLICT DO NOTHING RETURNING *;`, [thisTime]);
  }
}

app.listen(PORT, function() {
  console.info('Listening on port: ' + PORT);
})
<|endoftext|>