<commit_before>'use strict';

angular.module('riplive')

/**
 * Show an ADV unit.
 *
 * @return {undefined}
 */
.directive('advUnit', function adCode() {
    return {
        template: '

',
        replace: true,
        restrict: 'E',
        scope: {
            format: '@'
        },
        link: function postLink(scope, element, attrs) {
            var ads = {
                '300x250': {
                    width: 300,
                    height: 250,
                    uris: [
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=amazon_it&banner=1V2RBHACBX1Q1VCEAJR2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=it_dvd&banner=08M2AM5ZC1WWKCSVXW82&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=fire_tablets&banner=1GA55H79M98VE0GYSHG2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=it_generic&banner=1CMG6WCMHRWW9TZC7W82&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=kindle&banner=1GX6C5B0A6J8FDQGH302&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=it_books&banner=0H5K1FHKA4Y7X545WC82&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=mp3&banner=1H6NEGKY0M62VKM3G0R2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=computer&banner=1ZYB5QYD6B51EQ5XFTG2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=prime&banner=1WBK148GAZFW63V0KD02&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=it_videogames&banner=1ZNP3FFQSDW1KY634P82&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=libri_altre_lingue&banner=1REJ4SN451EJ410CRC02&f=ifr',
                    ]
                },
                '468x60': {
                    width: 468,
                    height: 60,
                    uris: [
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=amazon_it&banner=14MR2FNWX1R1ADQKE1R2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=buoni_regalo&banner=182W2KR50VX8DVQ6C702&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=it_dvd&banner=03GYP27QKDJJR9W8NCG2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=it_electronics&banner=03VE9DPC009VND5ZY4G2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=fire_tablets&banner=0XD04CNWXV5M436KEWR2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=kindle&banner=046785QRGY1N97Z94RR2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=it_books&banner=1YV9F2KP47DG9QZ1VN02&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=mp3&banner=1HE0C7NNR8QFW92DA202&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=it_music&banner=1VW6X8390FPM9AQB5YG2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=prime&banner=1N3HC4GD2DZPARKYEY82&f=ifr',
                    ]
                },
                '728x90': {
                    width: 728,
                    height: 90,
                    uris: [
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=amazon_it&banner=1DS02X4H3XQ0AYFT4WG2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=it_dvd&banner=1TYFE6FXWWP2HR3VV9R2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=fire_tablets&banner=0Z5S6G9VXG2HAY4Y0G82&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=it_generic&banner=1VE23Y2C8JA20QEKXQG2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=kindle&banner=1R6G5M3QJ2WXEWVYGQ02&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=it_books&banner=02QNBD0JYHW7YVEM56G2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=mp3&banner=1PH02WDW9WZRZZEG5GG2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=it_music&banner=0KNKKM01QFKP6N02Q202&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=computer&banner=12838Q6K8YW3SR02E9G2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=prime&banner=1T78Z23MDC0TKQ6ZFV82&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=it_videogames&banner=19Y39R78NQ9CWHF58MG2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=buoni_regalo&banner=0E8KY67SBDY5F63B91R2&f=ifr',
                    ]
                },
                'superbanner-alto_mb': {
                    supplier: 'moneybox',
                    width: 728,
                    height: 90,
                    type_adv: 1;
                },
                'rettangolo-alto_mb': {
                    supplier: 'moneybox',
                    width: 300,
                    height: 250,
                    type_adv: 2;
                }
            };

            var getRandomFormat = function(format) {
                if (!ads.hasOwnProperty(format)) {
                    return '';
                }

                var choosen = ads[format];
                var len = choosen.uris.length;
                var random = Math.floor(Math.random() * len);

                if (choosen.supplier == "moneybox") {
                  return '
'
                          + ''
                          + ''
                          + '
';
                } else {
                  return   '';
                }
            };

            element.html(getRandomFormat(scope.format));
        }
    };
});
<commit_msg>syntax error on adv object<commit_after>'use strict';

angular.module('riplive')

/**
 * Show an ADV unit.
 *
 * @return {undefined}
 */
.directive('advUnit', function adCode() {
    return {
        template: '

',
        replace: true,
        restrict: 'E',
        scope: {
            format: '@'
        },
        link: function postLink(scope, element, attrs) {
            var ads = {
                '300x250': {
                    width: 300,
                    height: 250,
                    uris: [
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=amazon_it&banner=1V2RBHACBX1Q1VCEAJR2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=it_dvd&banner=08M2AM5ZC1WWKCSVXW82&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=fire_tablets&banner=1GA55H79M98VE0GYSHG2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=it_generic&banner=1CMG6WCMHRWW9TZC7W82&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=kindle&banner=1GX6C5B0A6J8FDQGH302&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=it_books&banner=0H5K1FHKA4Y7X545WC82&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=mp3&banner=1H6NEGKY0M62VKM3G0R2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=computer&banner=1ZYB5QYD6B51EQ5XFTG2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=prime&banner=1WBK148GAZFW63V0KD02&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=it_videogames&banner=1ZNP3FFQSDW1KY634P82&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=12&l=ur1&category=libri_altre_lingue&banner=1REJ4SN451EJ410CRC02&f=ifr',
                    ]
                },
                '468x60': {
                    width: 468,
                    height: 60,
                    uris: [
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=amazon_it&banner=14MR2FNWX1R1ADQKE1R2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=buoni_regalo&banner=182W2KR50VX8DVQ6C702&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=it_dvd&banner=03GYP27QKDJJR9W8NCG2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=it_electronics&banner=03VE9DPC009VND5ZY4G2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=fire_tablets&banner=0XD04CNWXV5M436KEWR2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=kindle&banner=046785QRGY1N97Z94RR2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=it_books&banner=1YV9F2KP47DG9QZ1VN02&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=mp3&banner=1HE0C7NNR8QFW92DA202&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=it_music&banner=1VW6X8390FPM9AQB5YG2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=26&l=ur1&category=prime&banner=1N3HC4GD2DZPARKYEY82&f=ifr',
                    ]
                },
                '728x90': {
                    width: 728,
                    height: 90,
                    uris: [
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=amazon_it&banner=1DS02X4H3XQ0AYFT4WG2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=it_dvd&banner=1TYFE6FXWWP2HR3VV9R2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=fire_tablets&banner=0Z5S6G9VXG2HAY4Y0G82&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=it_generic&banner=1VE23Y2C8JA20QEKXQG2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=kindle&banner=1R6G5M3QJ2WXEWVYGQ02&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=it_books&banner=02QNBD0JYHW7YVEM56G2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=mp3&banner=1PH02WDW9WZRZZEG5GG2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=it_music&banner=0KNKKM01QFKP6N02Q202&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=computer&banner=12838Q6K8YW3SR02E9G2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=prime&banner=1T78Z23MDC0TKQ6ZFV82&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=it_videogames&banner=19Y39R78NQ9CWHF58MG2&f=ifr',
                        'http://rcm-eu.amazon-adsystem.com/e/cm?t=riplive-21&o=29&p=48&l=ur1&category=buoni_regalo&banner=0E8KY67SBDY5F63B91R2&f=ifr',
                    ]
                },
                'superbanner-alto_mb': {
                    supplier: 'moneybox',
                    width: 728,
                    height: 90,
                    type_adv: 1
                },
                'rettangolo-alto_mb': {
                    supplier: 'moneybox',
                    width: 300,
                    height: 250,
                    type_adv: 2
                }
            };

            var getRandomFormat = function(format) {
                if (!ads.hasOwnProperty(format)) {
                    return '';
                }

                var choosen = ads[format];
                var len = choosen.uris.length;
                var random = Math.floor(Math.random() * len);

                if (choosen.supplier == "moneybox") {
                  return '
'
                          + ''
                          + ''
                          + '
';
                } else {
                  return   '';
                }
            };

            element.html(getRandomFormat(scope.format));
        }
    };
});
<|endoftext|>


<commit_before>// TODO: source map support

function emitProperty(tree) {
  const block = () => {
    switch (tree.expr.type) {
      case "jsExpr":
        return `return ${tree.expr.content}`;
      case "jsBlock":
        return tree.expr.content;
    }
  }();

  // TODO: resolve dependencies
  return `
    this.bindProperty("${tree.name}", [], function () {
      ${block}
    }.bind(this));
  `;
}

function emitEventListener(tree) {
  const funcNames = {
    "on": "on",
    "append": "appendListener",
  };

  return `
    this.${funcNames[tree.type]}(${tree.event.content}, function () {
      ${tree.block.content}
    }.bind(this));
  `;
}

function getId(members, ids) {
  const idTree = members.find(t => t.type === "id");
  if (idTree) {
    if (ids.indexOf(idTree.name) >= 0) {
      throw new Error(`ID "${idTree.name}" already used`);
    }
  }
  const id = idTree ? idTree.name : `__component_${ids.length}`;
  ids.push(id);
  return id;
}

function emitComponent(tree, ids, className) {
  const id = getId(tree.members, ids);
  className = className || `Class_${id}`;

  const addProperties =
    tree.members.filter(t => t.type === "property")
      .map(t => `${className}.addProperty("${t.name}");\n`)
      .join("");

  return `
    class ${className} extends ${tree.name} {
      constructor() {
        ${emitMembers(tree.members, ids)}
      }
    }
    ${addProperties}
    ${id} = new ${className}();
  `
}

function emitMembers(members, ids) {
  const componentTrees = members.filter(t => t.type === "component");
  const propertyTrees = members.filter(t => t.type === "property");
  const eventListenerTrees = members.filter(t => t.type === "on" || t.type === "prepend");

  return componentTrees.map(t => emitComponent(t, ids)).join("") +
    propertyTrees.map(emitProperty).join("") +
    eventListenerTrees.map(emitEventListener).join("");
}

function emitComponentDefinition(tree) {
  const ids = [];

  const scope = ids.map(id => `let ${id};\n`).join("");
  const component = emitComponent(tree.component, ids, tree.name);

  return `
    const ${tree.name} = () => {
      ${scope}
      ${component}
      return ${tree.name}
    }();
  `;
}

function emitRoot(tree) {
  switch (tree.type) {
    case "jsBlock": {
      return tree.content;
    }
    case "componentDefinition": {
      return emitComponentDefinition(tree);
    }
  }
}

export default
function emit(trees) {
  return trees.map(emitRoot).join("\n");
}
<commit_msg>Use named parameters<commit_after>// TODO: source map support

function emitProperty(tree) {
  const block = () => {
    switch (tree.expr.type) {
      case "jsExpr":
        return `return ${tree.expr.content}`;
      case "jsBlock":
        return tree.expr.content;
    }
  }();

  // TODO: resolve dependencies
  return `
    this.bindProperty("${tree.name}", [], function () {
      ${block}
    }.bind(this));
  `;
}

function emitEventListener(tree) {
  const funcNames = {
    "on": "on",
    "append": "appendListener",
  };

  return `
    this.${funcNames[tree.type]}(${tree.event.content}, function () {
      ${tree.block.content}
    }.bind(this));
  `;
}

function getId(members, ids) {
  const idTree = members.find(t => t.type === "id");
  if (idTree) {
    if (ids.indexOf(idTree.name) >= 0) {
      throw new Error(`ID "${idTree.name}" already used`);
    }
  }
  const id = idTree ? idTree.name : `__component_${ids.length}`;
  ids.push(id);
  return id;
}

function emitComponent(tree, {ids, className}) {
  const id = getId(tree.members, ids);
  className = className || `Class_${id}`;

  const addProperties =
    tree.members.filter(t => t.type === "property")
      .map(t => `${className}.addProperty("${t.name}");\n`)
      .join("");

  return `
    class ${className} extends ${tree.name} {
      constructor() {
        ${emitMembers(tree.members, {ids})}
      }
    }
    ${addProperties}
    ${id} = new ${className}();
  `
}

function emitMembers(members, {ids}) {
  const componentTrees = members.filter(t => t.type === "component");
  const propertyTrees = members.filter(t => t.type === "property");
  const eventListenerTrees = members.filter(t => t.type === "on" || t.type === "prepend");

  return componentTrees.map(t => emitComponent(t, {ids})).join("") +
    propertyTrees.map(emitProperty).join("") +
    eventListenerTrees.map(emitEventListener).join("");
}

function emitComponentDefinition(tree) {
  const ids = [];

  const scope = ids.map(id => `let ${id};\n`).join("");
  const component = emitComponent(tree.component, {ids, className: tree.name});

  return `
    const ${tree.name} = () => {
      ${scope}
      ${component}
      return ${tree.name}
    }();
  `;
}

function emitRoot(tree) {
  switch (tree.type) {
    case "jsBlock": {
      return tree.content;
    }
    case "componentDefinition": {
      return emitComponentDefinition(tree);
    }
  }
}

export default
function emit(trees) {
  return trees.map(emitRoot).join("\n");
}
<|endoftext|>


<commit_before>
window.svg_gradient_helper = (function() {
  // Main object
  var svg_gradient_helper = {};
  var svgns = 'http://www.w3.org/2000/svg';

  // Private variables
  // -----------------
  var gradientStops = [];

  // Private functions
  // -----------------

  // create document fragment
  function createSvgNode(tag){
    var el = document.createElementNS(svgns, tag);
    return document.createDocumentFragment().appendChild(el);
  }

  function isPlainObj(o) {
    return (typeof o == 'object' && o.constructor == Object);
  }

  function isString(s) {
    return (typeof s == 'string' || s instanceof String);
  }

  function calculateOffset(idx, len){
    if(idx===0){ return 0.0 }
    if(idx===(len-1)){ return 1.0 }
    return idx/(len-1)
  }

  // Array of colors, offset is linearly interpolated, opacity is 1
  function gradStopsFromColorArray(gradArray) {
    // gradientStops output format:
    // [
    //   {color: #ffffff, offset:0, opacity:1},
    //   {color: #777777, offset:0.5, opacity: 1},
    //   {color: #000000, offset:1, opacity: 1}
    //]

    var gradStops = [];

    gradArray.forEach(function(color, idx, ar){
      var opacity = 1;
      var offset = calculateOffset(idx, ar.length);
      var stopObj = {color: color, offset: offset, opacity: opacity};
      var svgStop = gradStopObjToSvgStop(stopObj);

      gradStops.push(svgStop)
    });

    return gradStops;
  }

  function gradStopObjToSvgStop(gradStopObj){
    var svgStopNode = createSvgNode('stop');
    svgStopNode.setAttribute("offset", gradStopObj.offset);
    svgStopNode.setAttribute("stop-color", gradStopObj.color);
    svgStopNode.setAttribute("stop-opacity", gradStopObj.opacity);
    return svgStopNode;
  }

  function mapToValidOpts(userOpts, validOptKeys) {
    var validOpts = {};
    Object.keys(userOpts).forEach(function(userOptKey){
      if (validOptKeys.indexOf(userOptKey)>-1){
        validOpts[userOptKey] = userOpts[userOptKey];
      }
    });
    return validOpts;
  }

  function setVectors(vecs, vec, defVal){
    if (vecs === undefined || vecs === null) { vecs = {} }
    if (typeof vecs[vec] == 'string' || vecs[vec] instanceof String){
      if (vecs[vec].match(/\d+%$/)){
        return;
      } else {
        vecs[vec] = parseFloat(vecs[vec]);
      }
    }
    // convert to percentage string
    if (isNaN(vecs[vec])) { vecs[vec] = defVal }
    vecs[vec] = parseFloat(vecs[vec]);
    if (vecs[vec] < 0) { vecs[vec] = 0 }
    if (vecs[vec] > 1) { vecs[vec] = 1 }
    vecs[vec] = "" + vecs[vec]*100 + "%";
  }

  //gradientStops can be unsorted, it will be returned in offset order
  function makeGradientSvgStops(gradientStops){
    var gradientSvgStops = [];

    var firstGradientStop = gradientStops[0]

    // ToDo: Validate string is color string
    if ( isString(firstGradientStop) ) {
      var gradientSvgStops = gradStopsFromColorArray(gradientStops);
    }

    if ( isPlainObj(firstGradientStop) ) {

      var validGradientKeys = ["color", "offset", "opacity"];
      gradientStops.forEach(function(gradStopObj, idx){
        var validObj = mapToValidOpts(gradStopObj, validGradientKeys);
        var svgStop = gradStopObjToSvgStop(validObj);
        gradientSvgStops.push(svgStop);
      });
    }

    gradientSvgStops.sort( function(a,b){
      return parseFloat(a.getAttribute('offset')) - parseFloat(b.getAttribute('offset'))
    });

    return gradientSvgStops;
  }

  function linearGradient(id, gradientStops, svgVector){

    //Validations
    if ( typeof svgVector !== 'object'){
     svgVector = { x1: 0.0, y1: 0.0, x2: 0.0, y2: 1.0 };
    }
    setVectors(svgVector, "x1", 0.0);
    setVectors(svgVector, "y1", 0.0);
    setVectors(svgVector, "x2", 0.0);
    setVectors(svgVector, "y2", 1.0);

    //Options (not configurable at this point)
    var spreadMethod = "pad";

    var svgLinGradNode = createSvgNode('linearGradient');
    svgLinGradNode.setAttribute("id", id);

    svgLinGradNode.setAttribute("x1", svgVector.x1);
    svgLinGradNode.setAttribute("y1", svgVector.y1);
    svgLinGradNode.setAttribute("x2", svgVector.x2);
    svgLinGradNode.setAttribute("y2", svgVector.y2);

    gradientStops.forEach(function(gradStop){
      svgLinGradNode.appendChild(gradStop);
    });

    return svgLinGradNode;

  }

  function addDef(defsContent, parentSelector){
    var svgNode, defsNode;

    var parent = document.querySelector(parentSelector);

    var svgNodes = document.getElementsByTagNameNS(svgns, 'svg');

    var svgFinder = parent.querySelector('svg');

    //if there's no svg section create one
    if (svgFinder === null){
      svgNode = document.createElementNS(svgns, 'svg');
    } else {
      svgNode = document.getElementsByTagNameNS(svgns, 'svg')[0];
    }
    //we have an svgNode now

    var svgDefsFinder = parent.querySelector('svg defs');

    // if there is no defs section create one
    if (svgDefsFinder === null){
      var defsNode = document.createElementNS(svgns, 'defs');
    } else {
      defsNode = document.getElementsByTagNameNS(svgns, 'defs')[0];
    }
    // we have defsNode now

    defsNode.appendChild(defsContent);
    svgNode.appendChild(defsNode);
    parent.appendChild(svgNode);

  }

  // Public API
  // -----------------

  svg_gradient_helper.makeStops = makeGradientSvgStops;
  svg_gradient_helper.linearGradient = linearGradient;
  svg_gradient_helper.addDef = addDef;

  // Container for helper functions
  var helpers = svg_gradient_helper.helpers = {};

  // returns a regular document node from a CSS Lookup string,
  // jQuery node, or a regular document node (latter is just pass through)
  helpers.getNode = function(lookup) {

    if( isString(lookup)){
      return document.querySelector(lookup);
    }

    // if lookup is a jQuery node return normal node
    if (typeof jQuery !== 'undefined'  && lookup instanceof jQuery){ return lookup[0] }
    // if lookup is a D3 node return first node
    if (typeof d3 !== 'undefined'  && lookup instanceof d3.selection){
      //flattens array and gets first element
      var flatSelection = [].concat.apply([], lookup);
      return flatSelection[0]
    }

    return lookup;
  };

  // return global
  return svg_gradient_helper;
})();<commit_msg>reorganized the code for helpers<commit_after>
window.svg_gradient_helper = (function() {
  // Main object
  var svg_gradient_helper = {};
  var svgns = 'http://www.w3.org/2000/svg';

  // Private variables
  // -----------------
  var gradientStops = [];

  // Private functions
  // -----------------

  // create document fragment
  function createSvgNode(tag){
    var el = document.createElementNS(svgns, tag);
    return document.createDocumentFragment().appendChild(el);
  }

  function isPlainObj(o) {
    return (typeof o == 'object' && o.constructor == Object);
  }

  function isString(s) {
    return (typeof s == 'string' || s instanceof String);
  }

  function calculateOffset(idx, len){
    if(idx===0){ return 0.0 }
    if(idx===(len-1)){ return 1.0 }
    return idx/(len-1)
  }

  // Array of colors, offset is linearly interpolated, opacity is 1
  function gradStopsFromColorArray(gradArray) {
    // gradientStops output format:
    // [
    //   {color: #ffffff, offset:0, opacity:1},
    //   {color: #777777, offset:0.5, opacity: 1},
    //   {color: #000000, offset:1, opacity: 1}
    //]

    var gradStops = [];

    gradArray.forEach(function(color, idx, ar){
      var opacity = 1;
      var offset = calculateOffset(idx, ar.length);
      var stopObj = {color: color, offset: offset, opacity: opacity};
      var svgStop = gradStopObjToSvgStop(stopObj);

      gradStops.push(svgStop)
    });

    return gradStops;
  }

  function gradStopObjToSvgStop(gradStopObj){
    var svgStopNode = createSvgNode('stop');
    svgStopNode.setAttribute("offset", gradStopObj.offset);
    svgStopNode.setAttribute("stop-color", gradStopObj.color);
    svgStopNode.setAttribute("stop-opacity", gradStopObj.opacity);
    return svgStopNode;
  }

  function mapToValidOpts(userOpts, validOptKeys) {
    var validOpts = {};
    Object.keys(userOpts).forEach(function(userOptKey){
      if (validOptKeys.indexOf(userOptKey)>-1){
        validOpts[userOptKey] = userOpts[userOptKey];
      }
    });
    return validOpts;
  }

  function setVectors(vecs, vec, defVal){
    if (vecs === undefined || vecs === null) { vecs = {} }
    if (typeof vecs[vec] == 'string' || vecs[vec] instanceof String){
      if (vecs[vec].match(/\d+%$/)){
        return;
      } else {
        vecs[vec] = parseFloat(vecs[vec]);
      }
    }
    // convert to percentage string
    if (isNaN(vecs[vec])) { vecs[vec] = defVal }
    vecs[vec] = parseFloat(vecs[vec]);
    if (vecs[vec] < 0) { vecs[vec] = 0 }
    if (vecs[vec] > 1) { vecs[vec] = 1 }
    vecs[vec] = "" + vecs[vec]*100 + "%";
  }

  //gradientStops can be unsorted, it will be returned in offset order
  function makeGradientSvgStops(gradientStops){
    var gradientSvgStops = [];

    var firstGradientStop = gradientStops[0]

    // ToDo: Validate string is color string
    if ( isString(firstGradientStop) ) {
      var gradientSvgStops = gradStopsFromColorArray(gradientStops);
    }

    if ( isPlainObj(firstGradientStop) ) {

      var validGradientKeys = ["color", "offset", "opacity"];
      gradientStops.forEach(function(gradStopObj, idx){
        var validObj = mapToValidOpts(gradStopObj, validGradientKeys);
        var svgStop = gradStopObjToSvgStop(validObj);
        gradientSvgStops.push(svgStop);
      });
    }

    gradientSvgStops.sort( function(a,b){
      return parseFloat(a.getAttribute('offset')) - parseFloat(b.getAttribute('offset'))
    });

    return gradientSvgStops;
  }

  function linearGradient(id, gradientStops, svgVector){

    //Validations
    if ( typeof svgVector !== 'object'){
     svgVector = { x1: 0.0, y1: 0.0, x2: 0.0, y2: 1.0 };
    }
    setVectors(svgVector, "x1", 0.0);
    setVectors(svgVector, "y1", 0.0);
    setVectors(svgVector, "x2", 0.0);
    setVectors(svgVector, "y2", 1.0);

    //Options (not configurable at this point)
    var spreadMethod = "pad";

    var svgLinGradNode = createSvgNode('linearGradient');
    svgLinGradNode.setAttribute("id", id);

    svgLinGradNode.setAttribute("x1", svgVector.x1);
    svgLinGradNode.setAttribute("y1", svgVector.y1);
    svgLinGradNode.setAttribute("x2", svgVector.x2);
    svgLinGradNode.setAttribute("y2", svgVector.y2);

    gradientStops.forEach(function(gradStop){
      svgLinGradNode.appendChild(gradStop);
    });

    return svgLinGradNode;

  }

  function addDef(defsContent, parentSelector){
    var svgNode, defsNode;

    var parent = document.querySelector(parentSelector);

    var svgNodes = document.getElementsByTagNameNS(svgns, 'svg');

    var svgFinder = parent.querySelector('svg');

    //if there's no svg section create one
    if (svgFinder === null){
      svgNode = document.createElementNS(svgns, 'svg');
    } else {
      svgNode = document.getElementsByTagNameNS(svgns, 'svg')[0];
    }
    //we have an svgNode now

    var svgDefsFinder = parent.querySelector('svg defs');

    // if there is no defs section create one
    if (svgDefsFinder === null){
      var defsNode = document.createElementNS(svgns, 'defs');
    } else {
      defsNode = document.getElementsByTagNameNS(svgns, 'defs')[0];
    }
    // we have defsNode now

    defsNode.appendChild(defsContent);
    svgNode.appendChild(defsNode);
    parent.appendChild(svgNode);

  }

  // returns a regular document node from a CSS Lookup string,
  // jQuery node, or a regular document node (latter is just pass through)
  function getNode(lookup) {

    if( isString(lookup)){
      return document.querySelector(lookup);
    }

    // if lookup is a jQuery node return normal node
    if (typeof jQuery !== 'undefined'  && lookup instanceof jQuery){ return lookup[0] }
    // if lookup is a D3 node return first node
    if (typeof d3 !== 'undefined'  && lookup instanceof d3.selection){
      //flattens array and gets first element
      var flatSelection = [].concat.apply([], lookup);
      return flatSelection[0]
    }

    return lookup;
  }

  // Public API
  // -----------------

  svg_gradient_helper.makeStops = makeGradientSvgStops;
  svg_gradient_helper.linearGradient = linearGradient;
  svg_gradient_helper.addDef = addDef;

  // Container for helper functions
  svg_gradient_helper.helpers = {};
  svg_gradient_helper.helpers.getNode = getNode;

  // return global
  return svg_gradient_helper;
})();<|endoftext|>


<commit_before>module.exports = function(grunt) {
  var express = require('express'),
      lockFile = require('lockfile'),
      Helpers = require('./helpers'),
      fs = require('fs'),
      path = require('path');

  /**
  Task for serving the static files.

  Note: The expressServer:debug task looks for files in multiple directories.
  */
  grunt.registerTask('expressServer', function(target) {
    var app = express(),
        done = this.async();

    app.use(lock);

    if (target === 'debug') {
      // For `expressServer:debug`

      // Add livereload middlware after lock middleware if enabled
      if (Helpers.isPackageAvailable("connect-livereload")) {
        app.use(require("connect-livereload")());
      }

      // These three lines simulate what the `copy:assemble` task does
      app.use(static({ urlRoot: '/vendor', directory: 'vendor' }));
      app.use(static({ directory: 'public' }));
      app.use(static({ urlRoot: '/tests', directory: 'tests' })); // For test_helper.js and test_loader.js

      app.use(static({ directory: 'tmp/result' }));
      app.use(static({ file: 'tmp/result/index.html' })); // Gotta catch 'em all
    } else {
      // For `expressServer:dist`

      app.use(lock);
      app.use(static({ directory: 'dist' }));
      app.use(static({ file: 'dist/index.html' })); // Gotta catch 'em all
    }

    var port = process.env.PORT || 8000;
    app.listen(port);
    grunt.log.ok('Started development server on port %d.', port);
    if (!this.flags.keepalive) { done(); }
  });

  // Middleware
  // ==========

  function lock(req, res, next) { // Works with tasks/locking.js
    (function retry() {
      if (lockFile.checkSync('tmp/connect.lock')) {
        setTimeout(retry, 30);
      } else { next(); }
    })();
  }

  function static(options) {
    return function(req, res, next) { // Gotta catch 'em all (and serve index.html)
      var filePath = "";
      if (options.directory) {
        var regex = new RegExp('^' + (options.urlRoot || ''));
        // URL must begin with urlRoot's value
        if (!req.path.match(regex)) { next(); return; }
        filePath = options.directory + req.path.replace(regex, '');
      } else if (options.file) {
        filePath = options.file;
      } else { throw new Error('static() isn\'t properly configured!'); }

      fs.stat(filePath, function(err, stats) {
        if (err) { next(); return; } // Not a file, not a folder => can't handle it

        // Is it a directory? If so, search for an index.html in it.
        if (stats.isDirectory()) { filePath = path.join(filePath, 'index.html'); }

        // Serve the file
        res.sendfile(filePath, function(err) {
          if (err) { next(); return; }
          grunt.verbose.ok('Served: ' + filePath);
        });
      });
    };
  }
};
<commit_msg>Adds gzip compression.<commit_after>module.exports = function(grunt) {
  var express = require('express'),
      lockFile = require('lockfile'),
      Helpers = require('./helpers'),
      fs = require('fs'),
      path = require('path');

  /**
  Task for serving the static files.

  Note: The expressServer:debug task looks for files in multiple directories.
  */
  grunt.registerTask('expressServer', function(target) {
    var app = express(),
        done = this.async();

    app.use(lock);
    app.use(express.compress());

    if (target === 'debug') {
      // For `expressServer:debug`

      // Add livereload middlware after lock middleware if enabled
      if (Helpers.isPackageAvailable("connect-livereload")) {
        app.use(require("connect-livereload")());
      }

      // These three lines simulate what the `copy:assemble` task does
      app.use(static({ urlRoot: '/vendor', directory: 'vendor' }));
      app.use(static({ directory: 'public' }));
      app.use(static({ urlRoot: '/tests', directory: 'tests' })); // For test_helper.js and test_loader.js

      app.use(static({ directory: 'tmp/result' }));
      app.use(static({ file: 'tmp/result/index.html' })); // Gotta catch 'em all
    } else {
      // For `expressServer:dist`

      app.use(lock);
      app.use(static({ directory: 'dist' }));
      app.use(static({ file: 'dist/index.html' })); // Gotta catch 'em all
    }

    var port = process.env.PORT || 8000;
    app.listen(port);
    grunt.log.ok('Started development server on port %d.', port);
    if (!this.flags.keepalive) { done(); }
  });

  // Middleware
  // ==========

  function lock(req, res, next) { // Works with tasks/locking.js
    (function retry() {
      if (lockFile.checkSync('tmp/connect.lock')) {
        setTimeout(retry, 30);
      } else { next(); }
    })();
  }

  function static(options) {
    return function(req, res, next) { // Gotta catch 'em all (and serve index.html)
      var filePath = "";
      if (options.directory) {
        var regex = new RegExp('^' + (options.urlRoot || ''));
        // URL must begin with urlRoot's value
        if (!req.path.match(regex)) { next(); return; }
        filePath = options.directory + req.path.replace(regex, '');
      } else if (options.file) {
        filePath = options.file;
      } else { throw new Error('static() isn\'t properly configured!'); }

      fs.stat(filePath, function(err, stats) {
        if (err) { next(); return; } // Not a file, not a folder => can't handle it

        // Is it a directory? If so, search for an index.html in it.
        if (stats.isDirectory()) { filePath = path.join(filePath, 'index.html'); }

        // Serve the file
        res.sendfile(filePath, function(err) {
          if (err) { next(); return; }
          grunt.verbose.ok('Served: ' + filePath);
        });
      });
    };
  }
};
<|endoftext|>


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

var blocklist = 'zen.spamhaus.org';

exports.query = function queryDnsbl(ip, callback) {
	var reversedIp = ip.split('.').reverse().join('.');
	dns.resolve4(reversedIp+'.'+blocklist, function(err, addresses) {
		if (err) {
			// not on blacklist
			callback(false);
		} else {
			// on blacklist
			callback(true);
		}
	});
}
<commit_msg>Cache DNSBL results<commit_after>var dns = require('dns');

var blocklist = 'zen.spamhaus.org';

var dnsblCache = {};

exports.query = function queryDnsbl(ip, callback) {
	if (ip in dnsblCache) {
		callback(dnsblCache[ip]);
		return;
	}
	var reversedIp = ip.split('.').reverse().join('.');
	dns.resolve4(reversedIp+'.'+blocklist, function(err, addresses) {
		var isBlocked = dnsblCache[ip] = !err;
		callback(isBlocked);
	});
}
<|endoftext|>


<commit_before>/*
    Framework for building object relational database apps
    Copyright (C) 2019  John Rogelstad

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
/*jslint node*/
/**
    @module Workbooks
*/
(function (exports) {
    "use strict";

    const {Database} = require("../database");
    const {Feathers} = require("./feathers");
    const {Tools} = require("./tools");
    const f = require("../../common/core");

    const db = new Database();
    const feathers = new Feathers();
    const tools = new Tools();

    /**
        @class Workbooks
        @constructor
        @namespace Services
    */
    exports.Workbooks = function () {
        // ..........................................................
        // PRIVATE
        //

        let that = {};

        // ..........................................................
        // PUBLIC
        //

        /**
          Remove a workbook from the database.

            @method deleteWorkbook
            @param {Object} Request payload
            @param {String} [payload.user] User name
            @param {Object} [payload.data] Payload data
            @param {String} [payload.data.name] Workbook to delete
            @param {Object} [payload.client] Database client
            @return {Object} Promise
        */
        that.deleteWorkbook = function (obj) {
            return new Promise(function (resolve, reject) {
                let sql = "DELETE FROM \"$workbook\" WHERE name=$1;";
                let client = db.getClient(obj.client);

                tools.isSuperUser({
                    client: client,
                    user: obj.user
                }).then(function (isSuper) {
                    let err;

                    if (!isSuper) {
                        err = new Error(
                            "Only super users may delete workbooks."
                        );
                        err.statusCode = 401;
                        throw err;
                    }

                    client.query(sql, [obj.data.name], function (err) {
                        if (err) {
                            reject(err);
                            return;
                        }

                        resolve(true);
                    });
                }).catch(reject);
            });
        };

        /**
            @method getWorkbook
            @param {Object} payload
            @param {String} payload.user
            @param {Client} payload.client
            @param {Object} payload.data
            @param {String} payload.data.name Workbook name
            @return {Promise}
        */
        that.getWorkbook = function (obj) {
            return new Promise(function (resolve, reject) {
                let err;

                function callback(resp) {
                    if (!resp.length) {
                        err = new Error("Workbook not found");
                        err.statusCode = 404;
                        throw err;
                    }

                    resolve(resp[0]);
                }

                that.getWorkbooks({
                    user: obj.user,
                    data: obj.data,
                    client: obj.client
                }).then(callback).catch(reject);
            });
        };

        /**
            Resolve to workbook definition(s). If name is passed in payload
            only that workbook will be returned.

            @method getWorkbooks
            @param {Object} Request payload
            @param {Object} [payload.data] Workbook data
            @param {Object} [payload.data.name] Workbook name
            @param {Object} [payload.client] Database client
            @return {Promise}
        */
        that.getWorkbooks = function (obj) {
            return new Promise(function (resolve, reject) {
                let user = obj.user;
                let client = db.getClient(obj.client);

                function callback(isSuper) {
                    let params = [];
                    let sql;

                    sql = (
                        "SELECT name, description, module, " +
                        "launch_config AS \"launchConfig\", " +
                        "icon, " +
                        "default_config AS \"defaultConfig\", " +
                        "local_config AS \"localConfig\", " +
                        "to_json(ARRAY( SELECT ROW(role, can_read, " +
                        "can_update) " +
                        "  FROM \"$auth\" as auth " +
                        "  WHERE auth.object_pk = workbook._pk " +
                        "  ORDER BY auth.pk)) AS authorizations " +
                        "FROM \"$workbook\" AS workbook " +
                        "WHERE true "
                    );

                    if (!isSuper) {
                        params = [client.currentUser()];
                        sql += (
                            "AND EXISTS (" +
                            "  SELECT can_read FROM ( " +
                            "    SELECT can_read " +
                            "    FROM \"$auth\", pg_authid " +
                            "    WHERE pg_has_role(" +
                            "        $1, pg_authid.oid, 'member')" +
                            "      AND \"$auth\".object_pk=workbook._pk" +
                            "      AND \"$auth\".role=pg_authid.rolname" +
                            "    ORDER BY can_read DESC" +
                            "    LIMIT 1" +
                            "  ) AS data " +
                            "  WHERE can_read)"
                        );
                    }

                    if (obj.data.name) {
                        sql += " AND name=$2";
                        params.push(obj.data.name);
                    }

                    sql += " ORDER BY _pk";

                    client.query(sql, params, function (err, resp) {
                        function auths(a) {
                            return {
                                role: a.f1,
                                canRead: a.f2,
                                canUpdate: a.f3
                            };
                        }

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

                        resp.rows.forEach(function (row) {
                            row.authorizations = row.authorizations.map(auths);
                        });

                        resolve(resp.rows);
                    });
                }

                tools.isSuperUser({
                    client: client,
                    user: user
                }).then(callback).catch(reject);
            });
        };

        /**
            Check whether a user is authorized to perform an action on a
            particular feather (class) or object.

            Allowable actions: `canCreate`, `canRead`, `canUpdate", `canDelete`

            `canCreate` will only check feather names.

            @method workbookIsAuthorized
            @param {Object} Payload
            @param {Object} payload.data Payload data
            @param {String} payload.data.action
            @param {String} payload.data.name Workbook name
            @param {String} payload.data.user User.
            @param {String} payload.client Database client
            @return {Promise}
        */
        that.workbookIsAuthorized = function (obj) {
            return new Promise(function (resolve, reject) {
                let sql;
                let user = obj.data.user;
                let action = obj.data.action || "";
                let name = obj.data.name;
                let client = db.getClient(obj.client);

                action = action.toSnakeCase();

                function callback(isSuper) {
                    if (isSuper) {
                        resolve(true);
                        return;
                    }

                    sql = (
                        "SELECT _pk " +
                        "FROM \"$workbook\" AS workbook, " +
                        "  \"$auth\" AS auth, " +
                        "  pg_authid " +
                        "WHERE name = $1 " +
                        "  AND workbook._pk=auth.object_pk" +
                        "  AND auth.role=pg_authid.rolname " +
                        "  AND pg_has_role($2, pg_authid.oid, 'member')" +
                        "  AND " + action + " " +
                        "LIMIT 1;"
                    );

                    client.query(sql, [name, user]).then(function (resp) {
                        resolve(resp.rows.length > 0);
                    }).catch(reject);
                }

                if (action !== "can_read" && action !== "can_update") {
                    throw new Error(
                        "Only actions `canRead` and `canUpdate` supported " +
                        "for workbook."
                    );
                }

                if (!name) {
                    throw new Error("Authorization check requires name");
                }

                tools.isSuperUser({
                    client: client,
                    user: obj.data.user
                }).then(callback).catch(reject);
            });
        };

        /**
            Create or upate workbooks.

            @method saveWorkbook
            @param {Object} Payload
            @param {String} payload.user User name.
            @param {Object} payload.data Workbook data.
            @param {Object | Array} payload.data.specs Workbook
            specification(s).
            @param {Object} payload.client Database client
            @return {Promise}
        */
        that.saveWorkbook = function (obj) {
            return new Promise(function (resolve, reject) {
                let row;
                let nextWorkbook;
                let wb;
                let sql;
                let params;
                let authorizations;
                let id;
                let user = obj.user;
                let findSql = "SELECT * FROM \"$workbook\" WHERE name = $1;";
                let workbooks = (
                    Array.isArray(obj.data.specs)
                    ? obj.data.specs
                    : [obj.data.specs]
                );
                let len = workbooks.length;
                let n = 0;
                let oldAuth;
                let client = db.getClient(obj.client);

                findSql = (
                    "SELECT * FROM \"$workbook\" AS workbook, " +
                    "to_json(ARRAY( SELECT ROW(role) " +
                    "  FROM \"$auth\" as auth " +
                    "  WHERE auth.object_pk = workbook._pk " +
                    "  ORDER BY auth.pk)) AS authorizations " +
                    "WHERE name = $1;"
                );

                function execute() {
                    client.query(sql, params, function (err) {
                        let auths = [];
                        let requests = [];

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

                        // If no specific authorization, make one
                        if (authorizations === undefined) {
                            authorizations = [{
                                role: "everyone",
                                canCreate: null,
                                canRead: true,
                                canUpdate: true,
                                canDelete: null
                            }];
                        } else {
                           // Auths are local. Don't change anything
                           authorizations = [];
                        }

                        // Set new authorizations
                        if (authorizations) {
                            authorizations.forEach(function (auth) {
                                let found;
                                let actions;

                                if (auth === null) {
                                    return; // Was deleted
                                }

                                found = auths.find(
                                    (a) => a.data.role === auth.role
                                );

                                if (found) {
                                    actions = found.data.actions;
                                    actions.canCreate = null;
                                    actions.canUpdate = auth.canUpdate;
                                    actions.canRead = auth.canRead;
                                    actions.canDelete = null;
                                } else {
                                    auths.push({
                                        client: client,
                                        data: {
                                            id: id,
                                            role: auth.role,
                                            isInternal: true,
                                            actions: {
                                                canCreate: null,
                                                canRead: auth.canRead,
                                                canUpdate: auth.canUpdate,
                                                canDelete: null
                                            }
                                        }
                                    });
                                }
                            });
                        }

                        auths.forEach(function (auth) {
                            requests.push(
                                feathers.saveAuthorization(auth)
                            );
                        });
                        Promise.all(requests).then(nextWorkbook).catch(reject);
                    });
                }

                nextWorkbook = function () {
                    if (n < len) {
                        wb = workbooks[n];
                        authorizations = wb.authorizations;
                        n += 1;
                        oldAuth = false;

                        // Upsert workbook
                        client.query(
                            findSql,
                            [wb.name],
                            function (err, resp) {
                                let icon;
                                let launchConfig;
                                let localConfig;
                                let defaultConfig;

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

                                row = resp.rows[0];
                                if (row) {
                                    oldAuth = row.authorizations;

                                    // Update workbook
                                    sql = (
                                        "UPDATE \"$workbook\" SET " +
                                        "updated_by=$2, updated=now(), " +
                                        "description=$3, launch_config=$4," +
                                        "default_config=$5," +
                                        "local_config=$6, module=$7, " +
                                        "icon=$8 " +
                                        "WHERE name=$1;"
                                    );
                                    id = row.id;
                                    launchConfig = (
                                        wb.launchConfig || row.launch_config
                                    );
                                    icon = (
                                        wb.icon || row.icon
                                    );
                                    defaultConfig = (
                                        wb.defaultConfig || row.default_config
                                    );
                                    localConfig = (
                                        wb.localConfig || row.local_config
                                    );
                                    params = [
                                        wb.name,
                                        client.currentUser(),
                                        wb.description || row.description,
                                        JSON.stringify(launchConfig),
                                        JSON.stringify(defaultConfig),
                                        JSON.stringify(localConfig),
                                        wb.module,
                                        icon
                                    ];
                                    execute();
                                } else {
                                    tools.isSuperUser({
                                        client: client,
                                        user: user
                                    }).then(function (isSuper) {
                                        let e;

                                        if (!isSuper) {
                                            e = new Error(
                                                "Only super users may create" +
                                                " workbooks."
                                            );
                                            e.statusCode = 401;
                                            throw e;
                                        }

                                        // Insert new workbook
                                        sql = (
                                            "INSERT INTO \"$workbook\"" +
                                            "(_pk, id, name, description, " +
                                            "module, " +
                                            "launch_config, default_config, " +
                                            "local_config, icon, " +
                                            "created_by, updated_by, " +
                                            "created, updated, is_deleted) " +
                                            "VALUES (" +
                                            "nextval('object__pk_seq')," +
                                            "$1, $2, $3, $4, $5, $6, $7, $8," +
                                            "$8, $9, " +
                                            "now(), now(), false) " +
                                            "RETURNING _pk;"
                                        );
                                        id = f.createId();
                                        launchConfig = wb.launchConfig || {};
                                        localConfig = wb.localConfig || [];
                                        defaultConfig = wb.defaultConfig || [];
                                        icon = wb.icon || "folder";
                                        params = [
                                            id,
                                            wb.name,
                                            wb.description || "",
                                            wb.module,
                                            launchConfig,
                                            JSON.stringify(defaultConfig),
                                            JSON.stringify(localConfig),
                                            icon,
                                            client.currentUser()
                                        ];

                                        execute();
                                    }).catch(reject);
                                }
                            }
                        );
                        return;
                    }

                    resolve(true);
                };

                nextWorkbook();
            });
        };

        return that;
    };

}(exports));

<commit_msg>Revert "Update workbooks.js"<commit_after>/*
    Framework for building object relational database apps
    Copyright (C) 2019  John Rogelstad

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
/*jslint node*/
/**
    @module Workbooks
*/
(function (exports) {
    "use strict";

    const {Database} = require("../database");
    const {Feathers} = require("./feathers");
    const {Tools} = require("./tools");
    const f = require("../../common/core");

    const db = new Database();
    const feathers = new Feathers();
    const tools = new Tools();

    /**
        @class Workbooks
        @constructor
        @namespace Services
    */
    exports.Workbooks = function () {
        // ..........................................................
        // PRIVATE
        //

        let that = {};

        // ..........................................................
        // PUBLIC
        //

        /**
          Remove a workbook from the database.

            @method deleteWorkbook
            @param {Object} Request payload
            @param {String} [payload.user] User name
            @param {Object} [payload.data] Payload data
            @param {String} [payload.data.name] Workbook to delete
            @param {Object} [payload.client] Database client
            @return {Object} Promise
        */
        that.deleteWorkbook = function (obj) {
            return new Promise(function (resolve, reject) {
                let sql = "DELETE FROM \"$workbook\" WHERE name=$1;";
                let client = db.getClient(obj.client);

                tools.isSuperUser({
                    client: client,
                    user: obj.user
                }).then(function (isSuper) {
                    let err;

                    if (!isSuper) {
                        err = new Error(
                            "Only super users may delete workbooks."
                        );
                        err.statusCode = 401;
                        throw err;
                    }

                    client.query(sql, [obj.data.name], function (err) {
                        if (err) {
                            reject(err);
                            return;
                        }

                        resolve(true);
                    });
                }).catch(reject);
            });
        };

        /**
            @method getWorkbook
            @param {Object} payload
            @param {String} payload.user
            @param {Client} payload.client
            @param {Object} payload.data
            @param {String} payload.data.name Workbook name
            @return {Promise}
        */
        that.getWorkbook = function (obj) {
            return new Promise(function (resolve, reject) {
                let err;

                function callback(resp) {
                    if (!resp.length) {
                        err = new Error("Workbook not found");
                        err.statusCode = 404;
                        throw err;
                    }

                    resolve(resp[0]);
                }

                that.getWorkbooks({
                    user: obj.user,
                    data: obj.data,
                    client: obj.client
                }).then(callback).catch(reject);
            });
        };

        /**
            Resolve to workbook definition(s). If name is passed in payload
            only that workbook will be returned.

            @method getWorkbooks
            @param {Object} Request payload
            @param {Object} [payload.data] Workbook data
            @param {Object} [payload.data.name] Workbook name
            @param {Object} [payload.client] Database client
            @return {Promise}
        */
        that.getWorkbooks = function (obj) {
            return new Promise(function (resolve, reject) {
                let user = obj.user;
                let client = db.getClient(obj.client);

                function callback(isSuper) {
                    let params = [];
                    let sql;

                    sql = (
                        "SELECT name, description, module, " +
                        "launch_config AS \"launchConfig\", " +
                        "icon, " +
                        "default_config AS \"defaultConfig\", " +
                        "local_config AS \"localConfig\", " +
                        "to_json(ARRAY( SELECT ROW(role, can_read, " +
                        "can_update) " +
                        "  FROM \"$auth\" as auth " +
                        "  WHERE auth.object_pk = workbook._pk " +
                        "  ORDER BY auth.pk)) AS authorizations " +
                        "FROM \"$workbook\" AS workbook " +
                        "WHERE true "
                    );

                    if (!isSuper) {
                        params = [client.currentUser()];
                        sql += (
                            "AND EXISTS (" +
                            "  SELECT can_read FROM ( " +
                            "    SELECT can_read " +
                            "    FROM \"$auth\", pg_authid " +
                            "    WHERE pg_has_role(" +
                            "        $1, pg_authid.oid, 'member')" +
                            "      AND \"$auth\".object_pk=workbook._pk" +
                            "      AND \"$auth\".role=pg_authid.rolname" +
                            "    ORDER BY can_read DESC" +
                            "    LIMIT 1" +
                            "  ) AS data " +
                            "  WHERE can_read)"
                        );
                    }

                    if (obj.data.name) {
                        sql += " AND name=$2";
                        params.push(obj.data.name);
                    }

                    sql += " ORDER BY _pk";

                    client.query(sql, params, function (err, resp) {
                        function auths(a) {
                            return {
                                role: a.f1,
                                canRead: a.f2,
                                canUpdate: a.f3
                            };
                        }

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

                        resp.rows.forEach(function (row) {
                            row.authorizations = row.authorizations.map(auths);
                        });

                        resolve(resp.rows);
                    });
                }

                tools.isSuperUser({
                    client: client,
                    user: user
                }).then(callback).catch(reject);
            });
        };

        /**
            Check whether a user is authorized to perform an action on a
            particular feather (class) or object.

            Allowable actions: `canCreate`, `canRead`, `canUpdate", `canDelete`

            `canCreate` will only check feather names.

            @method workbookIsAuthorized
            @param {Object} Payload
            @param {Object} payload.data Payload data
            @param {String} payload.data.action
            @param {String} payload.data.name Workbook name
            @param {String} payload.data.user User.
            @param {String} payload.client Database client
            @return {Promise}
        */
        that.workbookIsAuthorized = function (obj) {
            return new Promise(function (resolve, reject) {
                let sql;
                let user = obj.data.user;
                let action = obj.data.action || "";
                let name = obj.data.name;
                let client = db.getClient(obj.client);

                action = action.toSnakeCase();

                function callback(isSuper) {
                    if (isSuper) {
                        resolve(true);
                        return;
                    }

                    sql = (
                        "SELECT _pk " +
                        "FROM \"$workbook\" AS workbook, " +
                        "  \"$auth\" AS auth, " +
                        "  pg_authid " +
                        "WHERE name = $1 " +
                        "  AND workbook._pk=auth.object_pk" +
                        "  AND auth.role=pg_authid.rolname " +
                        "  AND pg_has_role($2, pg_authid.oid, 'member')" +
                        "  AND " + action + " " +
                        "LIMIT 1;"
                    );

                    client.query(sql, [name, user]).then(function (resp) {
                        resolve(resp.rows.length > 0);
                    }).catch(reject);
                }

                if (action !== "can_read" && action !== "can_update") {
                    throw new Error(
                        "Only actions `canRead` and `canUpdate` supported " +
                        "for workbook."
                    );
                }

                if (!name) {
                    throw new Error("Authorization check requires name");
                }

                tools.isSuperUser({
                    client: client,
                    user: obj.data.user
                }).then(callback).catch(reject);
            });
        };

        /**
            Create or upate workbooks.

            @method saveWorkbook
            @param {Object} Payload
            @param {String} payload.user User name.
            @param {Object} payload.data Workbook data.
            @param {Object | Array} payload.data.specs Workbook
            specification(s).
            @param {Object} payload.client Database client
            @return {Promise}
        */
        that.saveWorkbook = function (obj) {
            return new Promise(function (resolve, reject) {
                let row;
                let nextWorkbook;
                let wb;
                let sql;
                let params;
                let authorizations;
                let id;
                let user = obj.user;
                let findSql = "SELECT * FROM \"$workbook\" WHERE name = $1;";
                let workbooks = (
                    Array.isArray(obj.data.specs)
                    ? obj.data.specs
                    : [obj.data.specs]
                );
                let len = workbooks.length;
                let n = 0;
                let oldAuth;
                let client = db.getClient(obj.client);

                findSql = (
                    "SELECT * FROM \"$workbook\" AS workbook, " +
                    "to_json(ARRAY( SELECT ROW(role) " +
                    "  FROM \"$auth\" as auth " +
                    "  WHERE auth.object_pk = workbook._pk " +
                    "  ORDER BY auth.pk)) AS authorizations " +
                    "WHERE name = $1;"
                );

                function execute() {
                    client.query(sql, params, function (err) {
                        let auths = [];
                        let requests = [];

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

                        // If no specific authorization, make one
                        if (authorizations === undefined) {
                            authorizations = [{
                                role: "everyone",
                                canCreate: null,
                                canRead: true,
                                canUpdate: true,
                                canDelete: null
                            }];
                        }

                        if (oldAuth) {
                            // Clear old auths in case of deletions
                            oldAuth.forEach(function (auth) {
                                auths.push({
                                    client: client,
                                    data: {
                                        id: id,
                                        role: auth.f1,
                                        isInternal: true,
                                        actions: {
                                            canCreate: false,
                                            canRead: false,
                                            canUpdate: false,
                                            canDelete: false
                                        }
                                    }
                                });
                            });
                        }

                        // Set new authorizations
                        if (authorizations) {
                            authorizations.forEach(function (auth) {
                                let found;
                                let actions;

                                if (auth === null) {
                                    return; // Was deleted
                                }

                                found = auths.find(
                                    (a) => a.data.role === auth.role
                                );

                                if (found) {
                                    actions = found.data.actions;
                                    actions.canCreate = null;
                                    actions.canUpdate = auth.canUpdate;
                                    actions.canRead = auth.canRead;
                                    actions.canDelete = null;
                                } else {
                                    auths.push({
                                        client: client,
                                        data: {
                                            id: id,
                                            role: auth.role,
                                            isInternal: true,
                                            actions: {
                                                canCreate: null,
                                                canRead: auth.canRead,
                                                canUpdate: auth.canUpdate,
                                                canDelete: null
                                            }
                                        }
                                    });
                                }
                            });
                        }

                        auths.forEach(function (auth) {
                            requests.push(
                                feathers.saveAuthorization(auth)
                            );
                        });
                        Promise.all(requests).then(nextWorkbook).catch(reject);
                    });
                }

                nextWorkbook = function () {
                    if (n < len) {
                        wb = workbooks[n];
                        authorizations = wb.authorizations;
                        n += 1;
                        oldAuth = false;

                        // Upsert workbook
                        client.query(
                            findSql,
                            [wb.name],
                            function (err, resp) {
                                let icon;
                                let launchConfig;
                                let localConfig;
                                let defaultConfig;

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

                                row = resp.rows[0];
                                if (row) {
                                    oldAuth = row.authorizations;

                                    // Update workbook
                                    sql = (
                                        "UPDATE \"$workbook\" SET " +
                                        "updated_by=$2, updated=now(), " +
                                        "description=$3, launch_config=$4," +
                                        "default_config=$5," +
                                        "local_config=$6, module=$7, " +
                                        "icon=$8 " +
                                        "WHERE name=$1;"
                                    );
                                    id = row.id;
                                    launchConfig = (
                                        wb.launchConfig || row.launch_config
                                    );
                                    icon = (
                                        wb.icon || row.icon
                                    );
                                    defaultConfig = (
                                        wb.defaultConfig || row.default_config
                                    );
                                    localConfig = (
                                        wb.localConfig || row.local_config
                                    );
                                    params = [
                                        wb.name,
                                        client.currentUser(),
                                        wb.description || row.description,
                                        JSON.stringify(launchConfig),
                                        JSON.stringify(defaultConfig),
                                        JSON.stringify(localConfig),
                                        wb.module,
                                        icon
                                    ];
                                    execute();
                                } else {
                                    tools.isSuperUser({
                                        client: client,
                                        user: user
                                    }).then(function (isSuper) {
                                        let e;

                                        if (!isSuper) {
                                            e = new Error(
                                                "Only super users may create" +
                                                " workbooks."
                                            );
                                            e.statusCode = 401;
                                            throw e;
                                        }

                                        // Insert new workbook
                                        sql = (
                                            "INSERT INTO \"$workbook\"" +
                                            "(_pk, id, name, description, " +
                                            "module, " +
                                            "launch_config, default_config, " +
                                            "local_config, icon, " +
                                            "created_by, updated_by, " +
                                            "created, updated, is_deleted) " +
                                            "VALUES (" +
                                            "nextval('object__pk_seq')," +
                                            "$1, $2, $3, $4, $5, $6, $7, $8," +
                                            "$8, $9, " +
                                            "now(), now(), false) " +
                                            "RETURNING _pk;"
                                        );
                                        id = f.createId();
                                        launchConfig = wb.launchConfig || {};
                                        localConfig = wb.localConfig || [];
                                        defaultConfig = wb.defaultConfig || [];
                                        icon = wb.icon || "folder";
                                        params = [
                                            id,
                                            wb.name,
                                            wb.description || "",
                                            wb.module,
                                            launchConfig,
                                            JSON.stringify(defaultConfig),
                                            JSON.stringify(localConfig),
                                            icon,
                                            client.currentUser()
                                        ];

                                        execute();
                                    }).catch(reject);
                                }
                            }
                        );
                        return;
                    }

                    resolve(true);
                };

                nextWorkbook();
            });
        };

        return that;
    };

}(exports));

<|endoftext|>


<commit_before>import Ember from 'ember';
import appendRange from '../utils/dom/append-range';
import appendCachedRange from '../utils/dom/append-cached-range';

const {
  run,
  Object: Obj
  } = Ember;

const DEFAULT_EXPIRES = 1000 * 5; // 5s

export default Obj.extend({
  _isSustainFactory: true,

  sustainService: null,

  // params exposed via the `{{sustain}}` helper
  component: '', // component name passed into the flexi-sustain marker
  label: null,
  model: null,
  copy: false,
  expires: DEFAULT_EXPIRES,

  // the element where the content should currently be rendered
  parent: null,

  // the content
  range: null,

  // reference to the sustain-container component where the content
  // was initially rendered
  _component: null,

  // caches the teardown handler
  removeTimeout: null,
  storeTimeout: null,

  // caches clone info
  _previousParent: null,
  _previousCopy: false,
  _previousClone: false,

  // caches a range when tearing down
  _cachedRange: false,

  cache() {
    this._cachedRange = this.getNodeRange();
  },

  remove() {
    this.cache();

    if (this.get('copy')) {
      this._previousParent = this.parent;
      this._previousCopy = true;
      this._previousClone = this.cloneNodeRange();
    }

    this.scheduleStorage();
    this.scheduleRemove();

    this.triggerHook('willMove');
  },

  triggerHook(name) {
    if (this._component[name]) {
      this._component[name]();
    }
    this._component.trigger(name);
  },

  _append(newParent) {
    if (this._cachedRange) {
      appendCachedRange(newParent, this._cachedRange);
      this._cachedRange = null;
    } else {
      this.triggerHook('willMove');
      appendRange(newParent, this.range.firstNode, this.range.lastNode);
    }
    this.triggerHook('didMove');

    // leave copy in old location
    if (this._previousClone) {
      let parent = this._previousParent;
      let clone = this._previousClone;

      appendCachedRange(parent, clone);
      this._previousClone = null;
      this._previousParent = null;
    }
  },

  // called each time the location of parent has changed
  insert(to) {
    run.cancel(this.removeTimeout);
    run.cancel(this.storeTimeout);

    // initial insert
    if (!this._isReady) {
      this.parent = to.parent;
      return;
    }

    // move to new location
    this._append(to.parent);

    // update params
    this.parent = to.parent;

    this.setProperties({
      copy: to.copy,
      model: to.model
    });

    this.updateExpires(to.expires);
  },

  updateExpires(newValue) {
    let oldValue = this.get('expires');
    let oIsForever = oldValue === 0 || oldValue === -1;
    let oIsDefined = oldValue || oldValue === 0;
    let nIsDefined = newValue || newValue === 0;
    let nIsForever = newValue === 0 || newValue === -1;

    if (nIsDefined && !oIsForever) {
      if (!oIsDefined || nIsForever || newValue > oldValue) {
        this.set('expires', newValue);
      }
    }
  },

  getNodeRange() {
    let node = this.range.firstNode;
    let list = [];

    while (node !== this.range.lastNode) {
      list.push(node);
      node = node.nextSibling;
    }
    list.push(node);

    return list;
  },

  cloneNodeRange() {
    let list = this.getNodeRange();

    for (let i = 0; i < list.length; i++) {
      list[i] = list[i].cloneNode(true);
    }

    return list;
  },

  scheduleStorage() {
    this.storeTimeout = run.next(this, this.store);
  },

  store() {
    appendRange(this._fragment, this.range.firstNode, this.range.lastNode);
  },

  scheduleRemove() {
    let expires = this.get('expires');

    if (expires === 0 || expires === -1) {
      return;
    }

    this.removeTimeout = run.later(this, this._selfDestruct, expires);
  },

  _selfDestruct() {
    if (this.parent && this.parent === this._component.element) {
      return;
    }

    this.destroy();
  },

  willDestroy() {
    this._super(...arguments);
    this.sustainService.removeSustain(this.get('label'));
    this.sustainService = null;

    // teardown DOM
    this.range = null;
    this._component.destroy();
    this._component = null;
    this.parent = null;

    // teardown clones
    this._previousParent = null;
    this._previousClone = null;

    // teardown async
    run.cancel(this.removeTimeout);
    this.removeTimeout = null;
  },

  _isReady: false,
  isReady() {
    this._isReady = true;

    this.range = {
      firstNode: this._fragment.firstChild,
      lastNode: this._fragment.lastChild
    };

    if (this.parent) {
      appendRange(this.parent, this.range.firstNode, this.range.lastNode);
      this.triggerHook('didMove');
    }
  },

  setupComponent() {
    let name = this.get('component');
    let model = this.get('model');

    this._component = this.owner.lookup(`component:${name}`);

    // if the component hasn't explicitly set it's layout, look it up
    // pre Ember 2.0, layout is a computed property that MUST be set
    // via get/set
    if (!this._component.get('layout')) {
      this._component.set('layout', this.owner.lookup(`template:${name}`));
    }
    this._component.set('model', model);

    let _super = this._component.willInsertElement;

    this._component.willInsertElement = () => {
      this.isReady();
      if (_super) {
        _super.call(this._component);
      }
    };
    this._fragment = this._component.renderToElement();
  },

  init() {
    this._super();
    this.setupComponent();

    if (!this.expires && this.expires !== 0) {
      this.expires = DEFAULT_EXPIRES;
    }
  }

});
<commit_msg>In a classic app sturcture components templates are located in the templates/components directory. Fallback to look up in a classic structure if a template isn't initially found.<commit_after>import Ember from 'ember';
import appendRange from '../utils/dom/append-range';
import appendCachedRange from '../utils/dom/append-cached-range';

const {
  run,
  Object: Obj
  } = Ember;

const DEFAULT_EXPIRES = 1000 * 5; // 5s

export default Obj.extend({
  _isSustainFactory: true,

  sustainService: null,

  // params exposed via the `{{sustain}}` helper
  component: '', // component name passed into the flexi-sustain marker
  label: null,
  model: null,
  copy: false,
  expires: DEFAULT_EXPIRES,

  // the element where the content should currently be rendered
  parent: null,

  // the content
  range: null,

  // reference to the sustain-container component where the content
  // was initially rendered
  _component: null,

  // caches the teardown handler
  removeTimeout: null,
  storeTimeout: null,

  // caches clone info
  _previousParent: null,
  _previousCopy: false,
  _previousClone: false,

  // caches a range when tearing down
  _cachedRange: false,

  cache() {
    this._cachedRange = this.getNodeRange();
  },

  remove() {
    this.cache();

    if (this.get('copy')) {
      this._previousParent = this.parent;
      this._previousCopy = true;
      this._previousClone = this.cloneNodeRange();
    }

    this.scheduleStorage();
    this.scheduleRemove();

    this.triggerHook('willMove');
  },

  triggerHook(name) {
    if (this._component[name]) {
      this._component[name]();
    }
    this._component.trigger(name);
  },

  _append(newParent) {
    if (this._cachedRange) {
      appendCachedRange(newParent, this._cachedRange);
      this._cachedRange = null;
    } else {
      this.triggerHook('willMove');
      appendRange(newParent, this.range.firstNode, this.range.lastNode);
    }
    this.triggerHook('didMove');

    // leave copy in old location
    if (this._previousClone) {
      let parent = this._previousParent;
      let clone = this._previousClone;

      appendCachedRange(parent, clone);
      this._previousClone = null;
      this._previousParent = null;
    }
  },

  // called each time the location of parent has changed
  insert(to) {
    run.cancel(this.removeTimeout);
    run.cancel(this.storeTimeout);

    // initial insert
    if (!this._isReady) {
      this.parent = to.parent;
      return;
    }

    // move to new location
    this._append(to.parent);

    // update params
    this.parent = to.parent;

    this.setProperties({
      copy: to.copy,
      model: to.model
    });

    this.updateExpires(to.expires);
  },

  updateExpires(newValue) {
    let oldValue = this.get('expires');
    let oIsForever = oldValue === 0 || oldValue === -1;
    let oIsDefined = oldValue || oldValue === 0;
    let nIsDefined = newValue || newValue === 0;
    let nIsForever = newValue === 0 || newValue === -1;

    if (nIsDefined && !oIsForever) {
      if (!oIsDefined || nIsForever || newValue > oldValue) {
        this.set('expires', newValue);
      }
    }
  },

  getNodeRange() {
    let node = this.range.firstNode;
    let list = [];

    while (node !== this.range.lastNode) {
      list.push(node);
      node = node.nextSibling;
    }
    list.push(node);

    return list;
  },

  cloneNodeRange() {
    let list = this.getNodeRange();

    for (let i = 0; i < list.length; i++) {
      list[i] = list[i].cloneNode(true);
    }

    return list;
  },

  scheduleStorage() {
    this.storeTimeout = run.next(this, this.store);
  },

  store() {
    appendRange(this._fragment, this.range.firstNode, this.range.lastNode);
  },

  scheduleRemove() {
    let expires = this.get('expires');

    if (expires === 0 || expires === -1) {
      return;
    }

    this.removeTimeout = run.later(this, this._selfDestruct, expires);
  },

  _selfDestruct() {
    if (this.parent && this.parent === this._component.element) {
      return;
    }

    this.destroy();
  },

  willDestroy() {
    this._super(...arguments);
    this.sustainService.removeSustain(this.get('label'));
    this.sustainService = null;

    // teardown DOM
    this.range = null;
    this._component.destroy();
    this._component = null;
    this.parent = null;

    // teardown clones
    this._previousParent = null;
    this._previousClone = null;

    // teardown async
    run.cancel(this.removeTimeout);
    this.removeTimeout = null;
  },

  _isReady: false,
  isReady() {
    this._isReady = true;

    this.range = {
      firstNode: this._fragment.firstChild,
      lastNode: this._fragment.lastChild
    };

    if (this.parent) {
      appendRange(this.parent, this.range.firstNode, this.range.lastNode);
      this.triggerHook('didMove');
    }
  },

  setupComponent() {
    let name = this.get('component');
    let model = this.get('model');

    this._component = this.owner.lookup(`component:${name}`);

    // if the component hasn't explicitly set it's layout, look it up
    // pre Ember 2.0, layout is a computed property that MUST be set
    // via get/set
    if (!this._component.get('layout')) {
      let template = this.owner.lookup(`template:${name}`);
      if (!template) {
        template = this.owner.lookup(`template:components/${name}`);
      }
      this._component.set('layout', template);
    }
    this._component.set('model', model);

    let _super = this._component.willInsertElement;

    this._component.willInsertElement = () => {
      this.isReady();
      if (_super) {
        _super.call(this._component);
      }
    };
    this._fragment = this._component.renderToElement();
  },

  init() {
    this._super();
    this.setupComponent();

    if (!this.expires && this.expires !== 0) {
      this.expires = DEFAULT_EXPIRES;
    }
  }

});
<|endoftext|>


<commit_before>var formData = new FormData(),
    xhr;

function init(){
        xhr = new XMLHttpRequest();
        xhr.open('POST', 'http:localhost:4000/api/scorm/uploadfiles', true);

        xhr.onload = function () {
            init();
        };
}

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

        // Only process image files.
        if (!f.type.match('image.*')) {
            alert("Sólo puedes cargar imágenes");
            continue;
        } else if(f.size >= 1048576){
            alert("La imágen supera el límite de 1 MB");
            continue;
        }

        var reader = new FileReader();

        // Closure to capture the file information.
        reader.onload = (function(theFile) {

               var name = uniqueId();
                    formData.append('files[]', f, name);
                    return function(e) {

                        pasteHtmlAtCaret('');
                    };

        })(f);

        // Read in the image file as a data URL.
        reader.readAsDataURL(f);
    }
}

var uniqueId = function () {
    // Math.random should be unique because of its seeding algorithm.
    // Convert it to base 36 (numbers + letters), and grab the first 9 characters
    // after the decimal.
    return '_' + Math.random().toString(36).substr(2, 9);
};

//Request upload file
function uploadFiles(){
    alert("Me llamaron papi");
    xhr.send(formData);
}

$(document).ready(function(){

    init();
    $('#insertimage').on("change", handleFileSelect);

});
<commit_msg>La url cuando se cargan las imagenes de la formulación reparada.<commit_after>var formData = new FormData(),
    xhr;

function init(){
        xhr = new XMLHttpRequest();
        xhr.open('POST', 'http:104.236.247.200:4000/api/scorm/uploadfiles', true);

        xhr.onload = function () {
            init();
        };
}

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

        // Only process image files.
        if (!f.type.match('image.*')) {
            alert("Sólo puedes cargar imágenes");
            continue;
        } else if(f.size >= 1048576){
            alert("La imágen supera el límite de 1 MB");
            continue;
        }

        var reader = new FileReader();

        // Closure to capture the file information.
        reader.onload = (function(theFile) {

               var name = uniqueId();
                    formData.append('files[]', f, name);
                    return function(e) {

                        pasteHtmlAtCaret('');
                    };

        })(f);

        // Read in the image file as a data URL.
        reader.readAsDataURL(f);
    }
}

var uniqueId = function () {
    // Math.random should be unique because of its seeding algorithm.
    // Convert it to base 36 (numbers + letters), and grab the first 9 characters
    // after the decimal.
    return '_' + Math.random().toString(36).substr(2, 9);
};

//Request upload file
function uploadFiles(){
    xhr.send(formData);
}

$(document).ready(function(){

    init();
    $('#insertimage').on("change", handleFileSelect);

});
<|endoftext|>