<commit_before>
// when a user hits the front page a set uuid should be created and user re-routed (or pushstate)
// the user can also be asked to provide a unique set name - so they will check against the list of known set names
// then that user is on that page set and they can put URLs into it
// they will also get a store folder link with the set uuid where they can find their output files
// users will run processes and the resulting facts will be stored as belonging to this page set
// there will later be an option to push the facts to the main fact store, but for now they are local stored in mongo

cmapi = 'http://cmapi.cottagelabs.com/';

var getUuid = function() {
    return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
    });
}

Sets = new Mongo.Collection("sets");
Facts = new Mongo.Collection("facts");

Router.map(function() {
    this.route('home', {
        path : '/',
        action: function() {
            this.redirect('/' + getUuid())
        }
    });
    this.route('set', {
        path : '/:_id',
        template : 'canary',
        waitOn : function() {
            return Meteor.subscribe('sets', this.params._id);
        },
        data : function() {
            return {
                facts : Facts.find({ set : this.params._id }, {sort : {creationAt : 'desc'}}),
                canarysetid: this.params._id
            }
        },
        action : function() {
            if ( Sets.findOne(this.params._id) === undefined ) {
                Meteor.call('createSet',{
                    _id: this.params._id,
                    urls: []
                })
            }
            Session.set('canarysetid', this.params._id);
            Meteor.subscribe('facts', this.params._id);
            this.render();
        }
    });
});

if (Meteor.isClient) {

    Meteor.startup(function () {
        setTimeout(function() {$('#urls').focus()}, 2000);
    });

    Template.canary.helpers({
        currentset: function() {
            return Sets.findOne(Session.get("canarysetid"));
        },
        urlscount: function() {
            return Sets.findOne(Session.get("canarysetid")).urls.length;
        },
        /*factdoccount: function () {
            var factdocs = [];
            var f = Facts.find({});
            for ( var i in f ) {
                if ( factdocs.indexOf(f[i]['source']) == -1 ) {
                    factdocs.push(f[i]['source']);
                }
            }
            return factdocs.length;
        },*/
        factcount: function () {
            return Facts.find({}).count();
        },
        factlist: function() {
            return Facts.find({}, {sort: {createdAt: -1}});
        },
        processing: function(proctype) {
            var ret = false;
            var currentset = Sets.findOne(Session.get("canarysetid"));
            for ( var u in currentset.urls ) {
                var tu = currentset.urls[u];
                if ( tu.results ) {
                    if ( tu.results[proctype] ) {
                        if ( tu.results[proctype].processing ) {
                            ret = true;
                        }
                    }
                }
            }
            return ret;
        }
    });

    Template.canary.events({
        "click .process": function (event) {
            var proctype = event.target.id;
            var params = {
            };
            if ( proctype == 'regex') {
                if ( $('#regexurl').val() ) {
                    params['-r.r'] = $('#regexurl').val();
                } else if ( $('#regextype').val() ) {
                    params['-r.r'] = $('#regextype').val();
                }
            }
            if ( !params['-r.r'] ) {
                alert('Choose a regex type or provide a URL to your own regex file first!');
            } else {
                //$('#'+proctype).addClass('disabled');
                Meteor.call('ami', {processor: proctype, params: params, canarysetid: Session.get("canarysetid")} );
            }
        },
        "keypress #urls": function (event) {
            var currentset = Sets.findOne(Session.get("canarysetid"));
            var urls = [];
            var knownones = [];
            var oldones = [];
            var newones = [];
            var keycode = (event.keyCode ? event.keyCode : event.which);
            if (keycode == '13') {
                var curls = $('#urls').val().split('\n');
                for ( var u in currentset.urls ) {
                    if ( curls.indexOf(currentset.urls[u]['url']) == -1 ) {
                        oldones.push(currentset.urls[u]['url']);
                    } else {
                        knownones.push(currentset.urls[u]['url']);
                        urls.push(currentset.urls[u]);
                    }
                }
                for ( var c in curls ) {
                    if ( curls[c].length > 1 ) {
                        if ( knownones.indexOf(curls[c]) == -1 ) {
                            newones.push(curls[c]);
                            urls.push({url: curls[c]});
                        }
                    }
                }
                if ( newones.length != 0 || oldones.length != 0 ) {
                    Sets.update(currentset._id, {$set: {urls: urls}});
                }
                for ( var n in oldones ) {
                    Meteor.call('removeFacts',{url: oldones[n]});
                }
                for ( var n in newones ) {
                    Meteor.call('quickscrape',{url: newones[n], canarysetid: Session.get("canarysetid")})
                }
            }
        }
    });

}

if (Meteor.isServer) {
    Meteor.startup(function () {
    });

    Meteor.publish("sets", function (canarysetid) {
        return Sets.find(canarysetid);
    });

    Meteor.publish("facts", function (canarysetid) {
        return Facts.find({"set": canarysetid});
    });

    // TODO: MOST OF THESE METHODS HAVE REPEATED CODE - SHOULD ABSTRACT OUT TO A METHOD THAT UPDATES THE URLS DATA
    // JUST NOT DONE IT COS I AM LEARNING METEOR RIGHT NOW AND NOT THINKING TIDILY
    Meteor.methods({
        ami: function(obj) {
            console.log('starting ami ' + obj.processor);
            console.log(obj);
            var currentset = Sets.findOne(obj.canarysetid);
            var params = {
                params: obj.params
            }
            if ( params.params['-r.r'] ) {
                var procr = obj.processor + '-' + params.params['-r.r'];
            } else {
                var procr = obj.processor;
            }
            for ( var u in currentset.urls ) {
                var tu = currentset.urls[u];
                params.params.cid = tu.cid;
                Facts.remove({processor:procr, url:tu.url});
                if ( tu.results === undefined ) { tu.results = {}; };
                tu.results[obj.processor] = {processing: true};
                Meteor.http.call('GET', cmapi+'ami'+obj.processor, params, function(sth,res) {
                    tu.results[obj.processor] = res.data;
                    console.log(res)
                    for ( var f in res.data.facts ) {
                        var fc = res.data.facts[f];
                        fc.set = obj.canarysetid;
                        fc.url = tu.url;
                        fc.processor = procr;
                        Meteor.call('createFact',fc);
                    }
                    Sets.update(currentset._id, {$set: {urls: currentset.urls}});
                });
            }
            Sets.update(currentset._id, {$set: {urls: currentset.urls}});
        },
        norma: function(obj) {
            Meteor.http.call('GET', cmapi+'norma', {params: {cid: obj.cid}}, function(sth,res) {
                var currentset = Sets.findOne(obj.canarysetid);
                for ( var u in currentset.urls ) {
                    var tu = currentset.urls[u];
                    if ( tu.url == obj.url ) {
                        if ( tu.results === undefined ) { tu.results = {}; };
                        console.log(res.data);
                        tu.results.norma = res.data;
                    }
                }
                Sets.update(currentset._id, {$set: {urls: currentset.urls}});
            });
        },
        retrieve: function(obj) {
            Meteor.http.call('GET', cmapi+'retrieve', {params: {url: obj.url, cid: obj.cid}}, function(sth,res) {
                var currentset = Sets.findOne(obj.canarysetid);
                for ( var u in currentset.urls ) {
                    var tu = currentset.urls[u];
                    if ( tu.url == obj.url ) {
                        if ( tu.results === undefined ) { tu.results = {}; };
                        tu.results.retrieve = res.data;
                        if ( res.data.retrieved ) {
                            tu.results.norma = {processing: true};
                            Meteor.call('norma',obj);
                        }
                    }
                }
                Sets.update(currentset._id, {$set: {urls: currentset.urls}});
            });
        },
        quickscrape: function(obj) {
            var currentset = Sets.findOne(obj.canarysetid);
            for ( var u in currentset.urls ) {
                var tu = currentset.urls[u];
                if ( tu.url == obj.url ) {
                    if ( tu.results === undefined ) { tu.results = {}; };
                    tu.results.quickscrape = {processing: true};
                }
            }
            Sets.update(currentset._id, {$set: {urls: currentset.urls}});
            Meteor.http.call('GET', cmapi+'quickscrape', {params: {url: obj.url}}, function(sth,res) {
                for ( var u in currentset.urls ) {
                    var tu = currentset.urls[u];
                    if ( tu.url == obj.url ) {
                        if ( tu.results === undefined ) { tu.results = {}; };
                        if ( res.data.files === undefined ) {
                            tu.results.quickscrape = {failed: true};
                        } else {
                            tu.results.quickscrape = res.data;
                            tu.cid = res.data.cid;
                            obj.cid = res.data.cid;
                            if ( res.data.files.indexOf('fulltext.html') == -1 ) {
                                // fulltext failed to be retrieved by quickscrape, so just try a retrieve on it
                                tu.results.retrieve = {processing: true};
                                Meteor.call('retrieve', obj)
                            } else {
                                // fulltext was there, so try norma
                                tu.results.norma = {processing: true};
                                Meteor.call('norma',obj);
                            }
                        }
                    }
                }
                Sets.update(currentset._id, {$set: {urls: currentset.urls}});
            });
        }
    });
}

Meteor.methods({
    createFact: function(obj) {
        var d = new Date();
        obj.createdAt = d;
        obj.updatedAt = d;
        Facts.insert(obj);
        console.log('fact created');
    },
    removeFacts: function(obj) {
        Facts.remove({url: obj.url});
    }
    createSet: function (obj) {
        var d = new Date();
        obj.createdAt = d;
        obj.updatedAt = d;
        Sets.insert(obj);
        console.log('set ' + obj._id + ' created');
    }
});

<commit_msg>fix to facts deletion<commit_after>
// when a user hits the front page a set uuid should be created and user re-routed (or pushstate)
// the user can also be asked to provide a unique set name - so they will check against the list of known set names
// then that user is on that page set and they can put URLs into it
// they will also get a store folder link with the set uuid where they can find their output files
// users will run processes and the resulting facts will be stored as belonging to this page set
// there will later be an option to push the facts to the main fact store, but for now they are local stored in mongo

cmapi = 'http://cmapi.cottagelabs.com/';

var getUuid = function() {
    return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
    });
}

Sets = new Mongo.Collection("sets");
Facts = new Mongo.Collection("facts");

Router.map(function() {
    this.route('home', {
        path : '/',
        action: function() {
            this.redirect('/' + getUuid())
        }
    });
    this.route('set', {
        path : '/:_id',
        template : 'canary',
        waitOn : function() {
            return Meteor.subscribe('sets', this.params._id);
        },
        data : function() {
            return {
                facts : Facts.find({ set : this.params._id }, {sort : {creationAt : 'desc'}}),
                canarysetid: this.params._id
            }
        },
        action : function() {
            if ( Sets.findOne(this.params._id) === undefined ) {
                Meteor.call('createSet',{
                    _id: this.params._id,
                    urls: []
                })
            }
            Session.set('canarysetid', this.params._id);
            Meteor.subscribe('facts', this.params._id);
            this.render();
        }
    });
});

if (Meteor.isClient) {

    Meteor.startup(function () {
        setTimeout(function() {$('#urls').focus()}, 2000);
    });

    Template.canary.helpers({
        currentset: function() {
            return Sets.findOne(Session.get("canarysetid"));
        },
        urlscount: function() {
            return Sets.findOne(Session.get("canarysetid")).urls.length;
        },
        /*factdoccount: function () {
            var factdocs = [];
            var f = Facts.find({});
            for ( var i in f ) {
                if ( factdocs.indexOf(f[i]['source']) == -1 ) {
                    factdocs.push(f[i]['source']);
                }
            }
            return factdocs.length;
        },*/
        factcount: function () {
            return Facts.find({}).count();
        },
        factlist: function() {
            return Facts.find({}, {sort: {createdAt: -1}});
        },
        processing: function(proctype) {
            var ret = false;
            var currentset = Sets.findOne(Session.get("canarysetid"));
            for ( var u in currentset.urls ) {
                var tu = currentset.urls[u];
                if ( tu.results ) {
                    if ( tu.results[proctype] ) {
                        if ( tu.results[proctype].processing ) {
                            ret = true;
                        }
                    }
                }
            }
            return ret;
        }
    });

    Template.canary.events({
        "click .process": function (event) {
            var proctype = event.target.id;
            var params = {
            };
            if ( proctype == 'regex') {
                if ( $('#regexurl').val() ) {
                    params['-r.r'] = $('#regexurl').val();
                } else if ( $('#regextype').val() ) {
                    params['-r.r'] = $('#regextype').val();
                }
            }
            if ( !params['-r.r'] ) {
                alert('Choose a regex type or provide a URL to your own regex file first!');
            } else {
                //$('#'+proctype).addClass('disabled');
                Meteor.call('ami', {processor: proctype, params: params, canarysetid: Session.get("canarysetid")} );
            }
        },
        "keypress #urls": function (event) {
            var currentset = Sets.findOne(Session.get("canarysetid"));
            var urls = [];
            var knownones = [];
            var oldones = [];
            var newones = [];
            var keycode = (event.keyCode ? event.keyCode : event.which);
            if (keycode == '13') {
                var curls = $('#urls').val().split('\n');
                for ( var u in currentset.urls ) {
                    if ( curls.indexOf(currentset.urls[u]['url']) == -1 ) {
                        oldones.push(currentset.urls[u]['url']);
                    } else {
                        knownones.push(currentset.urls[u]['url']);
                        urls.push(currentset.urls[u]);
                    }
                }
                for ( var c in curls ) {
                    if ( curls[c].length > 1 ) {
                        if ( knownones.indexOf(curls[c]) == -1 ) {
                            newones.push(curls[c]);
                            urls.push({url: curls[c]});
                        }
                    }
                }
                if ( newones.length != 0 || oldones.length != 0 ) {
                    Sets.update(currentset._id, {$set: {urls: urls}});
                }
                for ( var n in oldones ) {
                    Meteor.call('removeFacts',{url: oldones[n]});
                }
                for ( var n in newones ) {
                    Meteor.call('quickscrape',{url: newones[n], canarysetid: Session.get("canarysetid")})
                }
            }
        }
    });

}

if (Meteor.isServer) {
    Meteor.startup(function () {
    });

    Meteor.publish("sets", function (canarysetid) {
        return Sets.find(canarysetid);
    });

    Meteor.publish("facts", function (canarysetid) {
        return Facts.find({"set": canarysetid});
    });

    // TODO: MOST OF THESE METHODS HAVE REPEATED CODE - SHOULD ABSTRACT OUT TO A METHOD THAT UPDATES THE URLS DATA
    // JUST NOT DONE IT COS I AM LEARNING METEOR RIGHT NOW AND NOT THINKING TIDILY
    Meteor.methods({
        ami: function(obj) {
            console.log('starting ami ' + obj.processor);
            console.log(obj);
            var currentset = Sets.findOne(obj.canarysetid);
            var params = {
                params: obj.params
            }
            if ( params.params['-r.r'] ) {
                var procr = obj.processor + '-' + params.params['-r.r'];
            } else {
                var procr = obj.processor;
            }
            for ( var u in currentset.urls ) {
                var tu = currentset.urls[u];
                params.params.cid = tu.cid;
                Facts.remove({processor:procr, url:tu.url});
                if ( tu.results === undefined ) { tu.results = {}; };
                tu.results[obj.processor] = {processing: true};
                Meteor.http.call('GET', cmapi+'ami'+obj.processor, params, function(sth,res) {
                    tu.results[obj.processor] = res.data;
                    console.log(res)
                    for ( var f in res.data.facts ) {
                        var fc = res.data.facts[f];
                        fc.set = obj.canarysetid;
                        fc.url = tu.url;
                        fc.processor = procr;
                        Meteor.call('createFact',fc);
                    }
                    Sets.update(currentset._id, {$set: {urls: currentset.urls}});
                });
            }
            Sets.update(currentset._id, {$set: {urls: currentset.urls}});
        },
        norma: function(obj) {
            Meteor.http.call('GET', cmapi+'norma', {params: {cid: obj.cid}}, function(sth,res) {
                var currentset = Sets.findOne(obj.canarysetid);
                for ( var u in currentset.urls ) {
                    var tu = currentset.urls[u];
                    if ( tu.url == obj.url ) {
                        if ( tu.results === undefined ) { tu.results = {}; };
                        console.log(res.data);
                        tu.results.norma = res.data;
                    }
                }
                Sets.update(currentset._id, {$set: {urls: currentset.urls}});
            });
        },
        retrieve: function(obj) {
            Meteor.http.call('GET', cmapi+'retrieve', {params: {url: obj.url, cid: obj.cid}}, function(sth,res) {
                var currentset = Sets.findOne(obj.canarysetid);
                for ( var u in currentset.urls ) {
                    var tu = currentset.urls[u];
                    if ( tu.url == obj.url ) {
                        if ( tu.results === undefined ) { tu.results = {}; };
                        tu.results.retrieve = res.data;
                        if ( res.data.retrieved ) {
                            tu.results.norma = {processing: true};
                            Meteor.call('norma',obj);
                        }
                    }
                }
                Sets.update(currentset._id, {$set: {urls: currentset.urls}});
            });
        },
        quickscrape: function(obj) {
            var currentset = Sets.findOne(obj.canarysetid);
            for ( var u in currentset.urls ) {
                var tu = currentset.urls[u];
                if ( tu.url == obj.url ) {
                    if ( tu.results === undefined ) { tu.results = {}; };
                    tu.results.quickscrape = {processing: true};
                }
            }
            Sets.update(currentset._id, {$set: {urls: currentset.urls}});
            Meteor.http.call('GET', cmapi+'quickscrape', {params: {url: obj.url}}, function(sth,res) {
                for ( var u in currentset.urls ) {
                    var tu = currentset.urls[u];
                    if ( tu.url == obj.url ) {
                        if ( tu.results === undefined ) { tu.results = {}; };
                        if ( res.data.files === undefined ) {
                            tu.results.quickscrape = {failed: true};
                        } else {
                            tu.results.quickscrape = res.data;
                            tu.cid = res.data.cid;
                            obj.cid = res.data.cid;
                            if ( res.data.files.indexOf('fulltext.html') == -1 ) {
                                // fulltext failed to be retrieved by quickscrape, so just try a retrieve on it
                                tu.results.retrieve = {processing: true};
                                Meteor.call('retrieve', obj)
                            } else {
                                // fulltext was there, so try norma
                                tu.results.norma = {processing: true};
                                Meteor.call('norma',obj);
                            }
                        }
                    }
                }
                Sets.update(currentset._id, {$set: {urls: currentset.urls}});
            });
        }
    });
}

Meteor.methods({
    createFact: function(obj) {
        var d = new Date();
        obj.createdAt = d;
        obj.updatedAt = d;
        Facts.insert(obj);
        console.log('fact created');
    },
    removeFacts: function(obj) {
        Facts.remove({url: obj.url});
    },
    createSet: function (obj) {
        var d = new Date();
        obj.createdAt = d;
        obj.updatedAt = d;
        Sets.insert(obj);
        console.log('set ' + obj._id + ' created');
    }
});

<|endoftext|>


<commit_before>'use strict';

import * as cookies from 'cookies-js';
import * as util from './lib/util.js';

let queue = window.fathom.q || [];
let trackerUrl = '';

const commands = {
  "trackPageview": trackPageview,
  "setTrackerUrl": setTrackerUrl,
};

function newVisitorData() {
  return {
    sid: util.generateKey(),
    isNewVisitor: true,
    isNewSession: true,
    pagesViewed: [],
    lastSeen: +new Date(),
  }
}

function getData() {
  let thirtyMinsAgo = new Date();
  thirtyMinsAgo.setMinutes(thirtyMinsAgo.getMinutes() - 30);

  let data = cookies.get('_fathom');
  if(! data) {
    return newVisitorData();
  }

  try{
    data = JSON.parse(data);
  } catch(e) {
    console.error(e);
    return newVisitorData();
  }

  if(data.lastSeen < (+thirtyMinsAgo)) {
    data.isNewSession = true;
  }

  return data;
}

function findTrackerUrl() {
  const el = document.getElementById('fathom-script')
  return el ? el.src.replace('tracker.js', 'collect') : '';
}

function setTrackerUrl(v) {
  trackerUrl = v;
}

function trackPageview() {
  if(trackerUrl === '') {
    trackerUrl = findTrackerUrl();
  }

  // Respect "Do Not Track" requests
  if('doNotTrack' in navigator && navigator.doNotTrack === "1") {
    return;
  }

  // ignore prerendered pages
  if( 'visibilityState' in document && document.visibilityState === 'prerender' ) {
    return;
  }

  let req = window.location;

  // parse canonical, if page has one
  let canonical = document.querySelector('link[rel="canonical"][href]');
  if(canonical) {
    let a = document.createElement('a');
    a.href = canonical.href;

    // use parsed canonical as location object
    req = a;
  }

  // get path and pathname from location or canonical
  let path = req.pathname + req.search;
  let hostname = req.protocol + "//" + req.hostname;

  // if parsing path failed, default to main page
  if(!path) {
    path = '/';
  }

  // only set referrer if not internal
  let referrer = '';
  if(document.referrer.indexOf(location.hostname) < 0) {
    referrer = document.referrer;
  }

  let data = getData();
  const d = {
    sid: data.sid,
    p: path,
    h: hostname,
    r: referrer,
    u: data.pagesViewed.indexOf(path) == -1 ? 1 : 0,
    nv: data.isNewVisitor ? 1 : 0,
    ns: data.isNewSession ? 1 : 0,
  };

  let i = document.createElement('img');
  i.src = trackerUrl + util.stringifyObject(d);
  i.addEventListener('load', function() {
    let now = new Date();
    let midnight = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), 24, 0, 0));
    let expires = Math.round((midnight - now) / 1000);
    data.pagesViewed.push(path);
    data.isNewVisitor = false;
    data.isNewSession = false;
    data.lastSeen = +new Date();
    cookies.set('_fathom', JSON.stringify(data), { 'expires': expires });
  });
  document.body.appendChild(i);
  window.setTimeout(() => { document.body.removeChild(i)}, 1000);
}

// override global fathom object
window.fathom = function() {
  var args = [].slice.call(arguments);
  var c = args.shift();
  commands[c].apply(this, args);
};

// process existing queue
queue.forEach((i) => fathom.apply(this, i));
<commit_msg>only add path if not already in pagesViewed<commit_after>'use strict';

import * as cookies from 'cookies-js';
import * as util from './lib/util.js';

let queue = window.fathom.q || [];
let trackerUrl = '';

const commands = {
  "trackPageview": trackPageview,
  "setTrackerUrl": setTrackerUrl,
};

function newVisitorData() {
  return {
    sid: util.generateKey(),
    isNewVisitor: true,
    isNewSession: true,
    pagesViewed: [],
    lastSeen: +new Date(),
  }
}

function getData() {
  let thirtyMinsAgo = new Date();
  thirtyMinsAgo.setMinutes(thirtyMinsAgo.getMinutes() - 30);

  let data = cookies.get('_fathom');
  if(! data) {
    return newVisitorData();
  }

  try{
    data = JSON.parse(data);
  } catch(e) {
    console.error(e);
    return newVisitorData();
  }

  if(data.lastSeen < (+thirtyMinsAgo)) {
    data.isNewSession = true;
  }

  return data;
}

function findTrackerUrl() {
  const el = document.getElementById('fathom-script')
  return el ? el.src.replace('tracker.js', 'collect') : '';
}

function setTrackerUrl(v) {
  trackerUrl = v;
}

function trackPageview() {
  if(trackerUrl === '') {
    trackerUrl = findTrackerUrl();
  }

  // Respect "Do Not Track" requests
  if('doNotTrack' in navigator && navigator.doNotTrack === "1") {
    return;
  }

  // ignore prerendered pages
  if( 'visibilityState' in document && document.visibilityState === 'prerender' ) {
    return;
  }

  let req = window.location;

  // parse canonical, if page has one
  let canonical = document.querySelector('link[rel="canonical"][href]');
  if(canonical) {
    let a = document.createElement('a');
    a.href = canonical.href;

    // use parsed canonical as location object
    req = a;
  }

  // get path and pathname from location or canonical
  let path = req.pathname + req.search;
  let hostname = req.protocol + "//" + req.hostname;

  // if parsing path failed, default to main page
  if(!path) {
    path = '/';
  }

  // only set referrer if not internal
  let referrer = '';
  if(document.referrer.indexOf(location.hostname) < 0) {
    referrer = document.referrer;
  }

  let data = getData();
  const d = {
    sid: data.sid,
    p: path,
    h: hostname,
    r: referrer,
    u: data.pagesViewed.indexOf(path) == -1 ? 1 : 0,
    nv: data.isNewVisitor ? 1 : 0,
    ns: data.isNewSession ? 1 : 0,
  };

  let i = document.createElement('img');
  i.src = trackerUrl + util.stringifyObject(d);
  i.addEventListener('load', function() {
    let now = new Date();
    let midnight = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), 24, 0, 0));
    let expires = Math.round((midnight - now) / 1000);

    if( data.pagesViewed.indexOf(path) == -1 ) {
      data.pagesViewed.push(path);
    }

    data.isNewVisitor = false;
    data.isNewSession = false;
    data.lastSeen = +new Date();
    cookies.set('_fathom', JSON.stringify(data), { 'expires': expires });
  });
  document.body.appendChild(i);
  window.setTimeout(() => { document.body.removeChild(i)}, 1000);
}

// override global fathom object
window.fathom = function() {
  var args = [].slice.call(arguments);
  var c = args.shift();
  commands[c].apply(this, args);
};

// process existing queue
queue.forEach((i) => fathom.apply(this, i));
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
var CONFIG = JSON.parse(localStorage.getItem('CONFIG'));
var moment = require("moment");
var homeService = require("../home/homeService");
var Defaults = require('../../mixins/Defaults');
var Clock =  require('../../../client/components/clock');
import Popout from 'react-popout';

import io from 'socket.io-client';
var socket = io('http://localhost:3000');

module.exports = React.createClass({
	displayName: 'VIEW_Home',
	getInitialState: function() {
		return {
			viewName :"Home",
			temperature : '',
			day : '',
			date : '',
			weatherDesc : '',
			weatherIcon : '',
			iconPath : '',
			weatherCurrentSummary : '',
			weatherDailySummary : '',
			dailyWeather : [],
			newsFeed : [],
			schedules : [],
			isShow : false,
			selectedUrl : '',
			currentCommand : 'a'
		};
	},
	componentDidMount: function() {
		var self = this;
		this.getWeather();
		this.getNews();
		this.getSchedule();

		socket.on('receiveCommand', function(data) {
				console.log("command: ", data);
				self.handleCommand(data);
		});

	},

	openView: function(_viewName) {
		window.open(CONFIG.currentEnv.endpoint + _viewName, '_self', false); //open home
	},
	lookupIcon:function(_icon){
		var path = "";
		var icons = [{type:'clear-day',path :"images/weather/Sun.png"},//# clear sky day
		{type:'wind',path :"images/weather/Wind.png"},//#wind
		{type:'cloudy',path :"images/weather/Cloud.png"},//#cloudy day
		{type:'partly-cloudy-day',path :"images/weather/PartlySunny.png"},//# partly cloudy day
		{type:'rain',path :"images/weather/Rain.png"},
		{type:'snow',path :"images/weather/Snow.png"},
		{type:'snow-thin',path :"images/weather/Snow.png"},
		{type:'fog',path :"images/weather/Haze.png"},
		{type:'clear-night',path :"images/weather/Moon.png"},
		{type:'partly-cloudy-night',path :"images/weather/PartlyMoon.png"},
		{type:'thunderstorm',path :"images/weather/Storm.png"},
		{type:'tornado',path :"images/weather/Tornado.png"},
		{type:'hail',path :"images/weather/Hail.png"}];

		for(var i in icons){
			if(icons[i].type == _icon){
				path = icons[i].path;
			}
		}

		return path;

	},
	getWeather : function(){

		var self = this;
		var now = new Date();

		homeService.getWeather().then((res)=>{

			self.setState({
		    temperature: Math.round(parseFloat(res.currently.temperature)),
				weatherIcon : self.lookupIcon(res.currently.icon),
				weatherCurrentSummary: res.currently.summary,
				weatherDailySummary : res.daily.summary,
				dailyWeather : res.daily.data,
				day : moment(now).format('dddd'),
				date : moment(now).format('ll'),
				timer : 0
	    });

		}, (err)=>{
			console.log(err);
		});
	},
	getNews : function(){
		var self = this;
		homeService.getNews().then((res)=>{
			self.setState({
				newsFeed: res.articles
		  });
		}, (err)=>{
			console.log(err);
		});
	},

	handleCommand: function(_data){

		if(_data.type == "calendar" || _data.type == "news"){

			this.getUrl(_data.url);

		}else if(_data.type == "weather"){

		}else{

		}

	},

	getUrl :function(_url){

		var command = this.state.currentCommand; //<-- this will change after getting speech data

		command = "show calendar"//TODO : will replace

		if(command.indexOf("first") > -1 && command.indexOf("news") > -1){
			this.state.selectedUrl = this.state.newsFeed[0].url;
		}else if(command.indexOf("second") > -1 && command.indexOf("news") > -1){
			this.state.selectedUrl = this.state.newsFeed[1].url;
		}else if(command.indexOf("third") > -1 && command.indexOf("news") > -1){
			this.state.selectedUrl = this.state.newsFeed[2].url;
		}else if(command.indexOf("fourth") > -1 && command.indexOf("news") > -1){
			this.state.selectedUrl = this.state.newsFeed[3].url;
		}else if(command.indexOf("fifth") > -1 && command.indexOf("news") > -1){
			this.state.selectedUrl = this.state.newsFeed[4].url;
		}else if(command.indexOf("show") > -1 && command.indexOf("calendar") > -1){
			this.state.selectedUrl = "https://calendar.google.com/calendar/embed?src=heedoo21c%40gmail.com&ctz=America/New_York";
		}else{
			//dont understand
			this.closeModal();
			return;
		}

		this.openModal();
	},

	getSchedule : function(){

		var self = this;

		homeService.getSchedule().then((res)=>{
			 self.setState({
				 schedules : res.items
	    });
		}, (err)=>{
			console.log(err);
		});
	},

	openModal : function(_url){
		this.setState({isShow: true});
	},

	closeModal : function(){
		this.setState({isShow: false});
	},

	render () {

		var items = []; // row UI container
		var scheduleList = []; // row UI container
		var dailyWeatherBox = [];

		this.state.newsFeed.map( (item, i) => {
			if(i < 5){
				items.push(

						{"∙ " + item.title}

			    );
			}
		});

		this.state.schedules.map( (schedule, x) => {
			scheduleList.push(

					{"∙ " + moment(schedule.start.dateTime).format('ll')} {schedule.summary}

				);
		});

		this.state.dailyWeather.map( (_daily, j) => {

			dailyWeatherBox.push(

{moment(_daily.time*1000).format("ddd")}

						<spen>{Math.round(parseFloat(_daily.temperatureMax))} </spen> <spen style={{opacity:0.7}}>{Math.round(parseFloat(_daily.temperatureMin))} </spen>

			);
		});

		return (

{this.getUrl()}}>{this.state.temperature}°

					{this.closeModal()}}>

						<Clock name="Clock" UTCOffset="-5"/>

{this.state.weatherCurrentSummary}

							{dailyWeatherBox}

{this.state.day}

{this.state.date}

							  {items}

My Schedule

								  {scheduleList}

 this.getWeather() }>

					{ this.state.isShow ?
          <Popout title='Broswer' onClosing={this.closeModal} url={this.state.selectedUrl}>

          </Popout> : false }

		);
	}
});

/*

 this.getWeather() }> Weather

*/
<commit_msg>no message<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
var CONFIG = JSON.parse(localStorage.getItem('CONFIG'));
var moment = require("moment");
var homeService = require("../home/homeService");
var Defaults = require('../../mixins/Defaults');
var Clock =  require('../../../client/components/clock');
import Popout from 'react-popout';

import io from 'socket.io-client';
var socket = io('http://localhost:3000');

module.exports = React.createClass({
	displayName: 'VIEW_Home',
	getInitialState: function() {
		return {
			viewName :"Home",
			temperature : '',
			day : '',
			date : '',
			weatherDesc : '',
			weatherIcon : '',
			iconPath : '',
			weatherCurrentSummary : '',
			weatherDailySummary : '',
			dailyWeather : [],
			newsFeed : [],
			schedules : [],
			isShow : false,
			selectedUrl : '',
			currentCommand : 'a'
		};
	},
	componentDidMount: function() {
		var self = this;
		this.getWeather();
		this.getNews();
		this.getSchedule();

		socket.on('receiveCommand', function(data) {
				console.log("command: ", data);
				self.handleCommand(data);
		});

	},

	openView: function(_viewName) {
		window.open(CONFIG.currentEnv.endpoint + _viewName, '_self', false); //open home
	},
	lookupIcon:function(_icon){
		var path = "";
		var icons = [{type:'clear-day',path :"images/weather/Sun.png"},//# clear sky day
		{type:'wind',path :"images/weather/Wind.png"},//#wind
		{type:'cloudy',path :"images/weather/Cloud.png"},//#cloudy day
		{type:'partly-cloudy-day',path :"images/weather/PartlySunny.png"},//# partly cloudy day
		{type:'rain',path :"images/weather/Rain.png"},
		{type:'snow',path :"images/weather/Snow.png"},
		{type:'snow-thin',path :"images/weather/Snow.png"},
		{type:'fog',path :"images/weather/Haze.png"},
		{type:'clear-night',path :"images/weather/Moon.png"},
		{type:'partly-cloudy-night',path :"images/weather/PartlyMoon.png"},
		{type:'thunderstorm',path :"images/weather/Storm.png"},
		{type:'tornado',path :"images/weather/Tornado.png"},
		{type:'hail',path :"images/weather/Hail.png"}];

		for(var i in icons){
			if(icons[i].type == _icon){
				path = icons[i].path;
			}
		}

		return path;

	},
	getWeather : function(){

		var self = this;
		var now = new Date();

		homeService.getWeather().then((res)=>{

			self.setState({
		    temperature: Math.round(parseFloat(res.currently.temperature)),
				weatherIcon : self.lookupIcon(res.currently.icon),
				weatherCurrentSummary: res.currently.summary,
				weatherDailySummary : res.daily.summary,
				dailyWeather : res.daily.data,
				day : moment(now).format('dddd'),
				date : moment(now).format('ll'),
				timer : 0
	    });

		}, (err)=>{
			console.log(err);
		});
	},
	getNews : function(){
		var self = this;
		homeService.getNews().then((res)=>{
			self.setState({
				newsFeed: res.articles
		  });
		}, (err)=>{
			console.log(err);
		});
	},

	handleCommand: function(_data){

		if(_data.type == "calendar" || _data.type == "news"){

			this.getUrl(_data.url);

		}else if(_data.type == "weather"){

		}else{

		}

	},

	getUrl :function(_url){

		if(command.indexOf("first") > -1 && command.indexOf("news") > -1){
			this.state.selectedUrl = this.state.newsFeed[0].url;
		}else if(command.indexOf("second") > -1 && command.indexOf("news") > -1){
			this.state.selectedUrl = this.state.newsFeed[1].url;
		}else if(command.indexOf("third") > -1 && command.indexOf("news") > -1){
			this.state.selectedUrl = this.state.newsFeed[2].url;
		}else if(command.indexOf("fourth") > -1 && command.indexOf("news") > -1){
			this.state.selectedUrl = this.state.newsFeed[3].url;
		}else if(command.indexOf("fifth") > -1 && command.indexOf("news") > -1){
			this.state.selectedUrl = this.state.newsFeed[4].url;
		}else if(command.indexOf("show") > -1 && command.indexOf("calendar") > -1){
			this.state.selectedUrl = _url;
		}else{
			//dont understand
			this.closeModal();
			return;
		}

		this.openModal();
	},

	getSchedule : function(){

		var self = this;

		homeService.getSchedule().then((res)=>{
			 self.setState({
				 schedules : res.items
	    });
		}, (err)=>{
			console.log(err);
		});
	},

	openModal : function(_url){
		this.setState({isShow: true});
	},

	closeModal : function(){
		this.setState({isShow: false});
	},

	render () {

		var items = []; // row UI container
		var scheduleList = []; // row UI container
		var dailyWeatherBox = [];

		this.state.newsFeed.map( (item, i) => {
			if(i < 5){
				items.push(

						{"∙ " + item.title}

			    );
			}
		});

		this.state.schedules.map( (schedule, x) => {
			scheduleList.push(

					{"∙ " + moment(schedule.start.dateTime).format('ll')} {schedule.summary}

				);
		});

		this.state.dailyWeather.map( (_daily, j) => {

			dailyWeatherBox.push(

{moment(_daily.time*1000).format("ddd")}

						<spen>{Math.round(parseFloat(_daily.temperatureMax))} </spen> <spen style={{opacity:0.7}}>{Math.round(parseFloat(_daily.temperatureMin))} </spen>

			);
		});

		return (

{this.getUrl()}}>{this.state.temperature}°

					{this.closeModal()}}>

						<Clock name="Clock" UTCOffset="-5"/>

{this.state.weatherCurrentSummary}

							{dailyWeatherBox}

{this.state.day}

{this.state.date}

							  {items}

My Schedule

								  {scheduleList}

 this.getWeather() }>

					{ this.state.isShow ?
          <Popout title='Broswer' onClosing={this.closeModal} url={this.state.selectedUrl}>

          </Popout> : false }

		);
	}
});

/*

 this.getWeather() }> Weather

*/
<|endoftext|>


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

	var roomscrolloffset = 0.0;
	var actionscrolloffset = 0.3;

	var content;
	var pending_look;
	var waiting_for_room_description;
	var shown_user_list;
	var realms;

	var current_text_div = null;
	var current_status_div = null;
	var edit_button = null;
	var editcontrols = null;

	var scroll_position = -1;

	var init = function()
	{
    	content = null;
    	pending_look = null;
    	realms = null;
    	waiting_for_room_description = true;
    	shown_user_list = false;
	};

	var updateScrollPosition = function()
	{
		if (scroll_position == -1)
			scroll_position = $("#padding").offset().top;
	};

	var adjustScrolling = function(room)
	{
		if (room && (scroll_position == -1))
			updateScrollPosition();

		if (scroll_position != -1)
		{
	    	var menubarheight = $("#menubar").height();
	    	var screenheight = $(window).height();

	    	var voffset = scroll_position - menubarheight*2;
	    	if (!room)
	    		voffset -= screenheight * 0.2;

	    	$('html, body').animate(
	    		{
	    			scrollTop: voffset,
	    			duration: W.Effects.DefaultDuration,
	    			easing: W.Effects.DefaultEasing
	    		}
	    	);

	    	scroll_position = -1;
		}
	};

	var update_game_page = function()
	{
		if (pending_look)
			W.GamePage.LookEvent(pending_look);
		if (realms)
			W.GamePage.RealmsEvent(realms);
	};

	var update_realm_map = function()
	{
		if (W.CurrentRealm.uid === W.Userid)
		{
			var realm = realms.realms[W.CurrentRealm.id];
			if (realm)
				W.RealmEditor.Show(realm);
			else
			{
				/* Haven't had an update for this realm yet --- one will be
				 * along in a minute. */
			}
		}
    	else
    		W.RealmEditor.Hide();
	};

    W.GamePage =
    {
        Show: function ()
        {
        	init();

            $("#page").load("game.html",
            	function ()
            	{
            		console.log("game page loaded");

            		W.StandardMarkup();
            		content = $("#playarea");

                    $("#chatinput").keydown(
                        function (event)
                        {
                            if (event.keyCode === 13)
                            {
                            	var msg = $("#chatinput").text();
                            	$("#chatinput").text("");
                            	msg = msg.trim();
                            	if (msg != "")
                            	{
                            		W.Socket.Send(
                            			{
                            				command: "say",
                            				text: msg
                            			}
                            		);

                            		updateScrollPosition();
                            	}
                            }
                        }
                    );

                    $("#warptoentrypoint")
                    	.unbind()
                    	.click(
                        	function (event)
                        	{
                        		W.Socket.Send(
                        			{
                        			 	command: "warp",
                        			 	instance: W.CurrentInstance
                        			}
                        		);
                        		return false;
                        	}
                        );

                    $("#actionsarea").hide();
                    $("#editbutton").hide();

                    $("#menulogout")
                    	.unbind()
                    	.click(W.GamePage.LogoutEvent);

            		$("#page").hide();
            		W.Effects.ShowPage($("#page"))
            			.promise()
            			.done(update_game_page);
            	}
            );
        },

        MovedEvent: function(message)
        {
        	current_text_div.addClass("scrollback");
        	current_status_div.addClass("scrollback");
        	if (edit_button)
        	{
       			W.Effects.RemoveButton(edit_button);
        		edit_button = null;
        	}

        	waiting_for_room_description = true;
        	adjustScrolling(true);
        },

        LookEvent: function(message)
        {
        	if (!content)
        	{
        		pending_look = message;
        		return;
        	}
        	else
        		pending_look = null;

        	var update_text = function()
        	{
            	W.CurrentInstance = message.instance;
            	W.CurrentRealm = message.realm;
            	W.CurrentRoom = message.room;

            	$("#realmname").text(W.CurrentRealm.name);
            	$("#realmowner").text(W.CurrentRealm.user);
            	$("#instance").text(W.CurrentInstance);

            	var header = $("
").text(message.title);
            	var body = $("
");

            	var paras = message.description.split("\n");
            	for (var i = 0; i < paras.length; i++)
            		body.append($("
").text(paras[i]));

            	current_text_div.empty();

            	if (message.editable)
            	{
        			edit_button = $("#editbutton")
        				.clone()
        				.removeClass("template")
        				.appendTo(header)
        				.show()
        				.click(
        					function()
        					{
        						W.RoomEditor.Show(message);
        						return false;
        					}
        				);

        			W.Effects.ShowButton(edit_button);
            	}

            	current_text_div.append(header, body);

            	if (!shown_user_list)
            	{
            		var players = [];

            		$.each(message.contents,
            			function(name, uid)
            			{
            				if (uid != W.Userid)
            					players.push(name);
            			}
            		);

            		players.sort();

            		if (players.length > 0)
            		{
                		var s = "";
                		for (var i=0; i<(players.length-1); i++)
                			s += players[i] + ", ";

				if (players.length == 1)
					s = players[0] + " is here.";
                		else if (players.length > 1)
                			s += " and " + players[players.length-1] + " are here.";

           				$("
").text(s).appendTo(current_status_div);
            		}

            		shown_user_list = true;
            	}

            	update_realm_map();
        	};

        	if (waiting_for_room_description)
        	{
        		waiting_for_room_description = false;

        		current_text_div = $("
")
        			.hide()
        			.appendTo(content);

        		current_status_div = $("
")
        			.hide()
        			.appendTo(content);

        		update_text();
        		W.Effects.NewText(current_text_div, current_status_div);
        	}
        	else
        	{
        		W.Effects.HideText(current_text_div).promise().done(
        			function()
        			{
                		update_text();
                		W.Effects.ShowText(current_text_div);
        			}
        		);
        	}

        	var update_actions = function()
        	{
            	if (message.editable)
            	{
        			$("#actionseditbutton")
        				.show()
        				.unbind()
        				.click(
        					function()
        					{
        						W.RoomEditor.Show(message);
        						return false;
        					}
        				);
            	}
            	else
            		$("#actionseditbutton").hide();

            	var list = $("#actionslist");
            	list.empty();

            	var count = 0;
            	$.each(message.actions,
            		function (id, action)
            		{
                		var e = $("");
                		e.text(action.description);

                		e.click(
                			function()
                    		{
                    			W.Socket.Send(
                    				{
                    				 	command: "action",
                    				 	actionid: id
                    				}
                    			);

                    			updateScrollPosition();
                    			return false;
                    		}
                		);

                		var li = $("
");
                		li.append(e);
                		list.append(li);

                		count++;
            		}
            	);

            	if (count == 0)
            		list.append("
(There's nothing to do here.)
");
        	};

        	var show_actions = function()
        	{
    			update_actions();
    			W.Effects.ShowActions($("#actionsarea"));
        	};

        	if ($("#actionsarea").is(":visible"))
        	{
        		W.Effects.HideActions($("#actionsarea"))
        			.promise()
        			.done(show_actions);
        	}
        	else
        		show_actions();
        },

        ArrivedEvent: function(message)
        {
        	if (!current_status_div)
        		return;

			var m = $("
");
			m.text(message.user+" has arrived.");

			current_status_div.append(m);
			W.Effects.NewText(m);
        	adjustScrolling(false);
        },

        DepartedEvent: function(message)
        {
        	if (!current_status_div)
        		return;

			var m = $("
");
			m.text(message.user+" has left.");

			current_status_div.append(m);
			W.Effects.NewText(m);
        	adjustScrolling(false);
        },

        SpeechEvent: function(message)
        {
        	var s;
        	if (message.uid === W.Userid)
        		s = 'You say, “';
        	else
        		s = message.user + ' says, “';
        	s += message.text;
        	s += '”';

        	var m = $("
");
        	m.text(s);
        	m.hide();
        	current_status_div.append(m);
        	W.Effects.NewText(m);
        	adjustScrolling(false);
        },

        ActivityEvent: function(message)
        {
        	var m = $("
");
        	m.textWithBreaks(message.message);
        	m.hide();
        	current_status_div.append(m);
        	W.Effects.NewText(m);
        	adjustScrolling(false);
        },

        RealmsEvent: function(message)
        {
       		realms = message;
        	if (!content || !message)
        		return;

        	var srl = $("#specialrealmlist");
        	srl.empty();

        	$.each(message.specialrealms,
        		function (id, realm)
        		{
        			var a = $("").text(realm.name);

        			a.click(
        				function()
        				{
        					W.Socket.Send(
        						{
        						 	command: "warp",
        						 	instance: realm.instance
        						}
        					);
                    		return false;
        				}
        			);

        			srl.append($("
").append(a));
        		}
        	);

        	srl.append($("
"));
        	var li = $("
");
        	$("Warp to instance...")
        		.click(
        			function()
        			{
        				W.GamePage.WarpToInstanceEvent();
        				return false;
        			}
        		).appendTo(li);
        	li.appendTo(srl);

        	var yrl = $("#yourrealmlist");
        	yrl.empty();
        	$.each(message.realms,
        		function (id, realm)
        		{
        			var li = $("
");

        			var instanceid = realm.instances[0];

					var a = $("");
					a.text(realm.name)

        			a.click(
        				function()
        				{
        					W.Socket.Send(
        						{
        						 	command: "warp",
        						 	instance: instanceid
        						}
        					);
                    		return false;
        				}
        			);

					li.append(a);
        			yrl.append(li);
        		}
        	);

        	$("
").appendTo(yrl);

        	var createbutton = $("Create new realm")
            	.click(
                	function (event)
                	{
                		W.Socket.Send(
                			{
                				command: "createrealm",
                				name: "An Empty Realm"
                			}
                		);
                		return false;
                	}
                );
        	$("
").append(createbutton).appendTo(yrl);

        	update_realm_map();
        },

        LogoutEvent: function()
        {
        	W.Effects.HidePage($("#page"))
        		.promise()
        		.done(W.Socket.Disconnect);
        },

        WarpToInstanceEvent: function()
        {
        	$("#warptoinstancecancelbutton")
        		.unbind()
        		.click(
        			function()
        			{
        				W.Effects.HideDialogue($("#warptoinstance"));
        			}
        		);

        	$("#warptoinstanceokbutton")
        		.unbind()
        		.click(
        			function()
        			{
                		W.Socket.Send(
                			{
                			 	command: "warp",
                			 	instance: $("#warptoinstanceid").text()
                			}
                		);

        				W.Effects.HideDialogue($("#warptoinstance"));
        			}
        		);

        	$("#warptoinstanceid").text("");

        	return W.Effects.ShowDialogue($("#warptoinstance"));
        }
    };
}
)();
<commit_msg>Fix race where if the initial look event came in before the realms event, we would try to deference an unset variable. Fix bug where the player list would not be shown once the player had moved.<commit_after>(function()
{
	"use strict";

	var roomscrolloffset = 0.0;
	var actionscrolloffset = 0.3;

	var content;
	var pending_look;
	var waiting_for_room_description;
	var shown_user_list;
	var realms;

	var current_text_div = null;
	var current_status_div = null;
	var edit_button = null;
	var editcontrols = null;

	var scroll_position = -1;

	var init = function()
	{
    	content = null;
    	pending_look = null;
    	realms = null;
    	waiting_for_room_description = true;
    	shown_user_list = false;
	};

	var updateScrollPosition = function()
	{
		if (scroll_position == -1)
			scroll_position = $("#padding").offset().top;
	};

	var adjustScrolling = function(room)
	{
		if (room && (scroll_position == -1))
			updateScrollPosition();

		if (scroll_position != -1)
		{
	    	var menubarheight = $("#menubar").height();
	    	var screenheight = $(window).height();

	    	var voffset = scroll_position - menubarheight*2;
	    	if (!room)
	    		voffset -= screenheight * 0.2;

	    	$('html, body').animate(
	    		{
	    			scrollTop: voffset,
	    			duration: W.Effects.DefaultDuration,
	    			easing: W.Effects.DefaultEasing
	    		}
	    	);

	    	scroll_position = -1;
		}
	};

	var update_game_page = function()
	{
		if (pending_look)
			W.GamePage.LookEvent(pending_look);
		if (realms)
			W.GamePage.RealmsEvent(realms);
	};

	var update_realm_map = function()
	{
		if (W.CurrentRealm.uid === W.Userid)
		{
			var realm = null;
			if (realms)
				realm = realms.realms[W.CurrentRealm.id];
			if (realm)
				W.RealmEditor.Show(realm);
			else
			{
				/* Haven't had an update for this realm yet --- one will be
				 * along in a minute. */
			}
		}
    	else
    		W.RealmEditor.Hide();
	};

    W.GamePage =
    {
        Show: function ()
        {
        	init();

            $("#page").load("game.html",
            	function ()
            	{
            		console.log("game page loaded");

            		W.StandardMarkup();
            		content = $("#playarea");

                    $("#chatinput").keydown(
                        function (event)
                        {
                            if (event.keyCode === 13)
                            {
                            	var msg = $("#chatinput").text();
                            	$("#chatinput").text("");
                            	msg = msg.trim();
                            	if (msg != "")
                            	{
                            		W.Socket.Send(
                            			{
                            				command: "say",
                            				text: msg
                            			}
                            		);

                            		updateScrollPosition();
                            	}
                            }
                        }
                    );

                    $("#warptoentrypoint")
                    	.unbind()
                    	.click(
                        	function (event)
                        	{
                        		W.Socket.Send(
                        			{
                        			 	command: "warp",
                        			 	instance: W.CurrentInstance
                        			}
                        		);
                        		return false;
                        	}
                        );

                    $("#actionsarea").hide();
                    $("#editbutton").hide();

                    $("#menulogout")
                    	.unbind()
                    	.click(W.GamePage.LogoutEvent);

            		$("#page").hide();
            		W.Effects.ShowPage($("#page"))
            			.promise()
            			.done(update_game_page);
            	}
            );
        },

        MovedEvent: function(message)
        {
        	current_text_div.addClass("scrollback");
        	current_status_div.addClass("scrollback");
        	if (edit_button)
        	{
       			W.Effects.RemoveButton(edit_button);
        		edit_button = null;
        	}

        	waiting_for_room_description = true;
		shown_user_list = false;
        	adjustScrolling(true);
        },

        LookEvent: function(message)
        {
        	if (!content)
        	{
        		pending_look = message;
        		return;
        	}
        	else
        		pending_look = null;

        	var update_text = function()
        	{
            	W.CurrentInstance = message.instance;
            	W.CurrentRealm = message.realm;
            	W.CurrentRoom = message.room;

            	$("#realmname").text(W.CurrentRealm.name);
            	$("#realmowner").text(W.CurrentRealm.user);
            	$("#instance").text(W.CurrentInstance);

            	var header = $("
").text(message.title);
            	var body = $("
");

            	var paras = message.description.split("\n");
            	for (var i = 0; i < paras.length; i++)
            		body.append($("
").text(paras[i]));

            	current_text_div.empty();

            	if (message.editable)
            	{
        			edit_button = $("#editbutton")
        				.clone()
        				.removeClass("template")
        				.appendTo(header)
        				.show()
        				.click(
        					function()
        					{
        						W.RoomEditor.Show(message);
        						return false;
        					}
        				);

        			W.Effects.ShowButton(edit_button);
            	}

            	current_text_div.append(header, body);

            	if (!shown_user_list)
            	{
            		var players = [];

            		$.each(message.contents,
            			function(name, uid)
            			{
            				if (uid != W.Userid)
            					players.push(name);
            			}
            		);

            		players.sort();

            		if (players.length > 0)
            		{
                		var s = "";
                		for (var i=0; i<(players.length-1); i++)
                			s += players[i] + ", ";

				if (players.length == 1)
					s = players[0] + " is here.";
                		else if (players.length > 1)
                			s += " and " + players[players.length-1] + " are here.";

           				$("
").text(s).appendTo(current_status_div);
            		}

            		shown_user_list = true;
            	}

            	update_realm_map();
        	};

        	if (waiting_for_room_description)
        	{
        		waiting_for_room_description = false;

        		current_text_div = $("
")
        			.hide()
        			.appendTo(content);

        		current_status_div = $("
")
        			.hide()
        			.appendTo(content);

        		update_text();
        		W.Effects.NewText(current_text_div, current_status_div);
        	}
        	else
        	{
        		W.Effects.HideText(current_text_div).promise().done(
        			function()
        			{
                		update_text();
                		W.Effects.ShowText(current_text_div);
        			}
        		);
        	}

        	var update_actions = function()
        	{
            	if (message.editable)
            	{
        			$("#actionseditbutton")
        				.show()
        				.unbind()
        				.click(
        					function()
        					{
        						W.RoomEditor.Show(message);
        						return false;
        					}
        				);
            	}
            	else
            		$("#actionseditbutton").hide();

            	var list = $("#actionslist");
            	list.empty();

            	var count = 0;
            	$.each(message.actions,
            		function (id, action)
            		{
                		var e = $("");
                		e.text(action.description);

                		e.click(
                			function()
                    		{
                    			W.Socket.Send(
                    				{
                    				 	command: "action",
                    				 	actionid: id
                    				}
                    			);

                    			updateScrollPosition();
                    			return false;
                    		}
                		);

                		var li = $("
");
                		li.append(e);
                		list.append(li);

                		count++;
            		}
            	);

            	if (count == 0)
            		list.append("
(There's nothing to do here.)
");
        	};

        	var show_actions = function()
        	{
    			update_actions();
    			W.Effects.ShowActions($("#actionsarea"));
        	};

        	if ($("#actionsarea").is(":visible"))
        	{
        		W.Effects.HideActions($("#actionsarea"))
        			.promise()
        			.done(show_actions);
        	}
        	else
        		show_actions();
        },

        ArrivedEvent: function(message)
        {
        	if (!current_status_div)
        		return;

			var m = $("
");
			m.text(message.user+" has arrived.");

			current_status_div.append(m);
			W.Effects.NewText(m);
        	adjustScrolling(false);
        },

        DepartedEvent: function(message)
        {
        	if (!current_status_div)
        		return;

			var m = $("
");
			m.text(message.user+" has left.");

			current_status_div.append(m);
			W.Effects.NewText(m);
        	adjustScrolling(false);
        },

        SpeechEvent: function(message)
        {
        	var s;
        	if (message.uid === W.Userid)
        		s = 'You say, “';
        	else
        		s = message.user + ' says, “';
        	s += message.text;
        	s += '”';

        	var m = $("
");
        	m.text(s);
        	m.hide();
        	current_status_div.append(m);
        	W.Effects.NewText(m);
        	adjustScrolling(false);
        },

        ActivityEvent: function(message)
        {
        	var m = $("
");
        	m.textWithBreaks(message.message);
        	m.hide();
        	current_status_div.append(m);
        	W.Effects.NewText(m);
        	adjustScrolling(false);
        },

        RealmsEvent: function(message)
        {
       		realms = message;
        	if (!content || !message)
        		return;

        	var srl = $("#specialrealmlist");
        	srl.empty();

        	$.each(message.specialrealms,
        		function (id, realm)
        		{
        			var a = $("").text(realm.name);

        			a.click(
        				function()
        				{
        					W.Socket.Send(
        						{
        						 	command: "warp",
        						 	instance: realm.instance
        						}
        					);
                    		return false;
        				}
        			);

        			srl.append($("
").append(a));
        		}
        	);

        	srl.append($("
"));
        	var li = $("
");
        	$("Warp to instance...")
        		.click(
        			function()
        			{
        				W.GamePage.WarpToInstanceEvent();
        				return false;
        			}
        		).appendTo(li);
        	li.appendTo(srl);

        	var yrl = $("#yourrealmlist");
        	yrl.empty();
        	$.each(message.realms,
        		function (id, realm)
        		{
        			var li = $("
");

        			var instanceid = realm.instances[0];

					var a = $("");
					a.text(realm.name)

        			a.click(
        				function()
        				{
        					W.Socket.Send(
        						{
        						 	command: "warp",
        						 	instance: instanceid
        						}
        					);
                    		return false;
        				}
        			);

					li.append(a);
        			yrl.append(li);
        		}
        	);

        	$("
").appendTo(yrl);

        	var createbutton = $("Create new realm")
            	.click(
                	function (event)
                	{
                		W.Socket.Send(
                			{
                				command: "createrealm",
                				name: "An Empty Realm"
                			}
                		);
                		return false;
                	}
                );
        	$("
").append(createbutton).appendTo(yrl);

        	update_realm_map();
        },

        LogoutEvent: function()
        {
        	W.Effects.HidePage($("#page"))
        		.promise()
        		.done(W.Socket.Disconnect);
        },

        WarpToInstanceEvent: function()
        {
        	$("#warptoinstancecancelbutton")
        		.unbind()
        		.click(
        			function()
        			{
        				W.Effects.HideDialogue($("#warptoinstance"));
        			}
        		);

        	$("#warptoinstanceokbutton")
        		.unbind()
        		.click(
        			function()
        			{
                		W.Socket.Send(
                			{
                			 	command: "warp",
                			 	instance: $("#warptoinstanceid").text()
                			}
                		);

        				W.Effects.HideDialogue($("#warptoinstance"));
        			}
        		);

        	$("#warptoinstanceid").text("");

        	return W.Effects.ShowDialogue($("#warptoinstance"));
        }
    };
}
)();
<|endoftext|>


<commit_before>;(function () {
	var roundNumber = function (number, decimals) {
		return Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals);
	},

	toArray = function (object) {
		return [].slice.call(object);
	},

	convert = function (value, from, to, base, dpi, decimals) {
		var units = from + '-' + to,
			result,
			formulas = {
				'cm-em': value / 0.42175176,
				'cm-in': value * 0.39,
				'cm-mm': value * 10,
				'cm-pc': value / 0.42175176,
				'cm-pt': value * 28.3464566929,
				'cm-%': value / base * 100 / 2.54 * dpi,
				'cm-px': value / 2.54 * dpi,

				'em-cm': value * 0.42175176,
				'em-in': value * 0.166044,
				'em-mm': value / 0.237106301584,
				'em-pc': value,
				'em-pt': value * 11.955168,
				'em-%': value * 100,
				'em-px': value * base,

				'in-cm': value * 2.54,
				'in-em': value / 0.166044,
				'in-mm': value * 2.54 * 10,
				'in-pc': value / 0.166044,
				'in-pt': value / 0.014842519685,
				'in-%': value / base * 100 * dpi,
				'in-px': value * dpi,

				'mm-cm': value / 10,
				'mm-em': value * 0.237106301584,
				'mm-in': value * 0.39 / 10,
				'mm-pc': value / 4.42175176,
				'mm-pt': value / 0.352777777778,
				'mm-%': value / base * 100 / 2.54 * dpi / 10,
				'mm-px': value / 2.54 * dpi / 10,

				'pc-cm': value * 0.42175176,
				'pc-em': value,
				'pc-in': value * 0.166044,
				'pc-mm': value * 4.42175176,
				'pc-pt': value / 0.0836458341698,
				'pc-%': value * 100,
				'pc-px': value * base,

				'pt-cm': value / 28.3464566929,
				'pt-em': value / 11.955168,
				'pt-in': value * 0.014842519685,
				'pt-mm': value * 0.352777777778,
				'pt-pc': value * 0.0836458341698,
				'pt-%': value / (base - 4) * 100,
				'pt-px': value * 96 / 72,

				'%-cm': value * base / 100 * 2.54 / dpi,
				'%-em': value / 100,
				'%-in': value * base / 100 / dpi,
				'%-mm': value * base / 100 * 2.54 / dpi * 10,
				'%-pc': value / 100,
				'%-pt': value * (base - 4) / 100,
				'%-px': value * base / 100,

				'px-cm': value * 2.54 / dpi,
				'px-em': value / base,
				'px-in': value / dpi,
				'px-mm': value * 2.54 / dpi * 10,
				'px-pc': value / base,
				'px-pt': value * 72 / 96,
				'px-%': value / base * 100
			};

		result = formulas[units] || value;

		return (isNaN(result) ? 'N/A' : roundNumber(result, decimals) + to);
	},

	setupForm = function () {
		var selects = document.querySelectorAll('select'),
			settings = document.querySelectorAll('.settings input'),
			fragment = document.createDocumentFragment(),
			options = [],
			units = ['cm', 'em', 'in', 'mm', 'pc', 'pt', '%', 'px'];

		// Add the units
		units.forEach(function (unit) {
			var option = document.createElement('option');

			option.value = unit;
			option.textContent = unit;

			fragment.appendChild(option);
		});

		toArray(selects).forEach(function (select) {
			var fromUnit = localStorage.getItem('from-unit'),
				toUnit = localStorage.getItem('to-unit');

			select.appendChild(fragment.cloneNode(true));
		});

		// Add settings
		toArray(settings).forEach(function (setting) {
			var name = setting.name;

			setting.value = localStorage.getItem(name) || setting.value;
		});
	},

	run = function () {
		document.querySelector('.result').textContent = convert(
			document.querySelector('.from').value,
			document.querySelector('.from-unit').value,
			document.querySelector('.to-unit').value,
			document.querySelector('.base-size').value,
			document.querySelector('.dpi').value,
			document.querySelector('.decimals').value
		);
	};

	window.addEventListener('DOMContentLoaded', function () {
		var elements = toArray(document.querySelectorAll('input, select'));

		setupForm();

		elements.forEach(function (element) {
			element.addEventListener('change', run);
			element.addEventListener('keyup', run);
		});

		// Toogle display of setting forms
		document.querySelector('.toggle').addEventListener('click', function (e) {
			e.preventDefault();

			document.querySelector('.settings').classList.toggle('show');
		});

		// Save all values once every 30 seconds
		setInterval(function () {
			elements.forEach(function (element) {
				localStorage.setItem(element.name, element.value);
			});
		}, 30000);
	});
}());<commit_msg>Auto save from value and selected units<commit_after>;(function () {
	var roundNumber = function (number, decimals) {
		return Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals);
	},

	toArray = function (object) {
		return [].slice.call(object);
	},

	convert = function (value, from, to, base, dpi, decimals) {
		var units = from + '-' + to,
			result,
			formulas = {
				'cm-em': value / 0.42175176,
				'cm-in': value * 0.39,
				'cm-mm': value * 10,
				'cm-pc': value / 0.42175176,
				'cm-pt': value * 28.3464566929,
				'cm-%': value / base * 100 / 2.54 * dpi,
				'cm-px': value / 2.54 * dpi,

				'em-cm': value * 0.42175176,
				'em-in': value * 0.166044,
				'em-mm': value / 0.237106301584,
				'em-pc': value,
				'em-pt': value * 11.955168,
				'em-%': value * 100,
				'em-px': value * base,

				'in-cm': value * 2.54,
				'in-em': value / 0.166044,
				'in-mm': value * 2.54 * 10,
				'in-pc': value / 0.166044,
				'in-pt': value / 0.014842519685,
				'in-%': value / base * 100 * dpi,
				'in-px': value * dpi,

				'mm-cm': value / 10,
				'mm-em': value * 0.237106301584,
				'mm-in': value * 0.39 / 10,
				'mm-pc': value / 4.42175176,
				'mm-pt': value / 0.352777777778,
				'mm-%': value / base * 100 / 2.54 * dpi / 10,
				'mm-px': value / 2.54 * dpi / 10,

				'pc-cm': value * 0.42175176,
				'pc-em': value,
				'pc-in': value * 0.166044,
				'pc-mm': value * 4.42175176,
				'pc-pt': value / 0.0836458341698,
				'pc-%': value * 100,
				'pc-px': value * base,

				'pt-cm': value / 28.3464566929,
				'pt-em': value / 11.955168,
				'pt-in': value * 0.014842519685,
				'pt-mm': value * 0.352777777778,
				'pt-pc': value * 0.0836458341698,
				'pt-%': value / (base - 4) * 100,
				'pt-px': value * 96 / 72,

				'%-cm': value * base / 100 * 2.54 / dpi,
				'%-em': value / 100,
				'%-in': value * base / 100 / dpi,
				'%-mm': value * base / 100 * 2.54 / dpi * 10,
				'%-pc': value / 100,
				'%-pt': value * (base - 4) / 100,
				'%-px': value * base / 100,

				'px-cm': value * 2.54 / dpi,
				'px-em': value / base,
				'px-in': value / dpi,
				'px-mm': value * 2.54 / dpi * 10,
				'px-pc': value / base,
				'px-pt': value * 72 / 96,
				'px-%': value / base * 100
			};

		result = formulas[units] || value;

		return (isNaN(result) ? 'N/A' : roundNumber(result, decimals) + to);
	},

	setupForm = function () {
		var from = document.querySelector('.from'),
			selects = document.querySelectorAll('select'),
			settings = document.querySelectorAll('.settings input'),
			fragment = document.createDocumentFragment(),
			options = [],
			units = ['cm', 'em', 'in', 'mm', 'pc', 'pt', '%', 'px'];

		// Set from value
		from.value = localStorage.getItem(from.name) || '';

		// Add the units
		units.forEach(function (unit) {
			var option = document.createElement('option');

			option.value = unit;
			option.textContent = unit;

			fragment.appendChild(option);
		});

		toArray(selects).forEach(function (select) {
			var unit = localStorage.getItem(select.name),
				selected;

			if (unit) {
				selected = fragment.querySelector('[value=' + unit + ']');
				selected.defaultSelected = true;
			}

			select.appendChild(fragment.cloneNode(true));

			if (selected) {
				selected.defaultSelected = false;
			}
		});

		// Add settings
		toArray(settings).forEach(function (setting) {
			var name = setting.name;

			setting.value = localStorage.getItem(name) || setting.value;
		});
	},

	run = function () {
		document.querySelector('.result').textContent = convert(
			document.querySelector('.from').value,
			document.querySelector('.from-unit').value,
			document.querySelector('.to-unit').value,
			document.querySelector('.base-size').value,
			document.querySelector('.dpi').value,
			document.querySelector('.decimals').value
		);
	};

	window.addEventListener('DOMContentLoaded', function () {
		var elements = toArray(document.querySelectorAll('input, select'));

		setupForm();

		elements.forEach(function (element) {
			element.addEventListener('change', run);
			element.addEventListener('keyup', run);
		});

		// Toogle display of setting forms
		document.querySelector('.toggle').addEventListener('click', function (e) {
			e.preventDefault();

			document.querySelector('.settings').classList.toggle('show');
		});

		// Save all values once every 30 seconds
		setInterval(function () {
			elements.forEach(function (element) {
				localStorage.setItem(element.name, element.value);
			});
		}, 30000);
	});
}());<|endoftext|>


<commit_before>import axios from 'axios';

const ArticlesApi = {

  fetchAll() {
    const url = `${process.env.API_URL}api/articles`;
    console.log('url : ', url);

    const options = { headers: { 'Content-Type': 'application/json' } };

    return axios.get(url, options)
      .then((response) => {
        console.log('rapide');
        console.log(response.data);
        return response.data;
      })
      .catch((error) => {
        console.log('trop lent');

        return Promise.reject(error);
      });
  },
};

export default ArticlesApi;
<commit_msg>bsr(REC-19) : remove console log<commit_after>import axios from 'axios';

const ArticlesApi = {

  fetchAll() {
    const url = `${process.env.API_URL}api/articles`;
    const options = { headers: { 'Content-Type': 'application/json' } };

    return axios.get(url, options)
      .then(response => response.data);
  },
};

export default ArticlesApi;
<|endoftext|>


<commit_before>$(document).ready(function () {
  window.resetVotes = function () {
    localStorage.votedArray = "";
	  if (localStorage.host) {
    localStorage.setItem("STOP", "true");
    var object = {};
    object["userName"] = localStorage.userID;
     $.ajax({
         async: false,
         type: "POST",
         url: "http://spartify.herokuapp.com/clearVotes",
         dataType: "json",
         data: object,
         success: function (clearedData) {
           localStorage.STOP = "false";
           localStorage.votedArray = "";
	   location.reload();
         }
    });
	  }
}
    if (!document.hidden) {
    var userID;
    var baseURL;
    var searchQry;
    var myDataLength;
    var partyPlaylist;
    var listOfTracks = [];
    $("#filename").on('blur', function () {
	        $("#searchBoxContainer").css("margin-top", "0px !important");
	    	        $("#searchBoxContainer").css("position", "fixed");
	    	        $("#albumArt").css("position", "fixed");
	    	        $("#all").css("display", "block");
	    $("#html").scrollTop(0);
    });
    $("#searchBoxContainer").focus(function () {
       $("#html").scrollTop(0);
	    newToken();
    });
    $("#filename").on('focus', function () {
	        $("#searchBoxContainer").css("margin-top", "0px !important");
	    	        $("#searchBoxContainer").css("position", "absolute");
	    	        $("#albumArt").css("position", "absolute");
	    	        $("#all").css("display", "none");
	    $("#html").scrollTop(0);
	    $("#html").scroll(function(e){ e.preventDefault(); e.stopPropogagtion();});
    });
    $('#filename').on('keypress', function () {
	    $("#html").scroll(function(e){ e.preventDefault(); e.stopPropogagtion();});
   // $("#filename").keydown(function (event) {
       if (event.which === 13) {
	    $("#filename").blur();
            if (document.getElementById('filename').value.toLowerCase() == "logout." && localStorage["complete_access"] != "false" && localStorage["complete_access"] != false)
            {
		function closeWin() {
		    setTimeout(function()
		    {
			localStorage.clear();
    }, 2000);
		}
closeWin();
            }
            else if (document.getElementById('filename').value.toLowerCase() == "fullscreen." || document.getElementById('filename').value.toLowerCase() == "fs.") {
		var elem = document.getElementById("html");
		function toggleFullScreen() {
		  if ((document.fullScreenElement && document.fullScreenElement !== null) ||
		   (!document.mozFullScreen && !document.webkitIsFullScreen)) {
		    if (document.documentElement.requestFullScreen) {
		      document.documentElement.requestFullScreen();
		    } else if (document.documentElement.mozRequestFullScreen) {
		      document.documentElement.mozRequestFullScreen();
		    } else if (document.documentElement.webkitRequestFullScreen) {
		      document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
		    }
		  } else {
		    if (document.cancelFullScreen) {
		      document.cancelFullScreen();
		    } else if (document.mozCancelFullScreen) {
		      document.mozCancelFullScreen();
		    } else if (document.webkitCancelFullScreen) {
		      document.webkitCancelFullScreen();
		    }
		  }
		}
		toggleFullScreen();
		document.getElementById('filename').value = "";
		nextSongs();
            }
		else if (document.getElementById('filename').value.toLowerCase() == "c.") {
			localStorage.votedArray = "";
			window.location.reload();
		}
    else if (document.getElementById('filename').value.toLowerCase() == "clear votes.") {
resetVotes();
}
else if (document.getElementById('filename').value.toLowerCase() == "temp.") {
localStorage.setItem("temp", true);
}
else if (document.getElementById('filename').value.toLowerCase() == "i really want unlimited voting." || document.getElementById('filename').value.toLowerCase() == "uv.") {
resetVotes(1);
                localStorage.setItem("uv", "true");
                $("#filename").val("");
                nextSongs();
}
else if (document.getElementById('filename').value.toLowerCase() == "reload.") {
            	loading();
            	setTimeout(function(){
		window.location.reload();
		}, 1000);
            }
            else if (document.getElementById('filename').value.toLowerCase() == "leave party.") {
            	loading();
                window.localStorage.clear("CT");
                window.localStorage.clear("Snapster");
                window.localStorage.clear("clicked");
                window.localStorage.clear("currentTrack");
                window.localStorage.clear("current_token");
                window.localStorage.clear("complete_access");
                window.localStorage.clear("currentlyPlaying");
                window.localStorage.clear("currentlyPlayingID");
                window.localStorage.clear("currentlyPlayingWC");
                window.localStorage.clear("explicit");
                window.localStorage.clear("host");
                window.localStorage.clear("myData");
                window.localStorage.clear("lastFM");
                window.localStorage.clear("partyid");
                window.localStorage.clear("offsetNumber");
                window.localStorage.clear("totalSongs");
                window.localStorage.clear("url");
                window.localStorage.clear("userID");
                window.location.href = "http://spartify.herokuapp.com/thank-you-host.html";
            }
            else if (document.getElementById('filename').value.toLowerCase() == localStorage["password"].toString().toLowerCase() + ".") {
            	 localStorage["power_voter"] = "yes";
               location.reload();
       	    }
            else if (document.getElementById('filename').value == "") {
		nextSongs();
		$("#albumart").show();
		$("#results").attr("style", "");
		}
            else if (localStorage.Snapster) {
                $.ajax({
                    type: "GET",
                    url: "https://api.spotify.com/v1/users/" + localStorage['userID'] + "/playlists/" + localStorage['Snapster'] + "/tracks",
                    headers: { 'Authorization': 'Bearer ' + access_token  },
                    dataType: "json",
                    data: "formdata",
                    success: function (trackData) {
                        for (var i = 0; i < trackData.items.length; i++) {
                            listOfTracks[i] = trackData.items[i].track.name.toUpperCase() + " " + trackData.items[i].track.artists[0].name.toUpperCase();
                        }
                    }
                });
                try {
                    partyPlaylist = [];
                    baseURL = "https://api.spotify.com/v1/users/";
                    userID = $('#userID2').html();
                    searchQry = document.getElementById('filename').value.toLowerCase();
                    $.ajax({
                        type: "GET",
                        url: "https://api.spotify.com/v1/search?q=" + searchQry + "&type=track,artist&market=us&limit=50&offset=0",
                        headers: { 'Authorization': 'Bearer ' + access_token  },
                        dataType: "json",
                        data: "formdata",
                        success: function (myData) {
                            $("#albumart").hide();
                            $("#results").empty();
                            myDataLength = myData.tracks.items.length;
                            for (i = 0; i < myData.tracks.items.length; i++) {
                                if (localStorage["explicit"] != "true" && localStorage["explicit"] != true) {
                                    if (myData.tracks.items[i].explicit == false || myData.tracks.items[i].explicit == "false" && listOfTracks.indexOf(myData.tracks.items[i].name.toUpperCase() + " " + myData.tracks.items[i].artists[0].name.toUpperCase()) == -1) {
                                        $("#results").append("" + "

" + myData.tracks.items[i].artists[0].name + "

" + myData.tracks.items[i].name + "

 +
 ");
                                    }
                                }
                                else if (listOfTracks.indexOf(myData.tracks.items[i].name.toUpperCase() + " " + myData.tracks.items[i].artists[0].name.toUpperCase()) == -1) {
                                    $("#results").append("" + "

" + myData.tracks.items[i].artists[0].name + "

" + myData.tracks.items[i].name + "

 +
 ");
                                }
                            }
                            $("#results").css("padding-top", "86px");
                            $("#all").fadeIn(1000);
                        }
                    });
            }

                catch (exception) {
					// console.log(exception);
}

}
}
});
window.newSong = function(i) {
    $.ajax({
        type: "POST",
        url: $("#songLink" + i)[0].attributes[4].value,
        headers: { 'Authorization': 'Bearer ' + access_token  },
        dataType: "json",
        data: "formdata",
        success: function (dataFirst) {
            partyPlaylist = [];
            $("#albumart").show();
            $("#albumart").fadeIn(1000);
            $("#results").empty();
            $("#results").css("text-align", "center");
            $("#results").css("padding-top", "298px");
            $.ajax({
                type: "GET",
                url: "https://api.spotify.com/v1/users/" + localStorage['userID'] + "/playlists/" + localStorage['Snapster'] + "/tracks",
                headers: { 'Authorization': 'Bearer ' + access_token  },
                dataType: "json",
                data: "formdata",
                success: function (currentPLData) {
                    $("#filename").val("");
                    $("#results").css("padding-top", "");
                    $("#results").hide().fadeIn('fast');
                    nextSongs();
                }
            });
        }
    });
}

               }
});
<commit_msg>Update newSong.js<commit_after>$(document).ready(function () {
  window.resetVotes = function () {
    localStorage.votedArray = "";
	  if (localStorage.host) {
    localStorage.setItem("STOP", "true");
    var object = {};
    object["userName"] = localStorage.userID;
     $.ajax({
         async: false,
         type: "POST",
         url: "http://spartify.herokuapp.com/clearVotes",
         dataType: "json",
         data: object,
         success: function (clearedData) {
           localStorage.STOP = "false";
           localStorage.votedArray = "";
	   location.reload();
         }
    });
	  }
}
    if (!document.hidden) {
    var userID;
    var baseURL;
    var searchQry;
    var myDataLength;
    var partyPlaylist;
    var listOfTracks = [];
    $("#filename").on('blur', function () {
	        $("#searchBoxContainer").css("margin-top", "0px !important");
	    	        $("#searchBoxContainer").css("position", "fixed");
	    	        $("#albumArt").css("position", "fixed");
	    	        $("#all").css("display", "block");
	    $("#html").scrollTop(0);
    });
    $("#searchBoxContainer").focus(function () {
       $("#html").scrollTop(0);
	    newToken();
    });
    $("#filename").on('focus', function () {
	        $("#searchBoxContainer").css("margin-top", "0px !important");
	    	        $("#searchBoxContainer").css("position", "absolute");
	    	        $("#albumArt").css("position", "absolute");
	    	        $("#all").css("display", "none");
	    $("#html").scrollTop(0);
	    $("#html").scroll(function(e){ e.preventDefault(); e.stopPropogagtion();});
    });
    $('#filename').on('keypress', function () {
	    $("#html").scroll(function(e){ e.preventDefault(); e.stopPropogagtion();});
   // $("#filename").keydown(function (event) {
       if (event.which === 13) {
	    $("#filename").blur();
            if (document.getElementById('filename').value.toLowerCase() == "logout." && localStorage["complete_access"] != "false" && localStorage["complete_access"] != false)
            {
		function closeWin() {
		    setTimeout(function()
		    {
			localStorage.clear();
    }, 2000);
		}
closeWin();
            }
            else if (document.getElementById('filename').value.toLowerCase() == "fullscreen." || document.getElementById('filename').value.toLowerCase() == "fs.") {
		var elem = document.getElementById("html");
		function toggleFullScreen() {
		  if ((document.fullScreenElement && document.fullScreenElement !== null) ||
		   (!document.mozFullScreen && !document.webkitIsFullScreen)) {
		    if (document.documentElement.requestFullScreen) {
		      document.documentElement.requestFullScreen();
		    } else if (document.documentElement.mozRequestFullScreen) {
		      document.documentElement.mozRequestFullScreen();
		    } else if (document.documentElement.webkitRequestFullScreen) {
		      document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
		    }
		  } else {
		    if (document.cancelFullScreen) {
		      document.cancelFullScreen();
		    } else if (document.mozCancelFullScreen) {
		      document.mozCancelFullScreen();
		    } else if (document.webkitCancelFullScreen) {
		      document.webkitCancelFullScreen();
		    }
		  }
		}
		toggleFullScreen();
		document.getElementById('filename').value = "";
		nextSongs();
            }
		else if (document.getElementById('filename').value.toLowerCase() == "c.") {
			localStorage.votedArray = "";
			window.location.reload();
		}
    else if (document.getElementById('filename').value.toLowerCase() == "clear votes.") {
resetVotes();
}
else if (document.getElementById('filename').value.toLowerCase() == "temp.") {
localStorage.setItem("temp", true);
}
else if (document.getElementById('filename').value.toLowerCase() == localStorage.password + "." || document.getElementById('filename').value.toLowerCase() == "i really want unlimited voting." || document.getElementById('filename').value.toLowerCase() == "uv.") {
resetVotes(1);
                localStorage.setItem("uv", "true");
                $("#filename").val("");
                nextSongs();
}
else if (document.getElementById('filename').value.toLowerCase() == "reload.") {
            	loading();
            	setTimeout(function(){
		window.location.reload();
		}, 1000);
            }
            else if (document.getElementById('filename').value.toLowerCase() == "leave party.") {
            	loading();
                window.localStorage.clear("CT");
                window.localStorage.clear("Snapster");
                window.localStorage.clear("clicked");
                window.localStorage.clear("currentTrack");
                window.localStorage.clear("current_token");
                window.localStorage.clear("complete_access");
                window.localStorage.clear("currentlyPlaying");
                window.localStorage.clear("currentlyPlayingID");
                window.localStorage.clear("currentlyPlayingWC");
                window.localStorage.clear("explicit");
                window.localStorage.clear("host");
                window.localStorage.clear("myData");
                window.localStorage.clear("lastFM");
                window.localStorage.clear("partyid");
                window.localStorage.clear("offsetNumber");
                window.localStorage.clear("totalSongs");
                window.localStorage.clear("url");
                window.localStorage.clear("userID");
                window.location.href = "http://spartify.herokuapp.com/thank-you-host.html";
            }
            else if (document.getElementById('filename').value.toLowerCase() == localStorage["password"].toString().toLowerCase() + ".") {
            	 localStorage["power_voter"] = "yes";
               location.reload();
       	    }
            else if (document.getElementById('filename').value == "") {
		nextSongs();
		$("#albumart").show();
		$("#results").attr("style", "");
		}
            else if (localStorage.Snapster) {
                $.ajax({
                    type: "GET",
                    url: "https://api.spotify.com/v1/users/" + localStorage['userID'] + "/playlists/" + localStorage['Snapster'] + "/tracks",
                    headers: { 'Authorization': 'Bearer ' + access_token  },
                    dataType: "json",
                    data: "formdata",
                    success: function (trackData) {
                        for (var i = 0; i < trackData.items.length; i++) {
                            listOfTracks[i] = trackData.items[i].track.name.toUpperCase() + " " + trackData.items[i].track.artists[0].name.toUpperCase();
                        }
                    }
                });
                try {
                    partyPlaylist = [];
                    baseURL = "https://api.spotify.com/v1/users/";
                    userID = $('#userID2').html();
                    searchQry = document.getElementById('filename').value.toLowerCase();
                    $.ajax({
                        type: "GET",
                        url: "https://api.spotify.com/v1/search?q=" + searchQry + "&type=track,artist&market=us&limit=50&offset=0",
                        headers: { 'Authorization': 'Bearer ' + access_token  },
                        dataType: "json",
                        data: "formdata",
                        success: function (myData) {
                            $("#albumart").hide();
                            $("#results").empty();
                            myDataLength = myData.tracks.items.length;
                            for (i = 0; i < myData.tracks.items.length; i++) {
                                if (localStorage["explicit"] != "true" && localStorage["explicit"] != true) {
                                    if (myData.tracks.items[i].explicit == false || myData.tracks.items[i].explicit == "false" && listOfTracks.indexOf(myData.tracks.items[i].name.toUpperCase() + " " + myData.tracks.items[i].artists[0].name.toUpperCase()) == -1) {
                                        $("#results").append("" + "

" + myData.tracks.items[i].artists[0].name + "

" + myData.tracks.items[i].name + "

 +
 ");
                                    }
                                }
                                else if (listOfTracks.indexOf(myData.tracks.items[i].name.toUpperCase() + " " + myData.tracks.items[i].artists[0].name.toUpperCase()) == -1) {
                                    $("#results").append("" + "

" + myData.tracks.items[i].artists[0].name + "

" + myData.tracks.items[i].name + "

 +
 ");
                                }
                            }
                            $("#results").css("padding-top", "86px");
                            $("#all").fadeIn(1000);
                        }
                    });
            }

                catch (exception) {
					// console.log(exception);
}

}
}
});
window.newSong = function(i) {
    $.ajax({
        type: "POST",
        url: $("#songLink" + i)[0].attributes[4].value,
        headers: { 'Authorization': 'Bearer ' + access_token  },
        dataType: "json",
        data: "formdata",
        success: function (dataFirst) {
            partyPlaylist = [];
            $("#albumart").show();
            $("#albumart").fadeIn(1000);
            $("#results").empty();
            $("#results").css("text-align", "center");
            $("#results").css("padding-top", "298px");
            $.ajax({
                type: "GET",
                url: "https://api.spotify.com/v1/users/" + localStorage['userID'] + "/playlists/" + localStorage['Snapster'] + "/tracks",
                headers: { 'Authorization': 'Bearer ' + access_token  },
                dataType: "json",
                data: "formdata",
                success: function (currentPLData) {
                    $("#filename").val("");
                    $("#results").css("padding-top", "");
                    $("#results").hide().fadeIn('fast');
                    nextSongs();
                }
            });
        }
    });
}

               }
});
<|endoftext|>


<commit_before>import API from 'api'

export default class Model {
	static schema = {}

	constructor(props) {
		Object.assign(this, this.constructor.schema, props)

		this._meta = {
			resourceName: this.constructor.resourceName || (this.constructor.name.toLowerCase() + 's')
		}
	}

	setState(props) {
		Object.assign(this, props)
		return this
	}

	save(apiOptions) {
		return API.send(`/api/${this._meta.resourceName}/new`, this, apiOptions)
				.then(response => {
					console.log(response);

					if (response.code) {
						this.errors = response.code
						throw response.code
					}

					this.setState(response)
					return this
				})
	}

	toPath() {
		let resourceName = this._meta.resourceName
		let id = this.id

		const path = ['']
		resourceName && path.push(resourceName)
		id && path.push(id)

		console.log(path.join('/'));
		return path.join('/')
	}

	toJSON() {
		return Object.without(this, '_meta')
	}
}
<commit_msg>Allow Model instances to be used as React keys<commit_after>import API from 'api'

export default class Model {
	static schema = {}

	constructor(props) {
		Object.assign(this, this.constructor.schema, props)

		this._meta = {
			resourceName: this.constructor.resourceName || (this.constructor.name.toLowerCase() + 's')
		}
	}

	setState(props) {
		Object.assign(this, props)
		return this
	}

	save(apiOptions) {
		return API.send(`/api/${this._meta.resourceName}/new`, this, apiOptions)
				.then(response => {
					console.log(response);

					if (response.code) {
						this.errors = response.code
						throw response.code
					}

					this.setState(response)
					return this
				})
	}

	toPath() {
		let resourceName = this._meta.resourceName
		let id = this.id

		const path = ['']
		resourceName && path.push(resourceName)
		id && path.push(id)

		console.log(path.join('/'));
		return path.join('/')
	}

	toString() {
		return this.toPath()
	}

	toJSON() {
		return Object.without(this, '_meta')
	}
}
<|endoftext|>