Example #1
0
 this.getAll(function(err, items) {
   if (err) cb(err); else {
     cb(null, _.filter(items, iterator));
   }
 });
Example #2
0
    if (keys) {
        req = _.extend(req, {
            type: 'POST',
            processData: false,
            contentType: 'application/json',
            data: JSON.stringify({ keys: keys })
        });
    } else {
        req = _.extend(req, {
            type: 'GET'
        });
    }

    exports.request(req, callback);
};


/**
 * DB methods can only be called client-side
 */

_.each(_.keys(DB.prototype), function (k) {
    var _fn = DB.prototype[k];
    DB.prototype[k] = function () {
        if (!isBrowser()) {
            throw new Error(k + ' cannot be called server-side');
        }
        return _fn.apply(this, arguments);
    };
});
Example #3
0
 function(fpaths, next) {
   next(null, _.map(fpaths, function(fpath) { return rname + '.' + fpath; }));
 }
Example #4
0
module.exports = function expectConfig(config, debug) {
    var lines = [];

    if (!config.hosts[config.main]) {
        throw new Error('Configuration does not contain information about host "' + config.main + '"');
    }

    if (!debug) {
        lines.push('log_user 0');
    }

    if (config.vpncConfig) {
        lines.push('spawn sudo vpnc ' + config.vpncConfig);
        lines.push('interact');
    }

    if (debug) {
        lines.push('spawn ssh -v -F ' + config.sshConfig + ' ' + config.main);
    } else {
        lines.push('spawn ssh -F ' + config.sshConfig + ' ' + config.main);
    }

    lines.push('expect {');
    _.each(config.hosts, function (c, name) {
        if (c.user && c.password) {
            lines.push('  # ' + name);
            lines.push('  "' + c.user + '@' + c.addr + '" {');
            lines.push('    send "' + c.password + '\\n";');
            lines.push('    exp_continue;');
            lines.push('  }');

            if (name === config.main) {
                lines.push('  # ' + name + ' as only host');
                lines.push('  "Password: "******"' + c.password + '\\n";');
                lines.push('    exp_continue;');
                lines.push('  }');
            }
        }
    });

    lines.push('  -re "(%|\\\\$|#|>) ?$" {');
    lines.push('    send_user "\\nThe login sequence seems to have worked.\\n\\n";');
    if (config.forwards) {
        lines.push('    send_user "The following forwardings have been set up for you:\\n\\n";');
        _.each(config.forwards, function (fs, descr) {
            lines.push('    send_user "' + descr + ':\\n";');
            fs.forEach(function (f) {
                lines.push('    send_user "   ' + f.from + ' -> ' + f.to + '\\n";');
            });
            lines.push('    send_user "\\n";');
        });
    }
    lines.push('    send "\\r";');
    lines.push('    interact;');
    lines.push('  }');
    lines.push('  "Permission denied" {');
    lines.push('    send_user "Permission denied, failed to set up tunneling.\n";');
    lines.push('    exit 2;');
    lines.push('  }');
    lines.push('  timeout {');
    lines.push('    send_user "Unknown error, failed to set up tunneling.\n";');
    lines.push('    exit 2;');
    lines.push('  }');
    lines.push('}');

    return lines.join('\n') + '\n';
};
Example #5
0
function cleanstr(str)
{
	var str1 = str.split(" ")
	str1 = _.filter(str1, function(num){ return (num.indexOf("-")==-1 && num.indexOf("\\")==-1) });
	return str1.join(" ")
}
Example #6
0
exports.parseRaw = function (fields, raw, root, path) {
    var doc = {};
    path = path || [];
    root = root || doc;
    raw = raw || {};
    var fields_module = require('./fields');

    for (var k in fields) {
        var f = fields[k];
        var f_path = path.concat([k]);
        var r = raw[k];

        if (f instanceof fields_module.AttachmentField) {
            if (typeof r === 'string' && r !== '') {
                r = JSON.parse(r);
            }
            else {
                r = {};
            }
            var att = {};
            for (var rk in r) {
                att[f_path.join('/') + '/' + rk] = r[rk];
            }
            if (!root._attachments) {
                root._attachments = {};
            }
            _.extend(root._attachments, att);
        }
        else if (f instanceof fields_module.Field) {
            if (!f.isEmpty(r)) {
                doc[k] = f.parse(r);
            }
            else if (!f.omit_empty) {
                doc[k] = undefined;
            }
        }
        else if (f instanceof fields_module.Embedded) {
            if (!f.isEmpty(r)) {
                if (typeof r === 'string') {
                    if (r !== '') {
                        r = JSON.parse(r);
                    } else {
                        r = {};
                    }
                }
                doc[k] = exports.parseRaw(f.type.fields, r, root, f_path);
            }
        }
        else if (f instanceof fields_module.EmbeddedList) {
            doc[k] = [];
            if (!f.isEmpty(r)) {
                for (var i in r) {
                    if (typeof r[i] === 'string') {
                        if (r[i] !== '') {
                            r[i] = JSON.parse(r[i]);
                        } else {
                            r[i] = {};
                        }
                    }
                    doc[k][i] = exports.parseRaw(
                        f.type.fields, r[i], root, f_path.concat([i])
                    );
                }
            }
            if (!doc[k].length && f.omit_empty) {
                delete doc[k];
            }
        }
        else if (f instanceof Object) {
            doc[k] = exports.parseRaw(f, r, root, f_path);
        } else {
            throw new Error(
                'The field type `' + (typeof f) + '` is not supported.'
            );
        }
    }
    return doc;
};
Example #7
0
  
  K.tests = _.clone(tests);
  for (var t in K.tests) {
    K.testCurrent = t;
    try {
      if (typeof test === 'function') test.call(K);
    } catch (err) {
      
      
    }
  }
  
  var out = [];
  for (var t in tests) {
    
    out.push('<li class="'+typeof K.tests[t]+' '+ (K.tests[t] && typeof K.tests[t] != 'function' ? 'success' : 'error') +'">'+ t +' <pre>'+ tests[t].toString() +'</pre></li>');
  }
  
  delete K.tests;
  delete K.testCurrent;
  
  out.unshift('<ul>');
  out.push('</ul>');
  if (typeof cb == 'function') return cb.call(K, out.join("\n"));
  return out.join("\n");
};

//

_.extend(exports, sys);
Example #8
0
exports.bulkGet = function (keys, /*optional*/ q,
                            /*optional*/ options, callback) {
    var url;

    if (!utils.isBrowser()) {
        throw new Error(
            'bulkGet cannot be called server-side'
        );
    }
    if (keys && !_.isArray(keys)) {
        throw new Error(
            'bulkGet requires that _id values be supplied as a list'
        );
    }
    if (!callback) {
        if (!options) {
            /* Arity = 2: Omits q, options */
            callback = q;
            options = {};
            q = {};
        } else {
          /* Arity = 3: Omits options */
            callback = options;
            options = {};
        }
    }
    if (options.db) {
        /* Force leading slash; make absolute path */
        url = (options.db.substr(0, 1) !== '/' ? '/' : '') + options.db;
    } else {
        url = utils.getBaseURL() + '/_db';
    }

    /* Encode every query-string option:
        CouchDB requires that these be JSON, even though they
        will be URL-encoded as part of the request process. */

    for (var k in q) {
        q[k] = JSON.stringify(q[k]);
    }

    /* Make request:
        If we have a list of keys, use a post request containing
        a JSON-encoded list of keys. Otherwise, use a get request. */

    var req = {
        expect_json: true,
        url: url + '/_all_docs' + sanitize.url(q)
    };
    if (keys) {
        req = _.extend(req, {
            type: 'POST',
            processData: false,
            contentType: 'application/json',
            data: JSON.stringify({ keys: keys })
        });
    } else {
        req = _.extend(req, {
            type: 'GET'
        });
    }

    core.request(req, callback);
};
Example #9
0
(function() {

if (typeof module !== 'undefined' && module.exports) {
  var _ = require('underscore')._;
  _.mixin(require('underscore.string'));
  String.prototype.humanize = function() {
    return _(this).underscored().replace('_', ' ');
  }
  exports.newErrors = newErrors; 
  exports.validate = validate;
} else {
  var _ = this._;
  this.newErrors = newErrors;
  this.validate = validate;
}


var globalDefaultMessages = {
  required: "{{name}} is required.",
  length: {
    is: "{{name}} must be exactly {{compare_to}} characters.",
    min: "{{name}} must be at least {{compare_to}} characters.",
    max: "{{name}} must not exceed {{compare_to}} characters."
  },
  numericality: {
    onlyInteger: "{{name}} must be an integer.",
    greaterThan: "{{name}} must be greater than {{compare_to}}",
    greaterThanOrEqualTo: "{{name}} must be greater than or equal to {{compare_to}}.",
    equalTo: "{{name}} must be equal to {{compare_to}}.",
    lessThan: "{{name}} must be less than {{compare_to}}.",
    lessThanOrEqualTo: "{{name}} must be less than or equal to {{compare_to}}.",
    odd: "{{name}} must be an odd number.",
    even: "{{name}} must be an even number."    
  },
  format: {
    pattern: "{{name}} is not formatted correctly."
  }
}

var newErrors = function() {
  var _errors = {};
  return {
    errors: function() {return _errors},
    add: function(name, error) {
      if (!error) return;
      if (typeof error == 'string') {
        var messages = _errors[name];
        if (!messages) _errors[name] = messages = [];
        messages.push(error);        
      } else {
        _errors[name] = error;
      }
    },
    addToBase: function(error) {
      this.add('_base', error);
    },
    clear: function() {
      _errors = {};
    },
    count: function() {
      return this.size();
    },
    each: function(callback) {
      _.each(_errors, function(errors, name) {
        callback(name, errors);
      })
    },
    isEmpty: function() {
      return _.isEmpty(_errors);
    },
    messages: function() {
      return _.flatten(_.values(_errors));
    },
    isInvalid: function(name) {
      var error = _errors[name];
      if (!error) return false;
      if (typeof error == 'array') return error.length > 0;
      else return true;
    },
    length: function(){
      return this.size();
    },
    on: function(name) {
      return _errors[name];
    }, 
    onBase: function() {
      return _errors['_base'];
    },
    size: function() {
      return _.size(_errors);
    },
    toString: function() {
      return JSON.stringify(_errors);
    }
  };
}

function isBlank(v) { return v === undefined || v === null || v === ''; }

var valid_funcs = {
  required: function(val) {return !isBlank(val);},
  length: {
    is: function(val, compare_to) {return val.toString().length == compare_to;},
    max: function(val, compare_to) {return val.toString().length <= compare_to; },
    min: function(val, compare_to) {return val.toString().length >= compare_to; }
  },
  numericality: {
    onlyInteger: function(val) {return parseInt(val) == val;}, 
    odd: function(val) {return Math.abs(val) % 2 == 1;}, 
    even: function(val) {return val % 2 == 0;}, 
    greaterThan: function(val, compare_to) {return val > compare_to;},
    greaterThanOrEqualTo: function(val, compare_to) {return val >= compare_to;} ,
    equalTo: function(val, compare_to) {return val == compare_to;} ,
    lessThan: function(val, compare_to) {return val < compare_to;} ,
    lessThanOrEqualTo: function(val, compare_to) {return val <= compare_to;} 
  },
  format: {
    pattern: function(val, compare_to) {return val.toString().match(compare_to);}
  }
}
// we want to execute the validations in this order
var validation_types = ['required', 'length', 'numericality', 'format'];

var interpolation_scope_extractors = {
  length: {
    count: function(val) {return {count: val.length};},
    is: function(val) {return {count: val.length};},
    min: function(val) {return {count: val.length};},
    max: function(val) {return {count: val.length};},
  }
};

function validate(obj, config) {  
  
  var errors = newErrors();
  var defaultMessages = config.defaultMessages || {};
  _.without(validation_types, 'required').forEach(function(validation_type) {
    if (!defaultMessages[validation_type]) defaultMessages[validation_type] = {};
  });

  function test_and_add_error_message(prop_name, prop_config, validation_type, value, subtype) {
    if (!prop_config[validation_type]) return;
    var valid_func, compare_to, interpolation_scope_extractor;
    if (subtype) {
      if (prop_config[validation_type][subtype] == undefined) return;
      valid_func = valid_funcs[validation_type][subtype];
      compare_to = prop_config[validation_type][subtype];
      if (interpolation_scope_extractors[validation_type]) 
        interpolation_scope_extractor = interpolation_scope_extractors[validation_type][subtype];
    } else { 
      valid_func = valid_funcs[validation_type];
      compare_to = prop_config[validation_type];
      interpolation_scope_extractor = interpolation_scope_extractors[validation_type];
    }
    if (!valid_func(value, compare_to)) {
      var msg = prop_config.message;
      if (subtype) {
        msg = msg  || defaultMessages[validation_type][subtype] || 
                globalDefaultMessages[validation_type][subtype];
      } else {
        msg = msg  || defaultMessages[validation_type] || 
                globalDefaultMessages[validation_type];
      }
      var vars;
      if (interpolation_scope_extractor)
        vars = interpolation_scope_extractor(value);
      errors.add(prop_name, interpolate_msg(msg, prop_name, value, compare_to, vars));
      return false;
    } else {
      return true;
    }
  }
  
  _.forEach(config.properties, function(prop_config, prop_name) {
    var value = obj[prop_name];
    if (prop_config.object) {
      // recurse
      errors.add(prop_name, validate(value, prop_config.object));
      return; // no other validation types should apply if validation type is 'object'
    }
    for (var i = 0; i < validation_types.length; i++) {
      var validation_type = validation_types[i];
      if (!prop_config[validation_type]) continue;
      if (validation_type != 'required' && 
          (value === undefined || value === null )) 
          continue;
      if (typeof valid_funcs[validation_type] == 'function') {
        var is_valid = test_and_add_error_message(prop_name, prop_config, 
                         validation_type, value);
        if (!is_valid && validation_type == 'required') break;
      } else {
        _.keys(valid_funcs[validation_type]).forEach(function(subtype) {
          test_and_add_error_message(prop_name, prop_config, validation_type, 
            value, subtype);
        });        
      }
    }
  });
  if (!errors.isEmpty()) return errors;
}

function interpolate_msg(msg, name, value, compare_to, vars) {
  var interp_msg = msg.replace(/{{name}}/, name.humanize(true)).
                       replace(/{{value}}/, value).
                       replace(/{{compare_to}}/, compare_to);
  if (vars)
    _.forEach(vars, function(val, name) {
      interp_msg = interp_msg.replace('{{'+name+'}}', val); 
    });
  return interp_msg;
}


})();
Example #10
0
    this.listener = function(event) {
        var commandName = event.params[0];
        if(commandName.charAt(0) != '~') {
            return;
        }
        if(!_.has(dbot.commands, commandName)) {
            if(_.has(dbot.modules, 'quotes')) {
                var key = event.message.substring(1);
                dbot.api.quotes.getInterpolatedQuote(event.server,
                        event.channel.name, event.user, key, function(quote) {
                    if(quote) {
                        event.reply(key + ': ' + quote);
                    } else if(_.has(dbot.modules, 'spelling')) {
                        var commands = _.keys(dbot.commands)
                            winner = false,
                            closestMatch = Infinity;

                        _.each(commands, function(command) {
                            var distance = dbot.api.spelling.distance(commandName, command);
                            if(distance < closestMatch) {
                                closestMatch = distance;
                                winner = command;
                            }
                        }); 

                        if(closestMatch < 1) {
                            event.reply(commandName + ' not found. Did you mean ' + winner + '?');
                            return;
                        } else if(_.has(dbot.modules, 'quotes')) {
                            dbot.api.link.udLookup(key, function(word, definition) {
                                if(word) {
                                    event.reply(key + '[UD]: ' + definition);
                                } else {
                                    event.reply(dbot.t('category_not_found', { 'category': key }));
                                }
                            });
                        } else {
                            return;
                        }
                    }
                });
                return;
            }

             else if(_.has(dbot.modules, 'quotes')) {
                commandName = '~';
            } else {
                return;
            }
        } 
       
        this.api.hasAccess(event.rUser, event.channel, commandName, function(hasAccess) {
            dbot.api.ignore.isUserIgnoring(event.rUser, commandName, function(isIgnoring) {
                dbot.api.ignore.isUserBanned(event.rUser, commandName, function(isBanned) {
                    if(isBanned) {
                        if(this.config.banOutput && commandName != '~') {
                            event.reply(dbot.t('command_ban', {'user': event.user})); 
                        }
                    } else if(!hasAccess) {
                        if(this.config.accessOutput) {
                            event.reply(dbot.t('access_denied', { 'user': event.user }));
                        }
                    } else if(!isIgnoring && _.has(dbot.commands, commandName) && !dbot.commands[commandName].disabled) {
                        if(this.api.applyRegex(commandName, event)) {
                            try {
                                var command = dbot.commands[commandName];
                                var results = command.apply(dbot.modules[command.module], [event]);
                            } catch(err) {
                                if(dbot.config.debugMode == true) {
                                    var stack = err.stack.split('\n').slice(1, dbot.config.debugLevel + 1);

                                    event.reply('- Error in ' + commandName + ':');
                                    event.reply('- Message: ' + err);

                                    _.each(stack, function(stackLine, index) {
                                        event.reply('- Stack[' + index + ']: ' +
                                            stackLine.trim());
                                    });
                                }
                            }
                            if(!_.include(['~reload', '~load', '~unload', '~setconfig'], commandName)) dbot.api.event.emit('command', [ event ]);
                            dbot.save();
                        } else {
                            if(commandName !== '~') {
                                if(_.has(dbot.usage, commandName)) {
                                    event.reply('Usage: ' + dbot.usage[commandName]);
                                } else {
                                    event.reply(dbot.t('syntax_error'));
                                }
                            }
                        }
                    }
                }.bind(this));
            }.bind(this));
        }.bind(this));
    }.bind(this);
Example #11
0
 this.db.scan('channel_ignores', function(channel) {
     _.each(channel.ignores, function(module) {
         dbot.instance.ignoreTag(channel.name, module);
     });
 }, function(err) { });
Example #12
0
    req.db.read('ontologies', req.body.acronym, function(err, exOnt) { 
      if(!exOnt) { 
        if(_.has(req.files, 'ontology')) {
          fs.readFile(req.files.ontology.path, function (err, data) {
            var newName = req.body.acronym + '_1.ont',
                newPath = __dirname + '/../public/onts/' + newName;

            fs.writeFile(newPath, data, function (err) {
              // Create ontology in DB
              var time = Math.floor(Date.now()/1000);
              var ont = {
                'id': req.body.acronym,
                'name': req.body.name,
                'description': req.body.description,
                'lastSubDate': time,
                'submissions': {
                  
                },
                'status': 'untested',
                'source': 'manual',
                'owners': [ req.user.username ]
              };
              ont.submissions[time] = newName;

              req.db.save('ontologies', req.body.acronym, ont, function(err) {
                request.get(req.aberowl + 'reloadOntology.groovy', {
                  'qs': {
                    'name': req.body.acronym 
                  } // Later this will need API key
                }, function() {}); // we don't actually care about the response

                req.flash('info', 'Ontology uploaded successfully. Depending on the size of your ontology, you may want to grab a cup of tea while it\'s reasoning')
                res.redirect('/ontology/' + req.body.acronym);
              });
            });
          });
        } else if(_.has(req.body, 'url')) {
          // Create ontology in DB
            var time = Math.floor(Date.now()/1000);
            var ont = {
              'id': req.body.acronym,
              'name': req.body.name,
              'description': req.body.description,
              'lastSubDate': 0,
              'submissions': {
                
              },
              'status': 'untested',
              'source': req.body.url,
              'owners': [ req.user.username ]
            };
	    if (req.body.url.endsWith("owl") || req.body.url.endsWith("rdf")) {
		req.db.save('ontologies', req.body.acronym, ont, function(err) {
		    req.flash('info', 'Ontology added successfully and will be synchronised soon...')
		    res.redirect('/ontology/' + req.body.acronym);
		});
	    } else {
		req.flash('error', 'Link does not seem to point to an ontology file (must end with rdf or owl).')
		res.redirect('/ontology/' + req.body.acronym);
	    }
        } else {
          req.flash('error', 'You must give a URL or an ontology file!');
          res.redirect('/ontology/upload')
        }
      } else {
        req.flash('error', 'Ontology with acronym ' + req.body.acronym + ' already exists!');
        res.redirect('/ontology/upload')
      }
    });
Example #13
0
        var name = dir+'/'+files[i];
        if (fs.statSync(name).isDirectory()){
            getFiles(name,files_);
        } else {
            files_.push(name);
        }
    }
    return files_;
}

var olddatafile = getFiles('../../datasets/Initial')
var olddata = []


_.each(olddatafile, function(file, key, list){ 
	olddata = olddata.concat(JSON.parse(fs.readFileSync(file)))
}, this)

// console.log(olddata)
// process.exit(0)
var wasadd = 0
var notun = 0
var notadd = 0
var isobj = 0
var data = JSON.parse(fs.readFileSync(filename))

_.each(data, function(value, key, list){ 
	_.each(value['turns'], function(value1, key1, list1){

		if ('output' in value1)
			{
Example #14
0
 this.getAll(function(err, items) {
   if (err) cb(err); else {
     _.each(items, iterator);
     cb();
   }
 });
Example #15
0
var errsWithoutFields = function (errs) {
    return _.filter(errs, function (e) {
        return !e.field;
    });
};
Example #16
0
function validate(obj, config) {  
  
  var errors = newErrors();
  var defaultMessages = config.defaultMessages || {};
  _.without(validation_types, 'required').forEach(function(validation_type) {
    if (!defaultMessages[validation_type]) defaultMessages[validation_type] = {};
  });

  function test_and_add_error_message(prop_name, prop_config, validation_type, value, subtype) {
    if (!prop_config[validation_type]) return;
    var valid_func, compare_to, interpolation_scope_extractor;
    if (subtype) {
      if (prop_config[validation_type][subtype] == undefined) return;
      valid_func = valid_funcs[validation_type][subtype];
      compare_to = prop_config[validation_type][subtype];
      if (interpolation_scope_extractors[validation_type]) 
        interpolation_scope_extractor = interpolation_scope_extractors[validation_type][subtype];
    } else { 
      valid_func = valid_funcs[validation_type];
      compare_to = prop_config[validation_type];
      interpolation_scope_extractor = interpolation_scope_extractors[validation_type];
    }
    if (!valid_func(value, compare_to)) {
      var msg = prop_config.message;
      if (subtype) {
        msg = msg  || defaultMessages[validation_type][subtype] || 
                globalDefaultMessages[validation_type][subtype];
      } else {
        msg = msg  || defaultMessages[validation_type] || 
                globalDefaultMessages[validation_type];
      }
      var vars;
      if (interpolation_scope_extractor)
        vars = interpolation_scope_extractor(value);
      errors.add(prop_name, interpolate_msg(msg, prop_name, value, compare_to, vars));
      return false;
    } else {
      return true;
    }
  }
  
  _.forEach(config.properties, function(prop_config, prop_name) {
    var value = obj[prop_name];
    if (prop_config.object) {
      // recurse
      errors.add(prop_name, validate(value, prop_config.object));
      return; // no other validation types should apply if validation type is 'object'
    }
    for (var i = 0; i < validation_types.length; i++) {
      var validation_type = validation_types[i];
      if (!prop_config[validation_type]) continue;
      if (validation_type != 'required' && 
          (value === undefined || value === null )) 
          continue;
      if (typeof valid_funcs[validation_type] == 'function') {
        var is_valid = test_and_add_error_message(prop_name, prop_config, 
                         validation_type, value);
        if (!is_valid && validation_type == 'required') break;
      } else {
        _.keys(valid_funcs[validation_type]).forEach(function(subtype) {
          test_and_add_error_message(prop_name, prop_config, validation_type, 
            value, subtype);
        });        
      }
    }
  });
  if (!errors.isEmpty()) return errors;
}
Example #17
0
Form.prototype.renderFields = function (renderer, fields, values,
                                        raw, errs, path, options, root) {
    fields = fields || {};
    values = values || {};
    root = root || values;
    raw = raw || {};
    errs = errs || [];
    path = path || [];

    var that = this;
    var excludes = this.options.exclude;
    var field_subset = this.options.fields;
    var keys = _.keys(fields);

    var fields_module = require('./fields');

    return _.reduce(keys, function (html, k) {

        var f_path = path.concat([k]);

        if (excludes) {
            if (_.indexOf(excludes, f_path.join('.')) !== -1) {
                return html;
            }
        }
        if (field_subset) {
            if (_.indexOf(field_subset, f_path.join('.')) === -1) {
                return html;
            }
        }

        var f_errs = errsBelowPath(errs, f_path);
        var f = fields[k];

        if (f instanceof fields_module.AttachmentField) {
            return html + renderer.field(
                f,
                f_path,
                utils.attachmentsBelowPath(root, f_path),
                (raw[k] === undefined) ? values[k]: raw[k],
                f_errs,
                (options || {})
            );
        }
        else if (f instanceof fields_module.Field ||
                 f instanceof fields_module.Embedded ||
                 f instanceof fields_module.EmbeddedList) {

            return html + renderer.field(
                f,
                f_path,
                values[k],
                (raw[k] === undefined) ? values[k]: raw[k],
                f_errs,
                (options || {})
            );
        }
        else if (f instanceof Object) {
            return html + (k ? renderer.beginGroup(f_path) : '') +
                that.renderFields(
                    renderer,
                    f,
                    values[k],
                    (raw[k] === undefined) ? values[k]: raw[k],
                    errs,
                    f_path,
                    (options || {}),
                    root
                ) + (k ? renderer.endGroup(f_path) : '');
        } else {
            throw new Error(
                'The field type `' + (typeof f) + '` is not supported.'
            );
        }
    }, '');
};
Example #18
0
 each: function(callback) {
   _.each(_errors, function(errors, name) {
     callback(name, errors);
   })
 },
Example #19
0
function getByUser(user) {
    'use strict';
    return _.find(battleServers, function(bs) {
        return bs.isPlayerInIt(user.id);
    });
}
Example #20
0
 isEmpty: function() {
   return _.isEmpty(_errors);
 },
Example #21
0
 stream.addListener('end', function() {
     var args = _.clone(resultses);
     args.unshift(null);
     callback.apply({}, args);
 });
Example #22
0
 messages: function() {
   return _.flatten(_.values(_errors));
 },
Example #23
0
var Type = exports.Type = function Type(name, options) {
    if (typeof name !== 'string') {
        throw new Error('First argument must be the type name');
    }
    this.name = name;
    options = options || {};

    var f = {};
    f._id = fields.string({
        omit_empty: true,
        required: false,
        widget: widgets.hidden(),
        permissions: {
            update: permissions.fieldUneditable()
        },
        default_value: function (req) {
            return req.uuid;
        }
    });
    f._rev = fields.string({
        omit_empty: true,
        required: false,
        widget: widgets.hidden()
    });
    f._deleted = fields.boolean({
        omit_empty: true,
        required: false,
        widget: widgets.hidden()
    });
    f.type = fields.string({
        default_value: name,
        widget: widgets.hidden(),
        validators: [
            function (doc, val, raw) {
                if (val !== name) {
                    throw new Error('Unexpected value for type');
                }
            },
        ]
    });
    for (var k in options.fields) {
        if (options.fields.hasOwnProperty(k)) {
            f[k] = options.fields[k];
        }
    }

    options.fields = f;
    _.extend(this, _.defaults(options, {
        permissions: []
    }));

    if (options.display_name) {
        if (typeof options.display_name !== 'function') {
            this.display_name = function (doc) {
                if (typeof options.display_name === 'string') {
                    options.display_name = [options.display_name];
                }
                return utils.getPropertyPath(doc, options.display_name);
            };
        }
    }
};
Example #24
0
 size: function() {
   return _.size(_errors);
 },
Example #25
0
  _createWritePromises: function(branches, trackedBranches) {
    var writePromises = trackedBranches.map(function(branch) {
      console.log("looking at " + branch.name + ", " + branch.status);

      var info = branches[branch.name];
      if (info) {
        return this._db.updateTrackedBranch(branch.name, {
          name : branch.name,
          status : info.green ? 'success' : 'failed',
          previousStatus : branch.status || 'new',
          lastBuild : {
            time : info.last_built,
            url : info.url,
            sha : info.sha
          }
        });
      }
      else {
        console.log("Warning: did not find branch '" + branch.name + "' in server status JSON");
        return null;
      }
    }, this);

    return _.compact(writePromises);
  }

};

_.extend(BranchStatus.prototype, EventEmitter.prototype);

module.exports = BranchStatus;
Example #26
0
exports.overrideAttachments = function (excludes, field_subset, fields, doc_a, doc_b) {
    var exclude_paths = _.map((excludes || []), function (p) {
        return p.split('.');
    });
    var subset_paths = _.map((field_subset || []), function (p) {
        return p.split('.');
    });

    var a = doc_a._attachments || {};
    var b = doc_b._attachments || {};

    var a_keys = _.keys(a);
    var b_keys = _.keys(b);
    var all_keys = _.uniq(a_keys.concat(b_keys).sort(), true);

    var fields_module = require('./fields');

    _.each(all_keys, function (k) {
        var parts = k.split('/');
        var filename = parts.pop();
        var dir = parts.join('/');
        var f = utils.getPropertyPath(fields, dir);


        if (f instanceof fields_module.AttachmentField) {
            if (excludes) {
                for (var i = 0; i < exclude_paths.length; i++) {
                    if (utils.isSubPath(exclude_paths[i], dir.split('/'))) {
                        return;
                    }
                }
            }
            if (field_subset) {
                var in_subset = false;
                for (var j = 0; j < subset_paths.length; j++) {
                    if (utils.isSubPath(subset_paths[j], dir.split('/'))) {
                        in_subset = true;
                    }
                }
                if (!in_subset) {
                    return;
                }
            }
            // clear existing attachments
            for (var ak in a) {
                if (ak.slice(0, dir.length + 1) === dir + '/') {
                    delete a[ak];
                }
            }
            // copy over new attachments
            for (var bk in b) {
                if (bk.slice(0, dir.length + 1) === dir + '/') {
                    if (!doc_a._attachments) {
                        a = doc_a._attachments = {};
                    }
                    a[bk] = b[bk];
                }
            }
        }
        else if (b.hasOwnProperty(k)) {
            if (!doc_a._attachments) {
                a = doc_a._attachments = {};
            }
            a[k] = b[k];
        }
    });

    return doc_a;
};
Example #27
0
 function(expandedFields, next) {
   self._config.fields = _.flatten(expandedFields);
   next();
 }
Example #28
0
Form.prototype.validate = function (req) {
    /* This is the request payload:
        This contains all of the form fields that are used by
        formValuesToTree and parseRaw, and must be copied first. */

    this.raw = (req.form || {});

    var type_class = require('./types').Type;
    var tree = exports.formValuesToTree(this.raw);

    this.values = exports.override(
        this.options.exclude,
        this.options.fields,
        this.fields,
        this.values || fieldset.createDefaults(this.fields, req) || {},
        exports.parseRaw(this.fields, tree),
        []
    );

    this.errors = fieldset.validate(
        this.fields, this.values, this.values, this.raw, [], false
    );

    if (this.type) {
        if (this.type instanceof type_class) {
            // run top level permissions first
            var type_errs = this.type.authorizeTypeLevel(
                this.values, this.initial_doc, req.userCtx
            );
            if (type_errs.length) {
                this.errors = this.errors.concat(type_errs);
            }
            else {
                // if no top-level permissions errors, check each field
                this.errors = this.errors.concat(
                    this.type.authorize(
                        this.values, this.initial_doc, req.userCtx
                    )
                );
            }
        } else {
            /* Programmer error: display a useful diagnostic message */
            throw new Error(
                'Encountered a type object that is not an instance of' +
                    ' `Type`; check lib/types.js for proper instansiation'
            );
        }

    }
    else {
        this.errors = this.errors.concat(fieldset.authFieldSet(
            this.fields, this.values, this.initial_doc, this.values,
            this.initial_doc, req.userCtx, [], true
        ));
    }

    // clear field properties on errors for excluded fields
    var excludes = this.options.exclude;
    if (excludes) {
        var excl_paths = _.map(excludes, function (p) {
            return p.split('.');
        });
        this.errors = _.map(this.errors, function (e) {
            if (!e.field) {
                return e;
            }
            for (var i = 0, len = excl_paths.length; i < len; i++) {
                var path = excl_paths[i];
                if (utils.isSubPath(path, e.field)) {
                    e.message = e.field.join('.') + ': ' + (
                        e.message || e.toString()
                    );
                    delete e.field;
                    return e;
                }
            }
            return e;
        });
    }

    // clear field properties on errors not in fields subset
    var field_subset = this.options.fields;
    if (field_subset) {
        var subset_paths = _.map(field_subset, function (p) {
            return p.split('.');
        });
        this.errors = _.map(this.errors, function (e) {
            if (!e.field) {
                return e;
            }
            for (var i = 0, len = subset_paths.length; i < len; i++) {
                var path = subset_paths[i];
                if (!utils.isSubPath(path, e.field)) {
                    e.message = e.field.join('.') + ': ' + (
                        e.message || e.toString()
                    );
                    delete e.field;
                    return e;
                }
            }
            return e;
        });
    }

    return this;
};
Example #29
0
        }, function(err, widgetClass) {
          if (err) {
            if (err === errors.CLIENT_ONLY) {
              widgetEl.setAttribute("clientonly", "true");
              //still send the widget info to the calling code
              if (!widgetClassRegistry.findById(path)) widgetClassRegistry.add({id: path});
              if ($j('widget:first[clientonly!="true"]', node).length > 0) { //need an exit condition to prevent infinite (pseudo)recursion
                Widget.render(renderOptions, callback);
              } else {
                if (typeof callback === "function") {
                  result.scripts = scripts;
                  result.widgetClassRegistry = widgetClassRegistry;
                  result.widgets = widgets;
                  callback(null, result);
                }
              }
            } else {
              callback(err);
            }
          } else {
            //dump the widget class into the registry to track unique widget classes used in this render context
            var widgetClassPath = (widgetClass.path || widgetClass.id);
            if (widgetClassRegistry && !widgetClassRegistry.findById(widgetClassPath)) {
              widgetClassRegistry.add(widgetClass);
              //get the widget's css file tracked on the client
              if (context !== "widget" && (widgetClass.classDef && !widgetClass.classDef.prototype.serverOnly))  { //if only rendering a single widget, don't include this bit
                scripts.push("if (!feather.Widget.resources.findById('" + widgetClassPath + ".css')) {\n" +
                  "  feather.Widget.resources.add({id: '" + widgetClassPath + ".css'});\n" +
                  "}\n");
              }
            }

            //instantiate from the top down but render from the bottom up (into parent containers)...

            //set the options
            var options = {
              dom: dom,
              id: id,
              myid: myid,
              parent: parentWidget,
              request: req,
              node: widgetEl //allow the instance to look for any special custom tags it might support or to do any other thing it might want to do to the original node to augment behavior
            };
            var el = $j(widgetEl);

            //find any declaratively defined options
            var clientEnabledOptions = [];
            el.children("options").each(function(index, optionTag) {
              $j("option", optionTag).each(function(index, _opt) {
                var name = _opt.getAttribute("name"),
                  value = _opt.getAttribute("value"),
                  clientEnabled = _opt.getAttribute("client_enabled");
                try {
                  if (clientEnabled) {
                    clientEnabledOptions.push(name);
                  }
                  options[name] = JSON.parse(value);
                } catch (ex) {
                  options[name] = value;
                }
                $j(_opt).remove();
              });
            });

            //create the instance and cache some file and class info
            var instance                = new (widgetClass.classDef)(options);
            instance.clientFilePath     = widgetClass.clientFilePath;
            instance.templateFilePath   = widgetClass.templateFilePath;
            instance.template           = widgetClass.template;
            instance.clientCssFilePath  = widgetClass.clientCssFilePath;
            instance.clientCssHrefPath  = widgetClass.clientCssHrefPath;
            instance.options.renderTimeout = instance.options.renderTimeout || renderTimeout;

            if (req && !req.serverMethods[instance.widgetPath]) {
              bindServerMethods(instance);
            }

            //store the instance in the local-to-this-render-cycle registry
            widgets.add(instance);

            //now emit any client.js files and instance creation scripts needed
            //note: we want this script emitted before any children's script so that
            //instantiation on the client takes place in the right order
            if (instance.getClientScript && !instance.serverOnly) {
              var clientScript = instance.getClientScript(renderOptions);
              instance.scripts.push(clientScript);
            }

            //now auto-propagate the client_enabled options to the client
            if (!instance.serverOnly) {
              _.each(clientEnabledOptions, function(_opt) {
                instance.scripts.push('widget.options.' + _opt + ' = ' + JSON.stringify(options[_opt]) + ';');
              });
            }

            //recurse down the children tree first so rendering goes from the bottom up
            Widget.render(_.extend(_.clone(renderOptions), {
              node: widgetEl,
              idPrefix: id + "_",
              parentWidget: instance,
              level: level++,
              scripts: instance.scripts
            }), function(err) {
              if (err) callback(err); else {
                //get the declaratively defined html for the widget if there is any
                instance.contentTemplate = el.children("contentTemplate");

                //remove the widget node from the current parent and replace with an appropriate container
                //TODO: move this into an instance method that can be overridden for custom container wrapping
                var cssClass = widgetEl.getAttribute("class");
                var defaultClass = instance.widgetName.replace(/\./g, '_');
                if (cssClass) {
                  cssClass = 'class="' + defaultClass + ' ' + cssClass.replace(/\./g, '_') + '"';
                } else {
                  cssClass = 'class="' + defaultClass + '"';
                }
                instance.container = $j('<div id="' + id + '_Container" ' + cssClass + '></div>').insertBefore(widgetEl);

                if (!instance.serverOnly) {
                  instance.scripts.push([
                    'widget.fire("init");\n'
                  ].join(''));
                }

                el.remove(); //removes the actual "widget" tag now that a container div has been put in its place to hold any generated HTML

                //let the instance handle its own rendering (usually via a FSM controller),
                //which could very likely lead into more (pseudo)recursions if more children are rendered dynamically
                instance.render(renderOptions, function(err) {
                  if (err) callback(err); else {
                    //we've finished recursing down 1 branch... continue on down the siblings now
                    if ($j('widget:first[clientonly!="true"]', node).length > 0) { //need an exit condition to prevent infinite (pseudo)recursion
                      Widget.render(renderOptions, callback);
                    } else {
                      if (typeof callback === "function") {
                        result.scripts = scripts;
                        result.widgetClassRegistry = widgetClassRegistry;
                        result.widgets = widgets;
                        callback(null, result);
                      }
                    }
                  }
                });
              }
            });
          }
        });
Example #30
0
 fs.readdir('public/graphs', function (err, files) {
   res.end(_.map(_.filter(files, function (file) { return file.substring(file.length - 4, file.length) === '.png'; }), function (file) { return 'graphs/' + file; }).join(','));
 });