<commit_before>import jump from 'jump.js'

export default class Util {
    /**
     * Expand color to full RGBA string
     *
     * @param raw rgba value
     * @return RGBA string
     */
    static expandColor (num) {
        num >>>= 0;

        var b = num & 0xFF,
            g = (num & 0xFF00) >>> 8,
            r = (num & 0xFF0000) >>> 16,
            a = ((num & 0xFF000000) >>> 24) / 255;
        return "rgba(" + [r, g, b, a].join(",") + ")";
    }

    static entityEncode (string) {

        while (string.indexOf("<") !== -1) {
            string = string.replace("<", "<");
        }

        while (string.indexOf(">") !== -1) {
            string = string.replace(">", ">");
        }

        string = string.replace(/\n/g, '
');

        return string;
    }

    static generateSnippet (object) {

        if(typeof object.snippet != "undefined")
            return object.snippet;

        let snippet = object.snippet || object.data;
        let type = object.message_type || object.type;
        let mime_type = object.mime_type || "text/plain";

        snippet = mime_type == "text/plain" ? (snippet) : "Photo";

        if (type != 0 && type != 6 && type != 3 && type != 5)
            snippet = "You: " + snippet;

        return snippet;

    }

    static generateContact (id, title, color, accent, ligher, darker) {
        return {
            id: id,
            title: title,
            colors: {
                default: color,
                accent: accent,
                ligher: ligher,
                darker: darker
            }
        }
    }

    /**
        * Scroll to bottom
        * Scrolls thread to bottom of page; uses tween easing
        *
        * @param speed - default to zero (no animation)
        */
    static scrollToBottom(speed) {

        if (typeof speed == "undefined") // Speed defaults to zero
            speed = 0;

        const docu = document.getElementsByTagName("html")[0].clientHeight
        const body = document.getElementsByTagName("body")[0].clientHeight

        const bottom = Math.max(docu, body); // Calculate bottom

        // Jump to bottom
        jump(bottom, {
            duration: speed,
            easing: (t, b, c, d) => { // easeInOutCubic - @jaxgeller
                if ((t/=d/2) < 1) return c/2*t*t*t + b;
                return c/2*((t-=2)*t*t + 2) + b;
            }
        });
    }

    static snackbar(message) {
        var data = {}

        if(typeof message == "string")
            data = { message: message };
        else
            data = message

        var notification = document.querySelector('.mdl-js-snackbar');
        notification.MaterialSnackbar.showSnackbar(data);
    }
}

/**
* Contains element
* @param element value
*/
Array.prototype.contains = function(element) {
    return this.indexOf(element) > -1 ? true : false
}

/**
* Contains element, by key
* @param key
* @param element value
*/
Array.prototype.containsObjKey = function(key, element) {

    for (var i = 0; i < this.length; i++)
        if (this[i][key] === element)
            return true

    return false
}

<commit_msg>Hot fix: Remove hidden attr from snackbar<commit_after>import jump from 'jump.js'

export default class Util {
    /**
     * Expand color to full RGBA string
     *
     * @param raw rgba value
     * @return RGBA string
     */
    static expandColor (num) {
        num >>>= 0;

        var b = num & 0xFF,
            g = (num & 0xFF00) >>> 8,
            r = (num & 0xFF0000) >>> 16,
            a = ((num & 0xFF000000) >>> 24) / 255;
        return "rgba(" + [r, g, b, a].join(",") + ")";
    }

    static entityEncode (string) {

        while (string.indexOf("<") !== -1) {
            string = string.replace("<", "<");
        }

        while (string.indexOf(">") !== -1) {
            string = string.replace(">", ">");
        }

        string = string.replace(/\n/g, '
');

        return string;
    }

    static generateSnippet (object) {

        if(typeof object.snippet != "undefined")
            return object.snippet;

        let snippet = object.snippet || object.data;
        let type = object.message_type || object.type;
        let mime_type = object.mime_type || "text/plain";

        snippet = mime_type == "text/plain" ? (snippet) : "Photo";

        if (type != 0 && type != 6 && type != 3 && type != 5)
            snippet = "You: " + snippet;

        return snippet;

    }

    static generateContact (id, title, color, accent, ligher, darker) {
        return {
            id: id,
            title: title,
            colors: {
                default: color,
                accent: accent,
                ligher: ligher,
                darker: darker
            }
        }
    }

    /**
        * Scroll to bottom
        * Scrolls thread to bottom of page; uses tween easing
        *
        * @param speed - default to zero (no animation)
        */
    static scrollToBottom(speed) {

        if (typeof speed == "undefined") // Speed defaults to zero
            speed = 0;

        const docu = document.getElementsByTagName("html")[0].clientHeight
        const body = document.getElementsByTagName("body")[0].clientHeight

        const bottom = Math.max(docu, body); // Calculate bottom

        // Jump to bottom
        jump(bottom, {
            duration: speed,
            easing: (t, b, c, d) => { // easeInOutCubic - @jaxgeller
                if ((t/=d/2) < 1) return c/2*t*t*t + b;
                return c/2*((t-=2)*t*t + 2) + b;
            }
        });
    }

    static snackbar(message) {
        var data = {}

        if(typeof message == "string")
            data = { message: message };
        else
            data = message

        var notification = document.querySelector('.mdl-js-snackbar');
        notification.attributes.removeNamedItem("hidden");

        notification.MaterialSnackbar.showSnackbar(data);
    }
}

/**
* Contains element
* @param element value
*/
Array.prototype.contains = function(element) {
    return this.indexOf(element) > -1 ? true : false
}

/**
* Contains element, by key
* @param key
* @param element value
*/
Array.prototype.containsObjKey = function(key, element) {

    for (var i = 0; i < this.length; i++)
        if (this[i][key] === element)
            return true

    return false
}

<|endoftext|>


<commit_before>'use strict';

var Ractive = require('ractive');
require('ractive-adaptors-backbone');

var fs = require('fs');

var template = fs.readFileSync(__dirname + '/templates/index.ractive');
var editor = fs.readFileSync(__dirname + '/templates/partials/editor.ractive');
var browse = fs.readFileSync(__dirname + '/templates/partials/browse.ractive');

var _ = require('underscore');

var Home = Ractive.extend({
  el: 'body',
  template: (template.toString()),
  adapt: ['Backbone'],
  partials: {
    editor: (editor.toString()),
    browse: (browse.toString())
  },
  onrender: function(){
    this.on({
      open: this.open,
      save: this.save
    });

    this.observe('route', function(route){
      // feels a bit hackish, but beats manual setting anyday
      if(route){
        var routes = {};
        routes[route] = true;
        this.set('routes', routes);
      }
    });
  },
  save: function(event){
    event.context.documents.add(event.context.doc);
    event.context.doc.save();
  }
});

module.exports = Home;
<commit_msg>Removes reference to underscore<commit_after>'use strict';

var Ractive = require('ractive');
require('ractive-adaptors-backbone');

var fs = require('fs');

var template = fs.readFileSync(__dirname + '/templates/index.ractive');
var editor = fs.readFileSync(__dirname + '/templates/partials/editor.ractive');
var browse = fs.readFileSync(__dirname + '/templates/partials/browse.ractive');

var Home = Ractive.extend({
  el: 'body',
  template: (template.toString()),
  adapt: ['Backbone'],
  partials: {
    editor: (editor.toString()),
    browse: (browse.toString())
  },
  onrender: function(){
    this.on({
      open: this.open,
      save: this.save
    });

    this.observe('route', function(route){
      // feels a bit hackish, but beats manual setting anyday
      if(route){
        var routes = {};
        routes[route] = true;
        this.set('routes', routes);
      }
    });
  },
  save: function(event){
    event.context.documents.add(event.context.doc);
    event.context.doc.save();
  }
});

module.exports = Home;
<|endoftext|>


<commit_before>/* eslint no-param-reassign: "off" */
import Utils from './utils/utils';
import Directives from './utils/directives';
import VueRouter from './utils/vue-router';

// eslint-disable-next-line
IMPORT_COMPONENTS_BUNDLE

export default {
  install(Vue, Framework7) {
    // Event Hub
    const eventHub = new Vue();

    // Flags
    let f7Ready = false;
    let f7Instance;

    // Define protos
    Object.defineProperty(Vue.prototype, '$f7', {
      get() {
        return f7Instance;
      },
    });

    const $theme = {};
    Object.defineProperty(Vue.prototype, '$theme', {
      get() {
        return {
          ios: f7Instance ? f7Instance.theme === 'ios' : $theme.ios,
          md: f7Instance ? f7Instance.theme === 'md' : $theme.md,
        };
      },
    });
    Vue.prototype.Dom7 = Framework7.$;
    Vue.prototype.$$ = Framework7.$;
    Vue.prototype.$device = Framework7.device;

    // Init F7
    function initFramework7(rootEl, params, routes) {
      const f7Params = Utils.extend({}, (params || {}), { root: rootEl });
      if (routes && routes.length && !f7Params.routes) f7Params.routes = routes;

      f7Instance = new Framework7(f7Params);
      f7Ready = true;
      eventHub.$emit('f7Ready', f7Instance);
    }

    // Extend F7 Router
    Framework7.Router
      .use(VueRouter)
      .use({
        on: {
          routeChange(to, from, router) {
            eventHub.$emit('f7RouteChange', to, from, router);
          },
          routeChanged(to, from, router) {
            eventHub.$emit('f7RouteChanged', to, from, router);
          },
        },
      });

    // Mixin
    Vue.mixin({
      directives: Directives,
      components: {
        // eslint-disable-next-line
        REGISTER_COMPONENTS_BUNDLE
      },
      beforeCreate() {
        const self = this;
        if (self === self.$root) {
          const { theme } = (self.$options.framework7 || {});
          if (theme === 'md') $theme.md = true;
          if (theme === 'ios') $theme.ios = true;
          if (!theme || theme === 'auto') {
            $theme.ios = !!(Framework7.Device || Framework7.device).ios;
            $theme.md = !(Framework7.Device || Framework7.device).ios;
          }
        }

        let $route;
        let $router;
        let parent = self;
        while (parent && !$router && !$route) {
          if (parent.$f7route) $route = parent.$f7route;
          if (parent.$f7router) $router = parent.$f7router;
          else if (parent.f7View) {
            $router = parent.f7View.router;
          } else if (parent.$el && parent.$el.f7View) {
            $router = parent.$el.f7View.router;
          }
          parent = parent.$parent;
        }
        if ($route && $router) {
          self.$f7route = $route;
          self.$f7router = $router;
          self.$f7Route = $route;
          self.$f7Router = $router;
        }
      },
      beforeDestroy() {
        const self = this;
        if (self.$f7RouteChangeCallback) eventHub.$off('f7RouteChange', self.$f7RouteChangeCallback);
        if (self.$f7RouteChangedCallback) eventHub.$off('f7RouteChanged', self.$f7RouteChangedCallback);
      },
      created() {
        const self = this;

        const routeChangeCallback = self.onF7RouteChange || self.F7RouteChange || self.f7RouteChange || self.f7routeChange;
        const routeChangedCallback = self.onF7RouteChanged || self.F7RouteChanged || self.f7RouteChanged || self.f7routeChanged;
        if (!routeChangeCallback && !routeChangedCallback) return;

        function hasRouter(router) {
          return (self.$f7router && router === self.$f7router) ||
                 (!self.$f7router && self.$f7 && self.$f7.router);
        }

        function addRoutesCallbacks() {
          if (routeChangeCallback) {
            self.$f7RouteChangeCallback = function onRouteChange(to, from, router) {
              if (hasRouter(router)) {
                routeChangeCallback(to, from, router);
              }
            };
            eventHub.$on('f7RouteChange', self.$f7RouteChangeCallback);
          }
          if (routeChangedCallback) {
            self.$f7RouteChangedCallback = function onRouteChanged(to, from, router) {
              if (hasRouter(router)) {
                routeChangedCallback(to, from, router);
              }
            };
            eventHub.$on('f7RouteChanged', self.$f7RouteChangedCallback);
          }
        }

        if (!self.$f7) eventHub.$on('f7Ready', addRoutesCallbacks);
        else addRoutesCallbacks();
      },
      mounted() {
        const self = this;
        if (self === self.$root) {
          initFramework7(self.$root.$el, self.$options.framework7, self.$options.routes);
        }
        const callback = self.onF7Ready || self.onF7ready || self.onF7Init || self.onF7init || self.f7Ready || self.f7Init || self.f7ready || self.f7init;
        if (!callback) return;
        if (f7Ready) callback(f7Instance);
        else {
          eventHub.$on('f7Ready', (f7) => {
            callback(f7);
          });
        }
      },
    });
  },
};
<commit_msg>Check for global F7 as fallback and throw error message<commit_after>/* eslint no-param-reassign: "off" */
import Utils from './utils/utils';
import Directives from './utils/directives';
import VueRouter from './utils/vue-router';

// eslint-disable-next-line
IMPORT_COMPONENTS_BUNDLE

export default {
  install(Vue, Framework7 = window.Framework7) {
    // Check for F7
    if (typeof Framework7 === 'undefined') {
      throw new Error('Framework7 is undefined, make sure you have passed it as an argument: Vue.use(Framework7Vue, Framework7)');
    }
    // Event Hub
    const eventHub = new Vue();

    // Flags
    let f7Ready = false;
    let f7Instance;

    // Define protos
    Object.defineProperty(Vue.prototype, '$f7', {
      get() {
        return f7Instance;
      },
    });

    const $theme = {};
    Object.defineProperty(Vue.prototype, '$theme', {
      get() {
        return {
          ios: f7Instance ? f7Instance.theme === 'ios' : $theme.ios,
          md: f7Instance ? f7Instance.theme === 'md' : $theme.md,
        };
      },
    });
    Vue.prototype.Dom7 = Framework7.$;
    Vue.prototype.$$ = Framework7.$;
    Vue.prototype.$device = Framework7.device;

    // Init F7
    function initFramework7(rootEl, params, routes) {
      const f7Params = Utils.extend({}, (params || {}), { root: rootEl });
      if (routes && routes.length && !f7Params.routes) f7Params.routes = routes;

      f7Instance = new Framework7(f7Params);
      f7Ready = true;
      eventHub.$emit('f7Ready', f7Instance);
    }

    // Extend F7 Router
    Framework7.Router
      .use(VueRouter)
      .use({
        on: {
          routeChange(to, from, router) {
            eventHub.$emit('f7RouteChange', to, from, router);
          },
          routeChanged(to, from, router) {
            eventHub.$emit('f7RouteChanged', to, from, router);
          },
        },
      });

    // Mixin
    Vue.mixin({
      directives: Directives,
      components: {
        // eslint-disable-next-line
        REGISTER_COMPONENTS_BUNDLE
      },
      beforeCreate() {
        const self = this;
        if (self === self.$root) {
          const { theme } = (self.$options.framework7 || {});
          if (theme === 'md') $theme.md = true;
          if (theme === 'ios') $theme.ios = true;
          if (!theme || theme === 'auto') {
            $theme.ios = !!(Framework7.Device || Framework7.device).ios;
            $theme.md = !(Framework7.Device || Framework7.device).ios;
          }
        }

        let $route;
        let $router;
        let parent = self;
        while (parent && !$router && !$route) {
          if (parent.$f7route) $route = parent.$f7route;
          if (parent.$f7router) $router = parent.$f7router;
          else if (parent.f7View) {
            $router = parent.f7View.router;
          } else if (parent.$el && parent.$el.f7View) {
            $router = parent.$el.f7View.router;
          }
          parent = parent.$parent;
        }
        if ($route && $router) {
          self.$f7route = $route;
          self.$f7router = $router;
          self.$f7Route = $route;
          self.$f7Router = $router;
        }
      },
      beforeDestroy() {
        const self = this;
        if (self.$f7RouteChangeCallback) eventHub.$off('f7RouteChange', self.$f7RouteChangeCallback);
        if (self.$f7RouteChangedCallback) eventHub.$off('f7RouteChanged', self.$f7RouteChangedCallback);
      },
      created() {
        const self = this;

        const routeChangeCallback = self.onF7RouteChange || self.F7RouteChange || self.f7RouteChange || self.f7routeChange;
        const routeChangedCallback = self.onF7RouteChanged || self.F7RouteChanged || self.f7RouteChanged || self.f7routeChanged;
        if (!routeChangeCallback && !routeChangedCallback) return;

        function hasRouter(router) {
          return (self.$f7router && router === self.$f7router) ||
                 (!self.$f7router && self.$f7 && self.$f7.router);
        }

        function addRoutesCallbacks() {
          if (routeChangeCallback) {
            self.$f7RouteChangeCallback = function onRouteChange(to, from, router) {
              if (hasRouter(router)) {
                routeChangeCallback(to, from, router);
              }
            };
            eventHub.$on('f7RouteChange', self.$f7RouteChangeCallback);
          }
          if (routeChangedCallback) {
            self.$f7RouteChangedCallback = function onRouteChanged(to, from, router) {
              if (hasRouter(router)) {
                routeChangedCallback(to, from, router);
              }
            };
            eventHub.$on('f7RouteChanged', self.$f7RouteChangedCallback);
          }
        }

        if (!self.$f7) eventHub.$on('f7Ready', addRoutesCallbacks);
        else addRoutesCallbacks();
      },
      mounted() {
        const self = this;
        if (self === self.$root) {
          initFramework7(self.$root.$el, self.$options.framework7, self.$options.routes);
        }
        const callback = self.onF7Ready || self.onF7ready || self.onF7Init || self.onF7init || self.f7Ready || self.f7Init || self.f7ready || self.f7init;
        if (!callback) return;
        if (f7Ready) callback(f7Instance);
        else {
          eventHub.$on('f7Ready', (f7) => {
            callback(f7);
          });
        }
      },
    });
  },
};
<|endoftext|>


<commit_before>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

require(["jquery","sakai/sakai.api.core"], function($, sakai) {

    sakai_global.profile = sakai_global.profile || {};
    sakai_global.profile.main = sakai_global.profile.main || {};
    $.extend(true, sakai_global.profile.main, {
        config: sakai.config.Profile.configuration.defaultConfig,
        data: {},
        mode: {
            options: ["view", "edit"],
            value: "view"
        }
    });

    sakai_global.user = function() {

        var privdata = false;
        var pubdata = false;
        var privurl = false;
        var puburl = false;

        var contextType = false;
        var contextData = false;
        var qs = new Querystring();

        var setupProfile = function(pub) {
            var firstWidgetRef = "";
            $.each(sakai.config.Profile.configuration.defaultConfig, function(title, section) {
                var widgetID = ""+Math.ceil(Math.random() * 1000000000);
                var widgetUUID = ""+Math.ceil(Math.random() * 1000000000);
                pub.structure0.profile[title] = {
                    _ref: widgetID,
                    _order: section.order,
                    _altTitle: section.label,
                    _title: section.label
                };
                if (section.order === 0) {
                    firstWidgetRef = widgetID;
                }
                pub[widgetID] = {
                    page: "
"
                };
                pub[widgetUUID] = {
                    sectionid: title
                };
            });
            pub.structure0.profile._ref = firstWidgetRef;
        };

        var loadSpaceData = function(){
            var isMe = false;
            var userid = false;
            if (!qs.get("id") || qs.get("id") == sakai.data.me.user.userid) {
                isMe = true;
                userid = sakai.data.me.user.userid;
            } else {
                userid = qs.get("id");
            }
            privurl = "/~" + userid + "/private/privspace/";
            puburl = "/~" + userid + "/public/pubspace/";

            var publicToStore = false;
            var privateToStore = false;

            // Load public data from /~userid/private/pubspace
            sakai.api.Server.loadJSON(puburl, function(success, data){
                if (!success){
                    pubdata = $.extend(true, {}, sakai.config.defaultpubstructure);
                    publicToStore = $.extend(true, {}, sakai.config.defaultpubstructure);
                    setupProfile(pubdata);
                } else {
                    setupProfile(data);
                    pubdata = data;
                    pubdata = sakai.api.Server.cleanUpSakaiDocObject(pubdata);
                }
                if (!isMe){
                    addCounts();
                }
                if (isMe){
                    sakai.api.Server.loadJSON(privurl, function(success2, data2){
                        if (!success2){
                            privdata = $.extend(true, {}, sakai.config.defaultprivstructure);
                            privateToStore = $.extend(true, {}, sakai.config.defaultprivstructure);
                        } else {
                            privdata = data2;
                            privdata = sakai.api.Server.cleanUpSakaiDocObject(privdata);
                        }
                        generateNav();
                        if (publicToStore) {
                            sakai.api.Server.saveJSON(puburl, publicToStore);
                        }
                        if (privateToStore) {
                            sakai.api.Server.saveJSON(privurl, privateToStore);
                        }
                        addCounts();
                    });
                } else {
                    generateNav();
                }
            });
        };

        var addCounts = function(){
            addCount(pubdata, "library", contextData.counts["content"]);
            addCount(pubdata, "contacts", contextData.counts["contacts"]);
            addCount(pubdata, "memberships", contextData.counts["memberships"]);
        };

        var addCount = function(pubdata, pageid, count){
            if (pubdata.structure0) {
                for (var i in pubdata.structure0) {
                    if (i === pageid){
                        pubdata.structure0[i]._count = count;
                    }
                }
            }
        };

        var getUserPicture = function(profile, userid){
            var picture = "";
            if (profile.picture) {
                var picture_name = $.parseJSON(profile.picture).name;
                picture = "/~" + userid + "/public/profile/" + picture_name;
            }
            return picture;
        };

        var determineContext = function(){
            if (qs.get("id") && qs.get("id") !== sakai.data.me.user.userid){
                sakai.api.User.getUser(qs.get("id"), getProfileData);
            } else if (!sakai.data.me.user.anon){
                if (document.location.pathname === "/dev/user.html"){
                    document.location = "/dev/me.html";
                }
                sakai.api.Security.showPage();
                contextType = "user_me";
                // Set the profile data object
                sakai_global.profile.main.data = $.extend(true, {}, sakai.data.me.profile);
                sakai_global.profile.main.mode.value = "edit";
                contextData = {
                    "profile": sakai.data.me.profile,
                    "displayName": sakai.api.User.getDisplayName(sakai.data.me.profile),
                    "userid": sakai.data.me.user.userid,
                    "picture": getUserPicture(sakai.data.me.profile, sakai.data.me.user.userid)
                };
                determineContentContactsMemberships();
            } else {
                sakai.api.Security.sendToLogin();
            }
        };

        var getProfileData = function(exists, profile){
            if (!profile) {
                sakai.api.Security.sendToLogin();
            } else {
                sakai.api.Security.showPage();
                // Set the profile data object
                sakai_global.profile.main.data = $.extend(true, {}, profile);
                contextData = {
                    "profile": profile,
                    "displayName": sakai.api.User.getDisplayName(profile),
                    "userid": qs.get("id"),
                    "altTitle": true,
                    "picture": getUserPicture(profile, qs.get("id"))
                };
                if (sakai.data.me.user.anon) {
                    contextType = "user_anon";
                    determineContentContactsMemberships();
                } else {
                    sakai.api.User.getContacts(checkContact);
                }
            }
        };

        var checkContact = function(){
            var contacts = sakai.data.me.mycontacts;
            var isContact = false;
            var isContactInvited = false;
            var isContactPending = false;
            for (var i = 0; i < contacts.length; i++){
                if (contacts[i].profile.userid === qs.get("id")){
                    if (contacts[i].details["sakai:state"] === "ACCEPTED") {
                        isContact = true;
                    } else if (contacts[i].details["sakai:state"] === "INVITED"){
                        isContactInvited = true;
                    } else if (contacts[i].details["sakai:state"] === "PENDING"){
                        isContactPending = true;
                    }
                }
            }
            if (isContact){
                contextType = "contact";
            } else if (isContactInvited){
                contextType = "contact_invited";
            } else if (isContactPending){
                contextType = "contact_pending";
            } else {
                contextType = "user_other";
            }
            determineContentContactsMemberships();
        };

        var determineContentContactsMemberships = function(){
            contextData.counts = {};
            var contentURL = "/var/search/pool/manager-viewer.json?userid=" + contextData.userid + "&page=0&items=1";
            var contactsURL = "/var/contacts/findbyuser.json?userid=" + contextData.userid + "&page=0&items=1";
            var membershipsURL = "/system/me.infinity.json?uid=" + contextData.userid;

            $.ajax({
                url: contentURL,
                type: "GET",
                cache: false,
                success: function(data){
                    contextData.counts["content"] = data.total;
                    $.ajax({
                        url: contactsURL,
                        type: "GET",
                        cache: false,
                        success: function(data){
                            contextData.counts["contacts"] = data.total;
                            $.ajax({
                                url: membershipsURL,
                                type: "GET",
                                cache: false,
                                success: function(data){
                                    contextData.counts["memberships"] = sakai.api.Groups.getMemberships(data.groups).entry.length;
                                    renderEntity();
                                    loadSpaceData();
                                }
                            });
                        }
                    });

                }
            });
        };

        var generateNav = function(){
            if (contextType && contextType === "user_me" && contextData && pubdata && privdata) {
                $(window).trigger("lhnav.init", [pubdata, privdata, contextData, puburl, privurl]);
            } else if (contextType && contextType !== "user_me" && contextData && pubdata) {
                $(window).trigger("lhnav.init", [pubdata, false, contextData, puburl, privurl]);
            }
        };

        var renderEntity = function(){
            if (contextType && contextData) {
                $(window).trigger("sakai.entity.init", ["user", contextType, contextData]);
            }
        };

        $(window).bind("sakai.addToContacts.requested", function(ev, userToAdd){
            $('.sakai_addtocontacts_overlay').each(function(index) {
                contextType = "contact_pending";
                renderEntity();
            });
        });

        $("#entity_user_accept_invitation").live("click", function(){
            sakai.api.User.acceptContactInvite(contextData.userid);
            contextType = "contact";
            renderEntity();
        });

        $(window).bind("sakai.entity.ready", function(){
            renderEntity();
        });

        $(window).bind("lhnav.ready", function(){
            generateNav();
        });

        $(window).bind("complete.fileupload.sakai", determineContext);

        determineContext();
        renderEntity();
        generateNav();

    };

    sakai.api.Widgets.Container.registerForLoad("user");
});
<commit_msg>SAKIII-2897 - Make profile sections in personal space obey the configured profile<commit_after>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

require(["jquery","sakai/sakai.api.core"], function($, sakai) {

    sakai_global.profile = sakai_global.profile || {};
    sakai_global.profile.main = sakai_global.profile.main || {};
    $.extend(true, sakai_global.profile.main, {
        config: sakai.config.Profile.configuration.defaultConfig,
        data: {},
        mode: {
            options: ["view", "edit"],
            value: "view"
        }
    });

    sakai_global.user = function() {

        var privdata = false;
        var pubdata = false;
        var privurl = false;
        var puburl = false;

        var contextType = false;
        var contextData = false;
        var qs = new Querystring();

        var setupProfile = function(pub) {
            var firstWidgetRef = "";
            var profilestructure = {};
            profilestructure._title = pub.structure0.profile._title;
            profilestructure._altTitle = pub.structure0.profile._altTitle;
            profilestructure._order = pub.structure0.profile._order;
            pub.structure0.profile = {};
            $.each(sakai.config.Profile.configuration.defaultConfig, function(title, section) {
                var widgetID = ""+Math.ceil(Math.random() * 1000000000);
                var widgetUUID = ""+Math.ceil(Math.random() * 1000000000);
                profilestructure[title] = {
                    _ref: widgetID,
                    _order: section.order,
                    _altTitle: section.label,
                    _title: section.label
                };
                if (section.order === 0) {
                    firstWidgetRef = widgetID;
                }
                pub[widgetID] = {
                    page: "
"
                };
                pub[widgetUUID] = {
                    sectionid: title
                };
            });
            pub.structure0.profile = profilestructure;
            pub.structure0.profile._ref = firstWidgetRef;
        };

        var loadSpaceData = function(){
            var isMe = false;
            var userid = false;
            if (!qs.get("id") || qs.get("id") == sakai.data.me.user.userid) {
                isMe = true;
                userid = sakai.data.me.user.userid;
            } else {
                userid = qs.get("id");
            }
            privurl = "/~" + userid + "/private/privspace/";
            puburl = "/~" + userid + "/public/pubspace/";

            var publicToStore = false;
            var privateToStore = false;

            // Load public data from /~userid/private/pubspace
            sakai.api.Server.loadJSON(puburl, function(success, data){
                if (!success){
                    pubdata = $.extend(true, {}, sakai.config.defaultpubstructure);
                    publicToStore = $.extend(true, {}, sakai.config.defaultpubstructure);
                } else {
                    pubdata = data;
                    pubdata = sakai.api.Server.cleanUpSakaiDocObject(pubdata);
                }
                setupProfile(pubdata);
                if (!isMe){
                    addCounts();
                }
                if (isMe){
                    sakai.api.Server.loadJSON(privurl, function(success2, data2){
                        if (!success2){
                            privdata = $.extend(true, {}, sakai.config.defaultprivstructure);
                            privateToStore = $.extend(true, {}, sakai.config.defaultprivstructure);
                        } else {
                            privdata = data2;
                            privdata = sakai.api.Server.cleanUpSakaiDocObject(privdata);
                        }
                        generateNav();
                        if (publicToStore) {
                            sakai.api.Server.saveJSON(puburl, publicToStore);
                        }
                        if (privateToStore) {
                            sakai.api.Server.saveJSON(privurl, privateToStore);
                        }
                        addCounts();
                    });
                } else {
                    generateNav();
                }
            });
        };

        var addCounts = function(){
            addCount(pubdata, "library", contextData.counts["content"]);
            addCount(pubdata, "contacts", contextData.counts["contacts"]);
            addCount(pubdata, "memberships", contextData.counts["memberships"]);
        };

        var addCount = function(pubdata, pageid, count){
            if (pubdata.structure0) {
                for (var i in pubdata.structure0) {
                    if (i === pageid){
                        pubdata.structure0[i]._count = count;
                    }
                }
            }
        };

        var getUserPicture = function(profile, userid){
            var picture = "";
            if (profile.picture) {
                var picture_name = $.parseJSON(profile.picture).name;
                picture = "/~" + userid + "/public/profile/" + picture_name;
            }
            return picture;
        };

        var determineContext = function(){
            if (qs.get("id") && qs.get("id") !== sakai.data.me.user.userid){
                sakai.api.User.getUser(qs.get("id"), getProfileData);
            } else if (!sakai.data.me.user.anon){
                if (document.location.pathname === "/dev/user.html"){
                    document.location = "/dev/me.html";
                }
                sakai.api.Security.showPage();
                contextType = "user_me";
                // Set the profile data object
                sakai_global.profile.main.data = $.extend(true, {}, sakai.data.me.profile);
                sakai_global.profile.main.mode.value = "edit";
                contextData = {
                    "profile": sakai.data.me.profile,
                    "displayName": sakai.api.User.getDisplayName(sakai.data.me.profile),
                    "userid": sakai.data.me.user.userid,
                    "picture": getUserPicture(sakai.data.me.profile, sakai.data.me.user.userid)
                };
                determineContentContactsMemberships();
            } else {
                sakai.api.Security.sendToLogin();
            }
        };

        var getProfileData = function(exists, profile){
            if (!profile) {
                sakai.api.Security.sendToLogin();
            } else {
                sakai.api.Security.showPage();
                // Set the profile data object
                sakai_global.profile.main.data = $.extend(true, {}, profile);
                contextData = {
                    "profile": profile,
                    "displayName": sakai.api.User.getDisplayName(profile),
                    "userid": qs.get("id"),
                    "altTitle": true,
                    "picture": getUserPicture(profile, qs.get("id"))
                };
                if (sakai.data.me.user.anon) {
                    contextType = "user_anon";
                    determineContentContactsMemberships();
                } else {
                    sakai.api.User.getContacts(checkContact);
                }
            }
        };

        var checkContact = function(){
            var contacts = sakai.data.me.mycontacts;
            var isContact = false;
            var isContactInvited = false;
            var isContactPending = false;
            for (var i = 0; i < contacts.length; i++){
                if (contacts[i].profile.userid === qs.get("id")){
                    if (contacts[i].details["sakai:state"] === "ACCEPTED") {
                        isContact = true;
                    } else if (contacts[i].details["sakai:state"] === "INVITED"){
                        isContactInvited = true;
                    } else if (contacts[i].details["sakai:state"] === "PENDING"){
                        isContactPending = true;
                    }
                }
            }
            if (isContact){
                contextType = "contact";
            } else if (isContactInvited){
                contextType = "contact_invited";
            } else if (isContactPending){
                contextType = "contact_pending";
            } else {
                contextType = "user_other";
            }
            determineContentContactsMemberships();
        };

        var determineContentContactsMemberships = function(){
            contextData.counts = {};
            var contentURL = "/var/search/pool/manager-viewer.json?userid=" + contextData.userid + "&page=0&items=1";
            var contactsURL = "/var/contacts/findbyuser.json?userid=" + contextData.userid + "&page=0&items=1";
            var membershipsURL = "/system/me.infinity.json?uid=" + contextData.userid;

            $.ajax({
                url: contentURL,
                type: "GET",
                cache: false,
                success: function(data){
                    contextData.counts["content"] = data.total;
                    $.ajax({
                        url: contactsURL,
                        type: "GET",
                        cache: false,
                        success: function(data){
                            contextData.counts["contacts"] = data.total;
                            $.ajax({
                                url: membershipsURL,
                                type: "GET",
                                cache: false,
                                success: function(data){
                                    contextData.counts["memberships"] = sakai.api.Groups.getMemberships(data.groups).entry.length;
                                    renderEntity();
                                    loadSpaceData();
                                }
                            });
                        }
                    });

                }
            });
        };

        var generateNav = function(){
            if (contextType && contextType === "user_me" && contextData && pubdata && privdata) {
                $(window).trigger("lhnav.init", [pubdata, privdata, contextData, puburl, privurl]);
            } else if (contextType && contextType !== "user_me" && contextData && pubdata) {
                $(window).trigger("lhnav.init", [pubdata, false, contextData, puburl, privurl]);
            }
        };

        var renderEntity = function(){
            if (contextType && contextData) {
                $(window).trigger("sakai.entity.init", ["user", contextType, contextData]);
            }
        };

        $(window).bind("sakai.addToContacts.requested", function(ev, userToAdd){
            $('.sakai_addtocontacts_overlay').each(function(index) {
                contextType = "contact_pending";
                renderEntity();
            });
        });

        $("#entity_user_accept_invitation").live("click", function(){
            sakai.api.User.acceptContactInvite(contextData.userid);
            contextType = "contact";
            renderEntity();
        });

        $(window).bind("sakai.entity.ready", function(){
            renderEntity();
        });

        $(window).bind("lhnav.ready", function(){
            generateNav();
        });

        $(window).bind("complete.fileupload.sakai", determineContext);

        determineContext();
        renderEntity();
        generateNav();

    };

    sakai.api.Widgets.Container.registerForLoad("user");
});
<|endoftext|>


<commit_before>'use strict';

const uuid = require('uuid');
const baseX = require('base-x');
const base62 = baseX('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')

// expose node-uuid and baseX for convenience
module.exports.uuid = uuid;
module.exports.baseX = baseX;
module.exports.customBase = base62;
module.exports.length = 22;
module.exports.uuidLength = 32;
exports.v4 = v4;
exports.v1 = v1;
exports.encode = encode;
exports.decode = decode;

function v4() {
	const args = Array.prototype.slice.call(arguments);

	if (!args[1]) {
		// make sure we use a buffer to avoid getting an uuid with dashes
		args[1] = new Buffer(16);
	}

	const id = uuid.v4.apply(this, args);
	return encode(id);
};

function v1() {
	const args = Array.prototype.slice.call(arguments);

	if (!args[1]) {
		// make sure we use a buffer to avoid getting an uuid with dashes
		args[1] = new Buffer(16);
	}

	const id = uuid.v1.apply(this, args);
	return encode(id);
};

function encode(input, encoding) {
	encoding = encoding || 'hex';

	if (typeof input === 'string') {
		// remove the dashes to save some space
		input = new Buffer(input.replace(/-/g, ''), encoding);
	}
	return ensureLength(base62.encode(input), module.exports.length);
};

function decode(b62Str, encoding) {
	encoding = encoding || 'hex';
	const res = ensureLength(new Buffer(base62.decode(b62Str)).toString(encoding), module.exports.uuidLength);

	// re-add the dashes so the result looks like an uuid
	const resArray = res.split('');
	[8, 13, 18, 23].forEach((idx) => {
		resArray.splice(idx, 0, '-');
	});
	return resArray.join('');
};

function ensureLength(str, maxLen) {
	str = str + '';
	if (str.length < maxLen) {
		return padLeft(str, maxLen);
	}
	else if (str.length > maxLen) {
		return trimLeft(str, maxLen);
	}
	return str;
};

function padLeft(str, padding) {
	str = str + '';
	let pad = '';
	for (let i = str.length; i < padding; ++i) {
		pad += '0';
	}
	return pad + str;
};

function trimLeft(str, maxLen) {
	str = str + '';
	let trim = 0;
	while (str[trim] === '0' && (str.length - trim) > maxLen) {
		++trim;
	}
	return str.slice(trim);
};
<commit_msg>refactored<commit_after>'use strict';

const uuid = require('uuid');
const baseX = require('base-x');
const base62 = baseX('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
const OUTPUT_LENGTH = 22;
const UUID_LENGTH = 32;

// expose node-uuid and baseX for convenience
// exports.uuid = uuid;
// exports.baseX = baseX;
// exports.customBase = base62;
// exports.length = OUTPUT_LENGTH;
// exports.uuidLength = UUID_LENGTH;
// exports.v4 = v4;
// exports.v1 = v1;
// exports.encode = encode;
// exports.decode = decode;

class UUID62 {
	constructor() {
		this.base = base62;
	}

	get uuid() {
		return uuid;
	}

	get baseX() {
		return baseX;
	}

	get customBase() {
		return this.base;
	}

	set customBase(base) {
		this.base = base;
	}

	get length() {
		return OUTPUT_LENGTH;
	}

	get uuidLength() {
		return UUID_LENGTH;
	}

	v4() {
		const args = Array.prototype.slice.call(arguments);

		if (!args[1]) {
			// make sure we use a buffer to avoid getting an uuid with dashes
			args[1] = new Buffer(16);
		}

		const id = uuid.v4.apply(this, args);
		return this.encode(id);
	}

	v1() {
		const args = Array.prototype.slice.call(arguments);

		if (!args[1]) {
			// make sure we use a buffer to avoid getting an uuid with dashes
			args[1] = new Buffer(16);
		}

		const id = uuid.v1.apply(this, args);
		return this.encode(id);
	}

	encode(input, encoding) {
		encoding = encoding || 'hex';
		// console.log(input);

		if (typeof input === 'string') {
			// remove the dashes to save some space
			input = new Buffer(input.replace(/-/g, ''), encoding);
		}
		// console.log(input);
		return ensureLength(this.base.encode(input), OUTPUT_LENGTH);
	}

	decode(b62Str, encoding) {
		encoding = encoding || 'hex';
		const res = ensureLength(new Buffer(this.base.decode(b62Str)).toString(encoding), UUID_LENGTH);

		// re-add the dashes so the result looks like an uuid
		const resArray = res.split('');
		[8, 13, 18, 23].forEach((idx) => {
			resArray.splice(idx, 0, '-');
		});
		return resArray.join('');
	}
}

function ensureLength(str, maxLen) {
	str = str + '';
	if (str.length < maxLen) {
		return padLeft(str, maxLen);
	}
	else if (str.length > maxLen) {
		return trimLeft(str, maxLen);
	}
	return str;
}

function padLeft(str, padding) {
	str = str + '';
	let pad = '';
	for (let i = str.length; i < padding; ++i) {
		pad += '0';
	}
	return pad + str;
}

function trimLeft(str, maxLen) {
	str = str + '';
	let trim = 0;
	while (str[trim] === '0' && (str.length - trim) > maxLen) {
		++trim;
	}
	return str.slice(trim);
}

module.exports = new UUID62();
<|endoftext|>


<commit_before>var _ = require('lodash');
var combinations = require('./combination.js');
var ranks = {
    'J': 11,
    'Q': 12,
    'K': 13,
    'A': 14
};

var vanya = function(cards) {
    var hand_categories = {
        "straight_flush": false,
        "four": combinations.checkFour(cards),
        "full_house": combinations.checkFullHouse(cards),
        "flush": combinations.checkFlash(cards),
        "straight": false,
        "three": combinations.checkTrio(cards),
        "two": combinations.checkPair(cards)
    };

    return hand_categories;
};

module.exports = vanya;
<commit_msg>Improve v<commit_after>var _ = require('lodash');
var combinations = require('./combination.js');
var ranks = {
    'J': 11,
    'Q': 12,
    'K': 13,
    'A': 14
};

var vanya = function(cards) {

    function good(cards_) {
        var yeap = false;
        cards_.forEach(function(card) {
            if (ranks[card.rank]) {
                yeap = true;
            }
        })

        return yeap;
    }

    var hand_categories = {
        "straight_flush": false,
        "four": combinations.checkFour(cards),
        "full_house": combinations.checkFullHouse(cards),
        "flush": combinations.checkFlash(cards),
        "straight": false,
        "three": combinations.checkTrio(cards),
        "two": combinations.checkPair(cards),
        "good_kicker": good(cards)
    };

    return hand_categories;
};

module.exports = vanya;
<|endoftext|>


<commit_before>(function (window) {
  "use strict";

  var self;

  function ImageViewer(canvasId, imageUrl){
    self = this;

    // canvas
    this.canvas = document.getElementById(canvasId);
    this.context = this.canvas.getContext("2d");

    // image scale
    this.scale = 1;

    // canvas coordinates of image
    this.cx = 0;
    this.cy = 0;
    this.cwidth = 0;
    this.cheight = 0;

    // viewed part of the image
    this.sx = 0;
    this.sy = 0;
    this.swidth = 0;
    this.sheight = 0;

    // image
    this.image = new Image();
    this.image.addEventListener('load', this._onImageLoad, false);
    this.image.src = imageUrl;
  }

  ImageViewer.prototype._onImageLoad = function(){
    if(((self.canvas.height / self.image.height) * self.image.width) <= self.canvas.width){
      self.scale = self.canvas.height / self.image.height;
    } else {
      self.scale = self.canvas.width / self.image.width;
    }
    self.cx = (self.canvas.width - self.image.width * self.scale) / 2;
    self.cy = (self.canvas.height - self.image.height * self.scale) / 2;
    self.cwidth = self.image.width * self.scale;
    self.cheight = self.image.height * self.scale;
    self.swidth = self.image.width;
    self.sheight = self.image.height;

    self._render();
  };

  ImageViewer.prototype._render = function(){
    // draw image
    this.context.drawImage(
      this.image,
      this.sx, this.sy, this.swidth, this.sheight, // part of image
      this.cx, this.cy, this.cwidth, this.cheight  // position and size within canvas
    );
  };

  window.ImageViewer = ImageViewer;
}(window));
<commit_msg>added render loop, zooming<commit_after>(function (window) {
  "use strict";

  var self;

  function ImageViewer(canvasId, imageUrl){
    self = this;

    // canvas
    this.canvas = document.getElementById(canvasId);
    this.context = this.canvas.getContext("2d");

    // image scale
    this.scale = 1;
    this.scale_old = null;

    // image center
    this.center = {
      x: 0,
      y: 0
    }
    this.center_old = null;

    // image
    this.image = new Image();
    this.image.addEventListener('load', this._onImageLoad, false);
    this.image.src = imageUrl;
    this.image_old = null;

    // render loop
    this.FPS = 100/30;
    this.tickInterval = null;

    this.InputHandler = new InputHandler(this.canvas, this);
  }

  ImageViewer.prototype._onImageLoad = function(){
    // set scale to use as much space inside the canvas as possible
    if(((self.canvas.height / self.image.height) * self.image.width) <= self.canvas.width){
      self.scale = self.canvas.height / self.image.height;
    } else {
      self.scale = self.canvas.width / self.image.width;
    }

    // center at image center
    self.center.x = self.image.width / 2;
    self.center.y = self.image.height / 2;

    // start render loop
    self.tickInterval = setInterval(function(){self._render()}, self.FPS);
  };

  ImageViewer.prototype._isDirty = function(newScale){
    return !((this.image === this.image_old)
        && (this.center === this.center_old)
        && (this.scale === this.scale_old));
  };

  ImageViewer.prototype._render = function(){
    // check if dirty
    if(!this._isDirty()) return;

    // reset flags
    this.image_old = this.image;
    this.center_old = this.center;
    this.scale_old = this.scale;

    // clear canvas
    this.context.clearRect ( 0 , 0 , this.canvas.width, this.canvas.height );

    // calculate image properties
    var widthToRight = this.image.width - this.center.x
      , widthToLeft = this.center.x
      , heightToTop = this.center.y
      , heightToBottom = this.image.height - this.center.y
      , maxPartWidth = this.canvas.width / this.scale
      , maxPartHeight = this.canvas.height / this.scale
      , actualPartWidthRight = widthToRight >= (maxPartWidth / 2) ? maxPartWidth / 2 : widthToRight
      , actualPartWidthLeft = widthToLeft >= (maxPartWidth / 2) ? maxPartWidth / 2 : widthToLeft
      , actualPartWidth = actualPartWidthRight + actualPartWidthLeft
      , actualPartHeightTop = heightToTop >= (maxPartHeight / 2) ? maxPartHeight / 2 : heightToTop
      , actualPartHeightBottom = heightToBottom >= (maxPartHeight / 2) ? maxPartHeight / 2 : heightToBottom
      , actualPartHeight = actualPartHeightTop + actualPartHeightBottom
      , partX = this.center.x - actualPartWidthLeft
      , partY = this.center.y - actualPartHeightTop
      , canvasX = ((maxPartWidth / 2) - actualPartWidthLeft) * this.scale
      , canvasY = ((maxPartHeight / 2) - actualPartHeightTop) * this.scale
      , canvasWidth = actualPartWidth * this.scale
      , canvasHeight = actualPartHeight * this.scale;

    // draw image
    this.context.drawImage(
      this.image,
      partX, partY, actualPartWidth, actualPartHeight, // part of image
      canvasX, canvasY, canvasWidth, canvasHeight  // position and size within canvas
    );
  };

  function InputHandler(canvas, imageViewer) {
    this.canvas = canvas;
    this.imageViewer = imageViewer;

    this.canvas.addEventListener('DOMMouseScroll', this._onMouseWheel);
    this.canvas.addEventListener('mousewheel', this._onMouseWheel);
  };

  InputHandler.prototype._onMouseWheel = function(evt){
    if (!evt) evt = event;
    var zoomFactor = (evt.detail<0 || evt.wheelDelta>0)
                    ? 0.9 // up -> smaller
                    : 1.1; // down -> larger
    self.scale = self.scale * zoomFactor;
  };

  window.ImageViewer = ImageViewer;
}(window));
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var cheerio = require('cheerio');
var nopt = require('nopt');
var EOL = require('os').EOL;
var IMPORTS = 'link[rel="import"][href]';
var ELEMENTS = 'polymer-element';
var URL_ATTR = ['href', 'src', 'action', 'style'];
var URL_ATTR_SEL = '[' + URL_ATTR.join('],[') + ']';
var ABS_URL = /(^data:)|(^http[s]?:)|(^\/)/;
var URL = /url\([^)]*\)/g;
var URL_TEMPLATE = '{{.*}}';
var POLYMER = 'script[src $= "polymer.js"], script[src $= "polymer.min.js"]';

var import_buffer = [];
var imports_before_polymer = [];
var read = {};

var options = nopt(
  {
    'output': path,
    'input': path,
    'verbose': Boolean,
    'csp': Boolean,
    'inline': Boolean
  },
  {
    'o': ['--output'],
    'i': ['--input'],
    'v': ['--verbose']
  }
);

if (!options.input) {
  console.error('No input file given!');
  process.exit(1);
}

var DEFAULT_OUTPUT = 'vulcanized.html';
if (!options.output) {
  console.warn('Default output to vulcanized.html' + (options.csp ? ' and vulcanized.js' : '') + ' in the input directory.');
  options.output = path.resolve(path.dirname(options.input), DEFAULT_OUTPUT);
}

var outputDir = path.dirname(options.output);

function resolvePaths($, input, output) {
  var assetPath = path.relative(output, input);
  assetPath = assetPath.split(path.sep).join('/') + '/';
  // resolve attributes
  $(URL_ATTR_SEL).each(function() {
    URL_ATTR.forEach(function(a) {
      var val = this.attr(a);
      if (val) {
        if (val.search(URL_TEMPLATE) < 0) {
          if (a === 'style') {
            this.attr(a, rewriteURL(input, output, val));
          } else {
            this.attr(a, rewriteRelPath(input, output, val));
          }
        }
      }
    }, this);
  });
  // resolve style elements
  $('style').each(function() {
    var val = this.html();
    this.html(rewriteURL(input, output, val));
  });
  $(ELEMENTS).each(function() {
    this.attr('assetpath', assetPath);
  });
}

function rewriteRelPath(inputPath, outputPath, rel) {
  if (ABS_URL.test(rel)) {
    return rel;
  }
  var abs = path.resolve(inputPath, rel);
  var relPath = path.relative(outputPath, abs);
  return relPath.split(path.sep).join('/');
}

function rewriteURL(inputPath, outputPath, cssText) {
  return cssText.replace(URL, function(match) {
    var path = match.replace(/["']/g, "").slice(4, -1);
    path = rewriteRelPath(inputPath, outputPath, path);
    return 'url(' + path + ')';
  });
}

function readDocument(docname) {
  if (options.verbose) {
    console.log('Reading:', docname);
  }
  var content = fs.readFileSync(docname, 'utf8');
  return cheerio.load(content);
}

// inline relative linked stylesheets into <style> tags
function inlineSheets($, dir) {
  $('link[rel="stylesheet"]').each(function() {
    var href = this.attr('href');
    if (href && !ABS_URL.test(href)) {
      var filepath = path.resolve(dir, href);
      // fix up paths in the stylesheet to be relative to this import
      var content = rewriteURL(path.dirname(filepath), dir, fs.readFileSync(filepath, 'utf8'));
      var styleDoc = cheerio.load('<style>' + content + '</style>');
      var polymerScope = this.attr('polymer-scope');
      if (polymerScope) {
        styleDoc('style').attr('polymer-scope', polymerScope);
      }
      this.replaceWith(styleDoc.html());
    }
  });
}

function concat(filename) {
  if (!read[filename]) {
    read[filename] = true;
    var $ = readDocument(filename);
    var dir = path.dirname(filename);
    processImports($, dir);
    inlineSheets($, dir);
    resolvePaths($, dir, outputDir);
    import_buffer.push($.html());
  } else {
    if (options.verbose) {
      console.log('Dependency deduplicated');
    }
  }
}

function processImports($, prefix) {
  $(IMPORTS).each(function() {
    var href = this.attr('href');
    if (!ABS_URL.test(href)) {
      concat(path.resolve(prefix, href));
    } else {
      imports_before_polymer.push(this.html());
    }
  }).remove();
}

function findScriptLocation($) {
  var pos = $(POLYMER).last().parent();
  if (!pos.length) {
    pos = $('body');
  }
  if (!pos.length) {
    pos = $.root();
  }
  return pos;
}

function insertImport($, storedPosition, importText) {
  var pos = storedPosition;
  var operation = 'before';
  if (!pos.length) {
    // before polymer script in <head>
    pos = $('head ' + POLYMER).last();
  }
  if (!pos.length) {
    // at the bottom of head
    pos = $('head').last();
    operation = 'append';
  }
  if (!pos.length) {
    // at the bottom of <html>
    pos = $.root();
    operation = 'append';
  }

  pos[operation](importText);
}

function insertInlinedImports($, storedPosition, importText) {
  var pos = storedPosition;
  var operation = 'before';
  if (!pos.length) {
    pos = $('body').last();
    operation = 'prepend';
  }
  if (!pos.length) {
    pos = $.root();
  }
  pos[operation](importText);
}

function inlineScripts($) {
  $('script[src]').each(function() {
    var src = this.attr('src');
    if (!ABS_URL.test(src)) {
      this.removeAttr('src');
      this.html(fs.readFileSync(src, 'utf8'));
    }
  });
}

function handleMainDocument() {
  var $ = readDocument(options.input);
  var dir = path.dirname(options.input);
  // find the position of the last import's nextSibling
  var import_pos = $(IMPORTS).last().next();
  processImports($, dir);
  var output = import_buffer.join(EOL);

  // strip scripts into a separate file
  if (options.csp) {
    if (options.verbose) {
      console.log('Separating scripts into separate file');
    }
    var scripts = [];
    var scripts_after_polymer = [];
    var tempoutput = cheerio.load(output);

    tempoutput('script').each(function() {
      var src = this.attr('src');
      if (src) {
        // external script
        if (!ABS_URL.test(src)) {
          scripts.push(fs.readFileSync(src, 'utf8'));
        } else {
          // put an absolute path script after polymer.js in main document
          scripts_after_polymer.push(this.html());
        }
      } else {
        // inline script
        scripts.push(this.text());
      }
    }).remove();
    output = tempoutput.html();
    // join scripts with ';' to prevent breakages due to EOF semicolon insertion
    var script_name = path.basename(options.output, '.html') + '.js';
    fs.writeFileSync(script_name, scripts.join(';' + EOL), 'utf8');
    scripts_after_polymer.push('<script src="' + script_name + '"></script>');
    findScriptLocation($).append(EOL + scripts_after_polymer.join(EOL) + EOL);
  }

  insertImport($, import_pos, imports_before_polymer.join(EOL) + EOL);
  insertInlinedImports($, import_pos, output);
  if (!options.csp && options.inline) {
    inlineScripts($);
  }
  fs.writeFileSync(options.output, $.html(), 'utf8');
}

handleMainDocument();
<commit_msg>inlineScripts now uses html text and regex, not cheerio api<commit_after>var fs = require('fs');
var path = require('path');
var cheerio = require('cheerio');
var nopt = require('nopt');
var EOL = require('os').EOL;
var IMPORTS = 'link[rel="import"][href]';
var ELEMENTS = 'polymer-element';
var URL_ATTR = ['href', 'src', 'action', 'style'];
var URL_ATTR_SEL = '[' + URL_ATTR.join('],[') + ']';
var ABS_URL = /(^data:)|(^http[s]?:)|(^\/)/;
var URL = /url\([^)]*\)/g;
var URL_TEMPLATE = '{{.*}}';
var POLYMER = 'script[src $= "polymer.js"], script[src $= "polymer.min.js"]';

var import_buffer = [];
var imports_before_polymer = [];
var read = {};

var options = nopt(
  {
    'output': path,
    'input': path,
    'verbose': Boolean,
    'csp': Boolean,
    'inline': Boolean
  },
  {
    'o': ['--output'],
    'i': ['--input'],
    'v': ['--verbose']
  }
);

if (!options.input) {
  console.error('No input file given!');
  process.exit(1);
}

var DEFAULT_OUTPUT = 'vulcanized.html';
if (!options.output) {
  console.warn('Default output to vulcanized.html' + (options.csp ? ' and vulcanized.js' : '') + ' in the input directory.');
  options.output = path.resolve(path.dirname(options.input), DEFAULT_OUTPUT);
}

var outputDir = path.dirname(options.output);

function resolvePaths($, input, output) {
  var assetPath = path.relative(output, input);
  assetPath = assetPath.split(path.sep).join('/') + '/';
  // resolve attributes
  $(URL_ATTR_SEL).each(function() {
    URL_ATTR.forEach(function(a) {
      var val = this.attr(a);
      if (val) {
        if (val.search(URL_TEMPLATE) < 0) {
          if (a === 'style') {
            this.attr(a, rewriteURL(input, output, val));
          } else {
            this.attr(a, rewriteRelPath(input, output, val));
          }
        }
      }
    }, this);
  });
  // resolve style elements
  $('style').each(function() {
    var val = this.html();
    this.html(rewriteURL(input, output, val));
  });
  $(ELEMENTS).each(function() {
    this.attr('assetpath', assetPath);
  });
}

function rewriteRelPath(inputPath, outputPath, rel) {
  if (ABS_URL.test(rel)) {
    return rel;
  }
  var abs = path.resolve(inputPath, rel);
  var relPath = path.relative(outputPath, abs);
  return relPath.split(path.sep).join('/');
}

function rewriteURL(inputPath, outputPath, cssText) {
  return cssText.replace(URL, function(match) {
    var path = match.replace(/["']/g, "").slice(4, -1);
    path = rewriteRelPath(inputPath, outputPath, path);
    return 'url(' + path + ')';
  });
}

function readDocument(docname) {
  if (options.verbose) {
    console.log('Reading:', docname);
  }
  var content = fs.readFileSync(docname, 'utf8');
  return cheerio.load(content);
}

// inline relative linked stylesheets into <style> tags
function inlineSheets($, dir) {
  $('link[rel="stylesheet"]').each(function() {
    var href = this.attr('href');
    if (href && !ABS_URL.test(href)) {
      var filepath = path.resolve(dir, href);
      // fix up paths in the stylesheet to be relative to this import
      var content = rewriteURL(path.dirname(filepath), dir, fs.readFileSync(filepath, 'utf8'));
      var styleDoc = cheerio.load('<style>' + content + '</style>');
      var polymerScope = this.attr('polymer-scope');
      if (polymerScope) {
        styleDoc('style').attr('polymer-scope', polymerScope);
      }
      this.replaceWith(styleDoc.html());
    }
  });
}

function concat(filename) {
  if (!read[filename]) {
    read[filename] = true;
    var $ = readDocument(filename);
    var dir = path.dirname(filename);
    processImports($, dir);
    inlineSheets($, dir);
    resolvePaths($, dir, outputDir);
    import_buffer.push($.html());
  } else {
    if (options.verbose) {
      console.log('Dependency deduplicated');
    }
  }
}

function processImports($, prefix) {
  $(IMPORTS).each(function() {
    var href = this.attr('href');
    if (!ABS_URL.test(href)) {
      concat(path.resolve(prefix, href));
    } else {
      imports_before_polymer.push(this.html());
    }
  }).remove();
}

function findScriptLocation($) {
  var pos = $(POLYMER).last().parent();
  if (!pos.length) {
    pos = $('body');
  }
  if (!pos.length) {
    pos = $.root();
  }
  return pos;
}

function insertImport($, storedPosition, importText) {
  var pos = storedPosition;
  var operation = 'before';
  if (!pos.length) {
    // before polymer script in <head>
    pos = $('head ' + POLYMER).last();
  }
  if (!pos.length) {
    // at the bottom of head
    pos = $('head').last();
    operation = 'append';
  }
  if (!pos.length) {
    // at the bottom of <html>
    pos = $.root();
    operation = 'append';
  }

  pos[operation](importText);
}

function insertInlinedImports($, storedPosition, importText) {
  var pos = storedPosition;
  var operation = 'before';
  if (!pos.length) {
    pos = $('body').last();
    operation = 'prepend';
  }
  if (!pos.length) {
    pos = $.root();
  }
  pos[operation](importText);
}

function inlineScripts(htmlstring) {
  return htmlstring.replace(SCRIPT_SRC, function(match, src) {
    var out = match;
    if (!ABS_URL.test(src)) {
      out = '<script>' + fs.readFileSync(src, 'utf8') + '</script>';
    }
    return out;
  });
}

function handleMainDocument() {
  var $ = readDocument(options.input);
  var dir = path.dirname(options.input);
  // find the position of the last import's nextSibling
  var import_pos = $(IMPORTS).last().next();
  processImports($, dir);
  var output = import_buffer.join(EOL);

  // strip scripts into a separate file
  if (options.csp) {
    if (options.verbose) {
      console.log('Separating scripts into separate file');
    }
    var scripts = [];
    var scripts_after_polymer = [];
    var tempoutput = cheerio.load(output);

    tempoutput('script').each(function() {
      var src = this.attr('src');
      if (src) {
        // external script
        if (!ABS_URL.test(src)) {
          scripts.push(fs.readFileSync(src, 'utf8'));
        } else {
          // put an absolute path script after polymer.js in main document
          scripts_after_polymer.push(this.html());
        }
      } else {
        // inline script
        scripts.push(this.text());
      }
    }).remove();
    output = tempoutput.html();
    // join scripts with ';' to prevent breakages due to EOF semicolon insertion
    var script_name = path.basename(options.output, '.html') + '.js';
    fs.writeFileSync(script_name, scripts.join(';' + EOL), 'utf8');
    scripts_after_polymer.push('<script src="' + script_name + '"></script>');
    findScriptLocation($).append(EOL + scripts_after_polymer.join(EOL) + EOL);
  }

  insertImport($, import_pos, imports_before_polymer.join(EOL) + EOL);
  insertInlinedImports($, import_pos, output);
  var outhtml = $.html();
  if (!options.csp && options.inline) {
    outhtml = inlineScripts(outhtml);
  }
  fs.writeFileSync(options.output, outhtml, 'utf8');
}

handleMainDocument();
<|endoftext|>


<commit_before>function draw(){
    if(settings[3]){/*clear?*/
        buffer.clearRect(
            0,
            0,
            width,
            height
        )
    }

    buffer.lineWidth = settings[0];
    i = lines.length - 1;
    do{
        buffer.beginPath();
        buffer.moveTo(
            lines[i][0],
            lines[i][1]
        );
        buffer.lineTo(
            mouse_x,
            mouse_y
        );
        buffer.closePath();
        buffer.strokeStyle = 'rgb(' + lines[i][2] + ',' + lines[i][3] + ',' + lines[i][4] + ')';
        buffer.stroke()
    }while(i--)

    if(settings[3]){/*clear?*/
        canvas.clearRect(
            0,
            0,
            width,
            height
        )
    }
    canvas.drawImage(
        get('buffer'),
        0,
        0
    )
}

function get(i){
    return document.getElementById(i)
}

function randomize_lines(){
    lines = [];

    i = settings[1] - 1;/*number of lines*/
    do{
        /*create line with start_x, start_y, and random rgb color*/
        lines.push([
            random_number(width),
            random_number(height),
            random_number(255),
            random_number(255),
            random_number(255)
        ])
    }while(i--);

    draw()
}

function random_number(i){
    return Math.floor(Math.random() * i)
}

function resize(){
    if(mode > 0){
        width = get('buffer').width = get('canvas').width = window.innerWidth;
        height = get('buffer').height = get('canvas').height = window.innerHeight;
        mouse_x = x = width / 2;
        mouse_y = y = height / 2;
        randomize_lines()
    }
}

function save(){
    /*save settings into localStorage if differ from default*/

    if(get('randomize-key').value === 'R'){
        ls.removeItem('warped2');
        settings[2] = 'R'
    }else{
        settings[2] = get('randomize-key').value;
        ls.setItem('warped2',settings[2])
    }

    i = 1;
    do{
        j = [
            'line-width',
            'number-of-lines'
        ][i];
        if(get(j).value === [1,100][i] || isNaN(get(j).value) || get(j).value < 1){
            ls.removeItem('warped' + i);
            settings[i] = [1,100][i];
            get(j).value = settings[i]
        }else{
            settings[i] = parseInt(get(j).value);
            ls.setItem('warped' + i,settings[i])
        }
    }while(i--);

    i=1;
    do{
        settings[3 + i] = get(['clear','mouse-lock'][i]).checked;
        if(settings[3 + i]){
            ls.removeItem('warped' + (3 + i))
        }else{
            ls.setItem('warped' + (3 + i),0)
        }
    }while(i--)
}

function setmode(newmode){
    mode = newmode;
    if(mode > 0){
        save();

        get('page').innerHTML = '<canvas id=canvas></canvas>';
        buffer = get('buffer').getContext('2d');
        canvas = get('canvas').getContext('2d');

        resize()
    }else{
        buffer = 0;
        canvas = 0;

        get('page').innerHTML = '

Warped

SEIZURE WARNING!
FLASHING LIGHTS!

Lines

<input id=number-of-lines size=1 type=text value=' + settings[1] + '>Lines
<input id=line-width size=1 type=text value=' + settings[0] + '>Line Width
<input ' + (settings[4] ? 'checked ' : '') + 'id=mouse-lock type=checkbox>Mouse Lock

<input disabled size=3 style=border:0 type=text value=ESC>Main Menu
<input id=randomize-key maxlength=1 size=3 type=text value=' + settings[2] + '>Randomize

<input ' + (settings[3] ? 'checked ' : '') + 'id=clear type=checkbox>Clear
Reset Settings

'
    }
}

var buffer = 0;
var canvas = 0;
var height = 0;
var i = 0;
var j = 0;
var lines = [];
var ls = window.localStorage;
var mode = 0;
var mouse_x = 0;
var mouse_y = 0;
var settings = [
    ls.getItem('warped0') === null ? 1 : parseInt(ls.getItem('warped0')),/*line width*/
    ls.getItem('warped1') === null ? 100 : parseInt(ls.getItem('warped1')),/*number of lines*/
    ls.getItem('warped2') === null ? 'R' : ls.getItem('warped2'),/*randomize key*/
    ls.getItem('warped3') === null,/*clear?*/
    ls.getItem('warped4') === null/*mouse lock?*/
];
var x = 0;
var width = 0;
var y = 0;

resize();
setmode(0);

window.onkeydown = function(e){
    if(mode > 0){
        i = window.event ? event : e;
        i = i.charCode ? i.charCode : i.keyCode;
        if(String.fromCharCode(i) === settings[2]){/*randomize key*/
            randomize_lines()
        }else if(i === 27){/*ESC*/
            setmode(0)
        }
    }
};

window.onmousedown = function(e){
    if(mode > 0){
        e.preventDefault();
        if(!settings[4]){/*mouse not locked*/
            mouse_x = e.pageX;
            mouse_y = e.pageY;
            draw()
        }
    }
};

window.onmousemove = function(e){
    if(mode > 0 && settings[4]){/*mouse locked*/
        mouse_x = e.pageX;
        mouse_y = e.pageY;
        draw()
    }
}

window.onresize = resize
<commit_msg>improved formatting<commit_after>function draw(){
    if(settings[3]){/*clear?*/
        buffer.clearRect(
            0,
            0,
            width,
            height
        )
    }

    buffer.lineWidth = settings[0];
    i = lines.length - 1;
    do{
        buffer.beginPath();
        buffer.moveTo(
            lines[i][0],
            lines[i][1]
        );
        buffer.lineTo(
            mouse_x,
            mouse_y
        );
        buffer.closePath();
        buffer.strokeStyle = 'rgb(' + lines[i][2] + ',' + lines[i][3] + ',' + lines[i][4] + ')';
        buffer.stroke()
    }while(i--);

    if(settings[3]){/*clear?*/
        canvas.clearRect(
            0,
            0,
            width,
            height
        )
    }
    canvas.drawImage(
        get('buffer'),
        0,
        0
    )
}

function get(i){
    return document.getElementById(i)
}

function randomize_lines(){
    lines = [];

    i = settings[1] - 1;/*number of lines*/
    do{
        /*create line with start_x, start_y, and random rgb color*/
        lines.push([
            random_number(width),
            random_number(height),
            random_number(255),
            random_number(255),
            random_number(255)
        ])
    }while(i--);

    draw()
}

function random_number(i){
    return Math.floor(Math.random() * i)
}

function resize(){
    if(mode > 0){
        width = get('buffer').width = get('canvas').width = window.innerWidth;
        height = get('buffer').height = get('canvas').height = window.innerHeight;

        mouse_x = x = width / 2;
        mouse_y = y = height / 2;

        randomize_lines()
    }
}

function save(){
    /*save settings into localStorage if differ from default*/

    if(get('randomize-key').value === 'R'){
        ls.removeItem('warped2');
        settings[2] = 'R'
    }else{
        settings[2] = get('randomize-key').value;
        ls.setItem(
            'warped2',
            settings[2]
        )
    }

    i = 1;
    do{
        j = [
            'line-width',
            'number-of-lines'
        ][i];
        if(get(j).value === [1,100][i] || isNaN(get(j).value) || get(j).value < 1){
            ls.removeItem('warped' + i);
            settings[i] = [1,100][i];
            get(j).value = settings[i]
        }else{
            settings[i] = parseInt(get(j).value);
            ls.setItem('warped' + i,settings[i])
        }
    }while(i--);

    i = 1;
    do{
        settings[3 + i] = get(['clear','mouse-lock'][i]).checked;
        if(settings[3 + i]){
            ls.removeItem('warped' + (3 + i))
        }else{
            ls.setItem('warped' + (3 + i),0)
        }
    }while(i--)
}

function setmode(newmode){
    mode = newmode;
    if(mode > 0){
        save();

        get('page').innerHTML = '<canvas id=canvas></canvas>';
        buffer = get('buffer').getContext('2d');
        canvas = get('canvas').getContext('2d');

        resize()
    }else{
        buffer = 0;
        canvas = 0;

        get('page').innerHTML = '

Warped

SEIZURE WARNING!
FLASHING LIGHTS!

Lines

<input id=number-of-lines size=1 type=text value='
            + settings[1] + '>Lines
<input id=line-width size=1 type=text value='
            + settings[0] + '>Line Width
<input '
            + (settings[4] ? 'checked ' : '') + 'id=mouse-lock type=checkbox>Mouse Lock

<input disabled size=3 style=border:0 type=text value=ESC>Main Menu
<input id=randomize-key maxlength=1 size=3 type=text value='
            + settings[2] + '>Randomize

<input '
            + (settings[3] ? 'checked ' : '') + 'id=clear type=checkbox>Clear
Reset Settings

'
    }
}

var buffer = 0;
var canvas = 0;
var height = 0;
var i = 0;
var j = 0;
var lines = [];
var ls = window.localStorage;
var mode = 0;
var mouse_x = 0;
var mouse_y = 0;
var settings = [
    ls.getItem('warped0') === null ?   1 : parseInt(ls.getItem('warped0')),/*line width*/
    ls.getItem('warped1') === null ? 100 : parseInt(ls.getItem('warped1')),/*number of lines*/
    ls.getItem('warped2') === null ? 'R' : ls.getItem('warped2'),/*randomize key*/
    ls.getItem('warped3') === null,/*clear?*/
    ls.getItem('warped4') === null/*mouse lock?*/
];
var x = 0;
var width = 0;
var y = 0;

resize();
setmode(0);

window.onkeydown = function(e){
    if(mode > 0){
        i = window.event ? event : e;
        i = i.charCode ? i.charCode : i.keyCode;

        if(String.fromCharCode(i) === settings[2]){/*randomize key*/
            randomize_lines()
        }else if(i === 27){/*ESC*/
            setmode(0)
        }
    }
};

window.onmousedown = function(e){
    if(mode > 0){
        e.preventDefault();
        if(!settings[4]){/*mouse not locked*/
            mouse_x = e.pageX;
            mouse_y = e.pageY;
            draw()
        }
    }
};

window.onmousemove = function(e){
    if(mode > 0 && settings[4]){/*mouse locked*/
        mouse_x = e.pageX;
        mouse_y = e.pageY;
        draw()
    }
}

window.onresize = resize
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  config: {},
  globalRoutes: function (app) {
    app.get('/report', function (req, res) {
      res.json({dir: __dir});
    });
  }
};
<commit_msg>reports endpoint<commit_after>'use strict';

module.exports = {
  config: {},
  globalRoutes: function (app) {
    app.get('/report', function (req, res) {
      res.json({dir: __dirname});
    });
  }
};
<|endoftext|>


<commit_before>'use strict';
var request = require('request');
var fs = require('fs');
var Job = require('../../lib/models/job');

module.exports = {
  config: {},
  routes: function (app, context) {
    app.get('/report', function (req, res) {
      var org = req.params.org;
      var repo = req.params.repo;
      var branch = req.query.branch;
      var protocol = req.protocol;
      var hostName = req.get('Host');
      var project = org + '/' + repo;
      var jobsEndpoint = protocol + '://' + hostName + '/' + org + '/' + repo + '/jobs';
      Job.find({ project: project}, { fields: {_id: true}, sort: {finished: -1}}, function(err, docs){
        var id = docs[0]._id;
        var coveragLocation = '~/.strider/data/'+ org + '-' + repo + '-' + branch + '/job-' + id +'/coverage/index.html';
        fs.readFile(coveragLocation, 'utf8', function (err, data) {
          console.log(data, err);
          res.send(data);
        });
      });
      // request({url: jobsEndpoint}, function (er, response, body) {
      //   var myCookie = request.cookie(response.headers['set-cookie'][0]);
      //   var cookieJar = request.jar();
      //   cookieJar.setCookie(myCookie, jobsEndpoint);
      //   request({url: jobsEndpoint, jar: cookieJar}, function(err, response, body){
      //     res.send(body);
      //   });
      // });

      // res.json({user: req.session});

      // res.json({yes: app});
      // var jobsEndpoint = protocol + '://' + hostName + '/' + org + '/' + repo + '/jobs';
      // console.log('BODY', body);
      // var latestJobId = JSON.parse(body)[0];
    });
  },
  globalRoutes: function (app, context) {
    app.get('/report', function (req, res) {
      res.json({context: context});
    });
  }
};
<commit_msg>reports endpoint<commit_after>'use strict';
var request = require('request');
var fs = require('fs');
var Job = require('../../lib/models/job');

module.exports = {
  config: {},
  routes: function (app, context) {
    app.get('/report', function (req, res) {
      var org = req.params.org;
      var repo = req.params.repo;
      var branch = req.query.branch;
      var protocol = req.protocol;
      var hostName = req.get('Host');
      var project = org + '/' + repo;
      var jobsEndpoint = protocol + '://' + hostName + '/' + org + '/' + repo + '/jobs';
      var options = {
        limit: 1,
        sort: [['finished', 'desc']]
      };
      Job.find({ project: project}, options, function(err, docs){
        var id = docs[0]._id;
        var coveragLocation = '~/.strider/data/'+ org + '-' + repo + '-' + branch + '/job-' + id +'/coverage/index.html';
        fs.readFile(coveragLocation, 'utf8', function (err, data) {
          console.log(data, err);
          res.send(data);
        });
      });
      // request({url: jobsEndpoint}, function (er, response, body) {
      //   var myCookie = request.cookie(response.headers['set-cookie'][0]);
      //   var cookieJar = request.jar();
      //   cookieJar.setCookie(myCookie, jobsEndpoint);
      //   request({url: jobsEndpoint, jar: cookieJar}, function(err, response, body){
      //     res.send(body);
      //   });
      // });

      // res.json({user: req.session});

      // res.json({yes: app});
      // var jobsEndpoint = protocol + '://' + hostName + '/' + org + '/' + repo + '/jobs';
      // console.log('BODY', body);
      // var latestJobId = JSON.parse(body)[0];
    });
  },
  globalRoutes: function (app, context) {
    app.get('/report', function (req, res) {
      res.json({context: context});
    });
  }
};
<|endoftext|>


<commit_before>'use strict';
var request = require('request');
var fs = require('fs');
var Job = require('../../lib/models/job');
var _ = require('underscore');
var location = __dirname;

module.exports = {
  config: {},
  routes: function (app, context) {
    app.get('/report', function (req, res) {
      var org = req.params.org;
      var repo = req.params.repo;
      var branch = req.query.branch;
      var protocol = req.protocol;
      var hostName = req.get('Host');
      var project = org + '/' + repo;
      var jobsEndpoint = protocol + '://' + hostName + '/' + org + '/' + repo + '/jobs';
      var options = {
        limit: 1,
        sort: [['finished', 'desc']]
      };
      Job.find({ project: project, archived: null}, options, function(err, docs){
        var id = docs[0]._id;
        var home = process.env.HOME;
        var coverageLocation = home + '/.strider/data/'+ org + '-' + repo + '-' + branch + '/job-' + id +'/coverage';
        fs.readdir(coverageLocation, function (err, file) {
          var promises = [];
          var valid = [];
          _.each(file, function (item) {
            var index = item.indexOf('.');
            if (index !== -1) {
              var extension = item.substr(index, item.length);
              if (extension === '.js' || extension === '.html' || extension === '.css') {
                valid.push(item);
              }
            }
          });
          _.each(valid, function (item) {
            var index = item.indexOf('.');
            var extension = item.substr(index, item.length);
            var temp = (function (src) {
              return new Promise(function (resolve, reject) {
                fs.readFile(src, function (err, data) {
                  var returnData = '';
                  switch(extension){
                    case '.js':
                      returnData = '<script>' + data + '</script>';
                      break;
                    case '.css':
                      returnData = '<style>' + data + '</style>';
                      break;
                    default:
                      returnData = data;
                  }
                  resolve(returnData);
                });
              });
            })(item);
            promises.push(temp);
          });
          Promise.all(promises).then(function(finalStrings){
            var fileStrings = '';
            _.each(finalStrings, function (item) {
              fileStrings += item;
            });
            res.send(fileStrings);
          });
        });
      });
      // request({url: jobsEndpoint}, function (er, response, body) {
      //   var myCookie = request.cookie(response.headers['set-cookie'][0]);
      //   var cookieJar = request.jar();
      //   cookieJar.setCookie(myCookie, jobsEndpoint);
      //   request({url: jobsEndpoint, jar: cookieJar}, function(err, response, body){
      //     res.send(body);
      //   });
      // });

      // res.json({user: req.session});

      // res.json({yes: app});
      // var jobsEndpoint = protocol + '://' + hostName + '/' + org + '/' + repo + '/jobs';
      // console.log('BODY', body);
      // var latestJobId = JSON.parse(body)[0];
    });
  },
  globalRoutes: function (app, context) {
    app.get('/report', function (req, res) {
      res.json({context: context});
    });
  }
};
<commit_msg>reports endpoint<commit_after>'use strict';
var request = require('request');
var fs = require('fs');
var Job = require('../../lib/models/job');
var _ = require('underscore');
var location = __dirname;

module.exports = {
  config: {},
  routes: function (app, context) {
    app.get('/report', function (req, res) {
      var org = req.params.org;
      var repo = req.params.repo;
      var branch = req.query.branch;
      var protocol = req.protocol;
      var hostName = req.get('Host');
      var project = org + '/' + repo;
      var jobsEndpoint = protocol + '://' + hostName + '/' + org + '/' + repo + '/jobs';
      var options = {
        limit: 1,
        sort: [['finished', 'desc']]
      };
      Job.find({ project: project, archived: null}, options, function(err, docs){
        var id = docs[0]._id;
        var home = process.env.HOME;
        var coverageLocation = home + '/.strider/data/'+ org + '-' + repo + '-' + branch + '/job-' + id +'/coverage';
        fs.readdir(coverageLocation, function (err, file) {
          var promises = [];
          var valid = [];
          _.each(file, function (item) {
            var index = item.indexOf('.');
            if (index !== -1) {
              var extension = item.substr(index, item.length);
              if (extension === '.js' || extension === '.html' || extension === '.css') {
                valid.push(item);
              }
            }
          });
          _.each(valid, function (item) {
            var index = item.indexOf('.');
            var extension = item.substr(index, item.length);
            var temp = (function (src) {
              return new Promise(function (resolve, reject) {
                var filePath = coverageLocation + '/' + src;
                fs.readFile(filePath, function (err, data) {
                  var returnData = '';
                  switch(extension){
                    case '.js':
                      returnData = '<script>' + data + '</script>';
                      break;
                    case '.css':
                      returnData = '<style>' + data + '</style>';
                      break;
                    default:
                      returnData = data;
                  }
                  resolve(returnData);
                });
              });
            })(item);
            promises.push(temp);
          });
          Promise.all(promises).then(function(finalStrings){
            var fileStrings = '';
            _.each(finalStrings, function (item) {
              fileStrings += item;
            });
            res.send(fileStrings);
          });
        });
      });
      // request({url: jobsEndpoint}, function (er, response, body) {
      //   var myCookie = request.cookie(response.headers['set-cookie'][0]);
      //   var cookieJar = request.jar();
      //   cookieJar.setCookie(myCookie, jobsEndpoint);
      //   request({url: jobsEndpoint, jar: cookieJar}, function(err, response, body){
      //     res.send(body);
      //   });
      // });

      // res.json({user: req.session});

      // res.json({yes: app});
      // var jobsEndpoint = protocol + '://' + hostName + '/' + org + '/' + repo + '/jobs';
      // console.log('BODY', body);
      // var latestJobId = JSON.parse(body)[0];
    });
  },
  globalRoutes: function (app, context) {
    app.get('/report', function (req, res) {
      res.json({context: context});
    });
  }
};
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 Vanderbilt University, All rights reserved.
 *
 * Author: Tamas Kecskes
 */

var requirejs = require('requirejs');
requirejs.config({
	nodeRequire: require,
	baseUrl: __dirname,
    paths:{
        "logManager": "common/LogManager"
    }
});

module.exports = {
	clientStorage: requirejs('storage/clientstorage'),
	serverStorage: requirejs('storage/serverstorage'),
	core: requirejs('core/core'),
    standaloneServer: requirejs('server/standalone')
};
<commit_msg>now server user storage also available with library access<commit_after>/*
 * Copyright (C) 2013 Vanderbilt University, All rights reserved.
 *
 * Author: Tamas Kecskes
 */

var requirejs = require('requirejs');
requirejs.config({
	nodeRequire: require,
	baseUrl: __dirname,
    paths:{
        "logManager": "common/LogManager"
    }
});

module.exports = {
	clientStorage: requirejs('storage/clientstorage'),
	serverStorage: requirejs('storage/serverstorage'),
    serverUserStorage: requirejs('storage/serveruserstorage'),
	core: requirejs('core/core'),
    standaloneServer: requirejs('server/standalone')
};
<|endoftext|>