<commit_before>exports.Apply = function(databaseUrl) {

  var restify = require('restify');
  var mongojs = require('mongojs');
  var fs = require("fs");
  var ZSchema = require("z-schema");
  var nodemailer = require("nodemailer");
  var url = require('url');

  var validator = new ZSchema();
  var applicationSchema
  var jobSchema
  var bodyString = fs.readFileSync(__dirname+'/html/root.html', 'utf8');
  var apiString = fs.readFileSync(__dirname+'/api.json', 'utf8');
  var jobString = fs.readFileSync(__dirname+'/schema/job.schema', 'utf8');
  var applicationString = fs.readFileSync(__dirname+'/schema/application.schema', 'utf8');

  var emailConfig = JSON.parse(fs.readFileSync(__dirname+'/email/config.json', 'utf8'));

  var smtpTransport = nodemailer.createTransport("SMTP", emailConfig.smtp );

   // setup e-mail data with unicode symbols
  var mailOptions = {
    from: emailConfig.smtp.auth.user, // sender address
    to: emailConfig.toArray, // list of receivers
    subject: "Someone has applied", // Subject line
    text:""
  }

  var schema = JSON.parse(applicationString);
  validator.compileSchema(schema, function (err, compiledSchema) {
    applicationSchema = compiledSchema
  });

  schema = JSON.parse(jobString);
  validator.compileSchema(schema, function (err, compiledSchema) {
    jobSchema = compiledSchema
  });

  var collections = ["jobs", "applications"]

  var db = mongojs.connect(databaseUrl, collections);

  function root(req, res, next) {
    res.writeHead(200, {
      'Content-Length': Buffer.byteLength(bodyString),
      'Content-Type': 'text/html'
    });
    res.write(bodyString);
    res.end();
    // res.send({'*/apply/api':'how to apply for a job'})
  }

  function api(req, res, next){
    var api = JSON.parse(apiString)
    api.jobs.schema = JSON.parse(jobString)
    api.applications.schema = JSON.parse(applicationString)
    res.send(api)
  }

  function listJobs(req, res, next) {
    db.jobs.find(function(err, jobs) {
      if(err){
        console.log(err);
      }else{
        res.send(200, jobs);
      }
    });
  }

  function createJob(req, res, next){
    var job = req.params.job;
    if(job==undefined){
      job = req.params
    }
    validator.validate(job, jobSchema).then(function(report){
      db.jobs.insert(job,function(err, job) {
        if(err){
          res.send(400, {"code":"BadRequest","message":err});
        }else{
          res.send(200, job[0]);
        }
      });
    }).fail(function(err){
      res.send(400, {"code":"BadRequest","message":err});
    })
  }

  function deleteJob(req, res, next){
    var id = req.params.id
    if(id==undefined){
      res.send(400, {"code":"BadRequest","message":"id not provided."});
    }else{
      db.jobs.remove({_id:mongojs.ObjectId(id)}, true ,function(err, job) {
        res.send(204, job)
      });
    }
  }

  function getJob(req, res, next) {
    var id = req.params.id;
    if(id==undefined){
      res.send(400, {"code":"BadRequest","message":"id not provided."});
    }else{
      db.jobs.findOne({_id:mongojs.ObjectId(id)},function(err, job) {
        res.send(200, job)
      });
    }
  }

  function getApplication(req, res, next) {
    var id = req.params.id
    if(id==undefined){
      res.send(400, {"code":"BadRequest","message":"id not provided."});
    }else{
      db.applications.findOne({_id:mongojs.ObjectId(id)},function(err, application) {
        res.send(200, application)
      });
    }
  }

  function deleteApplication(req, res, next) {
    var id = req.params.id
    if(id==undefined){
      res.send(400, {"code":"BadRequest","message":"id not provided."});
    }else{
      db.applications.remove({_id:mongojs.ObjectId(id)}, true ,function(err, application) {
        res.send(204, application)
      });
    }
  }

  function updateApplication(req, res, next){
    var id = req.params.id
    var application = req.params.application
    if(id==undefined){
      res.send(400, {"code":"BadRequest","message":"id not provided."});
    }else if(application==undefined){
      application = req.params
    }
    validator.validate(application, applicationSchema)
    .then(function(report){
      db.applications.findOne({_id:mongojs.ObjectId(id)}, application ,function(err, application) {
        res.send(200, application[0])
      });
    })
    .fail(function(err){
      res.send(400, {"code":"BadRequest","message":err});
    })
  }

  function createApplication(req, res, next){
    var application = req.params.application;
    if(application==undefined){
      application = req.params
    }
    validator.validate(application, applicationSchema).then(function(report){
      db.jobs.findOne({_id:mongojs.ObjectId(application.jobId)},function(err, job) {
        db.applications.insert(application,function(err, application) {
          if(err){
            res.send(400, {"code":"BadRequest","message":err});
          }else{
            console.log("Setting applicationId: "+application[0])
            mailOptions.text="Application: "+JSON.stringify(application[0])
            smtpTransport.sendMail(mailOptions, function(error, response){
              if(error){
                console.log("Error sending mail"+error);
              }else{
                console.log("Message sent: " + response.message);
              }
            });
            res.send(200, application[0]);
          }
        });
      });
    }).fail(function(error){
      res.send(400, {"code":"BadRequest","messages":error});
    })
  }

  var server = restify.createServer({
    name: 'Apply'
  });

  server.use(restify.bodyParser());

  server.get('/', root);
  server.get('/api', api);

  server.get('/jobs', listJobs);
  server.get('/jobs/:id', getJob);
  server.post('/jobs', createJob);
  server.del('/jobs/:id', deleteJob);

  server.get('/applications/:id', getApplication);
  server.post('/applications', createApplication);
  server.put('/applications/:id', updateApplication);
  server.del('/applications/:id', deleteApplication);

  server.listen(8080, function() {
    console.log('%s listening at %s', server.name, server.url);
  });

};<commit_msg>Allow them<commit_after>exports.Apply = function(databaseUrl) {

  var restify = require('restify');
  var mongojs = require('mongojs');
  var fs = require("fs");
  var ZSchema = require("z-schema");
  var nodemailer = require("nodemailer");
  var url = require('url');

  var validator = new ZSchema();
  var applicationSchema
  var jobSchema
  var bodyString = fs.readFileSync(__dirname+'/html/root.html', 'utf8');
  var apiString = fs.readFileSync(__dirname+'/api.json', 'utf8');
  var jobString = fs.readFileSync(__dirname+'/schema/job.schema', 'utf8');
  var applicationString = fs.readFileSync(__dirname+'/schema/application.schema', 'utf8');

  var emailConfig = JSON.parse(fs.readFileSync(__dirname+'/email/config.json', 'utf8'));

  var smtpTransport = nodemailer.createTransport("SMTP", emailConfig.smtp );

   // setup e-mail data with unicode symbols
  var mailOptions = {
    from: emailConfig.smtp.auth.user, // sender address
    to: emailConfig.toArray, // list of receivers
    subject: "Someone has applied", // Subject line
    text:""
  }

  var schema = JSON.parse(applicationString);
  validator.compileSchema(schema, function (err, compiledSchema) {
    applicationSchema = compiledSchema
  });

  schema = JSON.parse(jobString);
  validator.compileSchema(schema, function (err, compiledSchema) {
    jobSchema = compiledSchema
  });

  var collections = ["jobs", "applications"]

  var db = mongojs.connect(databaseUrl, collections);

  function root(req, res, next) {
    res.writeHead(200, {
      'Content-Length': Buffer.byteLength(bodyString),
      'Content-Type': 'text/html'
    });
    res.write(bodyString);
    res.end();
    // res.send({'*/apply/api':'how to apply for a job'})
  }

  function api(req, res, next){
    var api = JSON.parse(apiString)
    api.jobs.schema = JSON.parse(jobString)
    api.applications.schema = JSON.parse(applicationString)
    res.send(api)
  }

  function listJobs(req, res, next) {
    db.jobs.find(function(err, jobs) {
      if(err){
        console.log(err);
      }else{
        res.send(200, jobs);
      }
    });
  }

  function createJob(req, res, next){
    var job = req.params.job;
    if(job==undefined){
      job = req.params
    }
    validator.validate(job, jobSchema).then(function(report){
      db.jobs.insert(job,function(err, job) {
        if(err){
          res.send(400, {"code":"BadRequest","message":err});
        }else{
          res.send(200, job[0]);
        }
      });
    }).fail(function(err){
      res.send(400, {"code":"BadRequest","message":err});
    })
  }

  function deleteJob(req, res, next){
    var id = req.params.id
    if(id==undefined){
      res.send(400, {"code":"BadRequest","message":"id not provided."});
    }else{
      db.jobs.remove({_id:mongojs.ObjectId(id)}, true ,function(err, job) {
        res.send(204, job)
      });
    }
  }

  function getJob(req, res, next) {
    var id = req.params.id;
    if(id==undefined){
      res.send(400, {"code":"BadRequest","message":"id not provided."});
    }else{
      db.jobs.findOne({_id:mongojs.ObjectId(id)},function(err, job) {
        res.send(200, job)
      });
    }
  }

  function getApplication(req, res, next) {
    var id = req.params.id
    if(id==undefined){
      res.send(400, {"code":"BadRequest","message":"id not provided."});
    }else{
      db.applications.findOne({_id:mongojs.ObjectId(id)},function(err, application) {
        res.send(200, application)
      });
    }
  }

  function deleteApplication(req, res, next) {
    var id = req.params.id
    if(id==undefined){
      res.send(400, {"code":"BadRequest","message":"id not provided."});
    }else{
      db.applications.remove({_id:mongojs.ObjectId(id)}, true ,function(err, application) {
        res.send(204, application)
      });
    }
  }

  function updateApplication(req, res, next){
    var id = req.params.id
    var application = req.params.application
    if(id==undefined){
      res.send(400, {"code":"BadRequest","message":"id not provided."});
    }else if(application==undefined){
      application = req.params
    }
    validator.validate(application, applicationSchema)
    .then(function(report){
      db.applications.findOne({_id:mongojs.ObjectId(id)}, application ,function(err, application) {
        res.send(200, application[0])
      });
    })
    .fail(function(err){
      res.send(400, {"code":"BadRequest","message":err});
    })
  }

  function createApplication(req, res, next){
    var application = req.params.application;
    if(application==undefined){
      application = req.params
    }
    validator.validate(application, applicationSchema).then(function(report){
      db.jobs.findOne({_id:mongojs.ObjectId(application.jobId)},function(err, job) {
        db.applications.insert(application,function(err, application) {
          if(err){
            res.send(400, {"code":"BadRequest","message":err});
          }else{
            console.log("Setting applicationId: "+application[0])
            mailOptions.text="Application: "+JSON.stringify(application[0])
            smtpTransport.sendMail(mailOptions, function(error, response){
              if(error){
                console.log("Error sending mail"+error);
              }else{
                console.log("Message sent: " + response.message);
              }
            });
            res.send(200, application[0]);
          }
        });
      });
    }).fail(function(error){
      res.send(400, {"code":"BadRequest","messages":error});
    })
  }

  var server = restify.createServer({
    name: 'Apply'
  });

  server.use(restify.bodyParser());
  server.use(restify.fullResponse());

  server.get('/', root);
  server.get('/api', api);

  server.get('/jobs', listJobs);
  server.get('/jobs/:id', getJob);
  server.post('/jobs', createJob);
  server.del('/jobs/:id', deleteJob);

  server.get('/applications/:id', getApplication);
  server.post('/applications', createApplication);
  server.put('/applications/:id', updateApplication);
  server.del('/applications/:id', deleteApplication);

  server.listen(8080, function() {
    console.log('%s listening at %s', server.name, server.url);
  });

};<|endoftext|>


<commit_before>if (typeof Prototype == 'undefined')
{
  warning = "ActiveScaffold Error: Prototype could not be found. Please make sure that your application's layout includes prototype.js (e.g. <%= javascript_include_tag :defaults %>) *before* it includes active_scaffold.js (e.g. <%= active_scaffold_includes %>).";
  alert(warning);
}

/*
 * Simple utility methods
 */

var ActiveScaffold = {
  stripe: function(tableBody) {
    var even = false;
    var tableBody = $(tableBody);
    var tableRows = tableBody.getElementsByTagName("tr");
    var length = tableBody.rows.length;

    for (var i = 0; i < length; i++) {
      var tableRow = tableBody.rows[i];
      //Make sure to skip rows that are create or edit rows or messages
      if (!tableRow.hasClassName("create")
        && !tableRow.hasClassName("update")
        && !tableRow.hasClassName("inline-adapter")
        && !tableRow.hasClassName("active-scaffold-calculations")) {

        if (even) {
          tableRow.addClassName("even");
        } else {
          tableRow.removeClassName("even");
        }
        even = !even;
      }
    }
  },
  toggleEmptyMessage: function(tableBody, emptyMessageElement) {
    // Check to see if this was the last element in the list
    if ($(tableBody).rows.length == 0) {
      $(emptyMessageElement).show();
    } else {
      $(emptyMessageElement).hide();
    }
  },
  removeSortClasses: function(active_scaffoldId) {
    $$('#' + active_scaffoldId + ' td.sorted').each(function(element) {
      element.removeClassName("sorted");
    });
    $$('#' + active_scaffoldId + ' th.sorted').each(function(element) {
      element.removeClassName("sorted");
      element.removeClassName("asc");
      element.removeClassName("desc");
    });
  },
  decrement_record_count: function(active_scaffoldId) {
    count = $$('#' + active_scaffoldId + ' span.active-scaffold-records').first();
    count.innerHTML = parseInt(count.innerHTML) - 1;
  },
  increment_record_count: function(active_scaffoldId) {
    count = $$('#' + active_scaffoldId + ' span.active-scaffold-records').first();
    count.innerHTML = parseInt(count.innerHTML) + 1;
  }
}

/*
 * Add-ons/Patches to Prototype
 */

/* patch to support replacing TR/TD/TBODY in Internet Explorer, courtesy of http://dev.rubyonrails.org/ticket/4273 */
Element.replace = function(element, html) {
  element = $(element);
  if (element.outerHTML) {
    try {
    element.outerHTML = html.stripScripts();
    } catch (e) {
      var tn = element.tagName;
      if(tn=='TBODY' || tn=='TR' || tn=='TD')
      {
              var tempDiv = document.createElement("div");
              tempDiv.innerHTML = '
' + html.stripScripts() + '
';
              element.parentNode.replaceChild(tempDiv.getElementsByTagName(tn).item(0), element);
      }
      else throw e;
    }
  } else {
    var range = element.ownerDocument.createRange();
    range.selectNodeContents(element);
    element.parentNode.replaceChild(range.createContextualFragment(html.stripScripts()), element);
  }
  setTimeout(function() {html.evalScripts()}, 10);
};

/*
 * URL modification support. Incomplete functionality.
 */
Object.extend(String.prototype, {
  append_params: function(params) {
    url = this;
    if (url.indexOf('?') == -1) url += '?';
    else if (url.indexOf('&') != url.length) url += '&';

    url += $H(params).collect(function(item) {
      return item.key + '=' + item.value;
    }).join('&');

    return url;
  }
});

/*
 * Nested Form... sorta
 */

Form.Pseudo = Class.create();
Form.Pseudo.prototype = {
  initialize: function(element, options) {
    this.element = $(element);
    this.href = $$("#" + this.element.id + " .form-action")[0].href;
    this.setOptions(options);

    // Put hook on buttons
    this.submitButtons = $$("#" + this.element.id + " .submit");
    for (var i=0; i < this.submitButtons.length; i++) {
      Event.observe(this.submitButtons[i], 'click', this.onSubmit.bindAsEventListener(this));
    }

    // find action uri for request
    this.formElements = Form.getElements(this.element);
    for (var i=0; i < this.formElements.length; i++) {
      Event.observe(this.formElements[i], 'keydown', this.onKeyPress.bindAsEventListener(this));
    }
  },

  setOptions: function(options) {
  this.options = { asynchronous: true,
                     evalScripts: true,
                     onLoading: this.onLoading.bindAsEventListener(this),
                     onLoaded: this.onComplete.bindAsEventListener(this) };
    Object.extend(this.options, options || {});
  },

  onKeyPress: function(event) {
    if (event.keyCode == Event.KEY_RETURN) {
      this.onSubmit(event);
    }
  },

  onLoading: function(request) {
    Form.disable(this.element);
  },

  onComplete: function(request) {
    Form.enable(this.element);
  },

  onSubmit: function(event) {
    var params = Object.extend(this.options, { parameters: Form.serialize(this.element) });
    new Ajax.Request(this.href, params);
    Event.stop(event);
  }
}

var PsuedoForm = {
  clear: function(element) {
    this.element = $(element);

    this.formElements = Form.getElements(this.element);
    for (var i=0; i < this.formElements.length; i++) {
      if (this.formElements[i].type.toLowerCase() != 'submit') {
        this.formElements[i].value = "";
      }
    }
  }
}

/**
 * A set of links. As a set, they can be controlled such that only one is "open" at a time, etc.
 */
ActiveScaffold.Actions = new Object();
ActiveScaffold.Actions.Abstract = function(){}
ActiveScaffold.Actions.Abstract.prototype = {
  initialize: function(links, target, loading_indicator, options) {
    this.target = $(target);
    this.loading_indicator = $(loading_indicator);
    this.options = options;
    this.links = links.collect(function(link) {
      return this.instantiate_link(link);
    }.bind(this));
  },

  instantiate_link: function(link) {
    throw 'unimplemented'
  }
}

/**
 * A DataStructures::ActionLink, represented in JavaScript.
 * Concerned with AJAX-enabling a link and adapting the result for insertion into the table.
 */
ActiveScaffold.ActionLink = new Object();
ActiveScaffold.ActionLink.Abstract = function(){}
ActiveScaffold.ActionLink.Abstract.prototype = {
  initialize: function(a, target, loading_indicator) {
    this.tag = $(a);
    this.url = this.tag.href;
    this.target = target;
    this.loading_indicator = loading_indicator;
    this.hide_target = false;
    this.position = this.tag.getAttribute('position');

    this.onclick = this.tag.onclick;
    this.tag.onclick = null;
    this.tag.observe('click', function(event) {
      this.open();
      Event.stop(event);
    }.bind(this));

    this.tag.action_link = this;
  },

  open: function() {
    if (this.is_disabled()) return;
    if (this.onclick && !this.onclick()) return;//e.g. confirmation messages
    if (this.position) this.disable();
    this.loading_indicator.style.visibility = 'visible';
    new Ajax.Request(this.url, {
      asynchronous: true,
      evalScripts: true,

      onSuccess: function(request) {
        if (this.position) {
          this.insert(request.responseText);
          if (this.hide_target) this.target.hide();
        }	else {
					evalResponse();
				}
      }.bind(this),

      onFailure: function(request) {
        if (this.position) this.enable()
      }.bind(this),

      onComplete: function(request) {
        this.loading_indicator.style.visibility = 'hidden';
      }.bind(this)
    });
  },

  insert: function(content) {
    throw 'unimplemented'
  },

  close: function() {
    this.enable();
    this.adapter.remove();
    if (this.hide_target) this.target.show();
  },

  get_new_adapter_id: function() {
    var id = 'adapter_';
    var i = 0;
    while ($(id + i)) i++;
    return id + i;
  },

  enable: function() {
    return this.tag.removeClassName('disabled');
  },

  disable: function() {
    return this.tag.addClassName('disabled');
  },

  is_disabled: function() {
    return this.tag.hasClassName('disabled');
  }
}

/**
 * Concrete classes for record actions
 */
ActiveScaffold.Actions.Record = Class.create();
ActiveScaffold.Actions.Record.prototype = Object.extend(new ActiveScaffold.Actions.Abstract(), {
  instantiate_link: function(link) {
    var l = new ActiveScaffold.ActionLink.Record(link, this.target, this.loading_indicator);
    l.refresh_url = this.options.refresh_url;
    if (l.position) l.url = l.url.append_params({adapter: '_list_inline_adapter'});
    l.set = this;
    return l;
  }
});

ActiveScaffold.ActionLink.Record = Class.create();
ActiveScaffold.ActionLink.Record.prototype = Object.extend(new ActiveScaffold.ActionLink.Abstract(), {
  insert: function(content) {
    this.set.links.each(function(item) {
      if (item.url != this.url && item.is_disabled() && item.adapter) item.close();
    }.bind(this));

    if (this.position == 'replace') {
      this.position = 'after';
      this.hide_target = true;
    }

    if (this.position == 'after') {
      new Insertion.After(this.target, content);
      this.adapter = this.target.next();
    }
    else if (this.position == 'before') {
      new Insertion.Before(this.target, content);
      this.adapter = this.target.previous();
    }
    else {
      return false;
    }

    this.adapter.down('a.inline-adapter-close').observe('click', function(event) {
      this.close_with_refresh();
      Event.stop(event);
    }.bind(this));

    new Effect.Highlight(this.adapter.down('td'));
  },

  close_with_refresh: function() {
    new Ajax.Request(this.refresh_url, {
      asynchronous: true,
      evalScripts: true,

      onSuccess: function(request) {
        Element.replace(this.target, request.responseText);
        var new_target = $(this.target.id);
        if (this.target.hasClassName('even')) new_target.addClassName('even');
        this.target = new_target;
        this.close();
      }.bind(this)
    });
  },

  enable: function() {
    this.set.links.each(function(item) {
      if (item.url != this.url) return;
      item.tag.removeClassName('disabled');
    }.bind(this));
  },

  disable: function() {
    this.set.links.each(function(item) {
      if (item.url != this.url) return;
      item.tag.addClassName('disabled');
    }.bind(this));
  }
});

/**
 * Concrete classes for table actions
 */
ActiveScaffold.Actions.Table = Class.create();
ActiveScaffold.Actions.Table.prototype = Object.extend(new ActiveScaffold.Actions.Abstract(), {
  instantiate_link: function(link) {
    var l = new ActiveScaffold.ActionLink.Table(link, this.target, this.loading_indicator);
    l.url = l.url.append_params({adapter: '_list_inline_adapter'});
    return l;
  }
});

ActiveScaffold.ActionLink.Table = Class.create();
ActiveScaffold.ActionLink.Table.prototype = Object.extend(new ActiveScaffold.ActionLink.Abstract(), {
  insert: function(content) {
    if (this.position == 'top') {
      new Insertion.Top(this.target, content);
      this.adapter = this.target.immediateDescendants().first();
    }
    else {
      throw 'Unknown position "' + this.position + '"'
    }

    this.adapter.down('a.inline-adapter-close').observe('click', function(event) {
      this.close();
      Event.stop(event);
    }.bind(this));

    new Effect.Highlight(this.adapter.down('td'));
  }
});<commit_msg>made it request.evelResponse<commit_after>if (typeof Prototype == 'undefined')
{
  warning = "ActiveScaffold Error: Prototype could not be found. Please make sure that your application's layout includes prototype.js (e.g. <%= javascript_include_tag :defaults %>) *before* it includes active_scaffold.js (e.g. <%= active_scaffold_includes %>).";
  alert(warning);
}

/*
 * Simple utility methods
 */

var ActiveScaffold = {
  stripe: function(tableBody) {
    var even = false;
    var tableBody = $(tableBody);
    var tableRows = tableBody.getElementsByTagName("tr");
    var length = tableBody.rows.length;

    for (var i = 0; i < length; i++) {
      var tableRow = tableBody.rows[i];
      //Make sure to skip rows that are create or edit rows or messages
      if (!tableRow.hasClassName("create")
        && !tableRow.hasClassName("update")
        && !tableRow.hasClassName("inline-adapter")
        && !tableRow.hasClassName("active-scaffold-calculations")) {

        if (even) {
          tableRow.addClassName("even");
        } else {
          tableRow.removeClassName("even");
        }
        even = !even;
      }
    }
  },
  toggleEmptyMessage: function(tableBody, emptyMessageElement) {
    // Check to see if this was the last element in the list
    if ($(tableBody).rows.length == 0) {
      $(emptyMessageElement).show();
    } else {
      $(emptyMessageElement).hide();
    }
  },
  removeSortClasses: function(active_scaffoldId) {
    $$('#' + active_scaffoldId + ' td.sorted').each(function(element) {
      element.removeClassName("sorted");
    });
    $$('#' + active_scaffoldId + ' th.sorted').each(function(element) {
      element.removeClassName("sorted");
      element.removeClassName("asc");
      element.removeClassName("desc");
    });
  },
  decrement_record_count: function(active_scaffoldId) {
    count = $$('#' + active_scaffoldId + ' span.active-scaffold-records').first();
    count.innerHTML = parseInt(count.innerHTML) - 1;
  },
  increment_record_count: function(active_scaffoldId) {
    count = $$('#' + active_scaffoldId + ' span.active-scaffold-records').first();
    count.innerHTML = parseInt(count.innerHTML) + 1;
  }
}

/*
 * Add-ons/Patches to Prototype
 */

/* patch to support replacing TR/TD/TBODY in Internet Explorer, courtesy of http://dev.rubyonrails.org/ticket/4273 */
Element.replace = function(element, html) {
  element = $(element);
  if (element.outerHTML) {
    try {
    element.outerHTML = html.stripScripts();
    } catch (e) {
      var tn = element.tagName;
      if(tn=='TBODY' || tn=='TR' || tn=='TD')
      {
              var tempDiv = document.createElement("div");
              tempDiv.innerHTML = '
' + html.stripScripts() + '
';
              element.parentNode.replaceChild(tempDiv.getElementsByTagName(tn).item(0), element);
      }
      else throw e;
    }
  } else {
    var range = element.ownerDocument.createRange();
    range.selectNodeContents(element);
    element.parentNode.replaceChild(range.createContextualFragment(html.stripScripts()), element);
  }
  setTimeout(function() {html.evalScripts()}, 10);
};

/*
 * URL modification support. Incomplete functionality.
 */
Object.extend(String.prototype, {
  append_params: function(params) {
    url = this;
    if (url.indexOf('?') == -1) url += '?';
    else if (url.indexOf('&') != url.length) url += '&';

    url += $H(params).collect(function(item) {
      return item.key + '=' + item.value;
    }).join('&');

    return url;
  }
});

/*
 * Nested Form... sorta
 */

Form.Pseudo = Class.create();
Form.Pseudo.prototype = {
  initialize: function(element, options) {
    this.element = $(element);
    this.href = $$("#" + this.element.id + " .form-action")[0].href;
    this.setOptions(options);

    // Put hook on buttons
    this.submitButtons = $$("#" + this.element.id + " .submit");
    for (var i=0; i < this.submitButtons.length; i++) {
      Event.observe(this.submitButtons[i], 'click', this.onSubmit.bindAsEventListener(this));
    }

    // find action uri for request
    this.formElements = Form.getElements(this.element);
    for (var i=0; i < this.formElements.length; i++) {
      Event.observe(this.formElements[i], 'keydown', this.onKeyPress.bindAsEventListener(this));
    }
  },

  setOptions: function(options) {
  this.options = { asynchronous: true,
                     evalScripts: true,
                     onLoading: this.onLoading.bindAsEventListener(this),
                     onLoaded: this.onComplete.bindAsEventListener(this) };
    Object.extend(this.options, options || {});
  },

  onKeyPress: function(event) {
    if (event.keyCode == Event.KEY_RETURN) {
      this.onSubmit(event);
    }
  },

  onLoading: function(request) {
    Form.disable(this.element);
  },

  onComplete: function(request) {
    Form.enable(this.element);
  },

  onSubmit: function(event) {
    var params = Object.extend(this.options, { parameters: Form.serialize(this.element) });
    new Ajax.Request(this.href, params);
    Event.stop(event);
  }
}

var PsuedoForm = {
  clear: function(element) {
    this.element = $(element);

    this.formElements = Form.getElements(this.element);
    for (var i=0; i < this.formElements.length; i++) {
      if (this.formElements[i].type.toLowerCase() != 'submit') {
        this.formElements[i].value = "";
      }
    }
  }
}

/**
 * A set of links. As a set, they can be controlled such that only one is "open" at a time, etc.
 */
ActiveScaffold.Actions = new Object();
ActiveScaffold.Actions.Abstract = function(){}
ActiveScaffold.Actions.Abstract.prototype = {
  initialize: function(links, target, loading_indicator, options) {
    this.target = $(target);
    this.loading_indicator = $(loading_indicator);
    this.options = options;
    this.links = links.collect(function(link) {
      return this.instantiate_link(link);
    }.bind(this));
  },

  instantiate_link: function(link) {
    throw 'unimplemented'
  }
}

/**
 * A DataStructures::ActionLink, represented in JavaScript.
 * Concerned with AJAX-enabling a link and adapting the result for insertion into the table.
 */
ActiveScaffold.ActionLink = new Object();
ActiveScaffold.ActionLink.Abstract = function(){}
ActiveScaffold.ActionLink.Abstract.prototype = {
  initialize: function(a, target, loading_indicator) {
    this.tag = $(a);
    this.url = this.tag.href;
    this.target = target;
    this.loading_indicator = loading_indicator;
    this.hide_target = false;
    this.position = this.tag.getAttribute('position');

    this.onclick = this.tag.onclick;
    this.tag.onclick = null;
    this.tag.observe('click', function(event) {
      this.open();
      Event.stop(event);
    }.bind(this));

    this.tag.action_link = this;
  },

  open: function() {
    if (this.is_disabled()) return;
    if (this.onclick && !this.onclick()) return;//e.g. confirmation messages
    if (this.position) this.disable();
    this.loading_indicator.style.visibility = 'visible';
    new Ajax.Request(this.url, {
      asynchronous: true,
      evalScripts: true,

      onSuccess: function(request) {
        if (this.position) {
          this.insert(request.responseText);
          if (this.hide_target) this.target.hide();
        }	else {
					request.evalResponse();
				}
      }.bind(this),

      onFailure: function(request) {
        if (this.position) this.enable()
      }.bind(this),

      onComplete: function(request) {
        this.loading_indicator.style.visibility = 'hidden';
      }.bind(this)
    });
  },

  insert: function(content) {
    throw 'unimplemented'
  },

  close: function() {
    this.enable();
    this.adapter.remove();
    if (this.hide_target) this.target.show();
  },

  get_new_adapter_id: function() {
    var id = 'adapter_';
    var i = 0;
    while ($(id + i)) i++;
    return id + i;
  },

  enable: function() {
    return this.tag.removeClassName('disabled');
  },

  disable: function() {
    return this.tag.addClassName('disabled');
  },

  is_disabled: function() {
    return this.tag.hasClassName('disabled');
  }
}

/**
 * Concrete classes for record actions
 */
ActiveScaffold.Actions.Record = Class.create();
ActiveScaffold.Actions.Record.prototype = Object.extend(new ActiveScaffold.Actions.Abstract(), {
  instantiate_link: function(link) {
    var l = new ActiveScaffold.ActionLink.Record(link, this.target, this.loading_indicator);
    l.refresh_url = this.options.refresh_url;
    if (l.position) l.url = l.url.append_params({adapter: '_list_inline_adapter'});
    l.set = this;
    return l;
  }
});

ActiveScaffold.ActionLink.Record = Class.create();
ActiveScaffold.ActionLink.Record.prototype = Object.extend(new ActiveScaffold.ActionLink.Abstract(), {
  insert: function(content) {
    this.set.links.each(function(item) {
      if (item.url != this.url && item.is_disabled() && item.adapter) item.close();
    }.bind(this));

    if (this.position == 'replace') {
      this.position = 'after';
      this.hide_target = true;
    }

    if (this.position == 'after') {
      new Insertion.After(this.target, content);
      this.adapter = this.target.next();
    }
    else if (this.position == 'before') {
      new Insertion.Before(this.target, content);
      this.adapter = this.target.previous();
    }
    else {
      return false;
    }

    this.adapter.down('a.inline-adapter-close').observe('click', function(event) {
      this.close_with_refresh();
      Event.stop(event);
    }.bind(this));

    new Effect.Highlight(this.adapter.down('td'));
  },

  close_with_refresh: function() {
    new Ajax.Request(this.refresh_url, {
      asynchronous: true,
      evalScripts: true,

      onSuccess: function(request) {
        Element.replace(this.target, request.responseText);
        var new_target = $(this.target.id);
        if (this.target.hasClassName('even')) new_target.addClassName('even');
        this.target = new_target;
        this.close();
      }.bind(this)
    });
  },

  enable: function() {
    this.set.links.each(function(item) {
      if (item.url != this.url) return;
      item.tag.removeClassName('disabled');
    }.bind(this));
  },

  disable: function() {
    this.set.links.each(function(item) {
      if (item.url != this.url) return;
      item.tag.addClassName('disabled');
    }.bind(this));
  }
});

/**
 * Concrete classes for table actions
 */
ActiveScaffold.Actions.Table = Class.create();
ActiveScaffold.Actions.Table.prototype = Object.extend(new ActiveScaffold.Actions.Abstract(), {
  instantiate_link: function(link) {
    var l = new ActiveScaffold.ActionLink.Table(link, this.target, this.loading_indicator);
    l.url = l.url.append_params({adapter: '_list_inline_adapter'});
    return l;
  }
});

ActiveScaffold.ActionLink.Table = Class.create();
ActiveScaffold.ActionLink.Table.prototype = Object.extend(new ActiveScaffold.ActionLink.Abstract(), {
  insert: function(content) {
    if (this.position == 'top') {
      new Insertion.Top(this.target, content);
      this.adapter = this.target.immediateDescendants().first();
    }
    else {
      throw 'Unknown position "' + this.position + '"'
    }

    this.adapter.down('a.inline-adapter-close').observe('click', function(event) {
      this.close();
      Event.stop(event);
    }.bind(this));

    new Effect.Highlight(this.adapter.down('td'));
  }
});<|endoftext|>


<commit_before>this.GobiertoAdmin.GlobalizedFormsComponent = (function() {
  function GlobalizedFormsComponent() {}

  GlobalizedFormsComponent.prototype.handle = function(message) {
    $(document).on("turbolinks:load", _handleGlobalizedForm);
  };

  function _handleGlobalizedForm() {
    var $globalizedForm = _findGlobalizedForm();
    if(!$globalizedForm.length) return;

    $globalizedForm.find('[data-toggle-edit-locale]').on("click", _toggleLocaleClickHandler);
    $globalizedForm.on("change", "input, select, textarea", _changeHandler);

    var currentLocale = $globalizedForm.find('[data-loaded-locale]').data('loaded-locale');
    if(currentLocale === undefined)
      currentLocale = I18n.defaultLocale;
    _activateLocale(currentLocale);
    _checkCompleted($globalizedForm);
  }

  function _toggleLocaleClickHandler(e){
    e.preventDefault();
    _activateLocale($(this).data('toggle-edit-locale'));
  }

  function _changeHandler(e){
    _checkCompleted(_findGlobalizedForm());
  }

  function _activateLocale(currentLocale){
    var $globalizedForm = _findGlobalizedForm();

    $globalizedForm.find('[data-toggle-edit-locale]').removeClass('selected');
    $globalizedForm.find('[data-toggle-edit-locale='+currentLocale+']').addClass('selected');

    $globalizedForm.find('[data-locale]').each(function(){
      $(this).data('locale') !== currentLocale ? $(this).hide() : $(this).show();
    });
  }

  function _checkCompleted($globalizedForm){
    $globalizedForm.find('[data-toggle-edit-locale]').each(function(){
      var locale = $(this).data('toggle-edit-locale');
      var completed = true;
      var $el = $globalizedForm.find('[data-locale='+locale+']');

      $el.find("input, select, textarea").each(function(){
        if($(this).attr('id') !== undefined && $(this).val() === ""){
          completed = false;
        }
      });

      $el = $globalizedForm.find('[data-toggle-edit-locale='+locale+']');
      completed ? $el.addClass('completed') : $el.removeClass('completed');
    });
  }

  function _findGlobalizedForm(){
    return $("form[data-globalized-form-container]");
  }

  return GlobalizedFormsComponent;
})();

this.GobiertoAdmin.globalized_forms_component = new GobiertoAdmin.GlobalizedFormsComponent;
<commit_msg>Fix locale switcher scope<commit_after>this.GobiertoAdmin.GlobalizedFormsComponent = (function() {
  function GlobalizedFormsComponent() {}

  GlobalizedFormsComponent.prototype.handle = function(message) {
    $(document).on("turbolinks:load", _handleGlobalizedForm);
  };

  function _handleGlobalizedForm() {
    var $container = _findGlobalizedFormContainer();
    if(!$container.length) return;

    $container.find('[data-toggle-edit-locale]').on("click", _toggleLocaleClickHandler);
    $container.on("change", "input, select, textarea", _changeHandler);

    var currentLocale = $container.find('[data-loaded-locale]').data('loaded-locale');
    if(currentLocale === undefined)
      currentLocale = I18n.defaultLocale;
    _activateLocale(currentLocale);
    _checkCompleted($container);
  }

  function _toggleLocaleClickHandler(e){
    e.preventDefault();
    _activateLocale($(this).data('toggle-edit-locale'));
  }

  function _changeHandler(e){
    _checkCompleted(_findGlobalizedFormContainer());
  }

  function _activateLocale(currentLocale){
    var $container = _findGlobalizedFormContainer();

    $container.find('[data-toggle-edit-locale]').removeClass('selected');
    $container.find('[data-toggle-edit-locale='+currentLocale+']').addClass('selected');

    $container.find('[data-locale]').each(function(){
      $(this).data('locale') !== currentLocale ? $(this).hide() : $(this).show();
    });
  }

  function _checkCompleted($container){
    $container.find('[data-toggle-edit-locale]').each(function(){
      var locale = $(this).data('toggle-edit-locale');
      var completed = true;
      var $el = $container.find('[data-locale='+locale+']');

      $el.find("input, select, textarea").each(function(){
        if($(this).attr('id') !== undefined && $(this).val() === ""){
          completed = false;
        }
      });

      $el = $container.find('[data-toggle-edit-locale='+locale+']');
      completed ? $el.addClass('completed') : $el.removeClass('completed');
    });
  }

  function _findGlobalizedFormContainer(){
    return $("form[data-globalized-form-container] .globalized_fields");
  }

  return GlobalizedFormsComponent;
})();

this.GobiertoAdmin.globalized_forms_component = new GobiertoAdmin.GlobalizedFormsComponent;
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */
foam.CLASS({
  package: 'foam.nanos.auth',
  name: 'User',

  implements: [
    'foam.nanos.auth.EnabledAware',
    'foam.nanos.auth.LastModifiedAware',
    'foam.nanos.auth.LastModifiedByAware'
  ],

  requires: [ 'foam.nanos.auth.Phone',
              'foam.nanos.auth.Address'
  ],

  documentation: '',

  tableColumns: [
    'id', 'enabled', 'type', 'firstName', 'lastName', 'organization', 'email'
  ],

  properties: [
    {
      class: 'Long',
      name: 'id',
      max: 999,
      tableWidth: 45
    },
    {
      class: 'String',
      // class: 'SPID',
      label: 'Service Provider',
      name: 'spid',
      documentation: "User's service provider."
    },
    {
      class: 'DateTime',
      name: 'lastLogin'
    },
    {
      class: 'String',
      name: 'firstName',
      tableWidth: 160
    },
    {
      class: 'String',
      name: 'middleName'
    },
    {
      class: 'String',
      name: 'lastName',
      tableWidth: 160
    },
    {
      class: 'String',
      name: 'organization',
      width: 175,
      tableWidth: 160
    },
    {
      class: 'String',
      name: 'department',
      width: 50
    },
    {
      class: 'EMail',
      name: 'email',
      width: 200,
      preSet: function (_, val) {
        return val.toLowerCase();
      },
      javaSetter:
`email_ = val.toLowerCase();
emailIsSet_ = true;`
    },
    {
      class: 'FObjectProperty',
      of: 'foam.nanos.auth.Phone',
      name: 'phone',
      factory: function() { return this.Phone.create(); },
      view: 'foam.nanos.auth.PhoneDetailView'
    },
    {
      class: 'FObjectProperty',
      of: 'foam.nanos.auth.Phone',
      name: 'mobile',
      factory: function() { return this.Phone.create(); },
      view: 'foam.nanos.auth.PhoneDetailView'
    },
    {
      class: 'String',
      name: 'type',
      tableWidth: 91,
      view: {
        class: 'foam.u2.view.ChoiceView',
        choices: [ 'Personal', 'Business', 'Shopper', 'Merchant', 'Broker', 'Bank' ]
      }
    },
    {
      class: 'Date',
      name: 'birthday'
    },
    {
      class: 'Blob',
      name: 'profilePicture',
      tableCellFormatter: function (value) {
        this.tag({ class: 'foam.u2.view.ImageBlobView' });
      }
    },
    {
      class: 'FObjectProperty',
      of: 'foam.nanos.auth.Address',
      name: 'address',
      factory: function() { return this.Address.create(); },
      view: 'foam.nanos.auth.AddressDetailView'
    },
    {
      class: 'FObjectArray',
      of: 'foam.core.FObject',
      name: 'accounts',
      hidden: true
    },
    {
      class: 'Reference',
      name: 'language',
      of: 'foam.nanos.auth.Language',
      value: 'en'
    },
    {
      class: 'String',
      name: 'timeZone',
      width: 5
      // TODO: create custom view or DAO
    },
    {
      class: 'Password',
      name: 'password',
      displayWidth: 30,
      width: 100
    },
    {
      class: 'Password',
      name: 'previousPassword',
      hidden: true,
      displayWidth: 30,
      width: 100
    },
    {
      class: 'DateTime',
      name: 'passwordLastModified'
    },
    // TODO: startDate, endDate,
    // TODO: do we want to replace 'note' with a simple ticket system?
    {
      class: 'String',
      name: 'note',
      displayWidth: 70,
      view: { class: 'foam.u2.tag.TextArea', rows: 4, cols: 100 }
    },
    // TODO: remove after demo
    {
      class: 'String',
      name: 'businessName',
      documentation: 'Name of the business',
      width: 50
    },
    {
      class: 'String',
      name: 'businessIdentificationNumber',
      width: 20,
      documentation: 'Business Identification Number (BIN)'
    },
    {
      class: 'String',
      name: 'bankIdentificationCode',
      width: 20,
      documentation: 'Bank Identification Code (BIC)'
    },
    {
      class: 'String',
      name: 'website',
      width: 50
    },
    {
      class: 'String',
      name: 'businessType',
      width: 15
    },
    {
      class: 'String',
      name: 'businessSector',
      width: 15
    }
  ],

  methods: [
    function label() {
      return this.organization || ( this.firstName + this.lastName );
    }
  ]
});
<commit_msg>Took out businessType and businessSector due to User refinement<commit_after>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */
foam.CLASS({
  package: 'foam.nanos.auth',
  name: 'User',

  implements: [
    'foam.nanos.auth.EnabledAware',
    'foam.nanos.auth.LastModifiedAware',
    'foam.nanos.auth.LastModifiedByAware'
  ],

  requires: [ 'foam.nanos.auth.Phone',
              'foam.nanos.auth.Address'
  ],

  documentation: '',

  tableColumns: [
    'id', 'enabled', 'type', 'firstName', 'lastName', 'organization', 'email'
  ],

  properties: [
    {
      class: 'Long',
      name: 'id',
      max: 999,
      tableWidth: 45
    },
    {
      class: 'String',
      // class: 'SPID',
      label: 'Service Provider',
      name: 'spid',
      documentation: "User's service provider."
    },
    {
      class: 'DateTime',
      name: 'lastLogin'
    },
    {
      class: 'String',
      name: 'firstName',
      tableWidth: 160
    },
    {
      class: 'String',
      name: 'middleName'
    },
    {
      class: 'String',
      name: 'lastName',
      tableWidth: 160
    },
    {
      class: 'String',
      name: 'organization',
      width: 175,
      tableWidth: 160
    },
    {
      class: 'String',
      name: 'department',
      width: 50
    },
    {
      class: 'EMail',
      name: 'email',
      width: 200,
      preSet: function (_, val) {
        return val.toLowerCase();
      },
      javaSetter:
`email_ = val.toLowerCase();
emailIsSet_ = true;`
    },
    {
      class: 'FObjectProperty',
      of: 'foam.nanos.auth.Phone',
      name: 'phone',
      factory: function() { return this.Phone.create(); },
      view: 'foam.nanos.auth.PhoneDetailView'
    },
    {
      class: 'FObjectProperty',
      of: 'foam.nanos.auth.Phone',
      name: 'mobile',
      factory: function() { return this.Phone.create(); },
      view: 'foam.nanos.auth.PhoneDetailView'
    },
    {
      class: 'String',
      name: 'type',
      tableWidth: 91,
      view: {
        class: 'foam.u2.view.ChoiceView',
        choices: [ 'Personal', 'Business', 'Shopper', 'Merchant', 'Broker', 'Bank' ]
      }
    },
    {
      class: 'Date',
      name: 'birthday'
    },
    {
      class: 'Blob',
      name: 'profilePicture',
      tableCellFormatter: function (value) {
        this.tag({ class: 'foam.u2.view.ImageBlobView' });
      }
    },
    {
      class: 'FObjectProperty',
      of: 'foam.nanos.auth.Address',
      name: 'address',
      factory: function() { return this.Address.create(); },
      view: 'foam.nanos.auth.AddressDetailView'
    },
    {
      class: 'FObjectArray',
      of: 'foam.core.FObject',
      name: 'accounts',
      hidden: true
    },
    {
      class: 'Reference',
      name: 'language',
      of: 'foam.nanos.auth.Language',
      value: 'en'
    },
    {
      class: 'String',
      name: 'timeZone',
      width: 5
      // TODO: create custom view or DAO
    },
    {
      class: 'Password',
      name: 'password',
      displayWidth: 30,
      width: 100
    },
    {
      class: 'Password',
      name: 'previousPassword',
      hidden: true,
      displayWidth: 30,
      width: 100
    },
    {
      class: 'DateTime',
      name: 'passwordLastModified'
    },
    // TODO: startDate, endDate,
    // TODO: do we want to replace 'note' with a simple ticket system?
    {
      class: 'String',
      name: 'note',
      displayWidth: 70,
      view: { class: 'foam.u2.tag.TextArea', rows: 4, cols: 100 }
    },
    // TODO: remove after demo
    {
      class: 'String',
      name: 'businessName',
      documentation: 'Name of the business',
      width: 50
    },
    {
      class: 'String',
      name: 'businessIdentificationNumber',
      width: 20,
      documentation: 'Business Identification Number (BIN)'
    },
    {
      class: 'String',
      name: 'bankIdentificationCode',
      width: 20,
      documentation: 'Bank Identification Code (BIC)'
    },
    {
      class: 'String',
      name: 'website',
      width: 50
    }
  ],

  methods: [
    function label() {
      return this.organization || ( this.firstName + this.lastName );
    }
  ]
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */
foam.CLASS({
  package: 'foam.nanos.auth',
  name: 'User',

  implements: [
    'foam.nanos.auth.EnabledAware',
    'foam.nanos.auth.LastModifiedAware',
    'foam.nanos.auth.LastModifiedByAware'
  ],

  documentation: '',

  tableColumns: [
    'id', 'enabled', 'firstName', 'lastName', 'organization', 'lastModified'
  ],

  properties: [
    {
      class: 'Long',
      name: 'id',
      max: 999,
      tableWidth: 45
    },
    {
      class: 'String',
      // class: 'SPID',
      label: 'Service Provider',
      name: 'spid',
      documentation: "User's service provider."
    },
    {
      class: 'DateTime',
      name: 'lastLogin'
    },
    {
      class: 'String',
      name: 'firstName',
      tableWidth: 160
    },
    {
      class: 'String',
      name: 'middleName'
    },
    {
      class: 'String',
      name: 'lastName',
      tableWidth: 160
    },
    {
      class: 'String',
      name: 'organization',
      width: 50,
      tableWidth: 160
    },
    {
      class: 'String',
      name: 'department',
      width: 50
    },
    {
      class: 'EMail',
      name: 'email',
      width: 50,
      preSet: function (_, val) {
        return val.toLowerCase();
      },
      javaSetter:
`email_ = val.toLowerCase();
emailIsSet_ = true;`
    },
    {
      class: 'FObjectProperty',
      of: 'foam.nanos.auth.Phone',
      name: 'phone',
      factory: function() { return foam.nanos.auth.Phone.create(); }
    },
    {
      class: 'FObjectProperty',
      of: 'foam.nanos.auth.Phone',
      name: 'mobile',
      factory: function() { return foam.nanos.auth.Phone.create(); }
    },
    {
      class: 'String',
      name: 'type',
      view: {
        class: 'foam.u2.view.ChoiceView',
        choices: [ 'Personal', 'Business', 'Broker', 'Bank' ]
      }
    },
    {
      class: 'Date',
      name: 'birthday'
    },
    {
      class: 'Blob',
      name: 'profilePicture',
      tableCellFormatter: function (value) {
        this.tag({ class: 'foam.u2.view.ImageBlobView' });
      }
    },
    {
      class: 'FObjectProperty',
      of: 'foam.nanos.auth.Address',
      name: 'address',
      factory: function() { return foam.nanos.auth.Address.create(); }
    },
    {
      class: 'FObjectArray',
      of: 'foam.core.FObject',
      name: 'accounts',
      hidden: true
    },
    {
      class: 'Reference',
      name: 'language',
      of: 'foam.nanos.auth.Language',
      value: 'en'
    },
    {
      class: 'String',
      name: 'timeZone',
      width: 5
      // TODO: create custom view or DAO
    },
    {
      class: 'Password',
      name: 'password',
      hidden: true,
      displayWidth: 30,
      width: 100
    },
    {
      class: 'Password',
      name: 'previousPassword',
      hidden: true,
      displayWidth: 30,
      width: 100
    },
    {
      class: 'DateTime',
      name: 'passwordLastModified'
    },
    // TODO: startDate, endDate,
    // TODO: do we want to replace 'note' with a simple ticket system?
    {
      class: 'String',
      name: 'note',
      displayWidth: 70,
      view: { class: 'foam.u2.tag.TextArea', rows: 4, cols: 100 }
    },
    // TODO: remove after demo
    {
      class: 'String',
      name: 'businessName',
      documentation: 'Name of the business',
      width: 50
    },
    {
      class: 'String',
      name: 'businessIdentificationNumber',
      width: 20,
      documentation: 'Business Identification Number (BIN)'
    },
    {
      class: 'String',
      name: 'bankIdentificationCode',
      width: 20,
      documentation: 'Bank Identification Code (BIC)'
    },
    {
      class: 'String',
      name: 'website',
      width: 50
    },
    {
      class: 'String',
      name: 'businessType',
      width: 15
    },
    {
      class: 'String',
      name: 'businessSector',
      width: 15
    }
  ],

  methods: [
    function label() {
      return this.organization || ( this.firstName + this.lastName );
    }
  ]
});
<commit_msg>addressDetailView<commit_after>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */
foam.CLASS({
  package: 'foam.nanos.auth',
  name: 'User',

  implements: [
    'foam.nanos.auth.EnabledAware',
    'foam.nanos.auth.LastModifiedAware',
    'foam.nanos.auth.LastModifiedByAware'
  ],

  documentation: '',

  tableColumns: [
    'id', 'enabled', 'firstName', 'lastName', 'organization', 'lastModified'
  ],

  properties: [
    {
      class: 'Long',
      name: 'id',
      max: 999,
      tableWidth: 45
    },
    {
      class: 'String',
      // class: 'SPID',
      label: 'Service Provider',
      name: 'spid',
      documentation: "User's service provider."
    },
    {
      class: 'DateTime',
      name: 'lastLogin'
    },
    {
      class: 'String',
      name: 'firstName',
      tableWidth: 160
    },
    {
      class: 'String',
      name: 'middleName'
    },
    {
      class: 'String',
      name: 'lastName',
      tableWidth: 160
    },
    {
      class: 'String',
      name: 'organization',
      width: 50,
      tableWidth: 160
    },
    {
      class: 'String',
      name: 'department',
      width: 50
    },
    {
      class: 'EMail',
      name: 'email',
      width: 50,
      preSet: function (_, val) {
        return val.toLowerCase();
      },
      javaSetter:
`email_ = val.toLowerCase();
emailIsSet_ = true;`
    },
    {
      class: 'FObjectProperty',
      of: 'foam.nanos.auth.Phone',
      name: 'phone',
      factory: function() { return foam.nanos.auth.Phone.create(); }
    },
    {
      class: 'FObjectProperty',
      of: 'foam.nanos.auth.Phone',
      name: 'mobile',
      factory: function() { return foam.nanos.auth.Phone.create(); }
    },
    {
      class: 'String',
      name: 'type',
      view: {
        class: 'foam.u2.view.ChoiceView',
        choices: [ 'Personal', 'Business', 'Broker', 'Bank' ]
      }
    },
    {
      class: 'Date',
      name: 'birthday'
    },
    {
      class: 'Blob',
      name: 'profilePicture',
      tableCellFormatter: function (value) {
        this.tag({ class: 'foam.u2.view.ImageBlobView' });
      }
    },
    {
      class: 'FObjectProperty',
      //of: 'foam.nanos.auth.Address',
      name: 'address',
      view: 'foam.u2.AddressDetailView'
    },
    {
      class: 'FObjectArray',
      of: 'foam.core.FObject',
      name: 'accounts',
      hidden: true
    },
    {
      class: 'Reference',
      name: 'language',
      of: 'foam.nanos.auth.Language',
      value: 'en'
    },
    {
      class: 'String',
      name: 'timeZone',
      width: 5
      // TODO: create custom view or DAO
    },
    {
      class: 'Password',
      name: 'password',
      hidden: true,
      displayWidth: 30,
      width: 100
    },
    {
      class: 'Password',
      name: 'previousPassword',
      hidden: true,
      displayWidth: 30,
      width: 100
    },
    {
      class: 'DateTime',
      name: 'passwordLastModified'
    },
    // TODO: startDate, endDate,
    // TODO: do we want to replace 'note' with a simple ticket system?
    {
      class: 'String',
      name: 'note',
      displayWidth: 70,
      view: { class: 'foam.u2.tag.TextArea', rows: 4, cols: 100 }
    },
    // TODO: remove after demo
    {
      class: 'String',
      name: 'businessName',
      documentation: 'Name of the business',
      width: 50
    },
    {
      class: 'String',
      name: 'businessIdentificationNumber',
      width: 20,
      documentation: 'Business Identification Number (BIN)'
    },
    {
      class: 'String',
      name: 'bankIdentificationCode',
      width: 20,
      documentation: 'Bank Identification Code (BIC)'
    },
    {
      class: 'String',
      name: 'website',
      width: 50
    },
    {
      class: 'String',
      name: 'businessType',
      width: 15
    },
    {
      class: 'String',
      name: 'businessSector',
      width: 15
    }
  ],

  methods: [
    function label() {
      return this.organization || ( this.firstName + this.lastName );
    }
  ]
});
<|endoftext|>


<commit_before>/*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

(function (document) {
  'use strict';

  // Grab a reference to our auto-binding template
  // and give it some initial binding values
  // Learn more about auto-binding templates at http://goo.gl/Dx1u2g
  var app = document.querySelector('#app');

  app.displayInstalledToast = function() {
    document.querySelector('#caching-complete').show();
  };

  // Listen for template bound event to know when bindings
  // have resolved and content has been stamped to the page
  app.addEventListener('template-bound', function() {
    console.log('Our app is ready to rock!');
  });

  // See https://github.com/Polymer/polymer/issues/1381
  window.addEventListener('WebComponentsReady', function() {
    document.querySelector('body').removeAttribute('unresolved');

    var pages = document.getElementById('pages');
    var firstPage = pages.selectedItem.getElementsByClassName('page')[0];
    if(firstPage){
      page.onSelect();
    }

    pages.addEventListener('iron-select', function(e){
      var page = e.detail.item.getElementsByClassName('page')[0];
      if(page){
        page.onSelect();
      }
    });

  });

})(document);

// TODO: Decide if we still want to suggest wrapping as it requires
// using webcomponents.min.js.
// wrap document so it plays nice with other libraries
// http://www.polymer-project.org/platform/shadow-dom.html#wrappers
// )(wrap(document));
<commit_msg>fixed typo<commit_after>/*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

(function (document) {
  'use strict';

  // Grab a reference to our auto-binding template
  // and give it some initial binding values
  // Learn more about auto-binding templates at http://goo.gl/Dx1u2g
  var app = document.querySelector('#app');

  app.displayInstalledToast = function() {
    document.querySelector('#caching-complete').show();
  };

  // Listen for template bound event to know when bindings
  // have resolved and content has been stamped to the page
  app.addEventListener('template-bound', function() {
    console.log('Our app is ready to rock!');
  });

  // See https://github.com/Polymer/polymer/issues/1381
  window.addEventListener('WebComponentsReady', function() {
    document.querySelector('body').removeAttribute('unresolved');

    var pages = document.getElementById('pages');
    var firstPage = pages.selectedItem.getElementsByClassName('page')[0];
    if(firstPage){
      firstPage.onSelect();
    }

    pages.addEventListener('iron-select', function(e){
      var page = e.detail.item.getElementsByClassName('page')[0];
      if(page){
        page.onSelect();
      }
    });

  });

})(document);

// TODO: Decide if we still want to suggest wrapping as it requires
// using webcomponents.min.js.
// wrap document so it plays nice with other libraries
// http://www.polymer-project.org/platform/shadow-dom.html#wrappers
// )(wrap(document));
<|endoftext|>


<commit_before>this.GobiertoPlans.PlansController = (function() {

    function PlansController() {}

    PlansController.prototype.show = function() {
      _loadPlan();
    };

    function _loadPlan() {

      // define the node root component
      Vue.component('node-root', {
        template: '#node-root-template',
        props: ['model'],
        data() {
          return {}
        },
        methods: {
          t(key) {
            return this.$root.t(key)
          },
          open() {
            // Trigger event
            this.$emit('selection', { ...this.model });

            // REVIEW: Revisar este bloque
            $('section.level_1 .js-img').velocity({flex: "0"});
            $('section.level_1 .js-info').velocity({padding: "1.5em"});
            $('section.level_1 .js-info h3, section.level_1 .js-info span').velocity({"font-size": "1.25rem" });

            $('section.level_1').velocity({flex: "0 0 25%"});
            $('section.level_2').velocity("transition.slideRightBigIn");
            $('section.level_2').css("display: flex");

          }
        }
      });

      // define the node list component
      Vue.component('node-list', {
        template: '#node-list-template',
        props: ['model'],
        data() {
          return {}
        },
        methods: {
          t(key) {
            return this.$root.t(key)
          },
          expand: function() {
            let l = this.model.level;

            if (l === 1) {
              this.$emit('selection', { ...this.model });

              // hacky
              $('section.level_' + (l + 1)).hide();
              $('section.level_' + (l + 2)).velocity("transition.slideRightBigIn");
              $('section.level_' + (l + 2)).css("display: flex");
            }

            if (l === 2) this.$emit("toggle");
          }
        }
      });

      new Vue({
        el: '#gobierto-planification',
        name: 'gobierto-planification',
        data: {
          json: {},
          activeNode: {},
          showTable: {}
        },
        created: function() {
          this.getJson();
        },
        mounted: function () {
          //close everything
          // REVIEW: provoca error
          // $(document).click(function (e) {
          //   e.preventDefault();
          //
          //   // if the target of the click isn't the container nor a descendant of the container REVIEW
          //   var container = $(".planification-content");
          //   if (!container.is(e.target) && container.has(e.target).length === 0) {
          //     this.activeNode = {};
          //
          //     $('section.level_1').removeAttr('style');
          //     $('section.level_1 .js-img').removeAttr('style');
          //     $('section.level_1 .js-info').removeAttr('style');
          //     $('section.level_1 .js-info h3, section.level_1 .js-info span').removeAttr('style');
          //   }
          // }).bind(this);
        },
        watch: {
          activeNode: {
            handler: function(node) {
              this.showTable = {};
              this.isOpen(node.level);
            },
            deep: true
          }
        },
        computed: {
          detail() {
            if (!this.json.length) return {}
            let detail = {};
            detail = {
              roots: this.json.length,
              lines: _.flatten(_.map(this.json, 'children')).length,
              actions: this.json.length,
              projects: this.json.length
            };
            return detail
          },
        },
        methods: {
          getJson: function() {
            $.getJSON('/sandbox/data/planification.json', function(json) {
              this.json = json;
            }.bind(this));
          },
          t(key) {
            return key[I18n.locale]
          },
          color(o) {
            if (this.isEmpty()) return 1;
            return this.activeNode.id % 5 + 1;
          },
          setSelection(model) {
            this.activeNode = model;
          },
          isOpen(level) {
            return level <= this.activeNode.level;
          },
          isEmpty() {
            return _.isEmpty(this.activeNode);
          },
          toggle(i) {
            Vue.set(this.showTable, i, !(this.showTable[i]));
          }
        }
      });
    };

    return PlansController;
  })();

  this.GobiertoPlans.plans_controller = new GobiertoPlans.PlansController;
<commit_msg>set colors based on root<commit_after>this.GobiertoPlans.PlansController = (function() {

    function PlansController() {}

    PlansController.prototype.show = function() {
      _loadPlan();
    };

    function _loadPlan() {

      // define the node root component
      Vue.component('node-root', {
        template: '#node-root-template',
        props: ['model'],
        data() {
          return {}
        },
        methods: {
          t(key) {
            return this.$root.t(key)
          },
          open() {
            // Trigger event
            this.$emit('selection', { ...this.model });

            // REVIEW: Revisar este bloque
            $('section.level_1 .js-img').velocity({flex: "0"});
            $('section.level_1 .js-info').velocity({padding: "1.5em"});
            $('section.level_1 .js-info h3, section.level_1 .js-info span').velocity({"font-size": "1.25rem" });

            $('section.level_1').velocity({flex: "0 0 25%"});
            $('section.level_2').velocity("transition.slideRightBigIn");
            $('section.level_2').css("display: flex");

          }
        }
      });

      // define the node list component
      Vue.component('node-list', {
        template: '#node-list-template',
        props: ['model'],
        data() {
          return {}
        },
        methods: {
          t(key) {
            return this.$root.t(key)
          },
          expand: function() {
            let l = this.model.level;

            if (l === 1) {
              this.$emit('selection', { ...this.model });

              // hacky
              $('section.level_' + (l + 1)).hide();
              $('section.level_' + (l + 2)).velocity("transition.slideRightBigIn");
              $('section.level_' + (l + 2)).css("display: flex");
            }

            if (l === 2) this.$emit("toggle");
          }
        }
      });

      new Vue({
        el: '#gobierto-planification',
        name: 'gobierto-planification',
        data: {
          json: {},
          activeNode: {},
          showTable: {},
          rootid: 0
        },
        created: function() {
          this.getJson();
        },
        mounted: function () {
          //close everything
          // REVIEW: provoca error
          // $(document).click(function (e) {
          //   e.preventDefault();
          //
          //   // if the target of the click isn't the container nor a descendant of the container REVIEW
          //   var container = $(".planification-content");
          //   if (!container.is(e.target) && container.has(e.target).length === 0) {
          //     this.activeNode = {};
          //
          //     $('section.level_1').removeAttr('style');
          //     $('section.level_1 .js-img').removeAttr('style');
          //     $('section.level_1 .js-info').removeAttr('style');
          //     $('section.level_1 .js-info h3, section.level_1 .js-info span').removeAttr('style');
          //   }
          // }).bind(this);
        },
        watch: {
          activeNode: {
            handler: function(node) {
              this.showTable = {};
              this.isOpen(node.level);
              // TODO: Necesito saber quién es el nodo raiz del nodo activo
            },
            deep: true
          }
        },
        computed: {
          detail() {
            if (!this.json.length) return {}
            let detail = {};
            detail = {
              roots: this.json.length,
              lines: _.flatten(_.map(this.json, 'children')).length,
              actions: this.json.length,
              projects: this.json.length
            };
            return detail
          },
        },
        methods: {
          getJson: function() {
            $.getJSON('/sandbox/data/planification.json', function(json) {
              this.json = json;
            }.bind(this));
          },
          t(key) {
            return key[I18n.locale]
          },
          color(o) {
            if (this.isEmpty()) return 1;
            return this.rootid % 5 + 1;
            // return this.activeNode.id % 5 + 1;
          },
          setSelection(model) {
            this.activeNode = model;

            // To know the root node
            if (this.activeNode.level === 0) {
              this.rootid = this.activeNode.id
            }
          },
          isOpen(level) {
            return level <= this.activeNode.level;
          },
          isEmpty() {
            return _.isEmpty(this.activeNode);
          },
          toggle(i) {
            Vue.set(this.showTable, i, !(this.showTable[i]));
          }
        }
      });
    };

    return PlansController;
  })();

  this.GobiertoPlans.plans_controller = new GobiertoPlans.PlansController;
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

var _http = require('http');

var _http2 = _interopRequireDefault(_http);

var _https = require('https');

var _https2 = _interopRequireDefault(_https);

var _s3 = require('s3');

var _s32 = _interopRequireDefault(_s3);

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _progress = require('progress');

var _progress2 = _interopRequireDefault(_progress);

var _cdnizer = require('cdnizer');

var _cdnizer2 = _interopRequireDefault(_cdnizer);

_http2['default'].globalAgent.maxSockets = _https2['default'].globalAgent.maxSockets = 50;

var S3Plugin = (function () {
  function S3Plugin() {
    var options = arguments.length <= 0 || arguments[0] === undefined ? { s3Options: {} } : arguments[0];

    _classCallCheck(this, S3Plugin);

    var s3Options = options.s3Options;
    var directory = options.directory;
    var include = options.include;
    var exclude = options.exclude;
    var basePath = options.basePath;
    var cdnizerOptions = options.cdnizerOptions;
    var htmlFiles = options.htmlFiles;

    this.requiredS3Opts = ['accessKeyId', 'secretAccessKey', 'Bucket'];
    this.isConnected = false;
    this.cdnizerOptions = cdnizerOptions;
    this.urlMappings = [];
    this.uploadTotal = 0;
    this.uploadProgress = 0;

    this.options = {
      directory: directory,
      include: include,
      exclude: exclude,
      htmlFiles: typeof htmlFiles === 'string' ? [htmlFiles] : htmlFiles
    };

    this.clientConfig = {
      maxAsyncS3: 50,
      s3Options: s3Options
    };

    if (!this.cdnizerOptions.files) this.cdnizerOptions.files = [];

    if (!this.cdnizerOptions) this.noCdnizer = true;
  }

  _createClass(S3Plugin, [{
    key: 'apply',
    value: function apply(compiler) {
      var _this = this;

      var hasRequiredOptions = this.requiredS3Opts.every(function (type) {
        return _this.clientConfig.s3Options[type];
      });

      // Set directory to output dir or custom
      this.options.directory = this.options.directory || compiler.options.output.path;

      compiler.plugin('after-emit', function (compilation, cb) {
        if (!hasRequiredOptions) {
          compilation.errors.push(new Error('S3Plugin: Must provide Bucket, secretAccessKey and accessKeyId'));
          cb();
        }

        _fs2['default'].readdir(_this.options.directory, function (error, files) {
          if (error) {
            compilation.errors.push(new Error('S3Plugin-ReadOutputDir: ' + error));
            cb();
          } else {
            _this.uploadFiles(_this.filterAllowedFiles(files)).then(_this.changeHtmlUrls.bind(_this)).then(function () {
              console.log('Finished Uploading to S3');
              cb();
            })['catch'](function (e) {
              //console.log(e)
              compilation.errors.push(new Error('S3Plugin: ' + e));
              cb();
            });
          }
        });
      });
    }
  }, {
    key: 'cdnizeHtml',
    value: function cdnizeHtml(htmlPath) {
      var _this2 = this;

      return new Promise(function (resolve, reject) {
        _fs2['default'].readFile(htmlPath, function (err, data) {
          if (err) return reject(err);

          _fs2['default'].writeFile(htmlPath, _this2.cdnizer(data.toString()), function (err) {
            if (err) return reject(err);

            resolve();
          });
        });
      });
    }
  }, {
    key: 'changeHtmlUrls',
    value: function changeHtmlUrls() {
      var _this3 = this;

      if (this.noCdnizer) return Promise.resolve();

      var _options = this.options;
      var directory = _options.directory;
      var htmlFiles = _options.htmlFiles;

      var allHtml = htmlFiles || _fs2['default'].readdirSync(directory).filter(function (file) {
        return /\.html$/.test(file);
      }).map(function (file) {
        return _path2['default'].resolve(directory, file);
      });

      this.cdnizer = (0, _cdnizer2['default'])(this.cdnizerOptions);

      return Promise.all(allHtml.map(function (file) {
        return _this3.cdnizeHtml(file);
      }));
    }
  }, {
    key: 'filterAllowedFiles',
    value: function filterAllowedFiles(files) {
      var _this4 = this;

      return files.reduce(function (res, file) {
        if (_this4.isIncludeOrExclude(file)) res.push({
          name: file,
          path: _path2['default'].resolve(_this4.options.directory, file)
        });

        return res;
      }, []);
    }
  }, {
    key: 'isIncludeOrExclude',
    value: function isIncludeOrExclude(file) {
      var isExclude;
      var isInclude;
      var _options2 = this.options;
      var include = _options2.include;
      var exclude = _options2.exclude;

      if (!include) isInclude = true;else isInclude = include.test(file);

      if (!exclude) isExclude = false;else isExclude = exclude.test(file);

      return isInclude && !isExclude;
    }
  }, {
    key: 'connect',
    value: function connect() {
      if (this.isConnected) return;

      this.client = _s32['default'].createClient(this.clientConfig);
      this.isConnected = true;
    }
  }, {
    key: 'uploadFiles',
    value: function uploadFiles() {
      var _this5 = this;

      var files = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0];

      return Promise.all(files.map(function (file) {
        return _this5.uploadFile(file.name, file.path);
      }));
    }
  }, {
    key: 'uploadFile',
    value: function uploadFile(fileName, file) {
      this.connect();
      var upload = this.client.uploadFile({
        localFile: file,
        s3Params: {
          Key: fileName,
          Bucket: this.clientConfig.s3Options.Bucket
        }
      });

      //var progressBar = new ProgressBar('Uploading [:bar] :percent :etas', {
      //complete: '>',
      //incomplete: '-',
      //total: 100
      //})

      this.cdnizerOptions.files.push(fileName);

      console.log('Uploading ', fileName);
      return new Promise(function (resolve, reject) {
        upload.on('error', reject);

        upload.on('progress', function () {
          var progress = (upload.progressAmount / upload.progressTotal).toFixed(2)

          //progressBar.update(progress)
          ;
        });

        upload.on('end', function () {
          return resolve(file);
        });
      });
    }
  }]);

  return S3Plugin;
})();

exports['default'] = S3Plugin;
module.exports = exports['default'];

<commit_msg>add ico to exclude list of content encoding<commit_after>'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

var _http = require('http');

var _http2 = _interopRequireDefault(_http);

var _https = require('https');

var _https2 = _interopRequireDefault(_https);

var _s3 = require('s3');

var _s32 = _interopRequireDefault(_s3);

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _progress = require('progress');

var _progress2 = _interopRequireDefault(_progress);

var _cdnizer = require('cdnizer');

var _cdnizer2 = _interopRequireDefault(_cdnizer);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

_http2['default'].globalAgent.maxSockets = _https2['default'].globalAgent.maxSockets = 50;

var DEFAULT_UPLOAD_OPTIONS = {
  ACL: 'public-read'
};

var DEFAULT_S3_OPTIONS = {
  region: 'us-west-2'
};

var S3Plugin = (function () {
  function S3Plugin() {
    var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

    _classCallCheck(this, S3Plugin);

    var _options$s3Options = options.s3Options;
    var s3Options = _options$s3Options === undefined ? {} : _options$s3Options;
    var _options$s3UploadOptions = options.s3UploadOptions;
    var s3UploadOptions = _options$s3UploadOptions === undefined ? {} : _options$s3UploadOptions;
    var directory = options.directory;
    var include = options.include;
    var exclude = options.exclude;
    var basePath = options.basePath;
    var cdnizerOptions = options.cdnizerOptions;
    var htmlFiles = options.htmlFiles;

    this.requiredS3Opts = ['accessKeyId', 'secretAccessKey'];
    this.requiredS3UpOpts = ['Bucket'];
    this.uploadOptions = s3UploadOptions;
    this.isConnected = false;
    this.cdnizerOptions = cdnizerOptions;
    this.urlMappings = [];
    this.uploadTotal = 0;
    this.uploadProgress = 0;

    this.options = {
      directory: directory,
      include: include,
      exclude: exclude,
      htmlFiles: typeof htmlFiles === 'string' ? [htmlFiles] : htmlFiles
    };

    this.clientConfig = {
      maxAsyncS3: 50,
      s3Options: _lodash2['default'].merge(s3Options, DEFAULT_S3_OPTIONS)
    };

    if (!this.cdnizerOptions.files) this.cdnizerOptions.files = [];

    if (!this.cdnizerOptions) this.noCdnizer = true;
  }

  _createClass(S3Plugin, [{
    key: 'apply',
    value: function apply(compiler) {
      var _this = this;

      var hasRequiredOptions = this.requiredS3Opts.every(function (type) {
        return _this.clientConfig.s3Options[type];
      });

      var hasRequiredUploadOpts = this.requiredS3UpOpts.every(function (type) {
        return _this.uploadOptions[type];
      });

      // Set directory to output dir or custom
      this.options.directory = this.options.directory || compiler.options.output.path || compiler.options.output.context || '.';

      compiler.plugin('after-emit', function (compilation, cb) {
        if (!hasRequiredOptions) {
          compilation.errors.push(new Error('S3Plugin: Must provide ' + _this.requiredS3Opts.join(' and ')));
          cb();
        }

        if (!_this.requiredS3UpOpts) {
          compilation.errors.push(new Error('S3Plugin-RequiredS3UploadOpts: ' + _this.requiredS3UpOpts.join(' and ')));
          cb();
        }

        _fs2['default'].readdir(_this.options.directory, function (error, files) {
          if (error) {
            compilation.errors.push(new Error('S3Plugin-ReadOutputDir: ' + error));
            cb();
          } else {
            _this.uploadFiles(_this.filterAllowedFiles(files)).then(_this.changeHtmlUrls.bind(_this)).then(function () {
              console.log('Finished Uploading to S3');
              cb();
            })['catch'](function (e) {
              compilation.errors.push(new Error('S3Plugin: ' + e));
              cb();
            });
          }
        });
      });
    }
  }, {
    key: 'cdnizeHtml',
    value: function cdnizeHtml(htmlPath) {
      var _this2 = this;

      return new Promise(function (resolve, reject) {
        _fs2['default'].readFile(htmlPath, function (err, data) {
          if (err) return reject(err);

          _fs2['default'].writeFile(htmlPath, _this2.cdnizer(data.toString()), function (err) {
            if (err) return reject(err);

            resolve();
          });
        });
      });
    }
  }, {
    key: 'changeHtmlUrls',
    value: function changeHtmlUrls() {
      var _this3 = this;

      if (this.noCdnizer) return Promise.resolve();

      var _options = this.options;
      var directory = _options.directory;
      var htmlFiles = _options.htmlFiles;

      var allHtml = (htmlFiles || _fs2['default'].readdirSync(directory).filter(function (file) {
        return /\.html$/.test(file);
      })).map(function (file) {
        return _path2['default'].resolve(directory, file);
      });

      this.cdnizer = (0, _cdnizer2['default'])(this.cdnizerOptions);

      return Promise.all(allHtml.map(function (file) {
        return _this3.cdnizeHtml(file);
      }));
    }
  }, {
    key: 'filterAllowedFiles',
    value: function filterAllowedFiles(files) {
      var _this4 = this;

      return files.reduce(function (res, file) {
        if (_this4.isIncludeOrExclude(file)) res.push({
          name: file,
          path: _path2['default'].resolve(_this4.options.directory, file)
        });

        return res;
      }, []);
    }
  }, {
    key: 'isIncludeOrExclude',
    value: function isIncludeOrExclude(file) {
      var isExclude;
      var isInclude;
      var _options2 = this.options;
      var include = _options2.include;
      var exclude = _options2.exclude;

      if (!include) isInclude = true;else isInclude = include.test(file);

      if (!exclude) isExclude = false;else isExclude = exclude.test(file);

      return isInclude && !isExclude;
    }
  }, {
    key: 'connect',
    value: function connect() {
      if (this.isConnected) return;

      this.client = _s32['default'].createClient(this.clientConfig);
      this.isConnected = true;
    }
  }, {
    key: 'uploadFiles',
    value: function uploadFiles() {
      var _this5 = this;

      var files = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0];

      return Promise.all(files.map(function (file) {
        return _this5.uploadFile(file.name, file.path);
      }));
    }
  }, {
    key: 'uploadFile',
    value: function uploadFile(fileName, file) {
      var upload,
          s3Params = _lodash2['default'].merge({ Key: fileName }, this.uploadOptions, DEFAULT_UPLOAD_OPTIONS);

      // Remove Gzip from encoding if ico
      if (/\.ico/.test(fileName) && s3Params.ContentEncoding === 'gzip') delete s3Params.ContentEncoding;

      this.connect();
      upload = this.client.uploadFile({
        localFile: file,
        s3Params: s3Params
      });

      //var progressBar = new ProgressBar('Uploading [:bar] :percent :etas', {
      //complete: '>',
      //incomplete: '-',
      //total: 100
      //})

      this.cdnizerOptions.files.push(fileName);
      this.cdnizerOptions.files.push(fileName + '*');

      console.log('Uploading ', fileName);
      return new Promise(function (resolve, reject) {
        upload.on('error', reject);

        upload.on('progress', function () {
          var progress = (upload.progressAmount / upload.progressTotal).toFixed(2)

          //progressBar.update(progress)
          ;
        });

        upload.on('end', function () {
          return resolve(file);
        });
      });
    }
  }]);

  return S3Plugin;
})();

exports['default'] = S3Plugin;
module.exports = exports['default'];

<|endoftext|>


<commit_before>"use strict";
//Config loggin level
var logger = require('winston');
logger.remove(logger.transports.Console);
logger.add(logger.transports.Console, {
	level: 'debug',
	colorize: true,
	timestamp: true
});

var path = require('path');
var fs = require('fs');
var request = require('request');
var https = require('https');
var exec = require('child_process').exec;

var CONFIG_PATH = path.join(process.cwd(), 'crowdin.json');
var crowdin = require(CONFIG_PATH);

/******* PRIVATE METHODS *******/
function refreshTranslations(callback) {
	logger.debug("Refreshing translation.");
	var opts = {
		uri: 'https://crowdin.com/api/project/' + crowdin.projectId + '/export',
		qs: {
			key: crowdin.apiKey
		}
	};
	request(opts, function(error, response) {
		if (!error && response.statusCode == 200) {
			logger.info("Translations refreshed.");
		} else {
			logger.error("Fail to refresh translation.");
		}
		callback(error);
	});
}

function downloadTranslations(callback) {
	logger.debug("Downloading translation.");
	var options = {
		hostname: 'crowdin.com',
		port: 443,
		path: '/api/project/' + crowdin.projectId + '/download/all.zip?key=' + crowdin.apiKey,
		method: 'GET'
	};

	var req = https.request(options, function(res) {
		res.on('data', function(chunk) {
			fs.appendFileSync('./all.zip', chunk);
		});
		res.on('end', function(error) {
			if (!error) {
				logger.info("Translations Dowloaded.");
			}
			callback(error);
		});
	});
	req.on('error', function(e) {
		logger.error('problem with request: ' + e.message);
	});
	req.end();
}

function uploadKeys(fileName, realFileName, callback) {
	logger.debug('Uploading traductions...');
	var formData = {};
	formData['files[' + fileName + ']'] = fs.createReadStream('./i18n/' + realFileName);

	request.post({
		url: 'https://crowdin.com/api/project/' + crowdin.projectId + '/add-file?key=' + crowdin.apiKey,
		formData: formData
	}, function(err) {
		if (err) {
			logger.error('Upload failed.', err);
		} else {
			logger.info('Traductions uploaded successfully!');
		}
		callback(err);
	});
}

function upgradeKeys(fileName, realFileName, callback) {
	logger.debug('Uploading traductions...');
	var formData = {};
	formData['files[' + fileName + ']'] = fs.createReadStream('./i18n/' + realFileName);

	request.post({
		url: 'https://crowdin.com/api/project/' + crowdin.projectId + '/update-file?key=' + crowdin.apiKey,
		formData: formData
	}, function(err) {
		if (err) {
			logger.error('Upload failed.', err);
		} else {
			logger.info('Traductions uploaded successfully!');
		}
		callback(err);
	});
}

function mergeTranslations(srcFile, outputFile, callback) {
	logger.info('Merging transalations.');
	exec("msgcat ./i18n/" + srcFile + " ./i18n/es-AR/" + srcFile + " -o ./i18n/" + outputFile, callback);
}

function initPaths(fileName) {
	logger.info('Initializing...');
	if (!fs.existsSync('./i18n')) {
		fs.mkdirSync('./i18n');
	}
	if (fs.existsSync('./i18n/' + fileName)) {
		fs.truncateSync('./i18n/' + fileName, 0);
	} else {
		fs.writeFileSync('./i18n/' + fileName, ' ');
	}
}

function removeDirectory(path) {
	exec('rm -rf ' + path, function(err) {
		if (err) {
			logger.warn("Error removing " + path + ". " + err);
		}
	});
}

function cleanOldTranslations(callback) {
	fs.unlink('./all.zip', function(error) {
		if (!error || error.code === 'ENOENT') {
			var files = fs.readdirSync('./i18n');
			files.map(function(file) {
				return path.join('./i18n', file);
			}).forEach(function(file) {
				var stats = fs.statSync(file);
				if (stats.isDirectory()) {
					removeDirectory(file);
				}
			});
			callback();
		} else {
			callback(error);
		}
	});
}

function unzipTranslations(callback) {
	logger.debug("Unziping.");
	exec('unzip ./all.zip -d i18n',
		function(error) {
			if (error !== null) {
				logger.error('exec error: ' + error);
			}
			callback();
		});
}

function scanDirectory(directory, fileName, callback) {
	logger.debug("Scaning " + directory + " for keys.");
	exec('find ' + directory + ' -iname "*.*" | xargs xgettext -j --from-code=UTF-8 --force-po --no-wrap -ktr:1 -ktrd:1 -ktrn:1,2 -ktrnd:1,2 -o i18n/' + fileName + ' -LJavaScript',
		function(error) {
			if (error !== null) {
				logger.warn("Error scaning directory " + directory);
			}
			callback(error);
		});
}

function gerateTranslationFile(fileName, callback) {
	initPaths(fileName);
	scanDirectory(crowdin.srcPath, fileName, callback);
}

/*******************************/
var createCrowdin = function(callback) {
	gerateTranslationFile(crowdin.filename, function(error) {
		if (!error) {
			uploadKeys(crowdin.filename, crowdin.filename, callback);
		}
	});
};

var downloadCrowdin = function(callback) {
	if (!fs.existsSync('./i18n')) {
		fs.mkdirSync('./i18n');
	}
	cleanOldTranslations(function(error) {
		if (error) {
			logger.error("Error cleaning up old translations.");
			callback(error);
		} else {
			refreshTranslations(function(error) {
				if (error) {
					logger.error("Error refreshing translations.");
					callback(error);
				} else {
					downloadTranslations(function(error) {
						if (error) {
							logger.error("Error dowloading translations.");
							callback(error);
						} else {
							unzipTranslations(function(error) {
								if (error) {
									logger.error("Error Unziping translations.");
								} else {
									logger.info("Tranlations updated sucessfull!");
								}
								callback(error);
							});
						}
					});
				}
			});
		}
	});
};

var uploadCrowdin = function(merge, callback) {
	gerateTranslationFile(crowdin.filename, function(error) {
		if (merge) {
			downloadCrowdin(function(error) {
				if (!error) {
					mergeTranslations(crowdin.filename, 'merged_' + crowdin.filename, function(error) {
						if (error) {
							logger.error('Error merging translations.');
							callback(error);
						} else {
							upgradeKeys(crowdin.filename, 'merged_' + crowdin.filename, callback);
						}
					});
				} else {
					callback(error);
				}
			});
		} else {
			if (error) {
				callback(error);
			} else {
				upgradeKeys(crowdin.filename, crowdin.filename, callback);
			}
		}
	});
};

module.exports.createCrowdin = createCrowdin;
module.exports.downloadCrowdin = downloadCrowdin;
module.exports.uploadCrowdin = uploadCrowdin;
module.exports.generateFile = gerateTranslationFile;
module.exports.defaultFileName = crowdin.filename;<commit_msg>closing ext files scope to ts and js as default<commit_after>"use strict";
//Config loggin level
var logger = require('winston');
logger.remove(logger.transports.Console);
logger.add(logger.transports.Console, {
	level: 'debug',
	colorize: true,
	timestamp: true
});

var path = require('path');
var fs = require('fs');
var request = require('request');
var https = require('https');
var exec = require('child_process').exec;

var CONFIG_PATH = path.join(process.cwd(), 'crowdin.json');
var crowdin = require(CONFIG_PATH);

/******* PRIVATE METHODS *******/
function refreshTranslations(callback) {
	logger.debug("Refreshing translation.");
	var opts = {
		uri: 'https://crowdin.com/api/project/' + crowdin.projectId + '/export',
		qs: {
			key: crowdin.apiKey
		}
	};
	request(opts, function(error, response) {
		if (!error && response.statusCode == 200) {
			logger.info("Translations refreshed.");
		} else {
			logger.error("Fail to refresh translation.");
		}
		callback(error);
	});
}

function downloadTranslations(callback) {
	logger.debug("Downloading translation.");
	var options = {
		hostname: 'crowdin.com',
		port: 443,
		path: '/api/project/' + crowdin.projectId + '/download/all.zip?key=' + crowdin.apiKey,
		method: 'GET'
	};

	var req = https.request(options, function(res) {
		res.on('data', function(chunk) {
			fs.appendFileSync('./all.zip', chunk);
		});
		res.on('end', function(error) {
			if (!error) {
				logger.info("Translations Dowloaded.");
			}
			callback(error);
		});
	});
	req.on('error', function(e) {
		logger.error('problem with request: ' + e.message);
	});
	req.end();
}

function uploadKeys(fileName, realFileName, callback) {
	logger.debug('Uploading traductions...');
	var formData = {};
	formData['files[' + fileName + ']'] = fs.createReadStream('./i18n/' + realFileName);

	request.post({
		url: 'https://crowdin.com/api/project/' + crowdin.projectId + '/add-file?key=' + crowdin.apiKey,
		formData: formData
	}, function(err) {
		if (err) {
			logger.error('Upload failed.', err);
		} else {
			logger.info('Traductions uploaded successfully!');
		}
		callback(err);
	});
}

function upgradeKeys(fileName, realFileName, callback) {
	logger.debug('Uploading traductions...');
	var formData = {};
	formData['files[' + fileName + ']'] = fs.createReadStream('./i18n/' + realFileName);

	request.post({
		url: 'https://crowdin.com/api/project/' + crowdin.projectId + '/update-file?key=' + crowdin.apiKey,
		formData: formData
	}, function(err) {
		if (err) {
			logger.error('Upload failed.', err);
		} else {
			logger.info('Traductions uploaded successfully!');
		}
		callback(err);
	});
}

function mergeTranslations(srcFile, outputFile, callback) {
	logger.info('Merging transalations.');
	exec("msgcat ./i18n/" + srcFile + " ./i18n/es-AR/" + srcFile + " -o ./i18n/" + outputFile, callback);
}

function initPaths(fileName) {
	logger.info('Initializing...');
	if (!fs.existsSync('./i18n')) {
		fs.mkdirSync('./i18n');
	}
	if (fs.existsSync('./i18n/' + fileName)) {
		fs.truncateSync('./i18n/' + fileName, 0);
	} else {
		fs.writeFileSync('./i18n/' + fileName, ' ');
	}
}

function removeDirectory(path) {
	exec('rm -rf ' + path, function(err) {
		if (err) {
			logger.warn("Error removing " + path + ". " + err);
		}
	});
}

function cleanOldTranslations(callback) {
	fs.unlink('./all.zip', function(error) {
		if (!error || error.code === 'ENOENT') {
			var files = fs.readdirSync('./i18n');
			files.map(function(file) {
				return path.join('./i18n', file);
			}).forEach(function(file) {
				var stats = fs.statSync(file);
				if (stats.isDirectory()) {
					removeDirectory(file);
				}
			});
			callback();
		} else {
			callback(error);
		}
	});
}

function unzipTranslations(callback) {
	logger.debug("Unziping.");
	exec('unzip ./all.zip -d i18n',
		function(error) {
			if (error !== null) {
				logger.error('exec error: ' + error);
			}
			callback();
		});
}

function scanDirectory(directory, fileName, extNames = ['js', 'ts'], callback) {
	logger.debug(`Scaning ${directory} for keys, in ${extNames.join(', ')} files`);

	let extquery = extNames.map(ext => `-iname "*.${ext}" -not -iname "*.spec.${ext}"`).join(' -o ');

	if (extNames.length > 1) extquery = `\\\( ${extquery} \\\)`;

	exec(`find + ${directory} ${extquery} | xargs xgettext -j --from-code=UTF-8 --force-po --no-wrap -ktr:1 -ktrd:1 -ktrn:1,2 -ktrnd:1,2 -o i18n/${fileName} -LJavaScript`,
		function(error) {
			if (error !== null) {
				logger.warn("Error scaning directory " + directory);
			}
			callback(error);
		});
}

function gerateTranslationFile(fileName, callback) {
	initPaths(fileName);
	scanDirectory(crowdin.srcPath, fileName, crowdin.extNames, callback);
}

/*******************************/
var createCrowdin = function(callback) {
	gerateTranslationFile(crowdin.filename, function(error) {
		if (!error) {
			uploadKeys(crowdin.filename, crowdin.filename, callback);
		}
	});
};

var downloadCrowdin = function(callback) {
	if (!fs.existsSync('./i18n')) {
		fs.mkdirSync('./i18n');
	}
	cleanOldTranslations(function(error) {
		if (error) {
			logger.error("Error cleaning up old translations.");
			callback(error);
		} else {
			refreshTranslations(function(error) {
				if (error) {
					logger.error("Error refreshing translations.");
					callback(error);
				} else {
					downloadTranslations(function(error) {
						if (error) {
							logger.error("Error dowloading translations.");
							callback(error);
						} else {
							unzipTranslations(function(error) {
								if (error) {
									logger.error("Error Unziping translations.");
								} else {
									logger.info("Tranlations updated sucessfull!");
								}
								callback(error);
							});
						}
					});
				}
			});
		}
	});
};

var uploadCrowdin = function(merge, callback) {
	gerateTranslationFile(crowdin.filename, function(error) {
		if (merge) {
			downloadCrowdin(function(error) {
				if (!error) {
					mergeTranslations(crowdin.filename, 'merged_' + crowdin.filename, function(error) {
						if (error) {
							logger.error('Error merging translations.');
							callback(error);
						} else {
							upgradeKeys(crowdin.filename, 'merged_' + crowdin.filename, callback);
						}
					});
				} else {
					callback(error);
				}
			});
		} else {
			if (error) {
				callback(error);
			} else {
				upgradeKeys(crowdin.filename, crowdin.filename, callback);
			}
		}
	});
};

module.exports.createCrowdin = createCrowdin;
module.exports.downloadCrowdin = downloadCrowdin;
module.exports.uploadCrowdin = uploadCrowdin;
module.exports.generateFile = gerateTranslationFile;
module.exports.defaultFileName = crowdin.filename;<|endoftext|>


<commit_before>/* global app:true */

'use strict';

var app = angular.module('artedaqApp', [
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'ngRoute'
]);

app.config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/posts.html',
        controller: 'PostsCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  });
<commit_msg>add firebase support<commit_after>/* global app:true */

'use strict';

var app = angular.module('artedaqApp', [
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'ngRoute'
  'firebase'
])
.constant('FIREBASE_URL', 'https://torid-fire-561.firebaseio.com/');

app.config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/posts.html',
        controller: 'PostsCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  });
<|endoftext|>