<commit_before>// # Export
//
// Export content in selected format
//
/*jslint node: true */
'use strict';

var annoLib = require('./annotations.js');

var mimeTypes = {
  tsv: 'application./tsv',
  ris: 'text/ris',
  json: 'application/json'
}, mainFields = ['title', 'uri', 'created', 'state'],
  risMap = {
  title: 'TI',
  uri: 'UR'
}, exportMap = GLOBAL.config.exportMap || {};

exports.export = function(type, options, req, res) {
  console.log(type, options);
  var mimeType = mimeTypes[type];

  var query = GLOBAL.svc.indexer.formQuery;

  query(options, function(err, results) {
    var ret;
    if (type === 'json') {
      ret = JSON.stringify(results, null, 2);
    } else if (type === 'ris') {
      ret = getRIS(results);
    } else {
      ret = getTSV(results);
    }
    res.setHeader('Content-Type', mimeType);
    res.setHeader('Content-Disposition', 'attachment; filename=' + GLOBAL.config.project + '-export-' + fn(options.size) + fn(options.annotations) + fn(options.terms) + new Date().getTime() + '.' + type);
    res.end(ret);
  });
};

function fn(val) {
  return val ? val + '-' : '';
}

var crlf = '\r\n', rsep = '  - ';
function getRIS(results) {
  if (!results.hits || results.hits.total < 1) {
    return '';
  }
  var ris = [];
  results.hits.hits.forEach(function(hit) {
    var res = hit._source;
    ris.push('TY' + rsep + (res.uri.indexOf('ncbi.nlm.nih.gov') ? 'ABST' : 'JFULL'));
    for (var f in risMap) {
      ris.push(f + rsep + res._source[f]);
    }
    res.annotations.forEach(function(anno) {
      var field = exportMap[anno.annotatedBy];
      if (!field) {
         var c = 0;
         while (exportMap['C' + (++c)]);
         field = 'C' + c;
         exportMap[anno.annotatedBy] = field;
       }
      ris.push(field + rsep + (anno.flattened.replace(new RegExp('.*' + annoLib.unitSep), '').replace(new RegExp(annoLib.unitSep), '/')));
    });

    ris.push(crlf);
  });
  return ris.join(crlf);
}

function getTSV(results) {
}
<commit_msg>ris import<commit_after>// # Export
//
// Export content in selected format
//
/*jslint node: true */
'use strict';

var annoLib = require('./annotations.js');

var mimeTypes = {
  tsv: 'application./tsv',
  ris: 'text/ris',
  json: 'application/json'
}, mainFields = ['title', 'uri', 'created', 'state'],
  risMap = {
  title: 'TI',
  uri: 'UR'
}, exportMap = GLOBAL.config.exportMap || {PubmedArticle: 'MH'};

exports.export = function(type, options, req, res) {
  console.log(type, options);
  var mimeType = mimeTypes[type];

  var query = GLOBAL.svc.indexer.formQuery;

  query(options, function(err, results) {
    var ret;
    if (type === 'json') {
      ret = JSON.stringify(results, null, 2);
    } else if (type === 'ris') {
      ret = getRIS(results);
    } else {
      ret = getTSV(results);
    }
    res.setHeader('Content-Type', mimeType);
    res.setHeader('Content-Disposition', 'attachment; filename=' + GLOBAL.config.project + '-export-' + fn(options.size) + fn(options.annotations) + fn(options.terms) + new Date().getTime() + '.' + type);
    res.end(ret);
  });
};

function fn(val) {
  return val ? val + '-' : '';
}

var crlf = '\r\n', rsep = '  - ';
function getRIS(results) {
  if (!results.hits || results.hits.total < 1) {
    return '';
  }
  var ris = [];
  results.hits.hits.forEach(function(hit) {
    var res = hit._source;
    ris.push('TY' + rsep + (res.uri.indexOf('ncbi.nlm.nih.gov') > -1 ? 'ABST' : 'JFULL'));
    for (var f in risMap) {
      ris.push(risMap[f] + rsep + res[f]);
    }
    res.annotations.forEach(function(anno) {
      var field = exportMap[anno.annotatedBy];
      if (!field) {
         var c = Object.keys(exportMap).length + 1;
         field = 'C' + c;
         while (exportMap[field] !== undefined) {
           c++;
           field = 'C' + c;
         }
         exportMap[anno.annotatedBy] = field;
       }
      ris.push(field + rsep + (anno.flattened.replace(new RegExp('.*?' + annoLib.unitSep), '').replace(new RegExp(annoLib.unitSep, 'g'), '/')));
    });

    ris.push(crlf);
  });
  console.log(exportMap);
  return ris.join(crlf);
}

function getTSV(results) {
}
<|endoftext|>


<commit_before>"use strict";

var url = require("url");
var util = require("util");

var cheerio = require("cheerio");
var request = require("request");

var registered_domains = {};

var max_req_len = 1000000; // 1MB

request = request.defaults({
  sendImmediately: true,
  timeout: 10000,
  headers: {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36"
  }
});

function parse_generic(url_path, $) {
  var title = $("html head title").text();

  if (title.length > 100) {
    title = title.slice(0, 100);
    title += "...";
  }

  return title;
}

function parse_github(url_path, $) {
  var description,
    forks,
    name,
    stargazers,
    ul;

  if (url_path.match("^\\/[\\w-]+\\/[\\w-]+\\/?$") === null) {
    return parse_generic(url_path, $);
  }

  ul = $("ul.pagehead-actions > li > a.js-social-count");
  stargazers = $(ul[0]).text().replace(/\s/g, "");
  ul = $("ul.pagehead-actions > li > a.social-count");
  forks = $(ul[2]).text().replace(/\s/g, "");
  // Horrible hack. Github sometimes switches the order of these.
  if (forks === stargazers) {
    forks = $(ul[1]).text().replace(/\s/g, "");
  }
  description = $("div.repository-description").text().trim();
  name = $(".entry-title > strong > a").text();
  if (name) {
    return util.format("%s (%s stars %s forks) %s", name, stargazers, forks, description);
  }
  return parse_generic(url_path, $);
}

function parse_hn(url_path, $) {
  var href,
    subtext,
    title;

  if (url_path.match("^\\/item\\?id=\\d+") === null) {
    return parse_generic(url_path, $);
  }
  title = $(".title > a");
  subtext = $(".subtext").text().replace(/\s+/g, " ");
  href = title.attr("href");
  if (title.text() && subtext && href) {
    subtext = subtext.replace(/\| past \| web /g, "");
    return util.format("%s (%s) %s", title.text(), href, subtext);
  }
  return parse_generic(url_path, $);
}

function parse_twitter(url_path, $) {
  var username,
    title,
    retweets,
    favorites;

  if (url_path.match("^\\/\\w+\\/status\\/\\d+") === null) {
    return parse_generic(url_path, $);
  }

  // TODO: only do this for paths that make sense
  username = $("div.permalink-tweet-container div.permalink-header a > span.username.js-action-profile-name > b").text();
  title = $("div.permalink-tweet-container p.tweet-text").text();
  retweets = $("div.tweet-stats-container > ul.stats > li.js-stat-count.js-stat-retweets.stat-count > a > strong").text().replace(/\s/g, "");
  favorites = $("div.tweet-stats-container > ul.stats > li.js-stat-count.js-stat-favorites.stat-count > a > strong").text().replace(/\s/g, "");

  return util.format("<@%s> %s (%s retweets, %s favorites)", username, title, retweets || 0, favorites || 0);
}

function parse_youtube(url_path, $) {
  var dislikes,
    duration,
    // Durations are ISO 8601 format: "PT48M42S"
    duration_regex = /^PT(?:(\d+)H)?(?:(\d+)M)?(\d+)S$/,
    likes,
    matches,
    rating,
    title,
    views;

  if (url_path.match("^\\/watch") === null) {
    return parse_generic(url_path, $);
  }

  // TODO: only do this for paths that make sense
  title = $("meta[itemprop=name]").attr("content");
  views = $("#watch7-views-info > div.watch-view-count").text().split(" ")[0] || 0;
  likes = $("#watch-header .like-button-renderer span.yt-uix-button-content").first().text().replace(/[\s,]/g, "") || 0;
  dislikes = $("#watch-header .like-button-renderer span.yt-uix-button-content").get(3);
  dislikes = $(dislikes).text().replace(/[\s,]/g, "") || 0;
  likes = parseInt(likes, 10);
  dislikes = parseInt(dislikes, 10);
  rating = Math.round(100 * likes / (likes + dislikes));
  duration = $("meta[itemprop=duration]").attr("content");
  matches = duration_regex.exec(duration);
  if (matches) {
    matches = {
      hours: parseInt(matches[1], 10),
      minutes: parseInt(matches[2], 10),
      seconds: parseInt(matches[3], 10),
    };
    // Youtube often sets hours to zero and minutes to >= 60
    if (matches.minutes >= 60) {
      matches.hours = Math.floor(matches.minutes / 60);
      matches.minutes = matches.minutes % 60;
    }
    if (matches.minutes < 10) {
      matches.minutes = "0" + matches.minutes;
    }
    if (matches.seconds < 10) {
      matches.seconds = "0" + matches.seconds;
    }
    duration = util.format("%s:%s", matches.minutes, matches.seconds);
    if (matches.hours) {
      duration = util.format("%s:%s", matches.hours, duration);
    }
  } else {
    duration = "";
  }
  return util.format("%s %s %s views %s%% like", title, duration, views, rating);
}

function parse(msg_url, body) {
  var domain,
    f,
    parsed_url,
    title,
    $;

  // This can throw. Caught in describe_url()
  $ = cheerio.load(body);

  parsed_url = url.parse(msg_url);
  // So hacky
  domain = parsed_url.hostname.split(".").slice(-2).join(".");
  f = registered_domains[domain];
  if (f) {
    title = f(parsed_url.path, $);
  } else {
    title = parse_generic(parsed_url.path, $);
  }

  return title.replace(/[\r\n]/g, " ").trim();
}

function describe_url(msg_url, cb) {
  var req,
    req_len = 0;
  req = request.get(msg_url, function (err, response, body) {
    var title;

    if (err) {
      return cb(err, body || response);
    }

    if (response.statusCode >= 400) {
      title = util.format("%s", response.statusCode);
      return cb(null, title);
    }

    if (!body) {
      return cb("No body in response", response);
    }

    try {
      title = parse(msg_url, body);
    } catch (e) {
      return cb(e, title);
    }

    return cb(null, title);
  });
  req.on("data", function (d) {
    req_len += d.length;
    if (req_len > max_req_len) {
      req.destroy();
    }
  });
}

function register(domain, f) {
  registered_domains[domain] = f;
}

register("github.com", parse_github);
register("ycombinator.com", parse_hn);
register("twitter.com", parse_twitter);
register("youtube.com", parse_youtube);

module.exports = {
  describe_url: describe_url,
  parse: parse,
  parse_generic: parse_generic,
  register: register,
};
<commit_msg>Add more headers so more sites think we're a browser.<commit_after>"use strict";

var url = require("url");
var util = require("util");

var cheerio = require("cheerio");
var request = require("request");

var registered_domains = {};

var max_req_len = 1000000; // 1MB

request = request.defaults({
  sendImmediately: true,
  timeout: 10000,
  headers: {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36",
    "Accept" :"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Language": "en-US,en;q=0.8",
    "Cache-Control": "max-age=0",
  }
});

function parse_generic(url_path, $) {
  var title = $("html head title").text();

  if (title.length > 100) {
    title = title.slice(0, 100);
    title += "...";
  }

  return title;
}

function parse_github(url_path, $) {
  var description,
    forks,
    name,
    stargazers,
    ul;

  if (url_path.match("^\\/[\\w-]+\\/[\\w-]+\\/?$") === null) {
    return parse_generic(url_path, $);
  }

  ul = $("ul.pagehead-actions > li > a.js-social-count");
  stargazers = $(ul[0]).text().replace(/\s/g, "");
  ul = $("ul.pagehead-actions > li > a.social-count");
  forks = $(ul[2]).text().replace(/\s/g, "");
  // Horrible hack. Github sometimes switches the order of these.
  if (forks === stargazers) {
    forks = $(ul[1]).text().replace(/\s/g, "");
  }
  description = $("div.repository-description").text().trim();
  name = $(".entry-title > strong > a").text();
  if (name) {
    return util.format("%s (%s stars %s forks) %s", name, stargazers, forks, description);
  }
  return parse_generic(url_path, $);
}

function parse_hn(url_path, $) {
  var href,
    subtext,
    title;

  if (url_path.match("^\\/item\\?id=\\d+") === null) {
    return parse_generic(url_path, $);
  }
  title = $(".title > a");
  subtext = $(".subtext").text().replace(/\s+/g, " ");
  href = title.attr("href");
  if (title.text() && subtext && href) {
    subtext = subtext.replace(/\| past \| web /g, "");
    return util.format("%s (%s) %s", title.text(), href, subtext);
  }
  return parse_generic(url_path, $);
}

function parse_twitter(url_path, $) {
  var username,
    title,
    retweets,
    favorites;

  if (url_path.match("^\\/\\w+\\/status\\/\\d+") === null) {
    return parse_generic(url_path, $);
  }

  // TODO: only do this for paths that make sense
  username = $("div.permalink-tweet-container div.permalink-header a > span.username.js-action-profile-name > b").text();
  title = $("div.permalink-tweet-container p.tweet-text").text();
  retweets = $("div.tweet-stats-container > ul.stats > li.js-stat-count.js-stat-retweets.stat-count > a > strong").text().replace(/\s/g, "");
  favorites = $("div.tweet-stats-container > ul.stats > li.js-stat-count.js-stat-favorites.stat-count > a > strong").text().replace(/\s/g, "");

  return util.format("<@%s> %s (%s retweets, %s favorites)", username, title, retweets || 0, favorites || 0);
}

function parse_youtube(url_path, $) {
  var dislikes,
    duration,
    // Durations are ISO 8601 format: "PT48M42S"
    duration_regex = /^PT(?:(\d+)H)?(?:(\d+)M)?(\d+)S$/,
    likes,
    matches,
    rating,
    title,
    views;

  if (url_path.match("^\\/watch") === null) {
    return parse_generic(url_path, $);
  }

  // TODO: only do this for paths that make sense
  title = $("meta[itemprop=name]").attr("content");
  views = $("#watch7-views-info > div.watch-view-count").text().split(" ")[0] || 0;
  likes = $("#watch-header .like-button-renderer span.yt-uix-button-content").first().text().replace(/[\s,]/g, "") || 0;
  dislikes = $("#watch-header .like-button-renderer span.yt-uix-button-content").get(3);
  dislikes = $(dislikes).text().replace(/[\s,]/g, "") || 0;
  likes = parseInt(likes, 10);
  dislikes = parseInt(dislikes, 10);
  rating = Math.round(100 * likes / (likes + dislikes));
  duration = $("meta[itemprop=duration]").attr("content");
  matches = duration_regex.exec(duration);
  if (matches) {
    matches = {
      hours: parseInt(matches[1], 10),
      minutes: parseInt(matches[2], 10),
      seconds: parseInt(matches[3], 10),
    };
    // Youtube often sets hours to zero and minutes to >= 60
    if (matches.minutes >= 60) {
      matches.hours = Math.floor(matches.minutes / 60);
      matches.minutes = matches.minutes % 60;
    }
    if (matches.minutes < 10) {
      matches.minutes = "0" + matches.minutes;
    }
    if (matches.seconds < 10) {
      matches.seconds = "0" + matches.seconds;
    }
    duration = util.format("%s:%s", matches.minutes, matches.seconds);
    if (matches.hours) {
      duration = util.format("%s:%s", matches.hours, duration);
    }
  } else {
    duration = "";
  }
  return util.format("%s %s %s views %s%% like", title, duration, views, rating);
}

function parse(msg_url, body) {
  var domain,
    f,
    parsed_url,
    title,
    $;

  // This can throw. Caught in describe_url()
  $ = cheerio.load(body);

  parsed_url = url.parse(msg_url);
  // So hacky
  domain = parsed_url.hostname.split(".").slice(-2).join(".");
  f = registered_domains[domain];
  if (f) {
    title = f(parsed_url.path, $);
  } else {
    title = parse_generic(parsed_url.path, $);
  }

  return title.replace(/[\r\n]/g, " ").trim();
}

function describe_url(msg_url, cb) {
  var req,
    req_len = 0;
  req = request.get(msg_url, function (err, response, body) {
    var title;

    if (err) {
      return cb(err, body || response);
    }

    if (response.statusCode >= 400) {
      title = util.format("%s", response.statusCode);
      return cb(null, title);
    }

    if (!body) {
      return cb("No body in response", response);
    }

    try {
      title = parse(msg_url, body);
    } catch (e) {
      return cb(e, title);
    }

    return cb(null, title);
  });
  req.on("data", function (d) {
    req_len += d.length;
    if (req_len > max_req_len) {
      req.destroy();
    }
  });
}

function register(domain, f) {
  registered_domains[domain] = f;
}

register("github.com", parse_github);
register("ycombinator.com", parse_hn);
register("twitter.com", parse_twitter);
register("youtube.com", parse_youtube);

module.exports = {
  describe_url: describe_url,
  parse: parse,
  parse_generic: parse_generic,
  register: register,
};
<|endoftext|>


<commit_before>// utility for generating a uid for each component file
// used in scoped CSS rewriting
var path = require('path')
var hash = require('hash-sum')
var cache = Object.create(null)

module.exports = function genId (file, context) {
  var contextPath = context.split(path.sep)
  var rootId = contextPath[contextPath.length - 1]
  file = rootId + '/' + path.relative(context, file)
  return cache[file] || (cache[file] = hash(file))
}
<commit_msg>fix consistent hash for windows<commit_after>// utility for generating a uid for each component file
// used in scoped CSS rewriting
var path = require('path')
var hash = require('hash-sum')
var cache = Object.create(null)
var sepRE = new RegExp(path.sep.replace('\\', '\\\\'), 'g')

module.exports = function genId (file, context) {
  var contextPath = context.split(path.sep)
  var rootId = contextPath[contextPath.length - 1]
  file = rootId + '/' + path.relative(context, file).replace(sepRE, '/')
  return cache[file] || (cache[file] = hash(file))
}
<|endoftext|>


<commit_before>'use strict';

var os = require('os');
var df = require('node-df');
var path = require('path');

var appRootDir = path.dirname(require.main.filename);
var pjson = require(appRootDir + path.sep +'package.json');

var DEFAULT_PATH = '/ping';

function get(callback) {

  df(function (error, diskInfo) {
    if (error) {
      return callback(null, {msg: 'Error fetching disk info', error: error});
    }
    callback(null, {
      timestamp: Date.now(),
      uptime: process.uptime(),

      application: {
        name: pjson.name,
        version: pjson.version,
        pid: process.pid,
        title: process.title,
        argv: process.argv,
        versions: process.versions
      },

      resources: {
        memory: process.memoryUsage(),
        loadavg: os.loadavg(),
        cpu: os.cpus(),
        disk: diskInfo,
        nics: os.networkInterfaces()
      },

      system: {
        arch: process.arch,
        platform: process.platform,
        type: os.type(),
        release: os.release(),
        hostname: os.hostname(),
        uptime: os.uptime(),
        cores: os.cpus().length,
        memory: os.totalmem()
      }
    });
  });
}

module.exports = function (path) {
  path = path || DEFAULT_PATH;

  return function *responce(next) {
    if (path === this.path) {
      this.body = yield get;
    } else {
      yield next;
    }
  };
};
<commit_msg>Update health.js<commit_after>'use strict';

var os = require('os');
var df = require('node-df');
var path = require('path');

var appRootDir = path.dirname(require.main.filename);
var pjson = require(appRootDir + path.sep +'package.json');

var DEFAULT_PATH = '/ping';

function get(callback) {

  df(function (error, diskInfo) {
    if (error) {
      return callback(null, {msg: 'Error fetching disk info', error: error});
    }
    callback(null, {
      timestamp: Date.now(),
      uptime: process.uptime(),

      application: {
        name: pjson.name,
        version: pjson.version,
        pid: process.pid,
        title: process.title,
        argv: process.argv,
        versions: process.versions,
        node_env: process.env.NODE_ENV
      },

      resources: {
        memory: process.memoryUsage(),
        loadavg: os.loadavg(),
        cpu: os.cpus(),
        disk: diskInfo,
        nics: os.networkInterfaces()
      },

      system: {
        arch: process.arch,
        platform: process.platform,
        type: os.type(),
        release: os.release(),
        hostname: os.hostname(),
        uptime: os.uptime(),
        cores: os.cpus().length,
        memory: os.totalmem()
      }
    });
  });
}

module.exports = function (path) {
  path = path || DEFAULT_PATH;

  return function *responce(next) {
    if (path === this.path) {
      this.body = yield get;
    } else {
      yield next;
    }
  };
};
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

define([], function() {

// ********************************************************************************************* //
// Constants

var Ci = Components.interfaces;
var Cc = Components.classes;
var Cu = Components.utils;

var Wrapper = {};

// ********************************************************************************************* //
// Wrappers

Wrapper.getContentView = function(object)
{
    if (typeof(object) === 'undefined' || object == null)
        return false;

    // There is an expception when accessing StorageList.wrappedJSObject (which is
    // instance of StorageObsolete)
    if (object instanceof window.StorageList)
        return false;

    return (object.wrappedJSObject);
}

Wrapper.unwrapObject = function(object)
{
    // TODO: We might be able to make this check more authoritative with QueryInterface.
    if (typeof(object) === 'undefined' || object == null)
        return object;

    // There is an expception when accessing StorageList.wrappedJSObject (which is
    // instance of StorageObsolete)
    if (object instanceof window.StorageList)
        return object;

    if (object.wrappedJSObject)
        return object.wrappedJSObject;

    return object;
}

Wrapper.unwrapIValue = function(object, viewChrome)
{
    var unwrapped = object.getWrappedValue();
    if (viewChrome)
        return unwrapped;

    try
    {
        // XPCSafeJSObjectWrapper is not defined in Firefox 4.0
        // this should be the only call to getWrappedValue in firebug
        if (typeof(XPCSafeJSObjectWrapper) != "undefined")
            return XPCSafeJSObjectWrapper(unwrapped);
        else if (typeof(unwrapped) == "object")
            return XPCNativeWrapper.unwrap(unwrapped);
        else
            return unwrapped;
    }
    catch (exc)
    {
        if (FBTrace.DBG_ERRORS)
            FBTrace.sysout("unwrapIValue FAILS for "+object+" cause: "+exc,
                {exc: exc, object: object, unwrapped: unwrapped});
        return unwrapped;
    }
}

Wrapper.unwrapIValueObject = function(scope, viewChrome)
{
    var scopeVars = {};
    var listValue = {value: null}, lengthValue = {value: 0};
    scope.getProperties(listValue, lengthValue);

    for (var i = 0; i < lengthValue.value; ++i)
    {
        var prop = listValue.value[i];
        var name = Wrapper.unwrapIValue(prop.name);
        if (prop.value.jsType === prop.value.TYPE_NULL) // null is an object (!)
            scopeVars[name] = null;
        else
        {
            if (!Wrapper.shouldIgnore(name))
                scopeVars[name] = Wrapper.unwrapIValue(prop.value, viewChrome);
        }
    }
    return scopeVars;
};

// ********************************************************************************************* //

Wrapper.ignoreVars =
{
    "__firebug__": 1,
    "eval": 1,

    // We are forced to ignore Java-related variables, because
    // trying to access them causes browser freeze
    "java": 1,
    "sun": 1,
    "Packages": 1,
    "JavaArray": 1,
    "JavaMember": 1,
    "JavaObject": 1,
    "JavaClass": 1,
    "JavaPackage": 1,
    // internal firebug things XXXjjb todo we should privatize these
    "_firebug": 1,
    "_createFirebugConsole": 1,
    "_FirebugCommandLine": 1,
    "loadFirebugConsole": 1,
};

Wrapper.shouldIgnore = function(name)
{
    return (Wrapper.ignoreVars[name] === 1);
};

// ********************************************************************************************* //

return Wrapper;

// ********************************************************************************************* //
});
<commit_msg>[1.9] Fixed comment typo<commit_after>/* See license.txt for terms of usage */

define([], function() {

// ********************************************************************************************* //
// Constants

var Ci = Components.interfaces;
var Cc = Components.classes;
var Cu = Components.utils;

var Wrapper = {};

// ********************************************************************************************* //
// Wrappers

Wrapper.getContentView = function(object)
{
    if (typeof(object) === 'undefined' || object == null)
        return false;

    // There is an exception when accessing StorageList.wrappedJSObject (which is
    // instance of StorageObsolete)
    if (object instanceof window.StorageList)
        return false;

    return (object.wrappedJSObject);
}

Wrapper.unwrapObject = function(object)
{
    // TODO: We might be able to make this check more authoritative with QueryInterface.
    if (typeof(object) === 'undefined' || object == null)
        return object;

    // There is an exception when accessing StorageList.wrappedJSObject (which is
    // instance of StorageObsolete)
    if (object instanceof window.StorageList)
        return object;

    if (object.wrappedJSObject)
        return object.wrappedJSObject;

    return object;
}

Wrapper.unwrapIValue = function(object, viewChrome)
{
    var unwrapped = object.getWrappedValue();
    if (viewChrome)
        return unwrapped;

    try
    {
        // XPCSafeJSObjectWrapper is not defined in Firefox 4.0
        // this should be the only call to getWrappedValue in firebug
        if (typeof(XPCSafeJSObjectWrapper) != "undefined")
            return XPCSafeJSObjectWrapper(unwrapped);
        else if (typeof(unwrapped) == "object")
            return XPCNativeWrapper.unwrap(unwrapped);
        else
            return unwrapped;
    }
    catch (exc)
    {
        if (FBTrace.DBG_ERRORS)
            FBTrace.sysout("unwrapIValue FAILS for "+object+" cause: "+exc,
                {exc: exc, object: object, unwrapped: unwrapped});
        return unwrapped;
    }
}

Wrapper.unwrapIValueObject = function(scope, viewChrome)
{
    var scopeVars = {};
    var listValue = {value: null}, lengthValue = {value: 0};
    scope.getProperties(listValue, lengthValue);

    for (var i = 0; i < lengthValue.value; ++i)
    {
        var prop = listValue.value[i];
        var name = Wrapper.unwrapIValue(prop.name);
        if (prop.value.jsType === prop.value.TYPE_NULL) // null is an object (!)
            scopeVars[name] = null;
        else
        {
            if (!Wrapper.shouldIgnore(name))
                scopeVars[name] = Wrapper.unwrapIValue(prop.value, viewChrome);
        }
    }
    return scopeVars;
};

// ********************************************************************************************* //

Wrapper.ignoreVars =
{
    "__firebug__": 1,
    "eval": 1,

    // We are forced to ignore Java-related variables, because
    // trying to access them causes browser freeze
    "java": 1,
    "sun": 1,
    "Packages": 1,
    "JavaArray": 1,
    "JavaMember": 1,
    "JavaObject": 1,
    "JavaClass": 1,
    "JavaPackage": 1,
    // internal firebug things XXXjjb todo we should privatize these
    "_firebug": 1,
    "_createFirebugConsole": 1,
    "_FirebugCommandLine": 1,
    "loadFirebugConsole": 1,
};

Wrapper.shouldIgnore = function(name)
{
    return (Wrapper.ignoreVars[name] === 1);
};

// ********************************************************************************************* //

return Wrapper;

// ********************************************************************************************* //
});
<|endoftext|>


<commit_before>/*
 * openi_data_api
 * openi-ict.eu
 *
 * Copyright (c) 2013 dmccarthy
 * Licensed under the MIT license.
 */

'use strict';

var dbc          = require('dbc');
var openiLogger  = require('openi-logger');
var openiUtils   = require('openi-cloudlet-utils');

var init = function(logger_params){
   this.logger  = openiLogger(logger_params);
};

var permissionsCheck = function(msg){

   var key   = msg.token.client_id + "+" + openiUtils.getCloudletId(msg.token)
   var perms = msg.json

   console.log(key, perms)

   return {"error":"incomplete"}

   dbc.assert(null !== msg.json);
   var auth_token, cloudletId, verify, key, permission, cloudletRestURL, cloudletDBObj;

   cloudletId      = openiUtils.getCloudletId(msg.token);
   cloudletRestURL = "http://" + msg.headers.host + '/api/v1/cloudlets/' + cloudletId;

   cloudletDBObj = {
      id             : cloudletId,
      location       : cloudletRestURL,
      alias          : msg.json.alias,
      username       : msg.json.username,
      _date_created  : new Date().toJSON()
   };

   return {
      'dao_actions'      : [
         {
            'action'      : 'POST',
            'database'    : cloudletId,
            'object_name' : 'meta',
            'object_data' : cloudletDBObj,
            'resp_type'   : 'cloudlet',
            'id'          : cloudletId,
            'bucket'      : 'permissions'
         }
      ],
      'clients'      : [
         {
            'uuid' : msg.uuid,
            'connId' : msg.connId
         }
      ]
   };

};

var parsePermissions = function(client_perms){

   var server_perms = { '@objects' : {}, '@types' : {} }

   for ( var i = 0; i < client_perms.length; i++ ){
      var perm = client_perms[i]
      if ( 'object' === perm.type ){
         if ( undefined === server_perms['@objects'][perm.ref] ){
            server_perms['@objects'][perm.ref] = {}
         }
         server_perms['@objects'][perm.ref][perm.access_type] = true
      }
      else if ( 'type' === perm.type ){
         if ( undefined === server_perms['@types'][perm.ref] ){
            server_perms['@types'][perm.ref] = {'@app_level' : {}, '@cloudlet_level' : {}}
         }

         if ('APP' === perm.access_level){
            server_perms['@types'][perm.ref]['@app_level'][perm.access_type] = true
         }
         else{
            server_perms['@types'][perm.ref]['@cloudlet_level'][perm.access_type] = true
         }
      }
      else if ( 'GraphObject' === perm.type ){
         console.log("TODO: Add type id mapping")
      }
   }

   return server_perms
}

var postPermissions = function(msg){

   var cloudlet_id = openiUtils.getCloudletId(msg.token)
   var third_party = msg.token.client_id

   var key         = third_party + "+" + cloudlet_id

   var permissions = {
      _date_created : new Date().toJSON(),
      status        : 'unpropagated',
      perms         : parsePermissions(msg.json)
   }

   return {
      'dao_actions'      : [
         {
            'action'      : 'UPDATE_PERMISSIONS',
            'database'    : key,
            'object_data' : permissions,
            'cloudlet_id' : cloudlet_id,
            'third_party' : third_party,
            'resp_type'   : 'permissions',
            'bucket'      : 'permissions'
         }
      ],
      'clients'      : [
         {
            'uuid' : msg.uuid,
            'connId' : msg.connId
         }
      ]
   };

};

var processMongrel2Message = function (msg) {

   this.logger.log('debug', 'process Mongrel 2 Message function');

   this.logger.log('debug', msg);

   if ( msg.headers.METHOD === 'POST' ){

      if ( "/api/v1/permissions/check" === msg.path || "/api/v1/permissions/check/" === msg.path ){
         return permissionsCheck(msg)
      }
      else{
         return postPermissions(msg)
      }
   }
};

module.exports.init                   = init;
module.exports.processMongrel2Message = processMongrel2Message;<commit_msg>Added GET permissions endpoint<commit_after>/*
 * openi_data_api
 * openi-ict.eu
 *
 * Copyright (c) 2013 dmccarthy
 * Licensed under the MIT license.
 */

'use strict';

var dbc          = require('dbc');
var openiLogger  = require('openi-logger');
var openiUtils   = require('openi-cloudlet-utils');

var init = function(logger_params){
   this.logger  = openiLogger(logger_params);
};

var permissionsCheck = function(msg){

   var key   = msg.token.client_id + "+" + openiUtils.getCloudletId(msg.token)
   var perms = msg.json

   console.log(key, perms)

   return {"error":"incomplete"}

   dbc.assert(null !== msg.json);
   var auth_token, cloudletId, verify, key, permission, cloudletRestURL, cloudletDBObj;

   cloudletId      = openiUtils.getCloudletId(msg.token);
   cloudletRestURL = "http://" + msg.headers.host + '/api/v1/cloudlets/' + cloudletId;

   cloudletDBObj = {
      id             : cloudletId,
      location       : cloudletRestURL,
      alias          : msg.json.alias,
      username       : msg.json.username,
      _date_created  : new Date().toJSON()
   };

   return {
      'dao_actions'      : [
         {
            'action'      : 'POST',
            'database'    : cloudletId,
            'object_name' : 'meta',
            'object_data' : cloudletDBObj,
            'resp_type'   : 'cloudlet',
            'id'          : cloudletId,
            'bucket'      : 'permissions'
         }
      ],
      'clients'      : [
         {
            'uuid' : msg.uuid,
            'connId' : msg.connId
         }
      ]
   };

};

var parsePermissions = function(client_perms){

   var server_perms = { '@objects' : {}, '@types' : {} }

   for ( var i = 0; i < client_perms.length; i++ ){
      var perm = client_perms[i]
      if ( 'object' === perm.type ){
         if ( undefined === server_perms['@objects'][perm.ref] ){
            server_perms['@objects'][perm.ref] = {}
         }
         server_perms['@objects'][perm.ref][perm.access_type] = true
      }
      else if ( 'type' === perm.type ){
         if ( undefined === server_perms['@types'][perm.ref] ){
            server_perms['@types'][perm.ref] = {'@app_level' : {}, '@cloudlet_level' : {}}
         }

         if ('APP' === perm.access_level){
            server_perms['@types'][perm.ref]['@app_level'][perm.access_type] = true
         }
         else{
            server_perms['@types'][perm.ref]['@cloudlet_level'][perm.access_type] = true
         }
      }
      else if ( 'GraphObject' === perm.type ){
         console.log("TODO: Add type id mapping")
      }
   }

   return server_perms
}

var getPermissions = function(msg){

   var cloudlet_id = openiUtils.getCloudletId(msg.token)
   var third_party = msg.token.client_id

   var key         = third_party + "+" + cloudlet_id

   return {
      'dao_actions'      : [
         {
            'action'      : 'GET',
            'database'    : key,
            'cloudlet_id' : cloudlet_id,
            'third_party' : third_party,
            'resp_type'   : 'permissions',
            'bucket'      : 'permissions'
         }
      ],
      'clients'      : [
         {
            'uuid' : msg.uuid,
            'connId' : msg.connId
         }
      ]
   };

};

var postPermissions = function(msg){

   var cloudlet_id = openiUtils.getCloudletId(msg.token)
   var third_party = msg.token.client_id

   var key         = third_party + "+" + cloudlet_id

   var permissions = {
      _date_created : new Date().toJSON(),
      status        : 'unpropagated',
      perms         : parsePermissions(msg.json)
   }

   return {
      'dao_actions'      : [
         {
            'action'      : 'UPDATE_PERMISSIONS',
            'database'    : key,
            'object_data' : permissions,
            'cloudlet_id' : cloudlet_id,
            'third_party' : third_party,
            'resp_type'   : 'permissions',
            'bucket'      : 'permissions'
         }
      ],
      'clients'      : [
         {
            'uuid' : msg.uuid,
            'connId' : msg.connId
         }
      ]
   };

};

var processMongrel2Message = function (msg) {

   this.logger.log('debug', 'process Mongrel 2 Message function');

   this.logger.log('debug', msg);

   if ( msg.headers.METHOD === 'GET' ){
      return getPermissions(msg)
   }
   else if ( msg.headers.METHOD === 'POST' ){

      if ( "/api/v1/permissions/check" === msg.path || "/api/v1/permissions/check/" === msg.path ){
         return permissionsCheck(msg)
      }
      else{
         return postPermissions(msg)
      }
   }
};

module.exports.init                   = init;
module.exports.processMongrel2Message = processMongrel2Message;<|endoftext|>


<commit_before>/*
 * openi_data_api
 * openi-ict.eu
 *
 * Copyright (c) 2013 dmccarthy
 * Licensed under the MIT license.
 */

'use strict';

var openiLogger  = require('openi-logger')
var openiUtils   = require('openi-cloudlet-utils')
var zmq          = require('m2nodehandler');
var url          = require('url');
var validator    = require('./validator.js');
var path         = require('path')
var filter       = require('./filter.js')

var init = function(logger_params){
   if (undefined === global.appRoot){
      global.appRoot = path.resolve(__dirname);
   }
   this.logger = openiLogger(logger_params);
}

var getCloudlet = function (path) {

   var parts   = path.split('/')
   var cletPos = 4;

   return parts[cletPos];

}

var getObject = function (path) {

   var parts   = path.split('/')
   var namePos = 5;

   return parts[namePos]

}

var getRevision = function (path) {

   var parts   = path.split('/')
   var namePos = 6;

   return parts[namePos]

}

var genPostMessage = function(msg, senderToDao, senderToClient, terminal_handler){

   var objectId   = 'o_' + openiUtils.hash(msg.json)
   var cloudletId = getCloudlet(msg.path)

   var dbName            = getCloudlet(msg.path) + '+' + objectId;
   var objectRestURL     = "http://" + msg.headers.host + '/api/v1/objects/' + cloudletId + '/' + objectId;

   var type = msg.json['@openi_type'];

   if(type.indexOf("t_") === 0) msg.json['@openi_type'] = "http://" + msg.headers.host + "/api/v1/types/" + type;

   validator.validateObject(msg.json['@openi_type'], msg.json['@data'], function(){

         var obj = {
            '@id'          : objectId,
            '@location'    : objectRestURL,
            '@cloudlet'    : cloudletId,
            '@openi_type'  : msg.json['@openi_type'],
            '@data'        : msg.json['@data'],
            _date_created  : new Date().toJSON(),
            _date_modified : new Date().toJSON()
         }

         senderToDao.send( {
            'dao_actions'      : [
               { 'action'       : 'POST',
                  'database'    : dbName,
                  'object_name' : objectId,
                  'object_data' : obj,
                  'id'          : objectId }
            ],
            'mongrel_sink' : terminal_handler,
            'clients'      : [
               {'uuid' : msg.uuid, 'connId' : msg.connId }
            ]
         });

      },
      function(errorMessage){

         var resp = zmq.Response(zmq.status.BAD_REQUEST_400, zmq.header_json, errorMessage)

         senderToClient.send(msg.uuid, msg.connId, resp);
      }
   );

}

var genPutMessage = function(msg, senderToDao, senderToClient, terminal_handler){

   var objectId    = getObject(  msg.path)
   var cloudletId  = getCloudlet(msg.path)
   var newObjectId = 'o_' + openiUtils.hash(msg.json)

   if (objectId === newObjectId){

      var message = { 'error' : true, 'message' : 'Object has not been altered.'};
      var resp    = new zmq.Response(zmq.status.BAD_REQUEST_400, zmq.header_json, message)
      error.send(msg.uuid, msg.connId, resp)

      return
   }

   var dbName = getCloudlet(msg.path) + '+' + getObject(  msg.path)
   var objectRestURL = "http://" + msg.headers.host + '/api/v1/objects/' + getCloudlet(msg.path) + '/' +  objectId;

   validator.validateObject(msg.json['@openi_type'], msg.json['@data'], function(){

         var obj = {
            '@id'          : objectId,
            '@location'    : objectRestURL,
            '@cloudlet'    : cloudletId,
            '@openi_type'  : msg.json['@openi_type'],
            '@data'        : msg.json['@data'],
            _date_created  : new Date().toJSON(),
            _date_modified : new Date().toJSON()
         }

         senderToDao.send({
            'dao_actions'      : [
               {
                  'action'       : 'PUT',
                  'database'     : dbName,
                  'revision'     : getRevision(msg.path),
                  'object_data'  : obj,
                  'id'           : objectRestURL
               }
            ],
            'mongrel_sink' : terminal_handler,
            'clients'      : [
               {'uuid' : msg.uuid, 'connId' : msg.connId }
            ]
         });

      },
      function(errorMessage){

         var resp = zmq.Response(zmq.status.BAD_REQUEST_400, zmq.header_json, errorMessage)

         senderToClient.send(msg.uuid, msg.connId, resp);
      }
   );
}

var genGetMessage = function(msg, senderToDao, senderToClient, terminal_handler){

   var hasObjectId = (typeof getObject(msg.path) !== 'undefined');

   if(hasObjectId) {
      var dbName = getCloudlet(msg.path) + '+' + getObject(msg.path)

      senderToDao.send({
         'dao_actions'      : [
            { 'action' : 'GET',   'database' : dbName }
         ],
         'mongrel_sink' : terminal_handler,
         'clients'      : [
            {'uuid' : msg.uuid, 'connId' : msg.connId }
         ]
      });
   }
   else if ('/api/v1/search' === msg.path){
      filter.filter(msg, senderToClient)
   }
   else{

      var url_parts = url.parse(msg.headers.URI, true);
      var query     = url_parts.query;

      var cloudletId = getCloudlet(msg.path)

      if(undefined !== query.property_filter || undefined !== query.with_property){
         filter.filter(msg, senderToClient, cloudletId)
         return
      }

      if ('true' === query.id_only ){
         cloudletId = cloudletId + '_id'
      }

      var key      = cloudletId;
      var viewName = 'object_by_cloudlet_id';

      if (undefined !== query.type){
         viewName = 'object_by_type';
         key      = cloudletId + '+' + query.type;
      }

      if (undefined !== query.only_show_properties){
         query.only_show_properties = query.only_show_properties.split(',')
      }

      senderToDao.send({
         'dao_actions'      : [
            {
               'action'       : 'VIEW',
               'key'         : key ,
               'design_doc'  : 'objects_views',
               'view_name'   : viewName,
               'count'       : Number(query.limit),
               'skip'        : Number(query.skip),
               'filter_show' : query.only_show_properties,
               'resp_type'   : 'object'
            }
         ],
         'mongrel_sink' : terminal_handler,
         'clients'      : [
            {'uuid' : msg.uuid, 'connId' : msg.connId }
         ]
      });
   }

}

var genDeleteMessage = function(msg, senderToDao, senderToClient, terminal_handler){

   var dbName = getCloudlet(msg.path) + '+' + getObject(  msg.path)

   senderToDao.send({
      'dao_actions'      : [
         { 'action' : 'DELETE',   'database' : dbName }
      ],
      'mongrel_sink' : terminal_handler,
      'clients'      : [
         {'uuid' : msg.uuid, 'connId' : msg.connId }
      ]
   });

}

var processMongrel2Message = function (msg, senderToDao, senderToClient, terminal_handler) {

   this.logger.logMongrel2Message(msg)

   //Deletes null variables
   for(var key in msg.json){
      if(msg.json[key] === null){
         delete msg.json[key];
      }
   }

   switch(msg.headers['METHOD']){
   case 'POST':
      genPostMessage(msg, senderToDao, senderToClient, terminal_handler)
      break;
   case 'GET':
      genGetMessage(msg, senderToDao, senderToClient, terminal_handler)
      break;
   case 'PUT':
      genPutMessage(msg, senderToDao, senderToClient, terminal_handler)
      break;
   case 'DELETE':
      genDeleteMessage(msg, senderToDao, senderToClient, terminal_handler)
      break;
   default:
      break;
   }

}

module.exports.init                   = init
module.exports.getObject              = getObject
module.exports.processMongrel2Message = processMongrel2Message<commit_msg>Set default @location to https<commit_after>/*
 * openi_data_api
 * openi-ict.eu
 *
 * Copyright (c) 2013 dmccarthy
 * Licensed under the MIT license.
 */

'use strict';

var openiLogger  = require('openi-logger')
var openiUtils   = require('openi-cloudlet-utils')
var zmq          = require('m2nodehandler');
var url          = require('url');
var validator    = require('./validator.js');
var path         = require('path')
var filter       = require('./filter.js')

var init = function(logger_params){
   if (undefined === global.appRoot){
      global.appRoot = path.resolve(__dirname);
   }
   this.logger = openiLogger(logger_params);
}

var getCloudlet = function (path) {

   var parts   = path.split('/')
   var cletPos = 4;

   return parts[cletPos];

}

var getObject = function (path) {

   var parts   = path.split('/')
   var namePos = 5;

   return parts[namePos]

}

var getRevision = function (path) {

   var parts   = path.split('/')
   var namePos = 6;

   return parts[namePos]

}

var genPostMessage = function(msg, senderToDao, senderToClient, terminal_handler){

   var objectId   = 'o_' + openiUtils.hash(msg.json)
   var cloudletId = getCloudlet(msg.path)

   var dbName            = getCloudlet(msg.path) + '+' + objectId;
   var objectRestURL     = "https://" + msg.headers.host + '/api/v1/objects/' + cloudletId + '/' + objectId;

   var type = msg.json['@openi_type'];

   if(type.indexOf("t_") === 0) msg.json['@openi_type'] = "http://" + msg.headers.host + "/api/v1/types/" + type;

   validator.validateObject(msg.json['@openi_type'], msg.json['@data'], function(){

         var obj = {
            '@id'          : objectId,
            '@location'    : objectRestURL,
            '@cloudlet'    : cloudletId,
            '@openi_type'  : msg.json['@openi_type'],
            '@data'        : msg.json['@data'],
            _date_created  : new Date().toJSON(),
            _date_modified : new Date().toJSON()
         }

         senderToDao.send( {
            'dao_actions'      : [
               { 'action'       : 'POST',
                  'database'    : dbName,
                  'object_name' : objectId,
                  'object_data' : obj,
                  'id'          : objectId }
            ],
            'mongrel_sink' : terminal_handler,
            'clients'      : [
               {'uuid' : msg.uuid, 'connId' : msg.connId }
            ]
         });

      },
      function(errorMessage){

         var resp = zmq.Response(zmq.status.BAD_REQUEST_400, zmq.header_json, errorMessage)

         senderToClient.send(msg.uuid, msg.connId, resp);
      }
   );

}

var genPutMessage = function(msg, senderToDao, senderToClient, terminal_handler){

   var objectId    = getObject(  msg.path)
   var cloudletId  = getCloudlet(msg.path)
   var newObjectId = 'o_' + openiUtils.hash(msg.json)

   if (objectId === newObjectId){

      var message = { 'error' : true, 'message' : 'Object has not been altered.'};
      var resp    = new zmq.Response(zmq.status.BAD_REQUEST_400, zmq.header_json, message)
      error.send(msg.uuid, msg.connId, resp)

      return
   }

   var dbName = getCloudlet(msg.path) + '+' + getObject(  msg.path)
   var objectRestURL = "https://" + msg.headers.host + '/api/v1/objects/' + getCloudlet(msg.path) + '/' +  objectId;

   validator.validateObject(msg.json['@openi_type'], msg.json['@data'], function(){

         var obj = {
            '@id'          : objectId,
            '@location'    : objectRestURL,
            '@cloudlet'    : cloudletId,
            '@openi_type'  : msg.json['@openi_type'],
            '@data'        : msg.json['@data'],
            _date_created  : new Date().toJSON(),
            _date_modified : new Date().toJSON()
         }

         senderToDao.send({
            'dao_actions'      : [
               {
                  'action'       : 'PUT',
                  'database'     : dbName,
                  'revision'     : getRevision(msg.path),
                  'object_data'  : obj,
                  'id'           : objectRestURL
               }
            ],
            'mongrel_sink' : terminal_handler,
            'clients'      : [
               {'uuid' : msg.uuid, 'connId' : msg.connId }
            ]
         });

      },
      function(errorMessage){

         var resp = zmq.Response(zmq.status.BAD_REQUEST_400, zmq.header_json, errorMessage)

         senderToClient.send(msg.uuid, msg.connId, resp);
      }
   );
}

var genGetMessage = function(msg, senderToDao, senderToClient, terminal_handler){

   var hasObjectId = (typeof getObject(msg.path) !== 'undefined');

   if(hasObjectId) {
      var dbName = getCloudlet(msg.path) + '+' + getObject(msg.path)

      senderToDao.send({
         'dao_actions'      : [
            { 'action' : 'GET',   'database' : dbName }
         ],
         'mongrel_sink' : terminal_handler,
         'clients'      : [
            {'uuid' : msg.uuid, 'connId' : msg.connId }
         ]
      });
   }
   else if ('/api/v1/search' === msg.path){
      filter.filter(msg, senderToClient)
   }
   else{

      var url_parts = url.parse(msg.headers.URI, true);
      var query     = url_parts.query;

      var cloudletId = getCloudlet(msg.path)

      if(undefined !== query.property_filter || undefined !== query.with_property){
         filter.filter(msg, senderToClient, cloudletId)
         return
      }

      if ('true' === query.id_only ){
         cloudletId = cloudletId + '_id'
      }

      var key      = cloudletId;
      var viewName = 'object_by_cloudlet_id';

      if (undefined !== query.type){
         viewName = 'object_by_type';
         key      = cloudletId + '+' + query.type;
      }

      if (undefined !== query.only_show_properties){
         query.only_show_properties = query.only_show_properties.split(',')
      }

      senderToDao.send({
         'dao_actions'      : [
            {
               'action'       : 'VIEW',
               'key'         : key ,
               'design_doc'  : 'objects_views',
               'view_name'   : viewName,
               'count'       : Number(query.limit),
               'skip'        : Number(query.skip),
               'filter_show' : query.only_show_properties,
               'resp_type'   : 'object'
            }
         ],
         'mongrel_sink' : terminal_handler,
         'clients'      : [
            {'uuid' : msg.uuid, 'connId' : msg.connId }
         ]
      });
   }

}

var genDeleteMessage = function(msg, senderToDao, senderToClient, terminal_handler){

   var dbName = getCloudlet(msg.path) + '+' + getObject(  msg.path)

   senderToDao.send({
      'dao_actions'      : [
         { 'action' : 'DELETE',   'database' : dbName }
      ],
      'mongrel_sink' : terminal_handler,
      'clients'      : [
         {'uuid' : msg.uuid, 'connId' : msg.connId }
      ]
   });

}

var processMongrel2Message = function (msg, senderToDao, senderToClient, terminal_handler) {

   this.logger.logMongrel2Message(msg)

   //Deletes null variables
   for(var key in msg.json){
      if(msg.json[key] === null){
         delete msg.json[key];
      }
   }

   switch(msg.headers['METHOD']){
   case 'POST':
      genPostMessage(msg, senderToDao, senderToClient, terminal_handler)
      break;
   case 'GET':
      genGetMessage(msg, senderToDao, senderToClient, terminal_handler)
      break;
   case 'PUT':
      genPutMessage(msg, senderToDao, senderToClient, terminal_handler)
      break;
   case 'DELETE':
      genDeleteMessage(msg, senderToDao, senderToClient, terminal_handler)
      break;
   default:
      break;
   }

}

module.exports.init                   = init
module.exports.getObject              = getObject
module.exports.processMongrel2Message = processMongrel2Message<|endoftext|>


<commit_before>/*
 * openi_data_api
 * openi-ict.eu
 *
 * Copyright (c) 2013 dmccarthy
 * Licensed under the MIT license.
 */

'use strict';

var openiLogger  = require('openi-logger')
var openiUtils   = require('openi-cloudlet-utils')
var zmq          = require('m2nodehandler');
var url          = require('url');
var validator    = require('./validator.js');
var path         = require('path')
var filter       = require('./filter.js')

var init = function(logger_params){
   if (undefined === global.appRoot){
      global.appRoot = path.resolve(__dirname);
   }
   this.logger = openiLogger(logger_params);
}

var getCloudlet = function (path) {

   var parts   = path.split('/')
   var cletPos = 4;

   return parts[cletPos];

}

var getObject = function (path) {

   var parts   = path.split('/')
   var namePos = 5;

   return parts[namePos]

}

var getRevision = function (path) {

   var parts   = path.split('/')
   var namePos = 6;

   return parts[namePos]

}

var genPostMessage = function(msg, senderToDao, senderToClient, terminal_handler){

   var objectId   = 'o_' + openiUtils.hash(msg.json)
   var cloudletId = getCloudlet(msg.path)

   var dbName            = getCloudlet(msg.path) + '+' + objectId;
   var objectRestURL     = "https://" + msg.headers.host + '/api/v1/objects/' + cloudletId + '/' + objectId;

   var type = msg.json['@openi_type'];

   if(type.indexOf("t_") === 0) msg.json['@openi_type'] = "http://" + msg.headers.host + "/api/v1/types/" + type;

   validator.validateObject(msg.json['@openi_type'], msg.json['@data'], function(){

         var obj = {
            '@id'          : objectId,
            '@location'    : objectRestURL,
            '@cloudlet'    : cloudletId,
            '@openi_type'  : msg.json['@openi_type'],
            '@data'        : msg.json['@data'],
            _date_created  : new Date().toJSON(),
            _date_modified : new Date().toJSON()
         }

         senderToDao.send( {
            'dao_actions'      : [
               { 'action'       : 'POST',
                  'database'    : dbName,
                  'object_name' : objectId,
                  'object_data' : obj,
                  'id'          : objectId }
            ],
            'mongrel_sink' : terminal_handler,
            'clients'      : [
               {'uuid' : msg.uuid, 'connId' : msg.connId }
            ]
         });

      },
      function(errorMessage){

         var resp = zmq.Response(zmq.status.BAD_REQUEST_400, zmq.header_json, errorMessage)

         senderToClient.send(msg.uuid, msg.connId, resp);
      }
   );

}

var genPutMessage = function(msg, senderToDao, senderToClient, terminal_handler){

   var objectId    = getObject(  msg.path)
   var cloudletId  = getCloudlet(msg.path)
   var newObjectId = 'o_' + openiUtils.hash(msg.json)

   if (objectId === newObjectId){

      var message = { 'error' : true, 'message' : 'Object has not been altered.'};
      var resp    = new zmq.Response(zmq.status.BAD_REQUEST_400, zmq.header_json, message)
      error.send(msg.uuid, msg.connId, resp)

      return
   }

   var dbName = getCloudlet(msg.path) + '+' + getObject(  msg.path)
   var objectRestURL = "https://" + msg.headers.host + '/api/v1/objects/' + getCloudlet(msg.path) + '/' +  objectId;

   validator.validateObject(msg.json['@openi_type'], msg.json['@data'], function(){

         var obj = {
            '@id'          : objectId,
            '@location'    : objectRestURL,
            '@cloudlet'    : cloudletId,
            '@openi_type'  : msg.json['@openi_type'],
            '@data'        : msg.json['@data'],
            _date_created  : new Date().toJSON(),
            _date_modified : new Date().toJSON()
         }

         senderToDao.send({
            'dao_actions'      : [
               {
                  'action'       : 'PUT',
                  'database'     : dbName,
                  'revision'     : getRevision(msg.path),
                  'object_data'  : obj,
                  'id'           : objectRestURL
               }
            ],
            'mongrel_sink' : terminal_handler,
            'clients'      : [
               {'uuid' : msg.uuid, 'connId' : msg.connId }
            ]
         });

      },
      function(errorMessage){

         var resp = zmq.Response(zmq.status.BAD_REQUEST_400, zmq.header_json, errorMessage)

         senderToClient.send(msg.uuid, msg.connId, resp);
      }
   );
}

var genGetMessage = function(msg, senderToDao, senderToClient, terminal_handler){

   var hasObjectId = (typeof getObject(msg.path) !== 'undefined');

   if(hasObjectId) {
      var dbName = getCloudlet(msg.path) + '+' + getObject(msg.path)

      senderToDao.send({
         'dao_actions'      : [
            { 'action' : 'GET',   'database' : dbName }
         ],
         'mongrel_sink' : terminal_handler,
         'clients'      : [
            {'uuid' : msg.uuid, 'connId' : msg.connId }
         ]
      });
   }
   else if ('/api/v1/search' === msg.path){
      filter.filter(msg, senderToClient)
   }
   else{

      var url_parts = url.parse(msg.headers.URI, true);
      var query     = url_parts.query;

      var cloudletId = getCloudlet(msg.path)

      if(undefined !== query.property_filter || undefined !== query.with_property){
         filter.filter(msg, senderToClient, cloudletId)
         return
      }

      if ('true' === query.id_only ){
         cloudletId = cloudletId + '_id'
      }

      var key      = cloudletId;
      var viewName = 'object_by_cloudlet_id';

      if (undefined !== query.type){
         viewName = 'object_by_type';
         key      = cloudletId + '+' + query.type;
      }

      if (undefined !== query.only_show_properties){
         query.only_show_properties = query.only_show_properties.split(',')
      }

      senderToDao.send({
         'dao_actions'      : [
            {
               'action'       : 'VIEW',
               'key'         : key ,
               'design_doc'  : 'objects_views',
               'view_name'   : viewName,
               'count'       : Number(query.limit),
               'skip'        : Number(query.skip),
               'filter_show' : query.only_show_properties,
               'resp_type'   : 'object'
            }
         ],
         'mongrel_sink' : terminal_handler,
         'clients'      : [
            {'uuid' : msg.uuid, 'connId' : msg.connId }
         ]
      });
   }

}

var genDeleteMessage = function(msg, senderToDao, senderToClient, terminal_handler){

   var dbName = getCloudlet(msg.path) + '+' + getObject(  msg.path)

   senderToDao.send({
      'dao_actions'      : [
         { 'action' : 'DELETE',   'database' : dbName }
      ],
      'mongrel_sink' : terminal_handler,
      'clients'      : [
         {'uuid' : msg.uuid, 'connId' : msg.connId }
      ]
   });

}

var processMongrel2Message = function (msg, senderToDao, senderToClient, terminal_handler) {

   this.logger.logMongrel2Message(msg)

   //Deletes null variables
   for(var key in msg.json){
      if(msg.json[key] === null){
         delete msg.json[key];
      }
   }

   switch(msg.headers['METHOD']){
   case 'POST':
      genPostMessage(msg, senderToDao, senderToClient, terminal_handler)
      break;
   case 'GET':
      genGetMessage(msg, senderToDao, senderToClient, terminal_handler)
      break;
   case 'PUT':
      genPutMessage(msg, senderToDao, senderToClient, terminal_handler)
      break;
   case 'DELETE':
      genDeleteMessage(msg, senderToDao, senderToClient, terminal_handler)
      break;
   default:
      break;
   }

}

module.exports.init                   = init
module.exports.getObject              = getObject
module.exports.processMongrel2Message = processMongrel2Message<commit_msg>Fixed bug with https and just typeid<commit_after>/*
 * openi_data_api
 * openi-ict.eu
 *
 * Copyright (c) 2013 dmccarthy
 * Licensed under the MIT license.
 */

'use strict';

var openiLogger  = require('openi-logger')
var openiUtils   = require('openi-cloudlet-utils')
var zmq          = require('m2nodehandler');
var url          = require('url');
var validator    = require('./validator.js');
var path         = require('path')
var filter       = require('./filter.js')

var init = function(logger_params){
   if (undefined === global.appRoot){
      global.appRoot = path.resolve(__dirname);
   }
   this.logger = openiLogger(logger_params);
}

var getCloudlet = function (path) {

   var parts   = path.split('/')
   var cletPos = 4;

   return parts[cletPos];

}

var getObject = function (path) {

   var parts   = path.split('/')
   var namePos = 5;

   return parts[namePos]

}

var getRevision = function (path) {

   var parts   = path.split('/')
   var namePos = 6;

   return parts[namePos]

}

var genPostMessage = function(msg, senderToDao, senderToClient, terminal_handler){

   var objectId   = 'o_' + openiUtils.hash(msg.json)
   var cloudletId = getCloudlet(msg.path)

   var dbName            = getCloudlet(msg.path) + '+' + objectId;
   var objectRestURL     = "https://" + msg.headers.host + '/api/v1/objects/' + cloudletId + '/' + objectId;

   var type = msg.json['@openi_type'];

   if(type.indexOf("t_") === 0) msg.json['@openi_type'] = "https://" + msg.headers.host + "/api/v1/types/" + type;

   validator.validateObject(msg.json['@openi_type'], msg.json['@data'], function(){

         var obj = {
            '@id'          : objectId,
            '@location'    : objectRestURL,
            '@cloudlet'    : cloudletId,
            '@openi_type'  : msg.json['@openi_type'],
            '@data'        : msg.json['@data'],
            _date_created  : new Date().toJSON(),
            _date_modified : new Date().toJSON()
         }

         senderToDao.send( {
            'dao_actions'      : [
               { 'action'       : 'POST',
                  'database'    : dbName,
                  'object_name' : objectId,
                  'object_data' : obj,
                  'id'          : objectId }
            ],
            'mongrel_sink' : terminal_handler,
            'clients'      : [
               {'uuid' : msg.uuid, 'connId' : msg.connId }
            ]
         });

      },
      function(errorMessage){

         var resp = zmq.Response(zmq.status.BAD_REQUEST_400, zmq.header_json, errorMessage)

         senderToClient.send(msg.uuid, msg.connId, resp);
      }
   );

}

var genPutMessage = function(msg, senderToDao, senderToClient, terminal_handler){

   var objectId    = getObject(  msg.path)
   var cloudletId  = getCloudlet(msg.path)
   var newObjectId = 'o_' + openiUtils.hash(msg.json)

   if (objectId === newObjectId){

      var message = { 'error' : true, 'message' : 'Object has not been altered.'};
      var resp    = new zmq.Response(zmq.status.BAD_REQUEST_400, zmq.header_json, message)
      error.send(msg.uuid, msg.connId, resp)

      return
   }

   var dbName = getCloudlet(msg.path) + '+' + getObject(  msg.path)
   var objectRestURL = "https://" + msg.headers.host + '/api/v1/objects/' + getCloudlet(msg.path) + '/' +  objectId;

   validator.validateObject(msg.json['@openi_type'], msg.json['@data'], function(){

         var obj = {
            '@id'          : objectId,
            '@location'    : objectRestURL,
            '@cloudlet'    : cloudletId,
            '@openi_type'  : msg.json['@openi_type'],
            '@data'        : msg.json['@data'],
            _date_created  : new Date().toJSON(),
            _date_modified : new Date().toJSON()
         }

         senderToDao.send({
            'dao_actions'      : [
               {
                  'action'       : 'PUT',
                  'database'     : dbName,
                  'revision'     : getRevision(msg.path),
                  'object_data'  : obj,
                  'id'           : objectRestURL
               }
            ],
            'mongrel_sink' : terminal_handler,
            'clients'      : [
               {'uuid' : msg.uuid, 'connId' : msg.connId }
            ]
         });

      },
      function(errorMessage){

         var resp = zmq.Response(zmq.status.BAD_REQUEST_400, zmq.header_json, errorMessage)

         senderToClient.send(msg.uuid, msg.connId, resp);
      }
   );
}

var genGetMessage = function(msg, senderToDao, senderToClient, terminal_handler){

   var hasObjectId = (typeof getObject(msg.path) !== 'undefined');

   if(hasObjectId) {
      var dbName = getCloudlet(msg.path) + '+' + getObject(msg.path)

      senderToDao.send({
         'dao_actions'      : [
            { 'action' : 'GET',   'database' : dbName }
         ],
         'mongrel_sink' : terminal_handler,
         'clients'      : [
            {'uuid' : msg.uuid, 'connId' : msg.connId }
         ]
      });
   }
   else if ('/api/v1/search' === msg.path){
      filter.filter(msg, senderToClient)
   }
   else{

      var url_parts = url.parse(msg.headers.URI, true);
      var query     = url_parts.query;

      var cloudletId = getCloudlet(msg.path)

      if(undefined !== query.property_filter || undefined !== query.with_property){
         filter.filter(msg, senderToClient, cloudletId)
         return
      }

      if ('true' === query.id_only ){
         cloudletId = cloudletId + '_id'
      }

      var key      = cloudletId;
      var viewName = 'object_by_cloudlet_id';

      if (undefined !== query.type){
         viewName = 'object_by_type';
         key      = cloudletId + '+' + query.type;
      }

      if (undefined !== query.only_show_properties){
         query.only_show_properties = query.only_show_properties.split(',')
      }

      senderToDao.send({
         'dao_actions'      : [
            {
               'action'       : 'VIEW',
               'key'         : key ,
               'design_doc'  : 'objects_views',
               'view_name'   : viewName,
               'count'       : Number(query.limit),
               'skip'        : Number(query.skip),
               'filter_show' : query.only_show_properties,
               'resp_type'   : 'object'
            }
         ],
         'mongrel_sink' : terminal_handler,
         'clients'      : [
            {'uuid' : msg.uuid, 'connId' : msg.connId }
         ]
      });
   }

}

var genDeleteMessage = function(msg, senderToDao, senderToClient, terminal_handler){

   var dbName = getCloudlet(msg.path) + '+' + getObject(  msg.path)

   senderToDao.send({
      'dao_actions'      : [
         { 'action' : 'DELETE',   'database' : dbName }
      ],
      'mongrel_sink' : terminal_handler,
      'clients'      : [
         {'uuid' : msg.uuid, 'connId' : msg.connId }
      ]
   });

}

var processMongrel2Message = function (msg, senderToDao, senderToClient, terminal_handler) {

   this.logger.logMongrel2Message(msg)

   //Deletes null variables
   for(var key in msg.json){
      if(msg.json[key] === null){
         delete msg.json[key];
      }
   }

   switch(msg.headers['METHOD']){
   case 'POST':
      genPostMessage(msg, senderToDao, senderToClient, terminal_handler)
      break;
   case 'GET':
      genGetMessage(msg, senderToDao, senderToClient, terminal_handler)
      break;
   case 'PUT':
      genPutMessage(msg, senderToDao, senderToClient, terminal_handler)
      break;
   case 'DELETE':
      genDeleteMessage(msg, senderToDao, senderToClient, terminal_handler)
      break;
   default:
      break;
   }

}

module.exports.init                   = init
module.exports.getObject              = getObject
module.exports.processMongrel2Message = processMongrel2Message<|endoftext|>


<commit_before>'use strict'
var vstamp = require('vigour-stamp')
var subscribe = require('./subscribe')

function keyToNumber (key) {
  var hash = 0
  if (key.length === 0) {
    return hash
  }
  for (let i = 0, len = key.length; i < len; i++) {
    hash = ((hash << 5) + hash) + key.charCodeAt(i)
    hash |= 0
  }
  console.log(hash)
  return hash
}

module.exports = {
  properties: {
    _lstamp: true,
    _sid: true,
    _subscriptions: true,
    cachedSyncPath: true
  },
  // make it easy to create different stamps when using a hub (source ids etc)
  _lstamp: 0,
  define: {
    isState: { value: true },
    keysCheck (val, key) {
      const target = val[key]
      return target &&
        target.isState &&
        !target.keyType
    },
    subscribe (subs, update, tree, stamp, attach, id) {
      return subscribe(this, subs, update, tree, stamp, attach, id)
    },
    sid () {
      if (!('_sid' in this)) {
        if (!this.key) {
          this._sid = 1
        } else {
          this._sid = this.cParent().sid() + keyToNumber(this.key)
          console.log(this._sid)
        }
      }
      return this._sid
    }
  },
  on: {
    data: {
      lstamp: function lstamp (val, stamp) {
        var parent = this.cParent()
        this._lstamp = stamp
        if (this._subscriptions) {
          let l = this
          vstamp.on(stamp, function () {
            l.emit('subscription', val, stamp)
          })
        } else {
          while (parent && parent._lstamp !== stamp) {
            lstampInner(parent, val, stamp)
            parent = parent.cParent()
          }
        }
      }
    }
  }
}

function lstampInner (parent, val, stamp) {
  parent._lstamp = stamp
  if (parent._subscriptions) {
    let l = parent
    vstamp.on(stamp, function () {
      l.emit('subscription', val, stamp)
    })
  } else if ('base' in parent.__on._data) {
    if (parent.__on._data.base) {
      parent.__on._data.base.each(function (p) {
        lstampInner(p, val, stamp)
      })
    }
  }
}
<commit_msg>convert sid to 32 bit int<commit_after>'use strict'
var vstamp = require('vigour-stamp')
var subscribe = require('./subscribe')

function keyToNumber (key) {
  var hash = 0
  for (let i = 0, len = key.length; i < len; i++) {
    hash = ((hash << 5) + hash) + key.charCodeAt(i)
    hash |= 0
  }
  console.log(hash)
  return hash
}

module.exports = {
  properties: {
    _lstamp: true,
    _sid: true,
    _subscriptions: true,
    cachedSyncPath: true
  },
  // make it easy to create different stamps when using a hub (source ids etc)
  _lstamp: 0,
  define: {
    isState: { value: true },
    keysCheck (val, key) {
      const target = val[key]
      return target &&
        target.isState &&
        !target.keyType
    },
    subscribe (subs, update, tree, stamp, attach, id) {
      return subscribe(this, subs, update, tree, stamp, attach, id)
    },
    sid () {
      if (!('_sid' in this)) {
        if (!this.key) {
          this._sid = 1
        } else {
          this._sid = this.cParent().sid() + keyToNumber(this.key)
          console.log(this._sid)
        }
      }
      return this._sid
    }
  },
  on: {
    data: {
      lstamp: function lstamp (val, stamp) {
        var parent = this.cParent()
        this._lstamp = stamp
        if (this._subscriptions) {
          let l = this
          vstamp.on(stamp, function () {
            l.emit('subscription', val, stamp)
          })
        } else {
          while (parent && parent._lstamp !== stamp) {
            lstampInner(parent, val, stamp)
            parent = parent.cParent()
          }
        }
      }
    }
  }
}

function lstampInner (parent, val, stamp) {
  parent._lstamp = stamp
  if (parent._subscriptions) {
    let l = parent
    vstamp.on(stamp, function () {
      l.emit('subscription', val, stamp)
    })
  } else if ('base' in parent.__on._data) {
    if (parent.__on._data.base) {
      parent.__on._data.base.each(function (p) {
        lstampInner(p, val, stamp)
      })
    }
  }
}
<|endoftext|>


<commit_before>"use strict";
var __version__='1.0.1';
function isChainable(name){
	name=name[0]=='.'?name.slice(1).split("(")[0]:name.split("(")[0];//remove '.' and "(" and ")"
	var tools={"activateGenerator":true,"deactivateGenerator":true,"setAxisValues":true,"resetGenerator":true,"addToFavourites":true,"removeFavourites":true,"getId":false,"getFavourites":false,
	"getBackup":false,"restoreBackup":false};
	return tools[name] != undefined ?tools[name]:false;//if the key does not exist in the above dictionary return  false else return its value
}
function TextShadow(args){
	function val(o){return $(o).val();}
	function abs(a){return Math.abs(a);}
	function bind(container,evnt,item,fn){
		$(function(){
			if(item)
				$(container).on(evnt,item,fn);
			else
				$(container).on(evnt,fn);
		});
	}
	var self=this;
	self.generator_markup=""+
	"
 "+
		"
"+
			"
Text shadow Generator
"+
			"
"+
			"
 "+
				"
 "+
					"
X-axis
 "+
					"<input type='range' class='text-shadow-sliders x-axis' min='-100' max='150' value=0>"+
				"
 "+
				"
"+
					"
Y-axis
 "+
					"<input type='range' class='text-shadow-sliders y-axis' min='-100' max='150' value=0> "
				+"
"
				+"
"+
					"
Blur
"+
					"<input type='range' class='text-shadow-sliders blur' min='0' max='10' step='0.1' value='0'> "+
				"
"+
			"
"+
			"

Shadow is applied here

 "+
			"
 "+
			"
"+
				"
Red
 "+
				"<input type='range' class='text-shadow-color-sliders' min='0' max='255' step='1' value='0'> "+
			"
"+
			"
 "+
				"
Green
 "+
				" <input type='range' class='text-shadow-color-sliders' min='0' max='255' step='1' value='0'>"+
			"
 "+
			"
 "+
				"
Blue
 "+
				" <input type='range' class='text-shadow-color-sliders' min='0' max='255' step='1' value='0'> "+
			"
 "+
			"
 "+
				"
Opacity
 "+
				"<input type='range' class='text-shadow-color-sliders opacity' min='0' max='1' step='0.1' value='1'> "+
			"
"+
			"
"+
		"
  "+
			"
text-shadow:0px 0px rgb(0,0,0);
  "+
		"
"+
	"
 ";
	self.host_id=null;
	if(typeof args != 'string' || !args || args[0]=='.' || !args[0]=="#"){
		throw new Error("Invalid id!!!"+args);
	}
	else
		self.host_id=args;
	self.shadow_code="none";
	self.content_backup=null;
	self.favourites=[];
	self.getId=function(){
		return self.host_id;
	};
	var render=function(){
		if(self.getId() != null && self.getId()[0]=='#')
			bind(document,"ready",null,function(){
				self.content_backup=$(self.host_id).html();
				$(self.host_id).html(self.generator_markup);
			});
		return self;
	};
	self.getBackup=function(){
		return self.content_backup;
	}
	self.restoreBackup=function(destination){
		if(!destination)
			throw new Error("Wrong destination");
		var isClass=destination[0]=='.';
		if(isClass){
			var answer=confirm("You are going to create duplicates of your backed content.Are you sure you want to continue");
			if(answer)
				$(destination).html(self.getBackup());
		}
		else
			$(destination).html(self.getBackup());
		return self;
	};
	self.getCode=function(){
		return self.shadow_code;
	};
	self.activateGenerator=function(){
		var host=self.getId();
		var code=self.getCode();
		bind(host,"mousemove touchmove",null,function(){
			var sliders=$(host+" .panel-body .text-shadow-sliders");
			var color_sliders=$(host+" .panel-body .text-shadow-color-sliders");
			var color=val(color_sliders[3]) != '1'?"rgba("+val(color_sliders[0])+","+val(color_sliders[1])+","+val(color_sliders[2])+","+val(color_sliders[3])+")":"rgb("+val(color_sliders[0])+","+val(color_sliders[1])+","+val(color_sliders[2])+")";
			self.shadow_code=val(sliders[0])+"px "+val(sliders[1])+"px ";
			if(val(sliders[2])!= '0')
				self.shadow_code+=val(sliders[2])+"px ";
			self.shadow_code+=color;
			$(host+ " .text-shadow-code-output").text("text-shadow:"+self.shadow_code+";");
			$(host+ " .panel .text-shadow-output").css("text-shadow",self.shadow_code);
		});
		return self;
	};
	self.deactivateGenerator=function(){
		$(self.getId()).off();
		return self;
	};
	self.setAxisValues=function(limit,value){
		//more validations to come here
		var sliders=$(self.getId()+" .text-shadow-sliders");
		if(isNaN(value) || !value || !limit)
			throw new Error("An error occured.");
		var value=abs(value);
		switch(limit.toUpperCase()){
			//we use for loop because we do not want to target every single slider
			case "MIN":
				for(var i=0;i<sliders.length-1;i++)
					$(sliders[i]).prop("min",value * -1);
				break;
			default:
				$(sliders[i]).prop("max",value);
		}//switch
		return self;
	};
	self.resetGenerator=function(){
		var host=self.getId();
		$(host+" .text-shadow-sliders").val(0);
		$(host+" .text-shadow-color-sliders").val(0);
		$(host+" .opacity").val(1);
		self.shadow_code="0px 0px rgb(0,0,0)";
		$(host+ " .text-shadow-code-output").text("text-shadow:"+self.shadow_code+";");
		$(host+ " .panel .text-shadow-output").css("text-shadow","none");
		return self;
	};
	self.addToFavourites=function(append){
		if(self.favourites.indexOf(self.getCode())== -1 && self.getCode() != "none")
			self.favourites.push(self.getCode());
		return self;
	};
	self.getFavourites=function(){
		return self.favourites;
	};
	self.removeFavourites=function(){
		var del;
		if( del=confirm("Are you sure you want to erase your favourites?"))
			self.favourites.length=0;
		return self;
	};
	self.showFavourites=function(){
		var error="Function has not been implemented yet and it is not part of the public API!!!!";
		//bootbox.alert("
"+error+"
");
		var favourites=self.getFavourites();
		var total=favourites.length;
		if(favourites.length<1)
			bootbox.alert("No favourites  to show!!!");
		else{
			var list_items;
			function renderlist(){
				var ul="
";
				var carrets="

"
				+"

";
				for(var i=0;i<total;i++)
					if(i<10)
						ul+="
text-shadow:"+favourites[i]+";
";
					else
						ul+="
text-shadow:"+favourites[i]+";
";
				ul+="
"+carrets;
				list_items=$(".favourite_item");
				for(var i=10;i<total;i++)
					$(list_items[i]).hide();
				return ul;
			}
			bootbox.alert(renderlist());
			bind(".list-group","click",".list-group-item",function(){
				$(".list-group li").removeClass('active');
				$(this).addClass('active');
			});
			bind(".show_less","click",null,function(){
				console.log("Total:"+favourites.length);
			});
			bind(".show_more","click",null,function(){
				var list_items=$(" .favourite_item");
				$(list_items).toggleClass("no-display");
				/*for(var start=total-10;start<total;start++)
					$(list_items[start]).removeClass("no-display");*/
			});
		}
		return self;
	};
	self.downloadFavourites=function(){
		var file="/********\n",blob;
		var items=self.getFavourites();
		if(items.length<1)
			return "No favourites found";
		for(var i=0;i<items.length;i++)
			file+="text-shadow:"+items[i]+";\n";
		file+="**************\n";
		try{
			blob=new Blob([file], {type: "text/plain;charset=utf-8"});
			saveAs(blob,"favourites.css");
		}
		catch(e){
			alert("Filesaver is missing!!!");
		}
	};
	render();
}<commit_msg>show only the first 10 favourites when pressing show favourites<commit_after>"use strict";
var __version__='1.0.1';
function isChainable(name){
	name=name[0]=='.'?name.slice(1).split("(")[0]:name.split("(")[0];//remove '.' and "(" and ")"
	var tools={"activateGenerator":true,"deactivateGenerator":true,"setAxisValues":true,"resetGenerator":true,"addToFavourites":true,"removeFavourites":true,"getId":false,"getFavourites":false,
	"getBackup":false,"restoreBackup":false};
	return tools[name] != undefined ?tools[name]:false;//if the key does not exist in the above dictionary return  false else return its value
}
function TextShadow(args){
	function val(o){return $(o).val();}
	function abs(a){return Math.abs(a);}
	function bind(container,evnt,item,fn){
		$(function(){
			if(item)
				$(container).on(evnt,item,fn);
			else
				$(container).on(evnt,fn);
		});
	}
	var self=this;
	var host=null;
	self.generator_markup=""+
	"
 "+
		"
"+
			"
Text shadow Generator
"+
			"
"+
			"
 "+
				"
 "+
					"
X-axis
 "+
					"<input type='range' class='text-shadow-sliders x-axis' min='-100' max='150' value=0>"+
				"
 "+
				"
"+
					"
Y-axis
 "+
					"<input type='range' class='text-shadow-sliders y-axis' min='-100' max='150' value=0> "
				+"
"
				+"
"+
					"
Blur
"+
					"<input type='range' class='text-shadow-sliders blur' min='0' max='10' step='0.1' value='0'> "+
				"
"+
			"
"+
			"

Shadow is applied here

 "+
			"
 "+
			"
"+
				"
Red
 "+
				"<input type='range' class='text-shadow-color-sliders' min='0' max='255' step='1' value='0'> "+
			"
"+
			"
 "+
				"
Green
 "+
				" <input type='range' class='text-shadow-color-sliders' min='0' max='255' step='1' value='0'>"+
			"
 "+
			"
 "+
				"
Blue
 "+
				" <input type='range' class='text-shadow-color-sliders' min='0' max='255' step='1' value='0'> "+
			"
 "+
			"
 "+
				"
Opacity
 "+
				"<input type='range' class='text-shadow-color-sliders opacity' min='0' max='1' step='0.1' value='1'> "+
			"
"+
			"
"+
		"
  "+
			"
text-shadow:0px 0px rgb(0,0,0);
  "+
		"
"+
	"
 ";
	self.host_id=null;
	if(typeof args != 'string' || !args || args[0]=='.' || !args[0]=="#"){
		throw new Error("Invalid id!!!"+args);
	}
	else
		self.host_id=host=args;
	self.shadow_code="none";
	self.content_backup=null;
	self.favourites=[];
	for(var i=1;i<=30;i++)self.favourites.push(i);
	self.getId=function(){
		return self.host_id;
	};
	var render=function(){
		if(host != null && host[0]=='#')
			bind(document,"ready",null,function(){
				self.content_backup=$(host).html();
				$(host).html(self.generator_markup);
			});
		return self;
	};
	self.getBackup=function(){
		return self.content_backup;
	}
	self.restoreBackup=function(destination){
		var backup=self.getBackup();
		if(!destination)
			throw new Error("Wrong destination");
		var isClass=destination[0]=='.';
		if(isClass){
			var answer=confirm("You are going to create duplicates of your backed content.Are you sure you want to continue");
			if(answer)
				$(destination).html(backup);
		}
		else
			$(destination).html(backup);
		return self;
	};
	self.getCode=function(){
		return self.shadow_code;
	};
	self.activateGenerator=function(){
		var code=self.getCode();
		bind(host,"mousemove touchmove",null,function(){
			var sliders=$(host+" .panel-body .text-shadow-sliders");
			var color_sliders=$(host+" .panel-body .text-shadow-color-sliders");
			var color=val(color_sliders[3]) != '1'?"rgba("+val(color_sliders[0])+","+val(color_sliders[1])+","+val(color_sliders[2])+","+val(color_sliders[3])+")":"rgb("+val(color_sliders[0])+","+val(color_sliders[1])+","+val(color_sliders[2])+")";
			self.shadow_code=val(sliders[0])+"px "+val(sliders[1])+"px ";
			if(val(sliders[2])!= '0')
				self.shadow_code+=val(sliders[2])+"px ";
			self.shadow_code+=color;
			$(host+ " .text-shadow-code-output").text("text-shadow:"+self.shadow_code+";");
			$(host+ " .panel .text-shadow-output").css("text-shadow",self.shadow_code);
		});
		return self;
	};
	self.deactivateGenerator=function(){
		$(host).off();
		return self;
	};
	self.setAxisValues=function(limit,value){
		//more validations to come here
		var sliders=$(host+" .text-shadow-sliders");
		if(isNaN(value) || !value || !limit)
			throw new Error("An error occured.");
		var value=abs(value);
		switch(limit.toUpperCase()){
			//we use for loop because we do not want to target every single slider
			case "MIN":
				for(var i=0;i<sliders.length-1;i++)
					$(sliders[i]).prop("min",value * -1);
				break;
			default:
				for(var i=0;i<sliders.length-1;i++)
					$(sliders[i]).prop("max",value);
		}//switch
		return self;
	};
	self.resetGenerator=function(){
		$(host+" .text-shadow-sliders").val(0);
		$(host+" .text-shadow-color-sliders").val(0);
		$(host+" .opacity").val(1);
		self.shadow_code="0px 0px rgb(0,0,0)";
		$(host+ " .text-shadow-code-output").text("text-shadow:"+self.shadow_code+";");
		$(host+ " .panel .text-shadow-output").css("text-shadow","none");
		return self;
	};
	self.addToFavourites=function(append){
		var code=self.getCode();
		if(self.favourites.indexOf(code)== -1 && code != "none")
			self.favourites.push(code);
		return self;
	};
	self.getFavourites=function(){
		return self.favourites;
	};
	self.removeFavourites=function(){
		var del;
		if( del=confirm("Are you sure you want to erase your favourites?"))
			self.favourites.length=0;
		return self;
	};
	self.showFavourites=function(){
		var error="Function has not been implemented yet and it is not part of the public API!!!!";
		var index=0;
		/*try{
			bootbox.alert("
"+error+"
");
		}
		catch(e){
			setTimeout(function(){
				console.warning(error);
			},3000);
		}*/
		var favourites=self.getFavourites();
		var total=favourites.length;
		if(favourites.length<1)
			bootbox.alert("No favourites  to show!!!");
		else{
			var list_items;
			function renderlist(){
				var ul="
";
				var carrets="

"
				+"

";
				for(var i=0;i<10;i++)
					ul+="
text-shadow:"+favourites[i]+";
";
				ul+="
"+carrets;
				list_items=$(".favourite_item");
				return ul;
			}
			bootbox.alert(renderlist());
			bind(".list-group","click",".list-group-item",function(){
				$(".list-group li").removeClass('active');
				$(this).addClass('active');
			});
			bind(".show_less","click",null,function(){
				console.log("Total:"+favourites.length);
			});
			bind(".show_more","click",null,function(){
				var current_list="";
				list_items=$(".favourite_item");
				for(var i=index;i<total-(total-10);i++){
					current_list+="
"+favourites[i]+"
";
				}
				$(".fix").html(current_list);
				console.log(current_list);
				index+=10;
			});
		}
		return self;
	};
	self.downloadFavourites=function(){
		var file="/********\n";
		var items=self.getFavourites();
		if(items.length<1)
			return "No favourites found";
		for(var i=0;i<items.length;i++)
			file+="text-shadow:"+items[i]+";\n";
		file+="**************\n";
		try{
			saveAs(new Blob([file], {type: "text/plain;charset=utf-8"}),"favourites.css");
		}
		catch(e){
			alert("Filesaver is missing!!!");
		}
	};
	render();
}<|endoftext|>