<commit_before>/**
 * User store
 * Keeps logged-in user's state
 */

import Cookie from 'cookie'
import Cookies from 'js-cookie'
import {setToken, $get, $post, $delete} from './axios' // Axios is a peer plugin dependency

const inBrowser = typeof window !== 'undefined'
const SSR = global.__VUE_SSR_CONTEXT__

function AuthStore (opts) {
  const self = this
  opts = opts || {}

    // ----------------------------------------
    // Default State
    // ----------------------------------------
  this.defaultState = {
    user: Object.assign({roles: [], scope: [], name: null}, opts.default_user),
    loggedIn: false,
    token: null
  }

    // ----------------------------------------
    // State
    // ----------------------------------------
  this.state = Object.assign({}, self.defaultState)

    // ----------------------------------------
    // Getters
    // ----------------------------------------
  this.getters = {}

    // ----------------------------------------
    // Mutations
    // ----------------------------------------
  this.mutations = {

    setUser (state, user) {
            // Fill user with defaults data
      state.user = Object.assign({}, self.defaultState.user, user)

            // Set actual loggedIn status
      state.loggedIn = Boolean(user)
    },

    setToken (state, token) {
      state.token = token

            // Setup axios
      setToken(token)

            // Store token in cookies
      if (inBrowser) {
        if (!token) {
          return Cookies.remove('token', opts.tokenCookie)
        }
        Cookies.set('token', token, opts.tokenCookie)
      }
    }

  }

    // ----------------------------------------
    // Actions
    // ----------------------------------------
  this.actions = {

    loadToken (ctx) {
            // Try to extract token from cookies
      const cookieStr = inBrowser ? document.cookie : SSR.req.headers.cookie
      const cookies = Cookie.parse(cookieStr || '') || {}
      const token = cookies.token

      ctx.commit('setToken', token)
    },

    fetch (ctx) {
            // Load user token
      ctx.dispatch('loadToken')

            // No token
      if (!ctx.state.token) {
        return
      }

            // Get user profile
      return $get('/auth/user').then(userData => {
        ctx.commit('setUser', userData.user)
      }).catch(() => {
        return ctx.dispatch('logout')
      })
    },

    login (ctx, {fields, endpoint = '/auth/login', session = false}) {
      return $post(endpoint, fields).then(tokenData => {
                // Session tokens
        if (session) {
          opts.tokenCookie = null
        }
        ctx.commit('setToken', tokenData.token || tokenData.id_token)
        return ctx.dispatch('fetch')
      })
    },

    logout (ctx, {endpoint = '/auth/logout', appendToken = false}) {
            // Unload user profile
      ctx.commit('setUser', null)

            // Create logout endpoint
      const endpoint = endpoint + appendToken ? `/${ctx.state.token}` : ''

            // Server side logout
      return $delete(endpoint).then(() => {
                // Unset token
        ctx.commit('setToken', null)
      }).catch(() => {
                // Unset token
        ctx.commit('setToken', null)
      })
    }
  }
}

export default AuthStore
<commit_msg>Fix syntax<commit_after>/**
 * User store
 * Keeps logged-in user's state
 */

import Cookie from 'cookie'
import Cookies from 'js-cookie'
import {setToken, $get, $post, $delete} from './axios' // Axios is a peer plugin dependency

const inBrowser = typeof window !== 'undefined'
const SSR = global.__VUE_SSR_CONTEXT__

function AuthStore (opts) {
  const self = this
  opts = opts || {}

    // ----------------------------------------
    // Default State
    // ----------------------------------------
  this.defaultState = {
    user: Object.assign({roles: [], scope: [], name: null}, opts.default_user),
    loggedIn: false,
    token: null
  }

    // ----------------------------------------
    // State
    // ----------------------------------------
  this.state = Object.assign({}, self.defaultState)

    // ----------------------------------------
    // Getters
    // ----------------------------------------
  this.getters = {}

    // ----------------------------------------
    // Mutations
    // ----------------------------------------
  this.mutations = {

    setUser (state, user) {
            // Fill user with defaults data
      state.user = Object.assign({}, self.defaultState.user, user)

            // Set actual loggedIn status
      state.loggedIn = Boolean(user)
    },

    setToken (state, token) {
      state.token = token

            // Setup axios
      setToken(token)

            // Store token in cookies
      if (inBrowser) {
        if (!token) {
          return Cookies.remove('token', opts.tokenCookie)
        }
        Cookies.set('token', token, opts.tokenCookie)
      }
    }

  }

    // ----------------------------------------
    // Actions
    // ----------------------------------------
  this.actions = {

    loadToken (ctx) {
            // Try to extract token from cookies
      const cookieStr = inBrowser ? document.cookie : SSR.req.headers.cookie
      const cookies = Cookie.parse(cookieStr || '') || {}
      const token = cookies.token

      ctx.commit('setToken', token)
    },

    fetch (ctx) {
            // Load user token
      ctx.dispatch('loadToken')

            // No token
      if (!ctx.state.token) {
        return
      }

            // Get user profile
      return $get('/auth/user').then(userData => {
        ctx.commit('setUser', userData.user)
      }).catch(() => {
        return ctx.dispatch('logout')
      })
    },

    login (ctx, {fields, endpoint = '/auth/login', session = false}) {
      return $post(endpoint, fields).then(tokenData => {
                // Session tokens
        if (session) {
          opts.tokenCookie = null
        }
        ctx.commit('setToken', tokenData.token || tokenData.id_token)
        return ctx.dispatch('fetch')
      })
    },

    logout (ctx, {endpoint = '/auth/logout', appendToken = false}) {
            // Unload user profile
      ctx.commit('setUser', null)

            // Append token
      if (appendToken) endpoint = endpoint + `/${ctx.state.token}`

            // Server side logout
      return $delete(endpoint).then(() => {
                // Unset token
        ctx.commit('setToken', null)
      }).catch(() => {
                // Unset token
        ctx.commit('setToken', null)
      })
    }
  }
}

export default AuthStore
<|endoftext|>


<commit_before>var gulp = require('gulp');
var _ = require('lodash');

var scaffoldUtils = require('./scaffold.utils.js');
var pathsHelper = require('../helpers/paths.helper');

var nodeName = {};
var nodeType = '';
var hasJS = true;
var hasSCSS = true;

gulp.task('addGeneratorPrompts', function() {
  var prompt = require('gulp-prompt');

  return gulp.src(`${pathsHelper.scaffold}/add.js`)
  .pipe(prompt.prompt([{
      type: 'list',
      name: 'nodeType',
      message: 'What would you like to add',
      choices: scaffoldUtils.ADDABLE_NODES
    },{
      type: 'input',
      name: 'nodeName',
      message: 'Name?'
    },{
      type: 'confirm',
      name: 'hasJS',
      message: 'Do you need a JavaScript file?',
      when: function(currHash) {
        return currHash.nodeType === 'Component';
      }
    },{
      type: 'confirm',
      name: 'hasSCSS',
      message: 'Do you need a SCSS file?',
      when: function(currHash) {
        return currHash.nodeType === 'Page';
      }
    }], function(res) {
      nodeName = scaffoldUtils.normalizeNodeName(res.nodeName, res.nodeType);
      nodeType = res.nodeType;

      if (_.has(res, 'hasJS')) {
        hasJS = res.hasJS;
      }

      if (_.has(res, 'hasSCSS')) {
        hasSCSS = res.hasSCSS;
      }
    }));
});

gulp.task('addGenerator', ['addGeneratorPrompts'], function() {
  var tap = require('gulp-tap');
  var path = require('path');
  var fs = require('fs-extra');
  var rename = require('gulp-rename');
  var { parse, stringify } = require('scss-parser');

  var folder = nodeType.toLowerCase();
  var fileTypes2Pipe = scaffoldUtils.getFileTypesToPipe(hasJS, hasSCSS);

  return gulp.src(`${pathsHelper.scaffold}/${folder}/*.{js,twig,yml,scss}`)
    .pipe(tap(function(file, t) {
      var extension = path.extname(file.path);

      scaffoldUtils.FIND_REPLACES.forEach(function(replaceItem) {
        var regex = new RegExp(`{% ${replaceItem.label} %}`, 'g');

        file.contents = Buffer.from(file.contents.toString().replace(regex, nodeName[replaceItem.value]));
      });

      switch(extension) {
        case '.scss':

          var fileRead = fs.readFileSync(pathsHelper.mainScss, 'utf8');

          var ast = parse(fileRead);
          var newAst = parse(`@import '../../${folder}s/${nodeName.directory}/${nodeName.file}';`).value[0];
          var spaceAst = parse('\n').value[0];

          var indexPlaceholder = _.findIndex(ast.value, {
            value: ` ${nodeType.toUpperCase()}_PLACEHOLDER `
          });

          ast.value.splice(indexPlaceholder, 0, spaceAst);
          ast.value.splice(indexPlaceholder, 0, newAst);

          fs.writeFile(pathsHelper.mainScss, stringify(ast));

          break;

        case '.js':

          var fileRead = fs.readFileSync(pathsHelper.pinguAppJs, 'utf8');

          var result = fileRead.replace(scaffoldUtils.JS_AUTOIMPORT_REGEX, [
            `import ${nodeName.component} from '../../../${folder}s/${nodeName.directory}/${nodeName.file}';`,
            '\n',
            `// ${scaffoldUtils.JS_AUTOIMPORT_STRING}`,
          ].join(''));

          var result2 = result.replace(scaffoldUtils.JS_COMPONENT_REGEX, [
            `this.components.${nodeName.component} = ${nodeName.component};`,
            '\n',
            `    // ${scaffoldUtils.JS_COMPONENT_STRING}`
          ].join(''));

          fs.writeFile(pathsHelper.pinguAppJs, result2);

          break;

        default:
          break;
      }
    }))
    .pipe(rename({
      basename: nodeName.file
    }))
    .pipe(gulp.dest(`${pathsHelper.src}//${folder}s/${nodeName.directory}/`));
})

<commit_msg>PNG-21 fix hasJs failure<commit_after>var gulp = require('gulp');
var _ = require('lodash');

var scaffoldUtils = require('./scaffold.utils.js');
var pathsHelper = require('../helpers/paths.helper');

var nodeName = {};
var nodeType = '';
var hasJS = true;
var hasSCSS = true;

gulp.task('addGeneratorPrompts', function() {
  var prompt = require('gulp-prompt');

  return gulp.src(`${pathsHelper.scaffold}/add.js`)
  .pipe(prompt.prompt([{
      type: 'list',
      name: 'nodeType',
      message: 'What would you like to add',
      choices: scaffoldUtils.ADDABLE_NODES
    },{
      type: 'input',
      name: 'nodeName',
      message: 'Name?'
    },{
      type: 'confirm',
      name: 'hasJS',
      message: 'Do you need a JavaScript file?',
      when: function(currHash) {
        return currHash.nodeType === 'Component';
      }
    },{
      type: 'confirm',
      name: 'hasSCSS',
      message: 'Do you need a SCSS file?',
      when: function(currHash) {
        return currHash.nodeType === 'Page';
      }
    }], function(res) {
      nodeName = scaffoldUtils.normalizeNodeName(res.nodeName, res.nodeType);
      nodeType = res.nodeType;

      if (_.has(res, 'hasJS')) {
        hasJS = res.hasJS;
      }

      if (_.has(res, 'hasSCSS')) {
        hasSCSS = res.hasSCSS;
      }
    }));
});

gulp.task('addGenerator', ['addGeneratorPrompts'], function() {
  var tap = require('gulp-tap');
  var path = require('path');
  var fs = require('fs-extra');
  var rename = require('gulp-rename');
  var { parse, stringify } = require('scss-parser');

  var folder = nodeType.toLowerCase();
  var fileTypes2Pipe = scaffoldUtils.getFileTypesToPipe(hasJS, hasSCSS);

  return gulp.src(`${pathsHelper.scaffold}/${folder}/*.{${fileTypes2Pipe}}`)
    .pipe(tap(function(file, t) {
      var extension = path.extname(file.path);

      scaffoldUtils.FIND_REPLACES.forEach(function(replaceItem) {
        var regex = new RegExp(`{% ${replaceItem.label} %}`, 'g');

        file.contents = Buffer.from(file.contents.toString().replace(regex, nodeName[replaceItem.value]));
      });

      switch(extension) {
        case '.scss':

          var fileRead = fs.readFileSync(pathsHelper.mainScss, 'utf8');

          var ast = parse(fileRead);
          var newAst = parse(`@import '../../${folder}s/${nodeName.directory}/${nodeName.file}';`).value[0];
          var spaceAst = parse('\n').value[0];

          var indexPlaceholder = _.findIndex(ast.value, {
            value: ` ${nodeType.toUpperCase()}_PLACEHOLDER `
          });

          ast.value.splice(indexPlaceholder, 0, spaceAst);
          ast.value.splice(indexPlaceholder, 0, newAst);

          fs.writeFile(pathsHelper.mainScss, stringify(ast));

          break;

        case '.js':

          var fileRead = fs.readFileSync(pathsHelper.pinguAppJs, 'utf8');

          var result = fileRead.replace(scaffoldUtils.JS_AUTOIMPORT_REGEX, [
            `import ${nodeName.component} from '../../../${folder}s/${nodeName.directory}/${nodeName.file}';`,
            '\n',
            `// ${scaffoldUtils.JS_AUTOIMPORT_STRING}`,
          ].join(''));

          var result2 = result.replace(scaffoldUtils.JS_COMPONENT_REGEX, [
            `this.components.${nodeName.component} = ${nodeName.component};`,
            '\n',
            `    // ${scaffoldUtils.JS_COMPONENT_STRING}`
          ].join(''));

          fs.writeFile(pathsHelper.pinguAppJs, result2);

          break;

        default:
          break;
      }
    }))
    .pipe(rename({
      basename: nodeName.file
    }))
    .pipe(gulp.dest(`${pathsHelper.src}//${folder}s/${nodeName.directory}/`));
})

<|endoftext|>


<commit_before>const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

const srcDir = path.resolve(__dirname, '..', 'src')
const distDir = path.resolve(__dirname, '..', 'dist')

module.exports = {
  // Where to fine the source code
  context: srcDir,

  // No source map for production build
  devtool: 'cheap-module-source-map',

  entry: [
    './index.js'
  ],

  output: {
    // The destination file name concatenated with hash (generated whenever you change your code).
    // The hash is really useful to let the browser knows when it should get a new bundle
    // or use the one in cache
    filename: 'main.[hash:8].js',

    // The destination folder where to put the output bundle
    path: distDir,

    // Wherever resource (css, js, img) you call <script src="..."></script>,
    // or css, or img use this path as the root
    publicPath: '/',

    // At some point you'll have to debug your code, that's why I'm giving you
    // for free a source map file to make your life easier
    sourceMapFilename: 'main.[hash:8].map'
  },

  // The devServer config is here to enable you to run the production build. I know you wanna see
  // the output of this awesome config with me (Webpack 2).
  devServer: {
    contentBase: distDir,
    historyApiFallback: true,
    port: 3000,
    compress: true,
    inline: false
  },

  module: {
    rules: [
      {
        // Webpack, when walking down the tree, whenever you see `.js` file use babel to transpile
        // the code to ES5. I don't want you to look into the node_modules folder.
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: [
          'babel-loader'
        ],
        include: srcDir
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            { loader: 'css-loader', options: { minimize: true } },
            // 'postcss-loader',
            'sass-loader'
          ]
        })
      },
      {
        test: /\.(eot?.+|svg?.+|ttf?.+|otf?.+|woff?.+|woff2?.+)$/,
        use: 'file-loader?name=assets/[name]-[hash:8].[ext]'
      },
      {
        test: /\.(jpg|jpeg|png|gif|ico|svg)$/,
        loader: 'url-loader',
        query: {
          // if less, bundle the asset inline, if greater, copy it to the dist/assets
          // folder using file-loader
          use: [
            'url-loader?limit=10000&name=assets/[name]-[hash:8].[ext]'
          ]
        }
      }
    ]
  },

  plugins: [
    new webpack.optimize.ModuleConcatenationPlugin(),
    new webpack.HashedModuleIdsPlugin(),

    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production')
      }
    }),

    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }),

    new HtmlWebpackPlugin({
      // where to find the html template
      template: path.join(srcDir, 'index.html'),

      // where to put the generated file
      path: distDir,

      // the output file name
      filename: 'index.html'
    }),

    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        screw_ie8: true,
        conditionals: true,
        unused: true,
        comparisons: true,
        sequences: true,
        dead_code: true,
        evaluate: true,
        if_return: true,
        join_vars: true
      },
      output: {
        comments: false
      }
    }),

    // Put all css code in this file
    new ExtractTextPlugin({
      filename: '[name].[contenthash:8].css',
      allChunks: true
    })
  ]
}
<commit_msg>config compression plugin<commit_after>const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const CompressionPlugin = require('compression-webpack-plugin')

const srcDir = path.resolve(__dirname, '..', 'src')
const distDir = path.resolve(__dirname, '..', 'dist')

module.exports = {
  // Where to fine the source code
  context: srcDir,

  // No source map for production build
  devtool: 'cheap-module-source-map',

  entry: [
    './index.js'
  ],

  output: {
    // The destination file name concatenated with hash (generated whenever you change your code).
    // The hash is really useful to let the browser knows when it should get a new bundle
    // or use the one in cache
    filename: 'main.[hash:8].js',

    // The destination folder where to put the output bundle
    path: distDir,

    // Wherever resource (css, js, img) you call <script src="..."></script>,
    // or css, or img use this path as the root
    publicPath: '/',

    // At some point you'll have to debug your code, that's why I'm giving you
    // for free a source map file to make your life easier
    sourceMapFilename: 'main.[hash:8].map'
  },

  // The devServer config is here to enable you to run the production build. I know you wanna see
  // the output of this awesome config with me (Webpack 2).
  devServer: {
    contentBase: distDir,
    historyApiFallback: true,
    port: 3000,
    compress: true,
    inline: false
  },

  module: {
    rules: [
      {
        // Webpack, when walking down the tree, whenever you see `.js` file use babel to transpile
        // the code to ES5. I don't want you to look into the node_modules folder.
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: [
          'babel-loader'
        ],
        include: srcDir
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            { loader: 'css-loader', options: { minimize: true } },
            // 'postcss-loader',
            'sass-loader'
          ]
        })
      },
      {
        test: /\.(eot?.+|svg?.+|ttf?.+|otf?.+|woff?.+|woff2?.+)$/,
        use: 'file-loader?name=assets/[name]-[hash:8].[ext]'
      },
      {
        test: /\.(jpg|jpeg|png|gif|ico|svg)$/,
        loader: 'url-loader',
        query: {
          // if less, bundle the asset inline, if greater, copy it to the dist/assets
          // folder using file-loader
          use: [
            'url-loader?limit=10240&name=assets/[name]-[hash:8].[ext]'
          ]
        }
      }
    ]
  },

  plugins: [
    new webpack.optimize.ModuleConcatenationPlugin(),
    new webpack.HashedModuleIdsPlugin(),

    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production')
      }
    }),

    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }),

    new HtmlWebpackPlugin({
      // where to find the html template
      template: path.join(srcDir, 'index.html'),

      // where to put the generated file
      path: distDir,

      // the output file name
      filename: 'index.html'
    }),

    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        screw_ie8: true,
        conditionals: true,
        unused: true,
        comparisons: true,
        sequences: true,
        dead_code: true,
        evaluate: true,
        if_return: true,
        join_vars: true
      },
      output: {
        comments: false
      }
    }),

    // Put all css code in this file
    new ExtractTextPlugin({
      filename: '[name].[contenthash:8].css',
      allChunks: true
    }),

    new CompressionPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: /\.js$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg?.+$/,
      threshold: 10240 // Only assets bigger than this size are processed
    })
  ]
}
<|endoftext|>


<commit_before>var client = require('../../../config/irc');
var io = require('../../../config/io');
var _user = require('../../users/model');
var request = require('request');
var profile = Number;

var toasts = io.of('/toasts').on('connection',function(socket){
  return socket;
});
var statusLuhbot = false;

client.connect().then(function(){
  statusLuhbot = true;
  console.log('luhbot conectado');
});

client.addListener('connected',function(adress,port){
  toasts.emit('newMessage',{msg:'Conectado'});
});

client.addListener('disconnected',function(reason){
  toasts.emit('newMessage',{msg:'Luhbot desconectado'});
  console.log('desconectado',reason)
});

client.addListener('connectfail',function(){
  toasts.emit('newMessage',{msg:'Luhbot não conseguiu se conectar'});
});

client.addListener('pong',function(l){
  statusLuhbot = l;
  toasts.emit('newMessage',{msg:'Latência luhbot :'+ statusLuhbot});
});

client.addListener('join',function(channel,username){
  client.say(channel, "Olar! sou a "+ username + " e vim amar vocês *-*");
  toasts.emit('newMessage',{msg:'Luhbot entrou na sala'});
});

client.addListener('chat',function(channel,user,message){
  if(!statusLuhbot){
    return false;
  }
  if(client.utils.uppercase(message) >= 0.4){
    client.say(channel, "@"+ user.username.toString() + " Ó U BAN VINO LEEEEEK");
    return;
  }
  var re = new RegExp(/(http(s)?:\/\/)?\w{2,}\.\w{2,}(\.\w{2,})*/g);
  if(re.test(message.toString())){
    client.timeout(channel, user.username, 10).then(function(){
      client.say(channel,'E da proxima vez, @' + user.username.toString() + ' vai mandar link na stream da sua avó!');
    });
  }
  var msg = message.toLowerCase();
  switch(true){
    case msg.split(' ').indexOf('!luhzinha') >= 0:
      client.say(channel,"Facebook: https://www.facebook.com/Luhzinhapage https://twitter.com/Luhzinhaluna https://www.youtube.com/user/luhzinhaplayer https://instagram.com/luhzinhaluna/");
      break;
    case msg.split(' ').indexOf('!subscribers') >= 0:
      client.say(channel,"Seja um subscriber! Subscribers tem direito a sorteios de jogos da steam, prioridade para jogar na live e um teamspeak para falar com a Luhzinha.");
      break;
    case msg.split(' ').indexOf('!eu') >= 0:
      _user.findOne({twitchId: profile},{bio:1},function(err,doc){
        if(err){
          throw new Error(err)
        }
        client.say(channel, doc.bio);
      });
      break;
    case msg.split(' ').indexOf('!ping') >= 0:
      client.say(channel,'@'+ user.username + ', pong');
      break;
    case msg.split(' ').indexOf('@luhbot') >= 0:
      var talks = [
        'Oiii tudo bem amore?',
        'Você fala muito :(',
        'Quero doce :(',
        'Amanda?',
        'Romero brito?',
        'SAMU?!?',
        'Seu **...'
      ];
      var index = Math.floor(Math.random() * 7) ;
      client.say(channel,talks[index]);
      break;
    default:
      console.log(message)
      // client.say(channel, '@'+user.username.toString() + ' disse ' + message.toString());
  }
});

var _irc = {
  join: function(req, res, next){
    if(statusLuhbot){
      res.json({msg:'Luhbot já está conectado'});
      return;
    }
    client.join(req.session.passport.user.twitchUser).then(function(){
      profile = req.session.passport.user.twitchId;
      toasts.emit('newMessage',{msg:'Entrando na sala'});
    });
    res.status(202).end();
  },
  ping : function(req, res, next){
    if(!statusLuhbot){
      res.json({msg:'Luhbot está desconectado'});
      return;
    }
    res.json({msg:'Enviando ping'});
    client.ping();
  },
  disconnect: function(req, res, next){
    if(!statusLuhbot){
      res.json({msg:'Luhbot está desconectado'});
      return;
    }
    statusLuhbot = false;
    res.json({msg:'Luhbot foi desconectado'});
  },
  forceRestart: function(req, res, next){
    res.status(501).end();
  }
}

module.exports = _irc;
<commit_msg>alter joins client<commit_after>var client = require('../../../config/irc');
var io = require('../../../config/io');
var _user = require('../../users/model');
var request = require('request');
var profile = Number;

var toasts = io.of('/toasts').on('connection',function(socket){
  return socket;
});
var statusLuhbot = false;

client.connect().then(function(){
  statusLuhbot = true;
  console.log('luhbot conectado');
});

client.addListener('connected',function(adress,port){
  toasts.emit('newMessage',{msg:'Conectado'});
});

client.addListener('disconnected',function(reason){
  toasts.emit('newMessage',{msg:'Luhbot desconectado'});
  console.log('desconectado',reason)
});

client.addListener('connectfail',function(){
  toasts.emit('newMessage',{msg:'Luhbot não conseguiu se conectar'});
});

client.addListener('pong',function(l){
  statusLuhbot = l;
  toasts.emit('newMessage',{msg:'Latência luhbot :'+ statusLuhbot});
});

client.addListener('join',function(channel,username){
  client.say(channel, "Olar! sou a "+ username + " e vim amar vocês *-*");
  toasts.emit('newMessage',{msg:'Luhbot entrou na sala'});
});

client.addListener('chat',function(channel,user,message){
  if(!statusLuhbot){
    return false;
  }
  if(client.utils.uppercase(message) >= 0.4){
    client.say(channel, "@"+ user.username.toString() + " Ó U BAN VINO LEEEEEK");
    return;
  }
  var re = new RegExp(/(http(s)?:\/\/)?\w{2,}\.\w{2,}(\.\w{2,})*/g);
  if(re.test(message.toString())){
    client.timeout(channel, user.username, 10).then(function(){
      client.say(channel,'E da proxima vez, @' + user.username.toString() + ' vai mandar link na stream da sua avó!');
    });
  }
  var msg = message.toLowerCase();
  switch(true){
    case msg.split(' ').indexOf('!luhzinha') >= 0:
      client.say(channel,"Facebook: https://www.facebook.com/Luhzinhapage https://twitter.com/Luhzinhaluna https://www.youtube.com/user/luhzinhaplayer https://instagram.com/luhzinhaluna/");
      break;
    case msg.split(' ').indexOf('!subscribers') >= 0:
      client.say(channel,"Seja um subscriber! Subscribers tem direito a sorteios de jogos da steam, prioridade para jogar na live e um teamspeak para falar com a Luhzinha.");
      break;
    case msg.split(' ').indexOf('!eu') >= 0:
      _user.findOne({twitchId: profile},{bio:1},function(err,doc){
        if(err){
          throw new Error(err)
        }
        client.say(channel, doc.bio);
      });
      break;
    case msg.split(' ').indexOf('!ping') >= 0:
      client.say(channel,'@'+ user.username + ', pong');
      break;
    case msg.split(' ').indexOf('@luhbot') >= 0:
      var talks = [
        'Oiii tudo bem amore?',
        'Você fala muito :(',
        'Quero doce :(',
        'Amanda?',
        'Romero brito?',
        'SAMU?!?',
        'Seu **...'
      ];
      var index = Math.floor(Math.random() * talks.length) ;
      client.say(channel,talks[index]);
      break;
    default:
      console.log(message)
      // client.say(channel, '@'+user.username.toString() + ' disse ' + message.toString());
  }
});

var _irc = {
  join: function(req, res, next){
    if(!statusLuhbot){
      res.json({msg:'Luhbot não está conectado'});
      return;
    }
    client.join(req.session.passport.user.twitchUser).then(function(){
      profile = req.session.passport.user.twitchId;
      toasts.emit('newMessage',{msg:'Entrando na sala'});
    });
    res.status(202).end();
  },
  ping : function(req, res, next){
    if(!statusLuhbot){
      res.json({msg:'Luhbot está desconectado'});
      return;
    }
    res.json({msg:'Enviando ping'});
    client.ping();
  },
  disconnect: function(req, res, next){
    if(!statusLuhbot){
      res.json({msg:'Luhbot está desconectado'});
      return;
    }
    statusLuhbot = false;
    res.json({msg:'Luhbot foi desconectado'});
  },
  forceRestart: function(req, res, next){
    res.status(501).end();
  }
}

module.exports = _irc;
<|endoftext|>


<commit_before>var files = require("./files.js");

// Set this env variable to a truthy value to force files.watchFile
// instead of files.pathwatcherWatch.
var canUsePathwatcher = !process.env.METEOR_WATCH_FORCE_POLLING;

var pollingInterval = canUsePathwatcher
  // Set this env variable to alter the watchFile polling interval.
  ? ~~process.env.METEOR_WATCH_POLLING_INTERVAL_MS || 5000
  : 500;

exports.watch = function watch(absPath, callback) {
  var lastPathwatcherEventTime = 0;
  var lastWatchFileEventTime = 0;

  // The maximum amount of time in milliseconds that we're willing to wait
  // for a pathwatcher event to fire, if it's ever going to fire.
  var pathwatcherLatencyBound = 50;

  var watcher = canUsePathwatcher && files.pathwatcherWatch(absPath, function() {
    // It's tempting to call files.unwatchFile(absPath, watchFileWrapper)
    // here, but previous pathwatcher success is no guarantee of future
    // pathwatcher reliability. For example, pathwatcher works just fine
    // when file changes originate from within a Vagrant VM, but changes
    // to shared files made outside the VM are invisible to pathwatcher,
    // so our only hope of catching them is to continue polling.

    // If a watchFile event fired very recently, ignore this event.
    var now = +new Date;
    if (now - lastWatchFileEventTime > pathwatcherLatencyBound) {
      lastPathwatcherEventTime = now;
      callback.apply(this, arguments);
    }
  });

  function watchFileWrapper() {
    // If a pathwatcher event fired in the last polling interval, ignore
    // this event.
    var now = +new Date;
    if (now - lastPathwatcherEventTime > pollingInterval) {
      lastWatchFileEventTime = now;
      console.log("firing watchFile event");
      callback.apply(this, arguments);
    } else {
      console.log("dropping watchFile event");
    }
  }

  // We use files.watchFile in addition to files.pathwatcherWatch as a
  // fail-safe to detect file changes even on network file systems.
  // However (unless canUsePathwatcher is false), we use a relatively long
  // default polling interval of 5000ms to save CPU cycles.
  files.watchFile(absPath, {
    persistent: false,
    interval: pollingInterval
  }, watchFileWrapper);

  var polling = true;

  return {
    close: function close() {
      if (watcher) {
        watcher.close();
        watcher = null;
      }

      if (polling) {
        polling = false;
        files.unwatchFile(absPath, watchFileWrapper);
      }
    }
  };
};
<commit_msg>Remove stray console.log statements.<commit_after>var files = require("./files.js");

// Set this env variable to a truthy value to force files.watchFile
// instead of files.pathwatcherWatch.
var canUsePathwatcher = !process.env.METEOR_WATCH_FORCE_POLLING;

var pollingInterval = canUsePathwatcher
  // Set this env variable to alter the watchFile polling interval.
  ? ~~process.env.METEOR_WATCH_POLLING_INTERVAL_MS || 5000
  : 500;

exports.watch = function watch(absPath, callback) {
  var lastPathwatcherEventTime = 0;
  var lastWatchFileEventTime = 0;

  // The maximum amount of time in milliseconds that we're willing to wait
  // for a pathwatcher event to fire, if it's ever going to fire.
  var pathwatcherLatencyBound = 50;

  var watcher = canUsePathwatcher && files.pathwatcherWatch(absPath, function() {
    // It's tempting to call files.unwatchFile(absPath, watchFileWrapper)
    // here, but previous pathwatcher success is no guarantee of future
    // pathwatcher reliability. For example, pathwatcher works just fine
    // when file changes originate from within a Vagrant VM, but changes
    // to shared files made outside the VM are invisible to pathwatcher,
    // so our only hope of catching them is to continue polling.

    // If a watchFile event fired very recently, ignore this event.
    var now = +new Date;
    if (now - lastWatchFileEventTime > pathwatcherLatencyBound) {
      lastPathwatcherEventTime = now;
      callback.apply(this, arguments);
    }
  });

  function watchFileWrapper() {
    // If a pathwatcher event fired in the last polling interval, ignore
    // this event.
    var now = +new Date;
    if (now - lastPathwatcherEventTime > pollingInterval) {
      lastWatchFileEventTime = now;
      callback.apply(this, arguments);
    }
  }

  // We use files.watchFile in addition to files.pathwatcherWatch as a
  // fail-safe to detect file changes even on network file systems.
  // However (unless canUsePathwatcher is false), we use a relatively long
  // default polling interval of 5000ms to save CPU cycles.
  files.watchFile(absPath, {
    persistent: false,
    interval: pollingInterval
  }, watchFileWrapper);

  var polling = true;

  return {
    close: function close() {
      if (watcher) {
        watcher.close();
        watcher = null;
      }

      if (polling) {
        polling = false;
        files.unwatchFile(absPath, watchFileWrapper);
      }
    }
  };
};
<|endoftext|>


<commit_before>// We use conses at the very end of the list for very fast O(1) push
var Cons = require("./Cons");
var avl  = require("./AVL");

// It's faster to use arrays for small lists
var array_limit = 125;

var ceiling = Math.ceil;

function array_insert_at(array, index, value) {
  var len = array.length + 1;

  var out = new Array(len);

  var i = 0;
  while (i < index) {
    out[i] = array[i];
    ++i;
  }

  out[i] = value;
  ++i;

  while (i < len) {
    out[i] = array[i - 1];
    ++i;
  }

  return out;
}

function array_modify_at(array, index, f) {
  var old_value = array[index];
  var new_value = f(old_value);

  if (old_value === new_value) {
    return array;

  } else {
    // It's fast enough to just use `array.slice`, rather than a custom function
    var new_array = array.slice();
    new_array[index] = new_value;
    return new_array;
  }
}

function array_remove_at(array, index) {
  var len = array.length - 1;

  var out = new Array(len);

  var i = 0;
  while (i < index) {
    out[i] = array[i];
    ++i;
  }

  while (i < len) {
    out[i] = array[i + 1];
    ++i;
  }

  return out;
}

// Converts a stack (reversed cons) into an array
function stack_to_array(a, size) {
  var out = new Array(size);

  while (size--) {
    out[size] = a.car;
    a = a.cdr;
  }

  return out;
}

function stack_nth(a, size, i) {
  while (--size !== i) {
    a = a.cdr;
  }

  return a.car;
}

function ArrayNode(left, right, array) {
  this.left  = left;
  this.right = right;
  this.array = array;
  this.size  = left.size + right.size + array.length;
  this.depth = avl.max(left.depth, right.depth) + 1;
}

ArrayNode.prototype.copy = function (left, right) {
  return new ArrayNode(left, right, this.array);
};

ArrayNode.prototype.forEach = function (f) {
  this.left.forEach(f);
  this.array.forEach(function (x) {
    f(x);
  });
  this.right.forEach(f);
};

function nth_has(index, len) {
  return index >= 0 && index < len;
}

function nth_get(node, index) {
  for (;;) {
    var left    = node.left;
    var l_index = left.size;

    if (index < l_index) {
      node = left;

    } else {
      index -= l_index;

      var array = node.array;
      var len   = array.length;
      if (index < len) {
        return array[index];

      } else {
        index -= len;
        node  = node.right;
      }
    }
  }
}

function nth_insert(node, index, value) {
  // TODO is this necessary ?
  if (node === nil) {
    return new ArrayNode(nil, nil, [value]);

  } else {
    var left    = node.left;
    var right   = node.right;
    var l_index = left.size;

    if (index < l_index) {
      var child = nth_insert(left, index, value);
      return avl.balanced_node(node, child, right);

    } else {
      index -= l_index;

      var array = node.array;
      var len   = array.length;
      // TODO test this
      if (index <= len) {
        array = array_insert_at(array, index, value);

        // TODO this fails when array_limit is 1
        if (len === array_limit) {
          var pivot  = ceiling(array.length / 2);
          var aleft  = array.slice(0, pivot);
          var aright = array.slice(pivot);

          if (left.depth < right.depth) {
            return new ArrayNode(avl.insert_max(left, new ArrayNode(nil, nil, aleft)), right, aright);
          } else {
            return new ArrayNode(left, avl.insert_min(right, new ArrayNode(nil, nil, aright)), aleft);
          }

        } else {
          return new ArrayNode(left, right, array);
        }

      } else {
        var child = nth_insert(right, index - len, value);
        return avl.balanced_node(node, left, child);
      }
    }
  }
}

function nth_modify(node, index, f) {
  var left    = node.left;
  var right   = node.right;
  var l_index = left.size;

  if (index < l_index) {
    var child = nth_modify(left, index, f);
    if (child === left) {
      return node;
    } else {
      return node.copy(child, right); // TODO test this
    }

  } else {
    index -= l_index;

    var array = node.array;
    var len   = array.length;
    // TODO test this
    if (index < len) {
      var new_array = array_modify_at(array, index, f);
      if (new_array === array) {
        return node;
      } else {
        return new ArrayNode(left, right, new_array);
      }

    } else {
      var child = nth_modify(right, index - len, f);
      if (child === right) {
        return node;
      } else {
        return node.copy(left, child); // TODO test this
      }
    }
  }
}

function nth_remove(node, index) {
  var left    = node.left;
  var right   = node.right;
  var l_index = left.size;

  if (index < l_index) {
    var child = nth_remove(left, index);
    return avl.balanced_node(node, child, right);

  } else {
    index -= l_index;

    var array = node.array;
    var len   = array.length;
    // TODO test this
    if (index < len) {
      // TODO use `array.length === 1` so we can skip the call to `array_remove_at`
      array = array_remove_at(array, index);

      if (array.length === 0) {
        return avl.concat(left, right);
      } else {
        return new ArrayNode(left, right, array);
      }

    } else {
      var child = nth_remove(right, index - len);
      return avl.balanced_node(node, left, child);
    }
  }
}

function ImmutableList(root, tail, tail_size) {
  this.root = root;
  this.tail = tail;
  this.tail_size = tail_size;
}

// TODO is this a good idea ?
ImmutableList.prototype = Object.create(null);

ImmutableList.prototype.forEach = function (f) {
  this.root.forEach(f);
  this.tail.forEachRev(f);
};

ImmutableList.prototype.isEmpty = function () {
  return this.root === avl.nil && this.tail === avl.nil;
};

ImmutableList.prototype.size = function () {
  return this.root.size + this.tail_size;
};

ImmutableList.prototype.has = function (index) {
  var len = this.size();

  if (index < 0) {
    index += len;
  }

  return nth_has(index, len);
};

ImmutableList.prototype.get = function (index, def) {
  var len = this.size();

  if (index < 0) {
    index += len;
  }

  if (nth_has(index, len)) {
    var root = this.root;
    var size = root.size;
    if (index < size) {
      return nth_get(root, index);
    } else {
      return stack_nth(this.tail, this.tail_size, index - size);
    }

  } else if (arguments.length === 2) {
    return def;

  } else {
    throw new Error("Index " + index + " is not valid");
  }
};

ImmutableList.prototype.insert = function (value, index) {
  if (arguments.length === 1) {
    index = -1;
  }

  var len = this.size();

  if (index < 0) {
    index += (len + 1);
  }

  var root      = this.root;
  var tail      = this.tail;
  var tail_size = this.tail_size;
  if (index === len) {
    if (tail_size === array_limit) {
      var node = avl.insert_max(root, new ArrayNode(nil, nil, stack_to_array(tail, tail_size)));
      return new ImmutableList(node, new Cons(value, nil), 1);

    } else {
      return new ImmutableList(root, new Cons(value, tail), tail_size + 1);
    }

  } else if (nth_has(index, len)) {
    var size = root.size;
    if (index < size) {
      return new ImmutableList(nth_insert(root, index, value), tail, tail_size);

    } else {
      var array = array_insert_at(stack_to_array(tail, tail_size), index - size, value);
      var node  = avl.insert_max(root, new ArrayNode(nil, nil, array));
      return new ImmutableList(node, nil, 0);
    }

  } else {
    throw new Error("Index " + index + " is not valid");
  }
};

ImmutableList.prototype.remove = function (index) {
  if (arguments.length === 0) {
    index = -1;
  }

  var len = this.size();

  if (index < 0) {
    index += len;
  }

  var root      = this.root;
  var tail      = this.tail;
  var tail_size = this.tail_size;

  if (tail !== nil && index === len - 1) {
    return new ImmutableList(root, tail.cdr, tail_size - 1);

  } else if (nth_has(index, len)) {
    var size = root.size;
    if (index < size) {
      return new ImmutableList(nth_remove(root, index), tail, tail_size);

    } else {
      var array = array_remove_at(stack_to_array(tail, tail_size), index - size);
      var node  = avl.insert_max(root, new ArrayNode(nil, nil, array));
      return new ImmutableList(node, nil, 0);
    }

  } else {
    throw new Error("Index " + index + " is not valid");
  }
};

ImmutableList.prototype.modify = function (index, f) {
  var len = this.size();

  if (index < 0) {
    index += len;
  }

  if (nth_has(index, len)) {
    var root = this.root;
    var tail = this.tail;
    var tail_size = this.tail_size;
    var size = root.size;

    if (tail !== nil && index === len - 1) {
      var value = f(tail.car);
      if (value === tail.car) {
        return this;
      } else {
        return new ImmutableList(root, new Cons(value, tail.cdr), tail_size);
      }

    } else if (index < size) {
      var node = nth_modify(root, index, f);
      if (node === root) {
        return this;
      } else {
        return new ImmutableList(node, tail, tail_size);
      }

    } else {
      var stack = stack_to_array(tail, tail_size);
      var array = array_modify_at(stack, index - size, f);
      if (array === stack) {
        return this;
      } else {
        var node = avl.insert_max(root, new ArrayNode(nil, nil, array));
        return new ImmutableList(node, nil, 0);
      }
    }

  } else {
    throw new Error("Index " + index + " is not valid");
  }
};

ImmutableList.prototype.concat = function (right) {
  if (right instanceof ImmutableList) {
    var lroot = this.root;
    var ltail = this.tail;

    var rroot = right.root;
    var rtail = right.tail;

    if (rroot === nil && rtail === nil) {
      return this;

    } else if (lroot === nil && ltail === nil) {
      return right;

    } else {
      if (ltail !== nil) {
        lroot = avl.insert_max(lroot, new ArrayNode(nil, nil, stack_to_array(ltail, this.tail_size)));
      }

      var node = avl.concat(lroot, rroot);
      return new ImmutableList(node, rtail, right.tail_size);
    }

  } else {
    var self = this;

    // TODO use iterator
    right.forEach(function (x) {
      self = self.insert(x);
    });

    return self;
  }
};

module.exports = ImmutableList;
<commit_msg>Update ImmutableList.js<commit_after>// We use conses at the very end of the list for very fast O(1) push
var Cons = require("./Cons");
var AVL  = require("./AVL");

var max = AVL.max;
var nil = AVL.nil;
var balanced_node = AVL.balanced_node;
var concat = AVL.concat;
var insert_min = AVL.insert_min;
var insert_max = AVL.insert_max;

// It's faster to use arrays for small lists
var array_limit = 125;

var ceiling = Math.ceil;

function array_insert_at(array, index, value) {
  var len = array.length + 1;

  var out = new Array(len);

  var i = 0;
  while (i < index) {
    out[i] = array[i];
    ++i;
  }

  out[i] = value;
  ++i;

  while (i < len) {
    out[i] = array[i - 1];
    ++i;
  }

  return out;
}

function array_modify_at(array, index, f) {
  var old_value = array[index];
  var new_value = f(old_value);

  if (old_value === new_value) {
    return array;

  } else {
    // It's fast enough to just use `array.slice`, rather than a custom function
    var new_array = array.slice();
    new_array[index] = new_value;
    return new_array;
  }
}

function array_remove_at(array, index) {
  var len = array.length - 1;

  var out = new Array(len);

  var i = 0;
  while (i < index) {
    out[i] = array[i];
    ++i;
  }

  while (i < len) {
    out[i] = array[i + 1];
    ++i;
  }

  return out;
}

// Converts a stack (reversed cons) into an array
function stack_to_array(a, size) {
  var out = new Array(size);

  while (size--) {
    out[size] = a.car;
    a = a.cdr;
  }

  return out;
}

function stack_nth(a, size, i) {
  while (--size !== i) {
    a = a.cdr;
  }

  return a.car;
}

function ArrayNode(left, right, array) {
  this.left  = left;
  this.right = right;
  this.array = array;
  this.size  = left.size + right.size + array.length;
  this.depth = max(left.depth, right.depth) + 1;
}

ArrayNode.prototype.copy = function (left, right) {
  return new ArrayNode(left, right, this.array);
};

ArrayNode.prototype.forEach = function (f) {
  this.left.forEach(f);
  this.array.forEach(function (x) {
    f(x);
  });
  this.right.forEach(f);
};

function nth_has(index, len) {
  return index >= 0 && index < len;
}

function nth_get(node, index) {
  for (;;) {
    var left    = node.left;
    var l_index = left.size;

    if (index < l_index) {
      node = left;

    } else {
      index -= l_index;

      var array = node.array;
      var len   = array.length;
      if (index < len) {
        return array[index];

      } else {
        index -= len;
        node  = node.right;
      }
    }
  }
}

function nth_insert(node, index, value) {
  // TODO is this necessary ?
  if (node === nil) {
    return new ArrayNode(nil, nil, [value]);

  } else {
    var left    = node.left;
    var right   = node.right;
    var l_index = left.size;

    if (index < l_index) {
      var child = nth_insert(left, index, value);
      return balanced_node(node, child, right);

    } else {
      index -= l_index;

      var array = node.array;
      var len   = array.length;
      // TODO test this
      if (index <= len) {
        array = array_insert_at(array, index, value);

        // TODO this fails when array_limit is 1
        if (len === array_limit) {
          var pivot  = ceiling(array.length / 2);
          var aleft  = array.slice(0, pivot);
          var aright = array.slice(pivot);

          if (left.depth < right.depth) {
            return new ArrayNode(insert_max(left, new ArrayNode(nil, nil, aleft)), right, aright);
          } else {
            return new ArrayNode(left, insert_min(right, new ArrayNode(nil, nil, aright)), aleft);
          }

        } else {
          return new ArrayNode(left, right, array);
        }

      } else {
        var child = nth_insert(right, index - len, value);
        return balanced_node(node, left, child);
      }
    }
  }
}

function nth_modify(node, index, f) {
  var left    = node.left;
  var right   = node.right;
  var l_index = left.size;

  if (index < l_index) {
    var child = nth_modify(left, index, f);
    if (child === left) {
      return node;
    } else {
      return node.copy(child, right); // TODO test this
    }

  } else {
    index -= l_index;

    var array = node.array;
    var len   = array.length;
    // TODO test this
    if (index < len) {
      var new_array = array_modify_at(array, index, f);
      if (new_array === array) {
        return node;
      } else {
        return new ArrayNode(left, right, new_array);
      }

    } else {
      var child = nth_modify(right, index - len, f);
      if (child === right) {
        return node;
      } else {
        return node.copy(left, child); // TODO test this
      }
    }
  }
}

function nth_remove(node, index) {
  var left    = node.left;
  var right   = node.right;
  var l_index = left.size;

  if (index < l_index) {
    var child = nth_remove(left, index);
    return balanced_node(node, child, right);

  } else {
    index -= l_index;

    var array = node.array;
    var len   = array.length;
    // TODO test this
    if (index < len) {
      // TODO use `array.length === 1` so we can skip the call to `array_remove_at`
      array = array_remove_at(array, index);

      if (array.length === 0) {
        return concat(left, right);
      } else {
        return new ArrayNode(left, right, array);
      }

    } else {
      var child = nth_remove(right, index - len);
      return balanced_node(node, left, child);
    }
  }
}

function ImmutableList(root, tail, tail_size) {
  this.root = root;
  this.tail = tail;
  this.tail_size = tail_size;
}

// TODO is this a good idea ?
ImmutableList.prototype = Object.create(null);

ImmutableList.prototype.forEach = function (f) {
  this.root.forEach(f);
  this.tail.forEachRev(f);
};

ImmutableList.prototype.isEmpty = function () {
  return this.root === nil && this.tail === nil;
};

ImmutableList.prototype.size = function () {
  return this.root.size + this.tail_size;
};

ImmutableList.prototype.has = function (index) {
  var len = this.size();

  if (index < 0) {
    index += len;
  }

  return nth_has(index, len);
};

ImmutableList.prototype.get = function (index, def) {
  var len = this.size();

  if (index < 0) {
    index += len;
  }

  if (nth_has(index, len)) {
    var root = this.root;
    var size = root.size;
    if (index < size) {
      return nth_get(root, index);
    } else {
      return stack_nth(this.tail, this.tail_size, index - size);
    }

  } else if (arguments.length === 2) {
    return def;

  } else {
    throw new Error("Index " + index + " is not valid");
  }
};

ImmutableList.prototype.insert = function (value, index) {
  if (arguments.length === 1) {
    index = -1;
  }

  var len = this.size();

  if (index < 0) {
    index += (len + 1);
  }

  var root      = this.root;
  var tail      = this.tail;
  var tail_size = this.tail_size;
  if (index === len) {
    if (tail_size === array_limit) {
      var node = insert_max(root, new ArrayNode(nil, nil, stack_to_array(tail, tail_size)));
      return new ImmutableList(node, new Cons(value, nil), 1);

    } else {
      return new ImmutableList(root, new Cons(value, tail), tail_size + 1);
    }

  } else if (nth_has(index, len)) {
    var size = root.size;
    if (index < size) {
      return new ImmutableList(nth_insert(root, index, value), tail, tail_size);

    } else {
      var array = array_insert_at(stack_to_array(tail, tail_size), index - size, value);
      var node  = insert_max(root, new ArrayNode(nil, nil, array));
      return new ImmutableList(node, nil, 0);
    }

  } else {
    throw new Error("Index " + index + " is not valid");
  }
};

ImmutableList.prototype.remove = function (index) {
  if (arguments.length === 0) {
    index = -1;
  }

  var len = this.size();

  if (index < 0) {
    index += len;
  }

  var root      = this.root;
  var tail      = this.tail;
  var tail_size = this.tail_size;

  if (tail !== nil && index === len - 1) {
    return new ImmutableList(root, tail.cdr, tail_size - 1);

  } else if (nth_has(index, len)) {
    var size = root.size;
    if (index < size) {
      return new ImmutableList(nth_remove(root, index), tail, tail_size);

    } else {
      var array = array_remove_at(stack_to_array(tail, tail_size), index - size);
      var node  = insert_max(root, new ArrayNode(nil, nil, array));
      return new ImmutableList(node, nil, 0);
    }

  } else {
    throw new Error("Index " + index + " is not valid");
  }
};

ImmutableList.prototype.modify = function (index, f) {
  var len = this.size();

  if (index < 0) {
    index += len;
  }

  if (nth_has(index, len)) {
    var root = this.root;
    var tail = this.tail;
    var tail_size = this.tail_size;
    var size = root.size;

    if (tail !== nil && index === len - 1) {
      var value = f(tail.car);
      if (value === tail.car) {
        return this;
      } else {
        return new ImmutableList(root, new Cons(value, tail.cdr), tail_size);
      }

    } else if (index < size) {
      var node = nth_modify(root, index, f);
      if (node === root) {
        return this;
      } else {
        return new ImmutableList(node, tail, tail_size);
      }

    } else {
      var stack = stack_to_array(tail, tail_size);
      var array = array_modify_at(stack, index - size, f);
      if (array === stack) {
        return this;
      } else {
        var node = insert_max(root, new ArrayNode(nil, nil, array));
        return new ImmutableList(node, nil, 0);
      }
    }

  } else {
    throw new Error("Index " + index + " is not valid");
  }
};

ImmutableList.prototype.concat = function (right) {
  if (right instanceof ImmutableList) {
    var lroot = this.root;
    var ltail = this.tail;

    var rroot = right.root;
    var rtail = right.tail;

    if (rroot === nil && rtail === nil) {
      return this;

    } else if (lroot === nil && ltail === nil) {
      return right;

    } else {
      if (ltail !== nil) {
        lroot = insert_max(lroot, new ArrayNode(nil, nil, stack_to_array(ltail, this.tail_size)));
      }

      var node = concat(lroot, rroot);
      return new ImmutableList(node, rtail, right.tail_size);
    }

  } else {
    var self = this;

    // TODO use iterator
    right.forEach(function (x) {
      self = self.insert(x);
    });

    return self;
  }
};

module.exports = ImmutableList;
<|endoftext|>


<commit_before>//
//   Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
//   Licensed 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.
//

'use strict';

var assert = require('assert'),
    wrapper = require('co-redis'),
    sendRedis = wrapper(require('redis').createClient()),
    rcvRedis = wrapper(require('redis').createClient()),
    co = require('co'),
    log = require('./log');

exports.createEndPoint = function(name) {
    return new Courier(name);
};

function Courier(name) {
    this.name = name;
    this.handlers = {};

    log.info('New Courier instance created.');
}

Courier.prototype.start = function () {
    co(function *() {
        while (1) {
            var result = yield rcvRedis.brpop('inbox:' + this.name, 0);
            var msg = JSON.parse(result[1]);
            var handler = this.handlers[msg.type];
            log.info('MSG RCVD [' + msg.__sender + ' -> ' + this.name + '] DATA: ' + result[1]);

            assert(handler, this.name + ': Missing message handler for: ' + msg.type);

            if (isGeneratorFunction(handler)) {
                yield handler(msg);
            } else {
                // Normal function
                handler(msg);
            }
        }
    }).call(this);
};

Courier.prototype.send = function *(dest, msg) {
    var data = convert(msg, this.name, dest);
    yield sendRedis.lpush('inbox:' + dest, data);
};

Courier.prototype.sendNoWait = function(dest, msg) {
    co(this.send).call(this, dest, msg);
};

Courier.prototype.on = function(type, callback) {
    this.handlers[type] = callback;
};

function convert(msg, sender, dest) {
    if (typeof msg === 'string') {
        msg = { type: msg };
    }
    msg.__sender = sender;
    msg = JSON.stringify(msg);

    log.info('MSG SENT [' + sender + ' -> ' + dest + '] DATA:' + msg);
    return msg;
}

function isGeneratorFunction(obj) {
  return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction';
}
<commit_msg>Fix indentation<commit_after>//
//   Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
//   Licensed 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.
//

'use strict';

var assert = require('assert'),
    wrapper = require('co-redis'),
    sendRedis = wrapper(require('redis').createClient()),
    rcvRedis = wrapper(require('redis').createClient()),
    co = require('co'),
    log = require('./log');

exports.createEndPoint = function(name) {
    return new Courier(name);
};

function Courier(name) {
    this.name = name;
    this.handlers = {};

    log.info('New Courier instance created.');
}

Courier.prototype.start = function () {
    co(function *() {
        while (1) {
            var result = yield rcvRedis.brpop('inbox:' + this.name, 0);
            var msg = JSON.parse(result[1]);
            var handler = this.handlers[msg.type];
            log.info('MSG RCVD [' + msg.__sender + ' -> ' + this.name + '] DATA: ' + result[1]);

            assert(handler, this.name + ': Missing message handler for: ' + msg.type);

            if (isGeneratorFunction(handler)) {
                yield handler(msg);
            } else {
                // Normal function
                handler(msg);
            }
        }
    }).call(this);
};

Courier.prototype.send = function *(dest, msg) {
    var data = convert(msg, this.name, dest);
    yield sendRedis.lpush('inbox:' + dest, data);
};

Courier.prototype.sendNoWait = function(dest, msg) {
    co(this.send).call(this, dest, msg);
};

Courier.prototype.on = function(type, callback) {
    this.handlers[type] = callback;
};

function convert(msg, sender, dest) {
    if (typeof msg === 'string') {
        msg = { type: msg };
    }
    msg.__sender = sender;
    msg = JSON.stringify(msg);

    log.info('MSG SENT [' + sender + ' -> ' + dest + '] DATA:' + msg);
    return msg;
}

function isGeneratorFunction(obj) {
    return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction';
}
<|endoftext|>


<commit_before>/*jshint eqeqeq:false */
console.log( __dirname );

// Given foo/ return foo
function stripSlash( path ) {
  return path.replace( /\/$/, '' );
}

var express = require('express'),
    fs = require('fs'),
    path = require('path'),
    jade = require('jade'),
    app = express.createServer(),
    clientSessions = require('client-sessions'),
    lessMiddleware = require('less-middleware'),
    CONFIG = require('config'),
    User = require( './lib/user' )( CONFIG.database ),
    filter = require( './lib/filter' )( User.isDBOnline ),
    sanitizer = require( './lib/sanitizer' ),
    FileStore = require('./lib/file-store.js'),
    utils,
    stores = {},
    TEMPLATES_DIR = CONFIG.dirs.templates,
    APP_HOSTNAME = stripSlash( CONFIG.dirs.appHostname ),
    // If a separate hostname is given for embed, use it, otherwise use app's hostname
    WWW_ROOT = path.resolve( CONFIG.dirs.wwwRoot || path.join( __dirname, ".." ) ),
    VALID_TEMPLATES = CONFIG.templates,
    EXPORT_ASSETS = CONFIG.exportAssets;

var templateConfigs = {};

function readTemplateConfig( templateName, templatedPath ) {
  var configPath = templatedPath.replace( '{{templateBase}}', TEMPLATES_DIR + '/' );
  fs.readFile( configPath, 'utf8', function( err, conf ) {
    var configPathBase = configPath.substring( 0, configPath.lastIndexOf( '/' ) );
    conf = JSON.parse( conf );
    conf.template = configPathBase + '/' + conf.template;
    templateConfigs[ templateName ] = conf;
  });
}

// parse configs ahead of any action that has to happen with them
for ( var templateName in VALID_TEMPLATES ) {
  if ( VALID_TEMPLATES.hasOwnProperty( templateName ) ) {
    readTemplateConfig( templateName, VALID_TEMPLATES[ templateName ] );
  }
}

console.log( "Templates Dir:", TEMPLATES_DIR );

app.configure( 'development', function() {
  app.use( lessMiddleware( WWW_ROOT ));
  CONFIG.additionalStaticRoots.forEach( function( dir ) {
    app.use( express.static( dir ) );
  });
});

function setupStore( config ) {
  var store = FileStore.create( config.type, config.options );
  if( store.requiresFileSystem ) {
    app.use( express.static( store.root, JSON.parse( JSON.stringify( CONFIG.staticMiddleware ) ) ) );
  }
  return store;
}

app.configure( function() {
  app.use( express.logger( CONFIG.logger ) )
    .use( express.static( WWW_ROOT, JSON.parse( JSON.stringify( CONFIG.staticMiddleware ) ) ) )
    .use( express.bodyParser() )
    .use( clientSessions( CONFIG.session ) )
    .use( express.csrf() )
    /* Show Zeus who's boss
     * This only affects requests under /api and /persona, not static files
     * because the static file writes the response header before we hit this middleware
     */
    .use( function( req, res, next ) {
      res.header( 'Cache-Control', 'no-store' );
      return next();
    })
    .set('view options', {layout: false});

  // File Store types and options come from JSON config file.
  stores.publish = setupStore( CONFIG.publishStore );
  stores.crash = setupStore( CONFIG.crashStore );
  stores.feedback = setupStore( CONFIG.feedbackStore );
  stores.images = setupStore( CONFIG.imageStore );

  utils = require( './lib/utils' )({
    EMBED_HOSTNAME: CONFIG.dirs.embedHostname ? stripSlash( CONFIG.dirs.embedHostname ) : APP_HOSTNAME,
    EMBED_SUFFIX: '_'
  }, stores );
});

require( 'express-persona' )( app, {
  audience: CONFIG.dirs.appHostname
});

require('./routes')( app, User, filter, sanitizer, stores, utils );

function writeEmbedShell( path, url, data, callback ) {
  if( !writeEmbedShell.templateFn ) {
    writeEmbedShell.templateFn = jade.compile( fs.readFileSync( 'views/embed-shell.jade', 'utf8' ),
                                          { filename: 'embed-shell.jade', pretty: true } );
  }

  stores.publish.write( path, writeEmbedShell.templateFn( data ), callback );
}

function writeEmbed( path, url, data, callback ) {
  if( !writeEmbed.templateFn ) {
    writeEmbed.templateFn = jade.compile( fs.readFileSync( 'views/embed.jade', 'utf8' ),
                                          { filename: 'embed.jade', pretty: true, debug: true } );
    console.log( writeEmbed.templateFn );
  }
console.log( writeEmbed.templateFn( data ) );
  stores.publish.write( path, writeEmbed.templateFn( data ), callback );
}

app.post( '/api/publish/:id',
  filter.isLoggedIn, filter.isStorageAvailable,
  function publishRoute( req, res ) {

  var email = req.session.email,
      id = parseInt( req.params.id, 10 );

  if ( isNaN( id ) ) {
    res.json( { error: "ID was not a number" }, 500 );
    return;
  }

  User.findProject( email, id, function( err, project ) {
    if ( err ) {
      res.json( { error: err }, 500);
      return;
    }

    if ( !project ) {
      res.json( { error: 'project not found' }, 404);
      return;
    }

    var i = 0,
        template = project.template;

    if( !( template && VALID_TEMPLATES[ template ] ) ) {
      res.json({ error: 'template not found' }, 500);
      return;
    }

    var projectData = JSON.parse( project.data, sanitizer.escapeHTMLinJSON ),
        templateConfig = templateConfigs[ template ],
        templateFile = templateConfig.template,
        baseHref;

    fs.readFile( templateFile, 'utf8', function( err, data ){
      if ( err ) {
        res.json( { error: 'error reading template file' }, 500 );
        return;
      }

      var headEndTagIndex,
          bodyEndTagIndex,
          externalAssetsString = '',
          popcornString = '',
          currentMedia,
          currentTrack,
          currentTrackEvent,
          mediaPopcornOptions,
          templateURL,
          baseString,
          headStartTagIndex,
          templateScripts,
          startString,
          numSources,
          j, k, len;

      templateURL = templateFile.substring( templateFile.indexOf( '/templates' ), templateFile.lastIndexOf( '/' ) );
      baseHref = APP_HOSTNAME + templateURL + "/";
      baseString = '\n  <base href="' + baseHref + '"/>';

      // look for script tags with data-butter-exclude in particular (e.g. butter's js script)
      data = data.replace( /\s*\n';
      }

      // If the template has custom plugins defined in it's config, add them to our exported page
      if ( templateConfig.plugin && templateConfig.plugin.plugins ) {
        var plugins = templateConfig.plugin.plugins;
        for ( i = 0, len = plugins.length; i < len; i++ ) {
          externalAssetsString += '\n  ';
        }
        externalAssetsString += '\n';
      }

      popcornString += '\n';

      data = startString + baseString + templateScripts + externalAssetsString +
             data.substring( headEndTagIndex, bodyEndTagIndex ) +
             popcornString + data.substring( bodyEndTagIndex );

      // Convert 1234567890 => "kf12oi"
      var idBase36 = utils.generateIdString( id ),
          publishUrl = utils.generatePublishUrl( id ),
          iframeUrl = utils.generateIframeUrl( id );

      function finished( err ) {
        if ( err ) {
          res.json({ error: 'internal server error' }, 500);
        } else {
          res.json({ error: 'okay', publishUrl: publishUrl, iframeUrl: iframeUrl });
        }
      }

      function publishEmbedShell() {
        // Write out embed shell HTML
        writeEmbedShell( idBase36, publishUrl,
                         {
                           author: project.author,
                           projectName: project.name,
                           embedShellSrc: publishUrl,
                           embedSrc: iframeUrl,
                           baseHref: APP_HOSTNAME
                         },
                         finished );
      }

      // This is a query string-only URL because of the <base> tag
      var remixUrl = "?savedDataUrl=/api/remix/" + project.id,
          mediaUrl = projectData.media[ 0 ].url,
          attribURL = Array.isArray( mediaUrl ) ? mediaUrl[ 0 ] : mediaUrl;

      writeEmbed( idBase36 + utils.constants().EMBED_SUFFIX, iframeUrl,
                  {
                    id: id,
                    author: project.author,
                    title: project.name,
                    mediaSrc: attribURL,
                    embedShellSrc: publishUrl,
                    baseHref: baseHref,
                    remixUrl: remixUrl,
                    templateScripts: templateScripts,
                    externalAssets: externalAssetsString,
                    // XXX: need a better way to wrap function, DOM needs to be ready
                    popcorn: popcornString.replace( /^\(function\(\)\{/m, "Popcorn( function(){" )
                                          .replace( /\}\(\)\);$/m, "});" )
                  },
                  publishEmbedShell );

    });
  });
});

app.get( '/dashboard', filter.isStorageAvailable, function( req, res ) {
  var email = req.session.email;

  if ( !email ) {
    res.render( 'dashboard-unauthorized.jade' );
    return;
  }

  User.findAllProjects( email, function( err, docs ) {
    var userProjects = [];

    docs.forEach( function( project ) {
      if ( project.template && VALID_TEMPLATES[ project.template ] ) {
        userProjects.push({
          // make sure _id is a string. saw some strange double-quotes on output otherwise
          _id: String(project.id),
          name: sanitizer.escapeHTML( project.name ),
          template: project.template,
          href: path.relative( WWW_ROOT, templateConfigs[ project.template ].template ) +
            "?savedDataUrl=/api/project/" + project.id,
          updatedAt: project.updatedAt
        });
      }
    });

    userProjects.sort( function( a, b ) {
      var aDate = Date.parse( a.updatedAt ),
          bDate = Date.parse( b.updatedAt );

      if ( aDate < bDate ) {
        return 1;
      }

      if ( aDate > bDate ) {
        return -1;
      }

      return 0;
    });

    res.render( 'dashboard.jade', {
      user: {
        csrf: req.session._csrf,
        email: email
      },
      projects: userProjects
    });
  });
});

var port = process.env.PORT || CONFIG.server.bindPort;

app.listen(port, CONFIG.server.bindIP, function() {
  var addy = app.address();
  console.log('HTTP Server started on http://' + CONFIG.server.bindIP + ':' + addy.port);
  console.log('Press Ctrl+C to stop');
});
<commit_msg>Revert "Bug 2929 - Add debug information for jade output"<commit_after>/*jshint eqeqeq:false */
console.log( __dirname );

// Given foo/ return foo
function stripSlash( path ) {
  return path.replace( /\/$/, '' );
}

var express = require('express'),
    fs = require('fs'),
    path = require('path'),
    jade = require('jade'),
    app = express.createServer(),
    clientSessions = require('client-sessions'),
    lessMiddleware = require('less-middleware'),
    CONFIG = require('config'),
    User = require( './lib/user' )( CONFIG.database ),
    filter = require( './lib/filter' )( User.isDBOnline ),
    sanitizer = require( './lib/sanitizer' ),
    FileStore = require('./lib/file-store.js'),
    utils,
    stores = {},
    TEMPLATES_DIR = CONFIG.dirs.templates,
    APP_HOSTNAME = stripSlash( CONFIG.dirs.appHostname ),
    // If a separate hostname is given for embed, use it, otherwise use app's hostname
    WWW_ROOT = path.resolve( CONFIG.dirs.wwwRoot || path.join( __dirname, ".." ) ),
    VALID_TEMPLATES = CONFIG.templates,
    EXPORT_ASSETS = CONFIG.exportAssets;

var templateConfigs = {};

function readTemplateConfig( templateName, templatedPath ) {
  var configPath = templatedPath.replace( '{{templateBase}}', TEMPLATES_DIR + '/' );
  fs.readFile( configPath, 'utf8', function( err, conf ) {
    var configPathBase = configPath.substring( 0, configPath.lastIndexOf( '/' ) );
    conf = JSON.parse( conf );
    conf.template = configPathBase + '/' + conf.template;
    templateConfigs[ templateName ] = conf;
  });
}

// parse configs ahead of any action that has to happen with them
for ( var templateName in VALID_TEMPLATES ) {
  if ( VALID_TEMPLATES.hasOwnProperty( templateName ) ) {
    readTemplateConfig( templateName, VALID_TEMPLATES[ templateName ] );
  }
}

console.log( "Templates Dir:", TEMPLATES_DIR );

app.configure( 'development', function() {
  app.use( lessMiddleware( WWW_ROOT ));
  CONFIG.additionalStaticRoots.forEach( function( dir ) {
    app.use( express.static( dir ) );
  });
});

function setupStore( config ) {
  var store = FileStore.create( config.type, config.options );
  if( store.requiresFileSystem ) {
    app.use( express.static( store.root, JSON.parse( JSON.stringify( CONFIG.staticMiddleware ) ) ) );
  }
  return store;
}

app.configure( function() {
  app.use( express.logger( CONFIG.logger ) )
    .use( express.static( WWW_ROOT, JSON.parse( JSON.stringify( CONFIG.staticMiddleware ) ) ) )
    .use( express.bodyParser() )
    .use( clientSessions( CONFIG.session ) )
    .use( express.csrf() )
    /* Show Zeus who's boss
     * This only affects requests under /api and /persona, not static files
     * because the static file writes the response header before we hit this middleware
     */
    .use( function( req, res, next ) {
      res.header( 'Cache-Control', 'no-store' );
      return next();
    })
    .set('view options', {layout: false});

  // File Store types and options come from JSON config file.
  stores.publish = setupStore( CONFIG.publishStore );
  stores.crash = setupStore( CONFIG.crashStore );
  stores.feedback = setupStore( CONFIG.feedbackStore );
  stores.images = setupStore( CONFIG.imageStore );

  utils = require( './lib/utils' )({
    EMBED_HOSTNAME: CONFIG.dirs.embedHostname ? stripSlash( CONFIG.dirs.embedHostname ) : APP_HOSTNAME,
    EMBED_SUFFIX: '_'
  }, stores );
});

require( 'express-persona' )( app, {
  audience: CONFIG.dirs.appHostname
});

require('./routes')( app, User, filter, sanitizer, stores, utils );

function writeEmbedShell( path, url, data, callback ) {
  if( !writeEmbedShell.templateFn ) {
    writeEmbedShell.templateFn = jade.compile( fs.readFileSync( 'views/embed-shell.jade', 'utf8' ),
                                          { filename: 'embed-shell.jade', pretty: true } );
  }

  stores.publish.write( path, writeEmbedShell.templateFn( data ), callback );
}

function writeEmbed( path, url, data, callback ) {
  if( !writeEmbed.templateFn ) {
    writeEmbed.templateFn = jade.compile( fs.readFileSync( 'views/embed.jade', 'utf8' ),
                                          { filename: 'embed.jade', pretty: true } );
  }

  stores.publish.write( path, writeEmbed.templateFn( data ), callback );
}

app.post( '/api/publish/:id',
  filter.isLoggedIn, filter.isStorageAvailable,
  function publishRoute( req, res ) {

  var email = req.session.email,
      id = parseInt( req.params.id, 10 );

  if ( isNaN( id ) ) {
    res.json( { error: "ID was not a number" }, 500 );
    return;
  }

  User.findProject( email, id, function( err, project ) {
    if ( err ) {
      res.json( { error: err }, 500);
      return;
    }

    if ( !project ) {
      res.json( { error: 'project not found' }, 404);
      return;
    }

    var i = 0,
        template = project.template;

    if( !( template && VALID_TEMPLATES[ template ] ) ) {
      res.json({ error: 'template not found' }, 500);
      return;
    }

    var projectData = JSON.parse( project.data, sanitizer.escapeHTMLinJSON ),
        templateConfig = templateConfigs[ template ],
        templateFile = templateConfig.template,
        baseHref;

    fs.readFile( templateFile, 'utf8', function( err, data ){
      if ( err ) {
        res.json( { error: 'error reading template file' }, 500 );
        return;
      }

      var headEndTagIndex,
          bodyEndTagIndex,
          externalAssetsString = '',
          popcornString = '',
          currentMedia,
          currentTrack,
          currentTrackEvent,
          mediaPopcornOptions,
          templateURL,
          baseString,
          headStartTagIndex,
          templateScripts,
          startString,
          numSources,
          j, k, len;

      templateURL = templateFile.substring( templateFile.indexOf( '/templates' ), templateFile.lastIndexOf( '/' ) );
      baseHref = APP_HOSTNAME + templateURL + "/";
      baseString = '\n  <base href="' + baseHref + '"/>';

      // look for script tags with data-butter-exclude in particular (e.g. butter's js script)
      data = data.replace( /\s*\n';
      }

      // If the template has custom plugins defined in it's config, add them to our exported page
      if ( templateConfig.plugin && templateConfig.plugin.plugins ) {
        var plugins = templateConfig.plugin.plugins;
        for ( i = 0, len = plugins.length; i < len; i++ ) {
          externalAssetsString += '\n  ';
        }
        externalAssetsString += '\n';
      }

      popcornString += '\n';

      data = startString + baseString + templateScripts + externalAssetsString +
             data.substring( headEndTagIndex, bodyEndTagIndex ) +
             popcornString + data.substring( bodyEndTagIndex );

      // Convert 1234567890 => "kf12oi"
      var idBase36 = utils.generateIdString( id ),
          publishUrl = utils.generatePublishUrl( id ),
          iframeUrl = utils.generateIframeUrl( id );

      function finished( err ) {
        if ( err ) {
          res.json({ error: 'internal server error' }, 500);
        } else {
          res.json({ error: 'okay', publishUrl: publishUrl, iframeUrl: iframeUrl });
        }
      }

      function publishEmbedShell() {
        // Write out embed shell HTML
        writeEmbedShell( idBase36, publishUrl,
                         {
                           author: project.author,
                           projectName: project.name,
                           embedShellSrc: publishUrl,
                           embedSrc: iframeUrl,
                           baseHref: APP_HOSTNAME
                         },
                         finished );
      }

      // This is a query string-only URL because of the <base> tag
      var remixUrl = "?savedDataUrl=/api/remix/" + project.id,
          mediaUrl = projectData.media[ 0 ].url,
          attribURL = Array.isArray( mediaUrl ) ? mediaUrl[ 0 ] : mediaUrl;

      writeEmbed( idBase36 + utils.constants().EMBED_SUFFIX, iframeUrl,
                  {
                    id: id,
                    author: project.author,
                    title: project.name,
                    mediaSrc: attribURL,
                    embedShellSrc: publishUrl,
                    baseHref: baseHref,
                    remixUrl: remixUrl,
                    templateScripts: templateScripts,
                    externalAssets: externalAssetsString,
                    // XXX: need a better way to wrap function, DOM needs to be ready
                    popcorn: popcornString.replace( /^\(function\(\)\{/m, "Popcorn( function(){" )
                                          .replace( /\}\(\)\);$/m, "});" )
                  },
                  publishEmbedShell );

    });
  });
});

app.get( '/dashboard', filter.isStorageAvailable, function( req, res ) {
  var email = req.session.email;

  if ( !email ) {
    res.render( 'dashboard-unauthorized.jade' );
    return;
  }

  User.findAllProjects( email, function( err, docs ) {
    var userProjects = [];

    docs.forEach( function( project ) {
      if ( project.template && VALID_TEMPLATES[ project.template ] ) {
        userProjects.push({
          // make sure _id is a string. saw some strange double-quotes on output otherwise
          _id: String(project.id),
          name: sanitizer.escapeHTML( project.name ),
          template: project.template,
          href: path.relative( WWW_ROOT, templateConfigs[ project.template ].template ) +
            "?savedDataUrl=/api/project/" + project.id,
          updatedAt: project.updatedAt
        });
      }
    });

    userProjects.sort( function( a, b ) {
      var aDate = Date.parse( a.updatedAt ),
          bDate = Date.parse( b.updatedAt );

      if ( aDate < bDate ) {
        return 1;
      }

      if ( aDate > bDate ) {
        return -1;
      }

      return 0;
    });

    res.render( 'dashboard.jade', {
      user: {
        csrf: req.session._csrf,
        email: email
      },
      projects: userProjects
    });
  });
});

var port = process.env.PORT || CONFIG.server.bindPort;

app.listen(port, CONFIG.server.bindIP, function() {
  var addy = app.address();
  console.log('HTTP Server started on http://' + CONFIG.server.bindIP + ':' + addy.port);
  console.log('Press Ctrl+C to stop');
});
<|endoftext|>


<commit_before>reportTypes = [
  {name: 'Opóźnienie'},
  {name: 'Pociąg zbyt zatłoczony, żeby wejść'},
  {name: 'Zatłoczona stacja'},
  {name: 'Zatłoczony pociąg'},
  {name: 'Pociąg stoi przed stacją'},
  {name: 'Uszkodzony pociąg'},
  {name: 'Akcja pogotowia medycznego'},
  {name: 'Akcja policji'},
  {name: 'Wszystko OK'}
];
<commit_msg>reorder report types<commit_after>reportTypes = [
  {name: 'Opóźnienie'},
  {name: 'Pociąg stoi przed stacją'},
  {name: 'Pociąg zbyt zatłoczony, żeby wejść'},
  {name: 'Zatłoczony pociąg'},
  {name: 'Zatłoczona stacja'},
  {name: 'Uszkodzony pociąg'},
  {name: 'Akcja pogotowia medycznego'},
  {name: 'Akcja policji'},
  {name: 'Wszystko OK'}
];
<|endoftext|>


<commit_before>"use strict";

apingApp.config(['$provide', function ($provide) {

    "use strict";
    apingApp.config(['$provide', function ($provide) {

        $provide.constant("apingApiKeys", {
            youtube : [
                {'apiKey':'<YOUR_YOUTUBE_API_KEY>'}
            ],
            instagram: [
                {'access_token':'<YOUR_INSTAGRAM_TOKEN>'}
            ],
            facebook: [
                {'access_token':'<YOUR_FACEBOOK_TOKEN>'}
            ],
            twitter: [
                {'bearer_token':'<YOUR_TWITTER_BEARER_TOKEN>'}
            ],
            vimeo: [
                {'access_token':'<YOUR_VIMEO_TOKEN>'}
            ],
        });

        $provide.constant("apingDefaultSettings", {
            templateUrl : "<PATH_TO_YOUR_DEFAULT_DESIGN>",
            items : 20, //items per request
            maxItems: 100, //max items per aping
            orderBy : "timestamp",
            orderReverse : "true",
            model: "social",
        });

    }]);

    $provide.constant("apingDefaultSettings", {
        templateUrl : "../src/aping_design_sample.html",
        items : 20, //items per request
        maxItems: 100, //max items per aping
        orderBy : "timestamp",
        orderReverse : "true",
        model: "social",
    });

}]);<commit_msg>impr: new apiKey mechanism<commit_after>"use strict";

apingApp.config(['$provide', function ($provide) {

    $provide.constant("apingApiKeys", {
        youtube : [
            {'apiKey':'<YOUR_YOUTUBE_API_KEY>'}
        ],
        instagram: [
            {'access_token':'<YOUR_INSTAGRAM_TOKEN>'}
        ],
        facebook: [
            {'access_token':'<YOUR_FACEBOOK_TOKEN>'}
        ],
        twitter: [
            {'bearer_token':'<YOUR_TWITTER_BEARER_TOKEN>'}
        ],
        vimeo: [
            {'access_token':'<YOUR_VIMEO_TOKEN>'}
        ],
    });

    $provide.constant("apingDefaultSettings", {
        templateUrl : "../src/aping_design_sample.html",
        items : 20, //items per request
        maxItems: 100, //max items per aping
        orderBy : "timestamp",
        orderReverse : "true",
        model: "social",
    });

}]);<|endoftext|>


<commit_before>module.exports = {
  "extends": "chiton/configurations/default",
  "env": {
    "node": true
  },
  "rules": {
    "callback-return": 2,
    "handle-callback-err": 2,
    "no-mixed-requires": 2,
    "no-new-require": 2,
    "no-path-concat": 2
  }
};
<commit_msg>Allow the use of arrow functions in Node<commit_after>module.exports = {
  "extends": "chiton/configurations/default",
  "env": {
    "node": true
  },
  "ecmaFeatures": {
    "arrowFunctions": true
  },
  "rules": {
    "arrow-body-style": [2, "as-needed"],
    "arrow-parens": [2, "as-needed"],
    "arrow-spacing": [2, {"after": true, "before": true}],
    "callback-return": 2,
    "handle-callback-err": 2,
    "no-arrow-condition": 2,
    "no-mixed-requires": 2,
    "no-new-require": 2,
    "no-path-concat": 2
  }
};
<|endoftext|>


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

var accountsDB = levelup('./accounts_db', {
    keyEncoding: 'utf-8',
    valueEncoding: 'json',
});

exports.createAccount = function (account) {
    accountsDB.put(account.name, account);
}

exports.getAccount = function (name, callback) {
    accountsDB.get(name, function (err, value) {
        if (err) {
            if (err.notFound) {
                callback(null, null);
            } else {
                callback(err, null);
            }
        } else {
            callback(null, value);
        }
    });
}

exports.getAccountsPublic = function (callback) {
    var accounts = [];
    accountsDB.createValueStream()
        .on('data', function (value) {
            accounts.push({
                'name': value.name
            });
        })
        .on('end', function () {
            callback(accounts);
        });
}
<commit_msg>Retrieve address of accounts<commit_after>var levelup = require('levelup');

var accountsDB = levelup('./accounts_db', {
    keyEncoding: 'utf-8',
    valueEncoding: 'json',
});

exports.createAccount = function (account) {
    accountsDB.put(account.name, account);
}

exports.getAccount = function (name, callback) {
    accountsDB.get(name, function (err, value) {
        if (err) {
            if (err.notFound) {
                callback(null, null);
            } else {
                callback(err, null);
            }
        } else {
            callback(null, value);
        }
    });
}

exports.getAccountsPublic = function (callback) {
    var accounts = [];
    accountsDB.createValueStream()
        .on('data', function (value) {
            accounts.push({
                'name': value.name,
                'address': value.address
            });
        })
        .on('end', function () {
            callback(accounts);
        });
}
<|endoftext|>


<commit_before>
include('helma/webapp/util');
include('io');
include("binary");

export('handleRequest', 'commitResponse');

module.shared = true;

/**
 * Handle a JSGI request.
 * @param module the module. Ignored if func is already a function.
 * @param func the function, either as function object or function name to be
 *             imported from module.
 * @param env the JSGI env object
 * @returns the JSGI response object
 */
function handleRequest(module, func, env) {
    initRequest(env);
    var app;
    if (typeof(func) == 'function') {
        app = func;
    } else {
        module = require(module);
        app = module[func];
        var middleware = module.middleware || [];
        app = middleware.reduceRight(middlewareWrapper, resolve(app));
    }
    if (!(typeof(app) == 'function')) {
        throw new Error('No valid JSGI app: ' + app);
    }
    var result = app(env);
    commitResponse(env, result);
}

/**
 * Set up the I/O related properties of a jsgi environment object.
 * @param env a jsgi request object
 */
function initRequest(env) {
    var input, errors;
    if (env.hasOwnProperty('jsgi.input')) {
        // already set up, probably because the original request threw a retry
        return;
    }
    Object.defineProperty(env, "jsgi.input", {
        get: function() {
            if (!input)
                input = new Stream(env['jsgi.servlet_request'].getInputStream());
            return input;
        }
    });
    Object.defineProperty(env, "jsgi.errors", {
        get: function() {
            if (!errors)
                errors = new Stream(java.lang.System.err);
            return errors;
        }
    });
}

/**
 * Apply the return value of a JSGI application to a servlet response.
 * This is used internally by the org.helma.jsgi.JsgiServlet class, so
 * you won't need this unless you're implementing your own servlet
 * based JSGI connector.
 *
 * @param env the JSGI env argument
 * @param result the object returned by a JSGI application
 */
function commitResponse(env, result) {
    var response = env['jsgi.servlet_response'];
    if (response.isCommitted()) {
        return;
    }
    if (!result) {
        throw new Error('No valid JSGI response: ' + result);
    }
    if (typeof result.then === "function") {
        // experimental support for asynchronous JSGI based on Jetty continuations
        var ContinuationSupport = org.mortbay.util.ajax.ContinuationSupport;
        var request = env['jsgi.servlet_request'];
        var continuation = ContinuationSupport.getContinuation(request, {});
        var handled = false;
        result.then(function(res) {
            if (continuation.isPending()) {
                request.setAttribute('_helma_response', res);
                continuation.resume();
            } else {
                commitResponse(env, res);
                handled = true;
            }
        });
        if (!handled) {
            continuation.suspend(30000);
        }
        return;
    }
    if (!result.status || !result.headers || !result.body) {
        throw new Error('No valid JSGI response: ' + result);
    }
    if (!result) {
        throw new Error("JSGI app did not return a response object");
    }
    if (typeof result.close == "function") {
        result = result.close();
    }
    var {status, headers, body} = result;
    response.status = status;
    for (var name in headers) {
        response.setHeader(name, headers[name]);
    }
    var charset = getMimeParameter(Headers(headers).get("Content-Type"), "charset") || "UTF-8";
    var output = response.getOutputStream();
    if (body && typeof body.forEach == "function") {
        var writer = function(part) {
            if (!(part instanceof Binary)) {
                part = part.toByteString(charset);
            }
            output.write(part);
        };
        body.forEach(writer);
        if (typeof body.close == "function") {
            body.close(writer);
        }
    } else {
        throw new Error("Response body doesn't implement forEach: " + body);
    }
    output.close();
}

/**
 * Convenience function that resolves a module id or object to a
 * JSGI middleware or application function. This assumes the function is
 * exported as "middleware" or "handleRequest".
 * @param module a function, module object, or moudule id
 */
function resolve(module) {
    if (typeof module == 'string') {
        module = require(module);
        return module.middleware || module.handleRequest;
    }
    return module;
}

/**
 * Helper function for wrapping middleware stacks
 * @param inner an app or middleware module or function wrapped by outer
 * @param outer a middleware module or function wrapping inner
 */
function middlewareWrapper(inner, outer) {
    return resolve(outer)(inner);
}
<commit_msg>Whitespace police<commit_after>
include('helma/webapp/util');
include('io');
include("binary");

export('handleRequest', 'commitResponse');

module.shared = true;

/**
 * Handle a JSGI request.
 * @param module the module. Ignored if func is already a function.
 * @param func the function, either as function object or function name to be
 *             imported from module.
 * @param env the JSGI env object
 * @returns the JSGI response object
 */
function handleRequest(module, func, env) {
    initRequest(env);
    var app;
    if (typeof(func) == 'function') {
        app = func;
    } else {
        module = require(module);
        app = module[func];
        var middleware = module.middleware || [];
        app = middleware.reduceRight(middlewareWrapper, resolve(app));
    }
    if (!(typeof(app) == 'function')) {
        throw new Error('No valid JSGI app: ' + app);
    }
    var result = app(env);
    commitResponse(env, result);
}

/**
 * Set up the I/O related properties of a jsgi environment object.
 * @param env a jsgi request object
 */
function initRequest(env) {
    var input, errors;
    if (env.hasOwnProperty('jsgi.input')) {
        // already set up, probably because the original request threw a retry
        return;
    }
    Object.defineProperty(env, "jsgi.input", {
        get: function() {
            if (!input)
                input = new Stream(env['jsgi.servlet_request'].getInputStream());
            return input;
        }
    });
    Object.defineProperty(env, "jsgi.errors", {
        get: function() {
            if (!errors)
                errors = new Stream(java.lang.System.err);
            return errors;
        }
    });
}

/**
 * Apply the return value of a JSGI application to a servlet response.
 * This is used internally by the org.helma.jsgi.JsgiServlet class, so
 * you won't need this unless you're implementing your own servlet
 * based JSGI connector.
 *
 * @param env the JSGI env argument
 * @param result the object returned by a JSGI application
 */
function commitResponse(env, result) {
    var response = env['jsgi.servlet_response'];
    if (response.isCommitted()) {
        return;
    }
    if (!result) {
        throw new Error('No valid JSGI response: ' + result);
    }
    if (typeof result.then === "function") {
        // experimental support for asynchronous JSGI based on Jetty continuations
        var ContinuationSupport = org.mortbay.util.ajax.ContinuationSupport;
        var request = env['jsgi.servlet_request'];
        var continuation = ContinuationSupport.getContinuation(request, {});
        var handled = false;
        result.then(function(res) {
            if (continuation.isPending()) {
                request.setAttribute('_helma_response', res);
                continuation.resume();
            } else {
                commitResponse(env, res);
                handled = true;
            }
        });
        if (!handled) {
            continuation.suspend(30000);
        }
        return;
    }
    if (!result.status || !result.headers || !result.body) {
        throw new Error('No valid JSGI response: ' + result);
    }
    if (!result) {
        throw new Error("JSGI app did not return a response object");
    }
    if (typeof result.close == "function") {
        result = result.close();
    }
    var {status, headers, body} = result;
    response.status = status;
    for (var name in headers) {
        response.setHeader(name, headers[name]);
    }
    var charset = getMimeParameter(Headers(headers).get("Content-Type"), "charset") || "UTF-8";
    var output = response.getOutputStream();
    if (body && typeof body.forEach == "function") {
        var writer = function(part) {
            if (!(part instanceof Binary)) {
                part = part.toByteString(charset);
            }
            output.write(part);
        };
        body.forEach(writer);
        if (typeof body.close == "function") {
            body.close(writer);
        }
    } else {
        throw new Error("Response body doesn't implement forEach: " + body);
    }
    output.close();
}

/**
 * Convenience function that resolves a module id or object to a
 * JSGI middleware or application function. This assumes the function is
 * exported as "middleware" or "handleRequest".
 * @param module a function, module object, or moudule id
 */
function resolve(module) {
    if (typeof module == 'string') {
        module = require(module);
        return module.middleware || module.handleRequest;
    }
    return module;
}

/**
 * Helper function for wrapping middleware stacks
 * @param inner an app or middleware module or function wrapped by outer
 * @param outer a middleware module or function wrapping inner
 */
function middlewareWrapper(inner, outer) {
    return resolve(outer)(inner);
}
<|endoftext|>