<commit_before>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
// https://github.com/misterGF/CoPilot/blob/master/src/main.js
import Vue from 'vue'
import App from './App'
import VueRouter from 'vue-router'

import { sync } from 'vuex-router-sync'
import routes from './router'
import store from './store'
import config from '@/config'

// import BootstrapVue from 'bootstrap-vue'
// import 'bootstrap/dist/css/bootstrap.css'
// import 'bootstrap-vue/dist/bootstrap-vue.css'
// Vue.use(BootstrapVue)

// import CellRender from '@/components/cellRender'
// Vue.use(CellRender)

// Include and set up feathers client
const Feathers = require('feathers/client')
const hooks = require('feathers-hooks')
  // const authentication = require('feathers-authentication/client')
const socketio = require('feathers-socketio/client')
const io = require('socket.io-client')
let socket = io(config.socketURI)
socket.on('connect', function () {
})
socket.on('disconnect', function () {
})
  // if (process.env.NODE_ENV !== 'development') {
  //   socket = io(config.serverURI, {path: '/eng/socket.io'})
  // } else {
  //   socket = io(config.serverURI)
  // }
const feathers = Feathers()
  .configure(socketio(socket))
  .configure(hooks())
  // .configure(authentication({storage: window.localStorage}))
  // Include it as a CommonJS module
const vueFeathers = require('vue-feathers')
  // And plug it in]
Vue.use(vueFeathers, feathers)

/* IView */
import iView from 'iview'
import locale from 'iview/dist/locale/en-US'
import 'iview/dist/styles/iview.css' // CSS

Vue.use(iView, { locale })

import VueParticles from 'vue-particles'
Vue.use(VueParticles)

/* Animated css */

import 'animate.css/animate.css'

// import AsyncComputed from 'vue-async-computed'
// Vue.use(AsyncComputed)

/* vue-split-panel */
import VueSplit from 'vue-split-panel'
Vue.use(VueSplit)

Vue.config.productionTip = false

/* eslint-disable no-new */
// cookies
var VueCookie = require('vue-cookie')
Vue.use(VueCookie)

// Routing logic
Vue.use(VueRouter)

var router = new VueRouter({
  routes: routes,
  mode: 'history',
  scrollBehavior: function (to, from, savedPosition) {
    return savedPosition || { x: 0, y: 0 }
  }
})

iView.LoadingBar.config({
  color: '#5cb85c',
  failedColor: '#f0ad4e',
  height: 5
})

import axios from 'axios'
import psl from 'psl'
// Some middleware to help us ensure the user is authenticated.
router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  iView.LoadingBar.config({ color: '#0e406d' })
  // window.console.log('Transition', transition)
  // router.app.$store.state.token
  let location = psl.parse(window.location.hostname) // get parent domain
  location = location.domain === null ? location.input : location.domain

  if (to.query.token) {
    router.app.$cookie.set('auth_token', to.query.token, { expires: 1, domain: location })
  }
  const token = router.app.$cookie.get('auth_token')
  store.state.token = token
  // set token in axios
  if (token) {
    axios.defaults.headers.common['authorization'] = token
  } else {
    delete axios.defaults.headers.common['authorization']
  }

  if (to.matched.some(record => record.meta.requiresAuth) && (!token || token === 'null' || store.state.token === undefined)) {
    next({
      path: '/login'
        // query: { redirect: to.fullPath }
    })
  } else {
    if (to.matched.some(record => record.meta.requiresAuth) || (to.path === '/login')) {
      store.dispatch('authenticateToken', token).then(response => {
        // get user role
        if (to.path !== '/') {
          if (to.matched.find(record => record.meta.role).meta.role.indexOf(parseInt(store.state.role)) === -1) {
            next({
              path: '/'
            })
          } else {
            next()
          }
        } else {
          if (store.state.role === 1) {
            next({
              path: '/admin/dashboard'
            })
          } else {
            next({
              path: '/dashboard'
            })
          }
        }
      }).catch(() => {
        router.app.$cookie.delete('auth_token', { domain: location })
        store.commit('SET_TOKEN', null)
        store.commit('SET_USER', null)
        store.commit('SET_ROLE', null)
        if (to.path !== '/login') {
          next({
            path: '/login'
          })
        } else {
          next()
        }
      })
    } else {
      next()
    }
  }
})

router.afterEach(route => {
  iView.LoadingBar.finish()
})

sync(store, router)
  // console.log('process.env.accesskey', process.env.accesskey)

new Vue({
  el: '#app',
  router,
  store: store,
  template: '<App/>',
  components: { App }
})
<commit_msg>removed tinymce globally import<commit_after>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
// https://github.com/misterGF/CoPilot/blob/master/src/main.js
import Vue from 'vue'
import App from './App'
import VueRouter from 'vue-router'

import { sync } from 'vuex-router-sync'
import routes from './router'
import store from './store'
import config from '@/config'

// import BootstrapVue from 'bootstrap-vue'
// import 'bootstrap/dist/css/bootstrap.css'
// import 'bootstrap-vue/dist/bootstrap-vue.css'
// Vue.use(BootstrapVue)

// import CellRender from '@/components/cellRender'
// Vue.use(CellRender)

// Include and set up feathers client
const Feathers = require('feathers/client')
const hooks = require('feathers-hooks')
  // const authentication = require('feathers-authentication/client')
const socketio = require('feathers-socketio/client')
const io = require('socket.io-client')
let socket = io(config.socketURI)
socket.on('connect', function () {
})
socket.on('disconnect', function () {
})
  // if (process.env.NODE_ENV !== 'development') {
  //   socket = io(config.serverURI, {path: '/eng/socket.io'})
  // } else {
  //   socket = io(config.serverURI)
  // }
const feathers = Feathers()
  .configure(socketio(socket))
  .configure(hooks())
  // .configure(authentication({storage: window.localStorage}))
  // Include it as a CommonJS module
const vueFeathers = require('vue-feathers')
  // And plug it in]
Vue.use(vueFeathers, feathers)

/* IView */
import iView from 'iview'
import locale from 'iview/dist/locale/en-US'
import 'iview/dist/styles/iview.css' // CSS

Vue.use(iView, { locale })

import VueParticles from 'vue-particles'
Vue.use(VueParticles)

/* Animated css */

import 'animate.css/animate.css'

// import AsyncComputed from 'vue-async-computed'
// Vue.use(AsyncComputed)

/* vue-split-panel */
import VueSplit from 'vue-split-panel'
Vue.use(VueSplit)

Vue.config.productionTip = false

/* eslint-disable no-new */
// cookies
var VueCookie = require('vue-cookie')
Vue.use(VueCookie)

// Routing logic
Vue.use(VueRouter)

var router = new VueRouter({
  routes: routes,
  mode: 'history',
  scrollBehavior: function (to, from, savedPosition) {
    return savedPosition || { x: 0, y: 0 }
  }
})

iView.LoadingBar.config({
  color: '#5cb85c',
  failedColor: '#f0ad4e',
  height: 5
})

import axios from 'axios'
import psl from 'psl'
// Some middleware to help us ensure the user is authenticated.
router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  iView.LoadingBar.config({ color: '#0e406d' })
  // window.console.log('Transition', transition)
  // router.app.$store.state.token
  let location = psl.parse(window.location.hostname) // get parent domain
  location = location.domain === null ? location.input : location.domain

  if (to.query.token) {
    router.app.$cookie.set('auth_token', to.query.token, { expires: 1, domain: location })
  }
  const token = router.app.$cookie.get('auth_token')
  store.state.token = token
  // set token in axios
  if (token) {
    axios.defaults.headers.common['authorization'] = token
  } else {
    delete axios.defaults.headers.common['authorization']
  }

  if (to.matched.some(record => record.meta.requiresAuth) && (!token || token === 'null' || store.state.token === undefined)) {
    next({
      path: '/login'
        // query: { redirect: to.fullPath }
    })
  } else {
    if (to.matched.some(record => record.meta.requiresAuth) || (to.path === '/login')) {
      store.dispatch('authenticateToken', token).then(response => {
        // get user role
        if (to.path !== '/') {
          if (to.matched.find(record => record.meta.role).meta.role.indexOf(parseInt(store.state.role)) === -1) {
            next({
              path: '/'
            })
          } else {
            next()
          }
        } else {
          if (store.state.role === 1) {
            next({
              path: '/admin/dashboard'
            })
          } else {
            next({
              path: '/dashboard'
            })
          }
        }
      }).catch(() => {
        router.app.$cookie.delete('auth_token', { domain: location })
        store.commit('SET_TOKEN', null)
        store.commit('SET_USER', null)
        store.commit('SET_ROLE', null)
        if (to.path !== '/login') {
          next({
            path: '/login'
          })
        } else {
          next()
        }
      })
    } else {
      next()
    }
  }
})

router.afterEach(route => {
  iView.LoadingBar.finish()
})

sync(store, router)
  // console.log('process.env.accesskey', process.env.accesskey)

new Vue({
  el: '#app',
  router,
  store: store,
  template: '<App/>',
  components: { App }
})
<|endoftext|>


<commit_before>'use strict';

var coreModules = require("soajs.core.modules");
var core = coreModules.core;
var provision = coreModules.provision;

var async = require("async");

var regEnvironment = (process.env.SOAJS_ENV || "dev");
regEnvironment = regEnvironment.toLowerCase();

var utils = require("./utils");

/**
 *
 * @param configuration
 * @returns {Function}
 */
module.exports = function (configuration) {
	var soajs = configuration.soajs;
	var param = configuration.param;
	var app = configuration.app;

	return function (req, res, next) {
        /**
         *	TODO: the below are the params that we should turn on per service per env to populate injectObj upon
         * 		urac
         * 		urac_Profile
         * 		urac_ACL
         * 		urac_AllEnvACL
         * 		package_ACL
         * 		package_AllEnvACL
         * 		application_ACL
         * 		application_AllEnvACL
		 * 		extKeyRequired ? maybe
         */
		if (req.soajs.registry.services[req.soajs.controller.serviceParams.name].extKeyRequired) {
			try {
				provision.getExternalKeyData(req.get("key"), req.soajs.registry.serviceConfig.key, function (err, keyObj) {
					if (err)
						req.soajs.log.warn(err);
					if (keyObj && keyObj.application && keyObj.application.package) {
						req.soajs.tenant = keyObj.tenant;
						req.soajs.tenant.key = {
							"iKey": keyObj.key,
							"eKey": keyObj.extKey
						};
						req.soajs.tenant.application = keyObj.application;
						provision.getPackageData(keyObj.application.package, function (err, packObj) {
							if (err)
								req.soajs.log.warn(err);
							if (packObj) {
								req.soajs.tenant.application.package_acl = packObj.acl;
								req.soajs.tenant.application.package_acl_all_env = packObj.acl_all_env;
								req.soajs.servicesConfig = keyObj.config;

								var serviceCheckArray = [function (cb) {
									cb(null, {
										"app": app,
										"soajs": soajs,
										"res": res,
										"req": req,
										"keyObj": keyObj,
										"packObj": packObj
									});
								}];

								serviceCheckArray.push(utils.securityGeoCheck);
								serviceCheckArray.push(utils.securityDeviceCheck);
								serviceCheckArray.push(utils.oauthCheck);
								serviceCheckArray.push(utils.uracCheck);
								serviceCheckArray.push(utils.serviceCheck);
								serviceCheckArray.push(utils.apiCheck);

								async.waterfall(serviceCheckArray, function (err, data) {
									if (err)
										return next(err);
									else {
										var serviceName = data.req.soajs.controller.serviceParams.name;
										var dataServiceConfig = data.servicesConfig || keyObj.config;
										var serviceConfig = {};

										if(dataServiceConfig.commonFields){
											serviceConfig.commonFields = dataServiceConfig.commonFields;
										}

										if(dataServiceConfig[serviceName]){
											serviceConfig[serviceName] = dataServiceConfig[serviceName];
										}

										var injectObj = {
											"tenant": {
												"id": keyObj.tenant.id,
												"code": keyObj.tenant.code,
												"roaming": data.req.soajs.tenant.roaming
											},
											"key": {
												/*
												    do not send the servicesConfig as it is, it should only send the service and commonFields
													ex:
														serviceConfig = {
															commonFields : { .... },
												            [serviceName] : { .... }
														}
												 */
												"config": serviceConfig,
												"iKey": keyObj.key,
												"eKey": keyObj.extKey
											},
											"application": {
                                                "product": keyObj.application.product,
                                                "package": keyObj.application.package,
                                                "appId": keyObj.application.appId,
                                                "acl": keyObj.application.acl,
                                                "acl_all_env": keyObj.application.acl_all_env
											},
											"package": {
												"acl": packObj.acl,
												"acl_all_env": packObj.acl_all_env
											},
											"device": data.device,
											"geo": data.geo
										};

										if (req.soajs.uracDriver)
                                            injectObj.urac = req.soajs.uracDriver.getProfile();

										if(serviceName.toLowerCase() !== 'dashboard'){
											delete injectObj.application.acl;
											delete injectObj.application.acl_all_env;
											delete injectObj.package.acl_all_env;
											delete injectObj.package.acl;
										}

										req.headers['soajsinjectobj'] = JSON.stringify(injectObj);

										return next();
									}
								});
							}
							else
								return next(152);
						});
					}
					else
						return next(153);
				});
			} catch (err) {
				req.soajs.log.error(150, err.stack);
				req.soajs.controllerResponse(core.error.getError(150));
			}
		}
		else {
			var oauthExec = function () {
				soajs.oauth(req, res, next);
			};
			return oauthExec();
		}
	};
};
<commit_msg>mapped commonFields inputs to servicesConfig to allow backward compatibility. common fields entry do not override existing serviceConfig entries.<commit_after>'use strict';

var coreModules = require("soajs.core.modules");
var core = coreModules.core;
var provision = coreModules.provision;

var async = require("async");

var regEnvironment = (process.env.SOAJS_ENV || "dev");
regEnvironment = regEnvironment.toLowerCase();

var utils = require("./utils");

/**
 *
 * @param configuration
 * @returns {Function}
 */
module.exports = function (configuration) {
	var soajs = configuration.soajs;
	var param = configuration.param;
	var app = configuration.app;

	return function (req, res, next) {
        /**
         *	TODO: the below are the params that we should turn on per service per env to populate injectObj upon
         * 		urac
         * 		urac_Profile
         * 		urac_ACL
         * 		urac_AllEnvACL
         * 		package_ACL
         * 		package_AllEnvACL
         * 		application_ACL
         * 		application_AllEnvACL
		 * 		extKeyRequired ? maybe
         */
		if (req.soajs.registry.services[req.soajs.controller.serviceParams.name].extKeyRequired) {
			try {
				provision.getExternalKeyData(req.get("key"), req.soajs.registry.serviceConfig.key, function (err, keyObj) {
					if (err)
						req.soajs.log.warn(err);
					if (keyObj && keyObj.application && keyObj.application.package) {
						req.soajs.tenant = keyObj.tenant;
						req.soajs.tenant.key = {
							"iKey": keyObj.key,
							"eKey": keyObj.extKey
						};
						req.soajs.tenant.application = keyObj.application;
						provision.getPackageData(keyObj.application.package, function (err, packObj) {
							if (err)
								req.soajs.log.warn(err);
							if (packObj) {
								req.soajs.tenant.application.package_acl = packObj.acl;
								req.soajs.tenant.application.package_acl_all_env = packObj.acl_all_env;
								req.soajs.servicesConfig = keyObj.config;

								var serviceCheckArray = [function (cb) {
									cb(null, {
										"app": app,
										"soajs": soajs,
										"res": res,
										"req": req,
										"keyObj": keyObj,
										"packObj": packObj
									});
								}];

								serviceCheckArray.push(utils.securityGeoCheck);
								serviceCheckArray.push(utils.securityDeviceCheck);
								serviceCheckArray.push(utils.oauthCheck);
								serviceCheckArray.push(utils.uracCheck);
								serviceCheckArray.push(utils.serviceCheck);
								serviceCheckArray.push(utils.apiCheck);

								async.waterfall(serviceCheckArray, function (err, data) {
									if (err)
										return next(err);
									else {
										var serviceName = data.req.soajs.controller.serviceParams.name;
										var dataServiceConfig = data.servicesConfig || keyObj.config;
										var serviceConfig = {};

										if(dataServiceConfig.commonFields){
											for (var i in dataServiceConfig.commonFields){
												//if servicesConfig already has an entry, entry overrides commonFields
												if(!serviceConfig[i]){
													serviceConfig[i] = dataServiceConfig.commonFields[i];
												}
											}
										}

										if(dataServiceConfig[serviceName]){
											serviceConfig[serviceName] = dataServiceConfig[serviceName];
										}

										var injectObj = {
											"tenant": {
												"id": keyObj.tenant.id,
												"code": keyObj.tenant.code,
												"roaming": data.req.soajs.tenant.roaming
											},
											"key": {
												/*
												    do not send the servicesConfig as it is, it should only send the service and commonFields
													ex:
														serviceConfig = {
															commonFields : { .... },
												            [serviceName] : { .... }
														}
												 */
												"config": serviceConfig,
												"iKey": keyObj.key,
												"eKey": keyObj.extKey
											},
											"application": {
                                                "product": keyObj.application.product,
                                                "package": keyObj.application.package,
                                                "appId": keyObj.application.appId,
                                                "acl": keyObj.application.acl,
                                                "acl_all_env": keyObj.application.acl_all_env
											},
											"package": {
												"acl": packObj.acl,
												"acl_all_env": packObj.acl_all_env
											},
											"device": data.device,
											"geo": data.geo
										};

										if (req.soajs.uracDriver)
                                            injectObj.urac = req.soajs.uracDriver.getProfile();

										if(serviceName.toLowerCase() !== 'dashboard'){
											delete injectObj.application.acl;
											delete injectObj.application.acl_all_env;
											delete injectObj.package.acl_all_env;
											delete injectObj.package.acl;
										}

										req.headers['soajsinjectobj'] = JSON.stringify(injectObj);

										return next();
									}
								});
							}
							else
								return next(152);
						});
					}
					else
						return next(153);
				});
			} catch (err) {
				req.soajs.log.error(150, err.stack);
				req.soajs.controllerResponse(core.error.getError(150));
			}
		}
		else {
			var oauthExec = function () {
				soajs.oauth(req, res, next);
			};
			return oauthExec();
		}
	};
};
<|endoftext|>


<commit_before>var casperModule = require('casper')
var casperOptions = {
    verbose: true,
    logLevel: 'error',
    colorizerType: 'Dummy',
    pageSettings: {
        webSecurityEnabled: false
    }
};

// Create casper instance
var casper = casperModule.create(casperOptions);
casper.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0');

var captureFolder = 'captures';
var musicFolder = 'music';

var scpwnrClient = require('public/scripts/scpwnr-client.js');
var Track = require('public/scripts/track.js');

var show = function(_object) {
    console.log(JSON.stringify(_object, undefined, 4));
};

var currentPwnr = {
    songsDownloaded: []
};

var openTrack = function(pageUrl) {
    casper.then(function() {
        var streamMp3Address = '';
        var mp3Adress = '';
        var titleText = '';
        var artistText = '';
        var albumText = '';

        if (/\/sets\/(.*)/.test(pageUrl)) {
            albumText = /\/sets\/(.*)/.exec(pageUrl)[1];
        }

        this.thenOpen(pageUrl);
        this.then(function() {
            // Attach event on resource request
            this.on('resource.requested', function(resource) {
                if (/api.soundcloud.com.*stream/i.test(resource.url)) {
                    streamMp3Address = resource.url;
                    this.log('*** Stream adress: GOTCHA', 'info');
                    this.log('*** Stream adress: ' + streamMp3Address, 'debug');
                }
            });

            // Click on the play button
            var selector = '.soundTitle.single';
            this.waitForSelector(selector, function() {
                this.click(selector + ' button');

                // Retrieve the MP3 informations
                // Retrive the title
                titleText = this.getElementInfo(selector + ' .soundTitle__title').text.trim();
                // Retrieve the artist
                artistText = this.getElementInfo(selector + ' .soundTitle__username').text.trim();

                // Open the stream MP3 address
                if (streamMp3Address == '') {
                    this.die('No stream found', 1);
                }
                this.thenOpen(streamMp3Address, {
                    method: 'get',
                    headers: {
                        "Accept": "application/json, text/javascript, */*; q=0.01"
                    }
                }, function() {

                    // Get the MP3 address
                    mp3Adress = JSON.parse(this.getPageContent()).http_mp3_128_url;
                    this.log('*** Mp3 adress: GOTCHA', 'info');
                    this.log('*** Mp3 adress: ' + mp3Adress, 'info');

                    // Download the mp3
                    this.then(function() {
                        var newTrack = new Track(titleText, artistText, mp3Adress);

                        var pathToFile = '';
                        if (!albumText) {
                            path = musicFolder + '/' + newTrack.getMp3Name();
                        }
                        else {
                            path = musicFolder + '/' + albumText + '/' + newTrack.getMp3Name();
                        }

                        this.download(mp3Adress, path);
                        currentPwnr.songsDownloaded.push(newTrack);
                    })
                });
            }, function() {
                this.capture(captureFolder + '/' +  pageUrl.replace(/\//g, '-') + '.png');
                this.die('No play button found at ' + pageUrl, 1);
            }, 2000);
        });
    });
};

var openSet = function(setUrl) {
    casper.thenOpen(setUrl);
    casper.then(function() {
        var setLinks = this.evaluate(function() {
            var setLinks = [];
            var listNodes = document.querySelectorAll('.listenDetails__trackList .trackItem__trackTitle');
            for (var i = 0; i < listNodes.length; i++) {
                setLinks.push(listNodes[i].href);
            }
            return setLinks;
        });

        if (setLinks.length == 0) {
            this.die("No song(s) in set found !", 1);
        }

        for (var i in setLinks) {
            openTrack(setLinks[i]);
        }
    });
};

var openUserlist = function(userlistUrl) {
    casper.thenOpen(userlistUrl);
    casper.then(function() {
        var linkList = this.evaluate(function() {
            var linkList = [];
            var listNodes = document.querySelectorAll('.userStreamItem a.soundTitle__title');

            for (var i = 0; i < listNodes.length; i++)  {
                linkList.push(listNodes[i].href);
            }

            return linkList;
        });

        if (linkList.length == 0) {
            this.die("No song(s) in userlist found !");
        }

        for (var i in linkList) {
            _open(linkList[i]);
        }
    });
};

// URL can be anything (a set, a userlist or a track)
var _open = function(url) {
    var type;
    if (casper.cli.options.type === undefined) {
        type = scpwnrClient.getUrlType(url);
    }
    else {
        type = casper.cli.options.type;
    }

    if (type == 'track') {
        openTrack(url);
    }
    else if (type == 'set') {
        openSet(url);
    }
    else if (type == 'user') {
        openUserlist(url);
    }

};

casper.start();

// Open all the arguments in command line
_open(scpwnrClient.getCleanedUrl(casper.cli.args[0]));
casper.then(function() {
    if (casper.cli.options.format == 'server') {
        for (var i in currentPwnr.songsDownloaded) {
            var track = currentPwnr.songsDownloaded[i];
            var trackInfos = track.getCleanInfos();
            console.log(trackInfos.artist + '|' + trackInfos.title + '|' + track.url);
        }
    }
});

if (!casper.cli.args.length) {
    casper.log('No arguments given !', 'error');
    casper.exit();
}
else {
    casper.run();
}

<commit_msg>Small fix for better soundcloud parsing<commit_after>var casperModule = require('casper')
var casperOptions = {
    verbose: true,
    logLevel: 'error',
    colorizerType: 'Dummy',
    pageSettings: {
        webSecurityEnabled: false
    }
};

// Create casper instance
var casper = casperModule.create(casperOptions);
casper.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0');

var captureFolder = 'captures';
var musicFolder = 'music';

var scpwnrClient = require('public/scripts/scpwnr-client.js');
var Track = require('public/scripts/track.js');

var show = function(_object) {
    console.log(JSON.stringify(_object, undefined, 4));
};

var currentPwnr = {
    songsDownloaded: []
};

var openTrack = function(pageUrl) {
    casper.then(function() {
        var streamMp3Address = '';
        var mp3Adress = '';
        var titleText = '';
        var artistText = '';
        var albumText = '';

        if (/\/sets\/(.*)/.test(pageUrl)) {
            albumText = /\/sets\/(.*)/.exec(pageUrl)[1];
        }

        this.thenOpen(pageUrl);
        this.then(function() {
            // Attach event on resource request
            this.on('resource.requested', function(resource) {
                if (/api.soundcloud.com.*stream/i.test(resource.url)) {
                    streamMp3Address = resource.url;
                    this.log('*** Stream adress: GOTCHA', 'info');
                    this.log('*** Stream adress: ' + streamMp3Address, 'debug');
                }
            });

            // Click on the play button
            var selectors = ['.soundTitle.single', '.soundTitle.soundTitle_hero'];
            this.waitForSelector(selectors.join(','), function() {
                this.click(selectors.map(function(value) {
                	return value + ' button';
                }).join(','));

                // Retrieve the MP3 informations
                // Retrive the title
                titleText = this.getElementInfo(selectors + ' .soundTitle__title').text.trim();
                // Retrieve the artist
                artistText = this.getElementInfo(selectors + ' .soundTitle__username').text.trim();

                // Open the stream MP3 address
                if (streamMp3Address == '') {
                    this.die('No stream found', 1);
                }
                this.thenOpen(streamMp3Address, {
                    method: 'get',
                    headers: {
                        "Accept": "application/json, text/javascript, */*; q=0.01"
                    }
                }, function() {

                    // Get the MP3 address
                    mp3Adress = JSON.parse(this.getPageContent()).http_mp3_128_url;
                    this.log('*** Mp3 adress: GOTCHA', 'info');
                    this.log('*** Mp3 adress: ' + mp3Adress, 'info');

                    // Download the mp3
                    this.then(function() {
                        var newTrack = new Track(titleText, artistText, mp3Adress);

                        var pathToFile = '';
                        if (!albumText) {
                            path = musicFolder + '/' + newTrack.getMp3Name();
                        }
                        else {
                            path = musicFolder + '/' + albumText + '/' + newTrack.getMp3Name();
                        }

                        this.download(mp3Adress, path);
                        currentPwnr.songsDownloaded.push(newTrack);
                    })
                });
            }, function() {
                this.capture(captureFolder + '/' +  pageUrl.replace(/\//g, '-') + '.png');
                this.die('No play button found at ' + pageUrl, 1);
            }, 2000);
        });
    });
};

var openSet = function(setUrl) {
    casper.thenOpen(setUrl);
    casper.then(function() {
        var setLinks = this.evaluate(function() {
            var setLinks = [];
            var listNodes = document.querySelectorAll('.listenDetails__trackList .trackItem__trackTitle');
            for (var i = 0; i < listNodes.length; i++) {
                setLinks.push(listNodes[i].href);
            }
            return setLinks;
        });

        if (setLinks.length == 0) {
            this.die("No song(s) in set found !", 1);
        }

        for (var i in setLinks) {
            openTrack(setLinks[i]);
        }
    });
};

var openUserlist = function(userlistUrl) {
    casper.thenOpen(userlistUrl);
    casper.then(function() {
        var linkList = this.evaluate(function() {
            var linkList = [];
            var listNodes = document.querySelectorAll('.userStreamItem a.soundTitle__title');

            for (var i = 0; i < listNodes.length; i++)  {
                linkList.push(listNodes[i].href);
            }

            return linkList;
        });

        if (linkList.length == 0) {
            this.die("No song(s) in userlist found !");
        }

        for (var i in linkList) {
            _open(linkList[i]);
        }
    });
};

// URL can be anything (a set, a userlist or a track)
var _open = function(url) {
    var type;
    if (casper.cli.options.type === undefined) {
        type = scpwnrClient.getUrlType(url);
    }
    else {
        type = casper.cli.options.type;
    }

    if (type == 'track') {
        openTrack(url);
    }
    else if (type == 'set') {
        openSet(url);
    }
    else if (type == 'user') {
        openUserlist(url);
    }

};

casper.start();

// Open all the arguments in command line
_open(scpwnrClient.getCleanedUrl(casper.cli.args[0]));
casper.then(function() {
    if (casper.cli.options.format == 'server') {
        for (var i in currentPwnr.songsDownloaded) {
            var track = currentPwnr.songsDownloaded[i];
            var trackInfos = track.getCleanInfos();
            console.log(trackInfos.artist + '|' + trackInfos.title + '|' + track.url);
        }
    }
});

if (!casper.cli.args.length) {
    casper.log('No arguments given !', 'error');
    casper.exit();
}
else {
    casper.run();
}

<|endoftext|>


<commit_before>
const request = require('request')
const fs = require('fs')
const cheerio = require('cheerio')
const tableparser = require('cheerio-tableparser')

let url = 'http://travel-made-simple.com/carry-on-size-chart/'
request(url, (err, res, body)=> {
  const $ = cheerio.load(body)
  tableparser($)
  let table = $(".carryonsize").parsetable(false,false,true)

  let airlines = []
  for(let i=1; i<table[0].length; i++){
    airlines.push({
      name: table[0][i],
      imperial: {
        height: Number(table[1][i]),
        width:  Number(table[2][i]),
        depth:  Number(table[3][i]),
        linear: Number(table[4][i]),
        weight: Number(table[5][i])
      },
      metric: {
        height: Number(table[1][i])*2.54, //Inches -> Centimeters
        width:  Number(table[2][i])*2.54,
        depth:  Number(table[3][i])*2.54,
        linear: Number(table[4][i])*2.54,
        weight: Number(table[5][i])*0.453592 //Pounds -> Kilo
      }
    })
  }
  writeOut(airlines)
})

function writeOut(file){
  fs.writeFile("./airline_list.json", JSON.stringify(file), (err) => {
      if (err) {
        console.error(err)
      }
      else{
        console.log('airline_list.json created.')
      }
  })
}
<commit_msg>added comments<commit_after>
const request = require('request')
const fs = require('fs')
const cheerio = require('cheerio')
const tableparser = require('cheerio-tableparser')

let url = 'http://travel-made-simple.com/carry-on-size-chart/'
request(url, (err, res, body)=> {
  const $ = cheerio.load(body)
  tableparser($)
  let table = $(".carryonsize").parsetable(false,false,true)

  let airlines = []
  for(let i=1; i<table[0].length; i++){
    airlines.push({
      name: table[0][i],
      imperial: {
        height: Number(table[1][i]), //Inches
        width:  Number(table[2][i]),
        depth:  Number(table[3][i]),
        linear: Number(table[4][i]),
        weight: Number(table[5][i]) //Pounds
      },
      metric: {
        height: Number(table[1][i])*2.54, //Inches -> Centimeters
        width:  Number(table[2][i])*2.54,
        depth:  Number(table[3][i])*2.54,
        linear: Number(table[4][i])*2.54,
        weight: Number(table[5][i])*0.453592 //Pounds -> Kilo
      }
    })
  }
  writeOut(airlines)
})

function writeOut(file){
  fs.writeFile("./airline_list.json", JSON.stringify(file), (err) => {
      if (err) {
        console.error(err)
      }
      else{
        console.log('airline_list.json created.')
      }
  })
}
<|endoftext|>


<commit_before>const { Builder, By, Key, until } = require('selenium-webdriver')
const Promise = require('bluebird')

const scrape = module.exports = (url, sId, pass, target) => {
  const waitForId        = id   => driver.wait(until.elementIsVisible(driver.findElement(By.id(id))), 1000)
  const inputCredentials = ()   => driver.findElement(By.id('login')).sendKeys(sId, Key.TAB, pass, Key.RETURN)
  const getHandles       = ()   => driver.getAllWindowHandles()
  const swap             = w    => driver.getAllWindowHandles().then((w) => driver.switchTo().window(w[w.length - 1]))
  const wait             = x    => driver.sleep(x)
  const maintain         = d    => d

  const driver = new Builder()
    .forBrowser('chrome')
    .build()

  return driver.get(url)
    .then(waitForId('login'))
    .then(waitForId('password'))
    .then(inputCredentials)
    .then(wait(1000))
    .then(swap)
    .then(() => driver.findElement(By.xpath('//a[@data-nav="sfgradebook001.w"]')).click())
    .then(() => driver.findElements(By.name('showGradeInfo')))
    .then(grades => Promise
        .resolve(grades)
        .filter(link => link.getAttribute('data-lit')
            .then(lit => lit == target))
        .mapSeries((link) =>
          Promise
            .resolve(link.getAttribute('innerHTML'))
            .then(score => Object.assign({}, { score: score }))
            .then(data =>
              driver.executeScript('arguments[0].scrollIntoView()', link)
                .then(driver.wait(until.elementIsVisible(link)))
                .then(link.click())
                .then(() => data))
            .then(data =>
              driver.wait(until.elementLocated(By.xpath('//a[@class="sf_DialogClose"][@style="display: block;"]')))
                .then(driver.wait(until.elementLocated(By.className('sf_DialogHtml'))))
                .then(driver.findElements(By.className('sf_DialogHtml')))
                .then(pane => driver.executeScript('return arguments[0][3].innerHTML', pane))
                .then(html => Object.assign(data, { pane: html })))
            .then(data =>
                driver.wait(until.elementIsVisible(driver.findElement(By.xpath('//a[@class="sf_DialogClose"][@style="display: block;"]'))))
                .then(driver.findElement(By.xpath('//a[@class="sf_DialogClose"][@style="display: block;"]')).click())
                .then(driver.wait(until.elementIsNotVisible(driver.findElement(By.xpath('//a[@class="sf_DialogClose"][@style="display: block;"]')))))
                .then(() => data))
        ))
}<commit_msg>Struggling<commit_after>const { Builder, By, Key, until } = require('selenium-webdriver')
const Promise = require('bluebird')

const scrape = module.exports = (url, sId, pass, target) => {
  const waitForId        = id   => driver.wait(until.elementIsVisible(driver.findElement(By.id(id))), 1000)
  const inputCredentials = ()   => driver.findElement(By.id('login')).sendKeys(sId, Key.TAB, pass, Key.RETURN)
  const getHandles       = ()   => driver.getAllWindowHandles()
  const swap             = w    => driver.getAllWindowHandles().then((w) => driver.switchTo().window(w[w.length - 1]))
  const wait             = x    => driver.sleep(x)
  const maintain         = d    => d

  const driver = new Builder()
    .forBrowser('chrome')
    .build()

  return driver.get(url)
    .then(waitForId('login'))
    .then(waitForId('password'))
    .then(inputCredentials)
    .then(wait(1000))
    .then(swap)
    .then(() => driver.findElement(By.xpath('//a[@data-nav="sfgradebook001.w"]')).click())
    .then(() => driver.findElements(By.name('showGradeInfo')))
    .then(grades => Promise
        .resolve(grades)
        .filter(link => link.getAttribute('data-lit')
            .then(lit => lit == target))
        .mapSeries((link) =>
          Promise
            .resolve(link.getAttribute('innerHTML'))
            .then(score => Object.assign({}, { score: score }))
            .then(data =>
              driver.executeScript('arguments[0].scrollIntoView()', link)
                .then(driver.wait(until.elementIsVisible(link)))
                .then(link.click())
                .then(() => data))
            .then(data =>
              driver.wait(until.elementLocated(By.xpath('//a[@class="sf_DialogClose"][@style="display: block;"]')))
                .then(driver.wait(until.elementLocated(By.className('sf_DialogHtml'))))
                .then(driver.findElements(By.className('sf_DialogHtml')))
                .then(pane => driver.executeScript('return arguments[0].innerHTML', pane))
                .then(html => Object.assign(data, { pane: html })))
            .then(data =>
                driver.wait(until.elementIsVisible(driver.findElement(By.xpath('//a[@class="sf_DialogClose"][@style="display: block;"]'))))
                .then(driver.findElement(By.xpath('//a[@class="sf_DialogClose"][@style="display: block;"]')).click())
                .then(driver.wait(until.elementIsNotVisible(driver.findElement(By.xpath('//a[@class="sf_DialogClose"][@style="display: block;"]')))))
                .then(() => data))
        ))
}<|endoftext|>


<commit_before>// JiakClient assumes the presence of jQuery and JSON libraries
// (or at least compatible $.ajax and JSON.stringify functions)
//
// Usage: instantiate a JiakClient with proper options, then use
// the store, fetch, remove, and walk function to get access to
// objects from Jiak.
//
// Examples:
//   var Client = new JiakClient('/jiak/');
//   Client.fetch('note', '123', function(note) {
//      note.object.text = 'Hello World';
//      Client.store(note);
//   });
//
//   Client.store({'bucket':'note'
//                 'object':{'text':'a new note'},
//                 'links':[]},
//                function(note) {
//                  alert('new note's key: '+note.key);
//                });
//
//   Client.walk(['note', '456'],
//               [{'bucket':'person', 'tag':'author'}],
//               function(data) {
//                 var authors = data.results[0];
//                 alert('note's author is: '+
//                       authors[0].object.name);
//               });

// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License.  You may obtain
// a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

function JiakClient(BaseUrl, Opts) {
    this.baseurl = BaseUrl;
    if (!(this.baseurl.slice(-1) == '/'))
        this.baseurl += '/';

    this.opts = Opts||{};
}

JiakClient.prototype.store = function(Object, Callback, NoReturnBody) {
    var req = {
        contentType: "application/json",
        dataType: "json"
    };

    if (this.opts.alwaysPost || !Object.key)
        req.type = 'POST';
    else
        req.type = 'PUT';

    req.url = this.baseurl+Object.bucket+'/';
    if (Object.key) req.url += Object.key;

    if (!(this.opts.noReturnBody || NoReturnBody))
        req.url += '?returnbody=true';

    if (typeof Callback == 'function')
        req.success = Callback;

    req.data = JSON.stringify(Object);

    return $.ajax(req);
}

JiakClient.prototype.fetch = function(Bucket, Key, Callback) {
    return $.ajax({
        url:      this.baseurl+Bucket+'/'+Key,
        dataType: "json",
        success:  Callback
    });
}

JiakClient.prototype.remove = function(Bucket, Key, Callback) {
    return $.ajax({
        type:    'DELETE',
        url:     this.baseurl+Bucket+'/'+Key,
        success: Callback
    });
}

JiakClient.prototype.walk = function(Start, Spec, Callback) {
    var req = {
        dataType: "json",
        success: Callback
    };

    // Start can be either and object with {bucket:B, key:K}
    // or a list with [Bucket, Key, ...]
    if ('bucket' in Start)
        req.url = this.baseurl+Start.bucket+'/'+Start.key+'/';
    else
        req.url = this.baseurl+Start[0]+'/'+Start[1]+'/';

    // Spec should be a list of objects with
    //    {bucket:B, tag:T, acc:A}
    // where B and T specify the bucket and tag to match in the link
    //   or are undefined to match anything
    // and A is 'true' to get the objects matched at this step, or
    //   false to have them excluded from the response (always true
    //   for the last step
    for (i in Spec) {
        req.url += (Spec[i].bucket||'_')+','+
            (Spec[i].tag||'_')+','+
            ((Spec[i].acc || i == Spec.length-1) ? '1' : '_')+'/';
    }

    return $.ajax(req);
}

JiakClient.prototype.setBucketSchema = function(Bucket, Schema, Callback) {
    if (!('required_fields' in Schema))
        Schema.required_fields = [];

    if (!('read_mask' in Schema))
        Schema.read_mask = Schema.allowed_fields;

    if (!('write_mask' in Schema))
        Schema.write_mask = Schema.read_mask;

    $.ajax({
        type:        'PUT',
        url:         this.baseurl+Bucket,
        contentType: 'application/json',
        data:        JSON.stringify({schema:Schema}),
        success:     Callback ? function() { Callback(true); } : undefined,
        error:       Callback ? function() { Callback(false); } : undefined
    });
}<commit_msg>via Tuncer Ayaz: Fix trivial errors in jiak.js sample code<commit_after>// JiakClient assumes the presence of jQuery and JSON libraries
// (or at least compatible $.ajax and JSON.stringify functions)
//
// Usage: instantiate a JiakClient with proper options, then use
// the store, fetch, remove, and walk function to get access to
// objects from Jiak.
//
// Examples:
//   var Client = new JiakClient('/jiak/');
//   Client.fetch('note', '123', function(note) {
//      note.object.text = 'Hello World';
//      Client.store(note);
//   });
//
//   Client.store({'bucket':'note',
//                 'object':{'text':'a new note'},
//                 'links':[]},
//                function(note) {
//                  alert("new note's key: "+note.key);
//                });
//
//   Client.walk(['note', '456'],
//               [{'bucket':'person', 'tag':'author'}],
//               function(data) {
//                 var authors = data.results[0];
//                 alert("note's author is: "+
//                       authors[0].object.name);
//               });

// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License.  You may obtain
// a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

function JiakClient(BaseUrl, Opts) {
    this.baseurl = BaseUrl;
    if (!(this.baseurl.slice(-1) == '/'))
        this.baseurl += '/';

    this.opts = Opts||{};
}

JiakClient.prototype.store = function(Object, Callback, NoReturnBody) {
    var req = {
        contentType: "application/json",
        dataType: "json"
    };

    if (this.opts.alwaysPost || !Object.key)
        req.type = 'POST';
    else
        req.type = 'PUT';

    req.url = this.baseurl+Object.bucket+'/';
    if (Object.key) req.url += Object.key;

    if (!(this.opts.noReturnBody || NoReturnBody))
        req.url += '?returnbody=true';

    if (typeof Callback == 'function')
        req.success = Callback;

    req.data = JSON.stringify(Object);

    return $.ajax(req);
}

JiakClient.prototype.fetch = function(Bucket, Key, Callback) {
    return $.ajax({
        url:      this.baseurl+Bucket+'/'+Key,
        dataType: "json",
        success:  Callback
    });
}

JiakClient.prototype.remove = function(Bucket, Key, Callback) {
    return $.ajax({
        type:    'DELETE',
        url:     this.baseurl+Bucket+'/'+Key,
        success: Callback
    });
}

JiakClient.prototype.walk = function(Start, Spec, Callback) {
    var req = {
        dataType: "json",
        success: Callback
    };

    // Start can be either and object with {bucket:B, key:K}
    // or a list with [Bucket, Key, ...]
    if ('bucket' in Start)
        req.url = this.baseurl+Start.bucket+'/'+Start.key+'/';
    else
        req.url = this.baseurl+Start[0]+'/'+Start[1]+'/';

    // Spec should be a list of objects with
    //    {bucket:B, tag:T, acc:A}
    // where B and T specify the bucket and tag to match in the link
    //   or are undefined to match anything
    // and A is 'true' to get the objects matched at this step, or
    //   false to have them excluded from the response (always true
    //   for the last step
    for (i in Spec) {
        req.url += (Spec[i].bucket||'_')+','+
            (Spec[i].tag||'_')+','+
            ((Spec[i].acc || i == Spec.length-1) ? '1' : '_')+'/';
    }

    return $.ajax(req);
}

JiakClient.prototype.setBucketSchema = function(Bucket, Schema, Callback) {
    if (!('required_fields' in Schema))
        Schema.required_fields = [];

    if (!('read_mask' in Schema))
        Schema.read_mask = Schema.allowed_fields;

    if (!('write_mask' in Schema))
        Schema.write_mask = Schema.read_mask;

    $.ajax({
        type:        'PUT',
        url:         this.baseurl+Bucket,
        contentType: 'application/json',
        data:        JSON.stringify({schema:Schema}),
        success:     Callback ? function() { Callback(true); } : undefined,
        error:       Callback ? function() { Callback(false); } : undefined
    });
}<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
var pg = require('pg');
var Q = require("q");
var request = require("request");
var newUser = require("./db");
var nlp = require("./nlp");
var pushConv = require("./push");

const scriptRules = require('./script.json');

function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

module.exports = new Script({
    processing: {
        //prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hello!  I\'m A16, the Agile2016 EventBot Concierge.  To find out what I can help you with type MENU for options or KEY for Keywords.')
                .then(() => 'speak');
        }
    },

    speak: {
        receive: (bot, message) => {
            console.log("===bot user ");
            console.log("===receive step 1",message);
            let upperText = message.text.trim().toUpperCase();

            var botUser = bot.userId;
            var authUsers = ['a30fa820d0a0f0216fa26070'];

            //Undone - currently only creates new user
            //needs to create conversation record and update it throughout the prcoess
            console.log("===before db",bot.store);
            newUser(bot)
              .then (console.log("===after db", bot.userId))

              //undone - test for userid and or message
              //look at stacking messages in DB and looking them up
              //end conversation and do not send a response to the user that kicked things off
              //
              if (authUsers.indexOf(bot.userId) !== -1) {
                if (message.text.substr(0,5) == '/msg ') {
                  upperText = upperText.substr(0,4);
                  pushConv(bot, message.text.substr(5));
                  console.log("****after push msg:  ",message.text);
                }
              }

            function updateSilent() {
                switch (upperText) {
                    case "CONNECT ME":
                        return bot.setProp("silent", true);
                    case "/SUPPORT":
                        return bot.setProp("silent", true);
                    case "DISCONNECT":
                        return bot.setProp("silent", false);
                    case "/A16":
                        console.log("*** ",upperText," ***");
                        processMessage(false);
                        return bot.setProp("silent", false);
                    default:
                        return Promise.resolve();
                }
            }

            console.log("===receive step 2",upperText);

            function getSilent() {
                return bot.getProp("silent");
            }

            function processMessage(isSilent) {
                if (isSilent) {
                    return Promise.resolve("speak");
                }

                var promises = [];
                var source;
                var fulfillmentSpeech;
                var simplified;
                promises.push(nlp(upperText, bot.userId));

                Q.all(promises).then(function(responses) {
                    // response is the JSON from API.ai
                    responses.forEach(function(response) {
                        //console.log("===in Q.all");
                        console.log("===received result from API.ai",response);
                        source = response.result.source;
                        if (source && source !== 'agent')
                        {
                            fulfillmentSpeech = response.result.fulfillment.speech;
                            simplified = response.result.parameters.simplified;
                        }
                        console.log("source: ", source);
                        console.log("fulfillmentSpeech: ", fulfillmentSpeech);
                        console.log("simplified: ", simplified);

                        respondMessage(source, fulfillmentSpeech, simplified);
                    });
                }, function(error) {
                    console.log("===Q all error ", error);
                });
                //return next();

            }

            function respondMessage(source, fulfillmentSpeech, simplified)
            {
                console.log("source: ", source);
                console.log("fulfillmentSpeech: ", fulfillmentSpeech);
                console.log("simplified: ", simplified);
                console.log("===receive step 3",upperText);

              if (source != 'agent')
                {
                    console.log("===source is ", source);
                    if (fulfillmentSpeech)
                    {
                        console.log("fulfillmentSpeech is: ", fulfillmentSpeech);
                        //return bot.say(fulfillmentSpeech).then(() => 'speak');
                        upperText = simplified.trim().toUpperCase();
                    }
                    else if (simplified)
                    {
                        console.log("simplified is: ", simplified);
                        upperText = simplified.toUpperCase();
                    }
                }
                if (!_.has(scriptRules, upperText)) {
                    console.log("===no rule", upperText);
                    return bot.say(`I'm sorry that is not something I know.  Type MENU or KEY for a list of things I can help you with.`).then(() => 'speak');
                }

                console.log("===receive step 3",upperText);

                var response = scriptRules[upperText];
                var lines = response.split('\n');

                bot.userId = botUser;

                var p = Promise.resolve();
                _.each(lines, function(line) {
                    line = line.trim();
                    p = p.then(function() {
                        console.log("=== p line",line);
                        return wait(50).then(function() {
                            return bot.say(line);
                        });
                    });
                });
                return p.then(() => 'speak');
            }

            return updateSilent()
                .then(getSilent)
                .then(processMessage);
        }
    }
});
<commit_msg>bot.store.api<commit_after>'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
var pg = require('pg');
var Q = require("q");
var request = require("request");
var newUser = require("./db");
var nlp = require("./nlp");
var pushConv = require("./push");

const scriptRules = require('./script.json');

function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

module.exports = new Script({
    processing: {
        //prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hello!  I\'m A16, the Agile2016 EventBot Concierge.  To find out what I can help you with type MENU for options or KEY for Keywords.')
                .then(() => 'speak');
        }
    },

    speak: {
        receive: (bot, message) => {
            console.log("===bot user ");
            console.log("===receive step 1",message);
            let upperText = message.text.trim().toUpperCase();

            var botUser = bot.userId;
            var authUsers = ['a30fa820d0a0f0216fa26070'];

            //Undone - currently only creates new user
            //needs to create conversation record and update it throughout the prcoess
            console.log("===before db",bot.store.api);
            newUser(bot)
              .then (console.log("===after db", bot.userId))

              //undone - test for userid and or message
              //look at stacking messages in DB and looking them up
              //end conversation and do not send a response to the user that kicked things off
              //
              if (authUsers.indexOf(bot.userId) !== -1) {
                if (message.text.substr(0,5) == '/msg ') {
                  upperText = upperText.substr(0,4);
                  pushConv(bot, message.text.substr(5));
                  console.log("****after push msg:  ",message.text);
                }
              }

            function updateSilent() {
                switch (upperText) {
                    case "CONNECT ME":
                        return bot.setProp("silent", true);
                    case "/SUPPORT":
                        return bot.setProp("silent", true);
                    case "DISCONNECT":
                        return bot.setProp("silent", false);
                    case "/A16":
                        console.log("*** ",upperText," ***");
                        processMessage(false);
                        return bot.setProp("silent", false);
                    default:
                        return Promise.resolve();
                }
            }

            console.log("===receive step 2",upperText);

            function getSilent() {
                return bot.getProp("silent");
            }

            function processMessage(isSilent) {
                if (isSilent) {
                    return Promise.resolve("speak");
                }

                var promises = [];
                var source;
                var fulfillmentSpeech;
                var simplified;
                promises.push(nlp(upperText, bot.userId));

                Q.all(promises).then(function(responses) {
                    // response is the JSON from API.ai
                    responses.forEach(function(response) {
                        //console.log("===in Q.all");
                        console.log("===received result from API.ai",response);
                        source = response.result.source;
                        if (source && source !== 'agent')
                        {
                            fulfillmentSpeech = response.result.fulfillment.speech;
                            simplified = response.result.parameters.simplified;
                        }
                        console.log("source: ", source);
                        console.log("fulfillmentSpeech: ", fulfillmentSpeech);
                        console.log("simplified: ", simplified);

                        respondMessage(source, fulfillmentSpeech, simplified);
                    });
                }, function(error) {
                    console.log("===Q all error ", error);
                });
                //return next();

            }

            function respondMessage(source, fulfillmentSpeech, simplified)
            {
                console.log("source: ", source);
                console.log("fulfillmentSpeech: ", fulfillmentSpeech);
                console.log("simplified: ", simplified);
                console.log("===receive step 3",upperText);

              if (source != 'agent')
                {
                    console.log("===source is ", source);
                    if (fulfillmentSpeech)
                    {
                        console.log("fulfillmentSpeech is: ", fulfillmentSpeech);
                        //return bot.say(fulfillmentSpeech).then(() => 'speak');
                        upperText = simplified.trim().toUpperCase();
                    }
                    else if (simplified)
                    {
                        console.log("simplified is: ", simplified);
                        upperText = simplified.toUpperCase();
                    }
                }
                if (!_.has(scriptRules, upperText)) {
                    console.log("===no rule", upperText);
                    return bot.say(`I'm sorry that is not something I know.  Type MENU or KEY for a list of things I can help you with.`).then(() => 'speak');
                }

                console.log("===receive step 3",upperText);

                var response = scriptRules[upperText];
                var lines = response.split('\n');

                bot.userId = botUser;

                var p = Promise.resolve();
                _.each(lines, function(line) {
                    line = line.trim();
                    p = p.then(function() {
                        console.log("=== p line",line);
                        return wait(50).then(function() {
                            return bot.say(line);
                        });
                    });
                });
                return p.then(() => 'speak');
            }

            return updateSilent()
                .then(getSilent)
                .then(processMessage);
        }
    }
});
<|endoftext|>


<commit_before>//  The calculator pseudoClass represents a four-function calculator.
//  The following both defines and constructs the singleton calculator object.

//  This file is part of Abacus For The Rest Of Us
//  Copyright (C) 2013 Max Galloway-Carson
//
//  Abacus For The Rest Of Us is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Affero General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//  GNU Affero General Public License for more details.
//
//  You should have received a copy of the GNU Affero General Public License
//  along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//  email me at: maxvgc@gmail.com

var calculator = (function () {

    'use strict';

    var model,
        view,
        controller;

//  model pseudoclass is an internal representation of
//  the calculator's state.

    model = {

        tally : 0, // running total since last clear

        operator : '+', // last operator pressed

        temp : '', // number, as it entered by user

        isClear : true, // flag indicates whether there has been output

//      The evaluate function performs a computation.
//      First, it performs the stored operation on temp and tally.
//      Then it stores the given operation for the next evaluation.
//
//      Returns the state to show to user.

        evaluate : function (operate) {

//      Special condition if there has not been output yet.

            var tempN = parseFloat(this.temp);

            if (this.isClear) {

                this.tally = tempN;
                this.isClear = false;

            } else {

//              Perform the stored operation on tally and temp

                switch (this.operator) {

                case '+':
                    this.tally += tempN;
                    break;

                case '-':
                    this.tally -= tempN;
                    break;

                case 'x':
                    this.tally *= tempN;
                    break;

                case '/':
                    this.tally /= tempN;
                    break;

                }
            }

//          In either case, update the display, and prepare for
//          next input

            this.temp = '0'; // reset temp
            this.operator = operate; // get ready to perform
            // the given operation

            if (isNaN(this.tally)) {
                this.reset();
            }

            return this.tally; // user sees result of computation
        },

//      The update function will take string representing a single
//      digit, and
//      append it to what the user has entered so far, both on the
//      screen and internally.
//      Returns the state to show to user.

        update : function (lastDigit) {

//          wipe out display to prevent leading zero
            if (this.temp === '0') {
                this.temp = '';
            }

//          concat display with new input
            this.temp += lastDigit;

            return this.temp; // user sees number entered thus far
        },

//      The reset function clears the calculator's instance
//      variables, and wipes the screen.

        reset : function () {
            this.tally = 0;
            this.operator = '+';
            this.temp = '0';
            this.isClear = true;
            return 0;
        }

    }; // end model

//  view is the representation of the screen.

    view = {

//      the object holding the output.

        display : {
            innerHTML : "0"
        },

//      method to set display to given number

        output : function (val) {

            this.display.innerHTML = val;

        },

//      Sets sets given object to be the new display.
//      Copies the old output into new display.

        setDisplay : function (newScreen) { // function

            if (typeof newScreen === 'object') {

                newScreen.innerHTML = this.display.innerHTML;

                this.display = newScreen;
            }
        }
    }; // end view

//  These are the calculator's publicly facing methods.
//  They should be consided the controller.

//  Enter number is called when a user presses a digit, and takes that
//  digit as a param. If possible, enterNumber will pass that digit
//  to the inner calculator's update method.

    controller = {
        enterNumber : function (num) {

            if (typeof model.update === 'function') {

//              Pass response from model's update method to
//              the view
                view.output(model.update(num));
            }
        },

//      Enter operator is called when a user presses an operator,
//      and takes that operator as a param. If possible, enterOperator
//      will pass that operator to the inner calculator's
//      evaluate method.

        enterOperator : function (opp) {

            if (typeof model.evaluate === 'function') {

//              Pass response from model's evaluate method to
//              the view
                view.output(model.evaluate(opp));
            }
        },

//      Clear is called when a user presses the clear button, and
//      takes no params. If possible, clear will call the inner
//      calculator's reset method.

        clear : function () {

            if (typeof model.reset === 'function') {

//              Pass response from model's reset method to
//              the view
                view.output(model.reset());
            }
        },

//      Set Display takes an object, and set it to be the
//      Calculator's new output field.

        setDisplay : function (obj) {

            view.setDisplay(obj);
        }
    };

    return controller;

}()); // end calculator definition

// This is where the setup for the calculator happens. It's all
// inside an anonymous function, so the vars and the functions
// will go away at the end.

(function () {

    'use strict';

    var numbers,
        operators,
        i,
        k;

//  First, create click handlers for the buttons

//  function takes a number button dom element, and
//  attaches calc's enterNumber method to its click event
    function bindNum(obj) {
        obj.onclick = function () {
            calculator.enterNumber(this.value); // 'this' is obj (a num btn)
        };
    }

//  function takes a function button dom element, and
//  attaches calc's enterOperator method to its click event
    function bindOpp(obj) {
        obj.onclick = function () {
            calculator.enterOperator(this.value); // 'this' is obj (a fn btn)
        };
    }

//  Second, run setup routine, in which page elements are bound to
//  calculator methods.

//  Start by calling the calcuator's init method, passing
//  in an output element to be the display.

    /*jslint browser:true*/

    calculator.setDisplay(document.getElementById('out'));

//  Move onto binding the numbers' click
//  event to the calculator's update method.

    numbers = document.getElementsByClassName('number');

    for (i = 0; i < numbers.length; i += 1) {

//      clicking a number will update the display and
//      the temp variable

        bindNum(numbers[i]);
    }

    operators = document.getElementsByClassName('operator');

    for (k = 0; k < operators.length; k += 1) {

//      clicking an operator will make the calculator
//      perform an operation.

        bindOpp(operators[k]);

    }

//  lastly, bind the clear function to the clear buttons' click event

    document.getElementById('clear').onclick = function () {
        calculator.clear();
    };

//  try to install app in firefox os if it is not already installed
    var request = navigator.mozApps.getSelf();

    request.onsuccess = function (){
        if(!request.result) { // not installed yet, initiate request
            console.log('not installed yet');
            var request2 = navigator.mozApps.install(location.protocol + '//' + location.host + '/manifest.webapp');

            request2.onsuccess = function() {
                console.log('app installed successfully');
              };
              request2.onerror = function() {
                  console.log(location.host);
                console.log('app failed to install');
              };

        } else {
            console.log('already installed');
            navigator.mozApps.mgmt.launch(location.protocol + '//' + location.host + ');
                    var request3 = window.navigator.mozApps.getInstalled();
            request3.onerror = function(e) {
              alert("Error calling getInstalled: " + request3.error.name);
            };
            request3.onsuccess = function(e) {
              alert("Success, number of apps: " + request3.result.length);
              var appsRecord = request3.result;
              console.log(appsRecord);
            };
            }

        request.onerror = function () {
            console.log('Error checking installation status: ' + this.error.message);

          };
    };

}()); // end the anonymous init function, and invoke it
<commit_msg>syntax error<commit_after>//  The calculator pseudoClass represents a four-function calculator.
//  The following both defines and constructs the singleton calculator object.

//  This file is part of Abacus For The Rest Of Us
//  Copyright (C) 2013 Max Galloway-Carson
//
//  Abacus For The Rest Of Us is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Affero General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//  GNU Affero General Public License for more details.
//
//  You should have received a copy of the GNU Affero General Public License
//  along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//  email me at: maxvgc@gmail.com

var calculator = (function () {

    'use strict';

    var model,
        view,
        controller;

//  model pseudoclass is an internal representation of
//  the calculator's state.

    model = {

        tally : 0, // running total since last clear

        operator : '+', // last operator pressed

        temp : '', // number, as it entered by user

        isClear : true, // flag indicates whether there has been output

//      The evaluate function performs a computation.
//      First, it performs the stored operation on temp and tally.
//      Then it stores the given operation for the next evaluation.
//
//      Returns the state to show to user.

        evaluate : function (operate) {

//      Special condition if there has not been output yet.

            var tempN = parseFloat(this.temp);

            if (this.isClear) {

                this.tally = tempN;
                this.isClear = false;

            } else {

//              Perform the stored operation on tally and temp

                switch (this.operator) {

                case '+':
                    this.tally += tempN;
                    break;

                case '-':
                    this.tally -= tempN;
                    break;

                case 'x':
                    this.tally *= tempN;
                    break;

                case '/':
                    this.tally /= tempN;
                    break;

                }
            }

//          In either case, update the display, and prepare for
//          next input

            this.temp = '0'; // reset temp
            this.operator = operate; // get ready to perform
            // the given operation

            if (isNaN(this.tally)) {
                this.reset();
            }

            return this.tally; // user sees result of computation
        },

//      The update function will take string representing a single
//      digit, and
//      append it to what the user has entered so far, both on the
//      screen and internally.
//      Returns the state to show to user.

        update : function (lastDigit) {

//          wipe out display to prevent leading zero
            if (this.temp === '0') {
                this.temp = '';
            }

//          concat display with new input
            this.temp += lastDigit;

            return this.temp; // user sees number entered thus far
        },

//      The reset function clears the calculator's instance
//      variables, and wipes the screen.

        reset : function () {
            this.tally = 0;
            this.operator = '+';
            this.temp = '0';
            this.isClear = true;
            return 0;
        }

    }; // end model

//  view is the representation of the screen.

    view = {

//      the object holding the output.

        display : {
            innerHTML : "0"
        },

//      method to set display to given number

        output : function (val) {

            this.display.innerHTML = val;

        },

//      Sets sets given object to be the new display.
//      Copies the old output into new display.

        setDisplay : function (newScreen) { // function

            if (typeof newScreen === 'object') {

                newScreen.innerHTML = this.display.innerHTML;

                this.display = newScreen;
            }
        }
    }; // end view

//  These are the calculator's publicly facing methods.
//  They should be consided the controller.

//  Enter number is called when a user presses a digit, and takes that
//  digit as a param. If possible, enterNumber will pass that digit
//  to the inner calculator's update method.

    controller = {
        enterNumber : function (num) {

            if (typeof model.update === 'function') {

//              Pass response from model's update method to
//              the view
                view.output(model.update(num));
            }
        },

//      Enter operator is called when a user presses an operator,
//      and takes that operator as a param. If possible, enterOperator
//      will pass that operator to the inner calculator's
//      evaluate method.

        enterOperator : function (opp) {

            if (typeof model.evaluate === 'function') {

//              Pass response from model's evaluate method to
//              the view
                view.output(model.evaluate(opp));
            }
        },

//      Clear is called when a user presses the clear button, and
//      takes no params. If possible, clear will call the inner
//      calculator's reset method.

        clear : function () {

            if (typeof model.reset === 'function') {

//              Pass response from model's reset method to
//              the view
                view.output(model.reset());
            }
        },

//      Set Display takes an object, and set it to be the
//      Calculator's new output field.

        setDisplay : function (obj) {

            view.setDisplay(obj);
        }
    };

    return controller;

}()); // end calculator definition

// This is where the setup for the calculator happens. It's all
// inside an anonymous function, so the vars and the functions
// will go away at the end.

(function () {

    'use strict';

    var numbers,
        operators,
        i,
        k;

//  First, create click handlers for the buttons

//  function takes a number button dom element, and
//  attaches calc's enterNumber method to its click event
    function bindNum(obj) {
        obj.onclick = function () {
            calculator.enterNumber(this.value); // 'this' is obj (a num btn)
        };
    }

//  function takes a function button dom element, and
//  attaches calc's enterOperator method to its click event
    function bindOpp(obj) {
        obj.onclick = function () {
            calculator.enterOperator(this.value); // 'this' is obj (a fn btn)
        };
    }

//  Second, run setup routine, in which page elements are bound to
//  calculator methods.

//  Start by calling the calcuator's init method, passing
//  in an output element to be the display.

    /*jslint browser:true*/

    calculator.setDisplay(document.getElementById('out'));

//  Move onto binding the numbers' click
//  event to the calculator's update method.

    numbers = document.getElementsByClassName('number');

    for (i = 0; i < numbers.length; i += 1) {

//      clicking a number will update the display and
//      the temp variable

        bindNum(numbers[i]);
    }

    operators = document.getElementsByClassName('operator');

    for (k = 0; k < operators.length; k += 1) {

//      clicking an operator will make the calculator
//      perform an operation.

        bindOpp(operators[k]);

    }

//  lastly, bind the clear function to the clear buttons' click event

    document.getElementById('clear').onclick = function () {
        calculator.clear();
    };

//  try to install app in firefox os if it is not already installed
    var request = navigator.mozApps.getSelf();

    request.onsuccess = function (){
        if(!request.result) { // not installed yet, initiate request
            console.log('not installed yet');
            var request2 = navigator.mozApps.install(location.protocol + '//' + location.host + '/manifest.webapp');

            request2.onsuccess = function() {
                console.log('app installed successfully');
              };
              request2.onerror = function() {
                  console.log(location.host);
                console.log('app failed to install');
              };

        } else {
            console.log('already installed');
            navigator.mozApps.mgmt.launch(location.protocol + '//' + location.host );
                    var request3 = window.navigator.mozApps.getInstalled();
            request3.onerror = function(e) {
              alert("Error calling getInstalled: " + request3.error.name);
            };
            request3.onsuccess = function(e) {
              alert("Success, number of apps: " + request3.result.length);
              var appsRecord = request3.result;
              console.log(appsRecord);
            };
            }

        request.onerror = function () {
            console.log('Error checking installation status: ' + this.error.message);

          };
    };

}()); // end the anonymous init function, and invoke it
<|endoftext|>


<commit_before>
'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;

const scriptRules = require('./script.json');

//CREATE WELCOME TEXT
var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 8 )
{
  groet = "Goeiemorgen 🌝.  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else
if ( myDate.getHours() >8 )
{
  groet = "Goeiemorgen 🌝 ";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag 🌞";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17&& myDate.getHours() <= 20 )
{
groet = "Goedenavond 🌙";
}
else
if (myDate.getHours() > 20  || myDate.getHours() <= 24 )
{
  groet = "Goedenavond 🌙  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom. ";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();
        return bot.say(`${groet}... Wat voor soort hypotheek zoek je? `)
        .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
        .then(() => bot.say(`%[Starters Hypotheek](postback:hypotheektype_starter)`))
        .then(() => bot.say (`%[Nieuwe hypotheek](postback:hypotheektype_nieuw) `))
        .then(() => bot.say (`%[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
        .then(() => 'speak');
    }
},

  speak: {
          receive: (bot, message) => {

              const upperText = message.text.trim();

              function updateSilent() {
                  switch (upperText) {
                      //THE MORTGAGE STUFF
                      case 'Hoi':
                            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
                            .then(() => 'woningType()')
                          break;
                      case 'Starters Hypotheek':
                          return bot.say(`Wat voor type woning zoek je? `)
                          .then(() => bot.say(`%[🏬 Appartement](postback:hypotheekkeuze_appartement) %[🏠 Huis](postback:hypotheekkeuze_huis) %[📭 Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
                          .then(() => 'woningType')
                              break;
                      case 'Nieuwe hypotheek':
                          return bot.say(`😞 Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
                          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[💼 Zoek Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/jelocatie.aspx)`))
                            .then(() => 'finish')
                          break;
                      case 'Hypotheek oversluiten':
                          return bot.say(`😟 Het spijt me maar op dit moment biedt Independer alleen  Starters een hypotheek.`)
                          .then(()=> bot.say(`Als het allemaal wel zo ver is, wil je dan een update ontvangen? %[Ja, dat wil ik wel](postback:update_ja) %[Nee, dat hoeft niet](postback:update_nee)`))
                            .then(() => 'updateOntvangen')
                          break;
                      //THE REST
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              woningType: {
                      receive: (bot, message) => {

                          const typeWoning = message.text.trim();

                          function updateWoning() {
                            switch(typeWoning.text) {
                              case '🏬 Appartement':
                                  return bot.say(`Nice!`)
                                  .then(() => 'vervolgVragen')
                                  break;
                              case '🏠 Huis':
                                  return bot.say(`Leuk`)
                                  .then(() => 'vervolgVragen')
                                  break;
                              case '📭 Vakantiewoning':
                                  return bot.say(`Gezellig`)
                                  .then(() => 'vervolgVragen')
                                  break;
                              default:
                                receive => 'processing'
                                break;
                            }
                          }
                        }
                      }

              function askName() {
                woningType: {
receive: (bot, message) => {

  }
},
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              //CHECK INPUT  FLOW
              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  //BASICALLY ERROR OR NO TXT
                  if (!_.has(scriptRules, upperText)) {
                      return bot.say(`![](http://www.bieg.nl/beeld/speechbubble.gif)`).then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
      }
});
<commit_msg>ccv<commit_after>
'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;

const scriptRules = require('./script.json');

//CREATE WELCOME TEXT
var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 8 )
{
  groet = "Goeiemorgen 🌝.  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else
if ( myDate.getHours() >8 )
{
  groet = "Goeiemorgen 🌝 ";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag 🌞";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17&& myDate.getHours() <= 20 )
{
groet = "Goedenavond 🌙";
}
else
if (myDate.getHours() > 20  || myDate.getHours() <= 24 )
{
  groet = "Goedenavond 🌙  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom. ";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();
        return bot.say(`${groet}... Wat voor soort hypotheek zoek je? `)
        .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
        .then(() => bot.say(`%[Starters Hypotheek](postback:hypotheektype_starter)`))
        .then(() => bot.say (`%[Nieuwe hypotheek](postback:hypotheektype_nieuw) `))
        .then(() => bot.say (`%[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
        .then(() => 'speak');
    }
},

  speak: {
          receive: (bot, message) => {

              const upperText = message.text.trim();

              function updateSilent() {
                  switch (upperText) {
                      //THE MORTGAGE STUFF
                      case 'Hoi':
                            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
                            .then(() => woningType())
                          break;
                      case 'Starters Hypotheek':
                          return bot.say(`Wat voor type woning zoek je? `)
                          .then(() => bot.say(`%[🏬 Appartement](postback:hypotheekkeuze_appartement) %[🏠 Huis](postback:hypotheekkeuze_huis) %[📭 Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
                          .then(() => woningType())
                              break;
                      case 'Nieuwe hypotheek':
                          return bot.say(`😞 Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
                          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[💼 Zoek Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/jelocatie.aspx)`))
                            .then(() => 'finish')
                          break;
                      case 'Hypotheek oversluiten':
                          return bot.say(`😟 Het spijt me maar op dit moment biedt Independer alleen  Starters een hypotheek.`)
                          .then(()=> bot.say(`Als het allemaal wel zo ver is, wil je dan een update ontvangen? %[Ja, dat wil ik wel](postback:update_ja) %[Nee, dat hoeft niet](postback:update_nee)`))
                            .then(() => 'updateOntvangen')
                          break;
                      //THE REST
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function woningType(){
                      receive: (bot, message) => {

                          const typeWoning = message.text.trim();

                          function updateWoning() {
                            switch(typeWoning.text) {
                              case '🏬 Appartement':
                                  return bot.say(`Nice!`)
                                  .then(() => 'vervolgVragen')
                                  break;
                              case '🏠 Huis':
                                  return bot.say(`Leuk`)
                                  .then(() => 'vervolgVragen')
                                  break;
                              case '📭 Vakantiewoning':
                                  return bot.say(`Gezellig`)
                                  .then(() => 'vervolgVragen')
                                  break;
                              default:
                                receive => 'processing'
                                break;
                            }
                          }
                        }
                      }

              function getSilent() {
                  return bot.getProp("silent");
              }

              //CHECK INPUT  FLOW
              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  //BASICALLY ERROR OR NO TXT
                  if (!_.has(scriptRules, upperText)) {
                      return bot.say(`![](http://www.bieg.nl/beeld/speechbubble.gif)`).then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
      }
});
<|endoftext|>