<commit_before>// ==UserScript==
// @name         CheckItForMe
// @version      0.19
// @match        https://scrap.tf/raffles
// @match        https://scrap.tf/raffles/ending
// @require      https://code.jquery.com/jquery-2.2.4.min.js#sha256=BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=
// @updateURL    https://raw.githubusercontent.com/GuilloOme/CheckThisForMe/master/checkItForMe.js
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    var RELOAD_DELAY = 10,
        ENTERING_DELAY = 2.5;

    var todoRaffleList = [],
        raffleIndex = 0,
        interval = randomInterval(RELOAD_DELAY);

    $(document).ready(function() {
        console.info('Bot: Started');

        if(parseInt($('.user-notices-count').html()) > 0){
            console.info('Bot: There is new message(s)!');
            $('link[rel*="icon"]').remove();
            $('head').append('<link href="data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAABILAAASCwAAAAAAAAAAAAAAAAADAAAABgAAAAYAAAAGAAAABgAAAAYAAAAGAAAABgAAAAYAAAAGAAAABgAAAAYAAAAGAAAABwAAAAcAAAADAAAAmwAHCcIACQvCAAkLwgAJC8IACQvCAAkLwgAJDMIACQzCAAkMwgAJDMIACQzCAAkMwgAJDMIACArDAAAAmwAAAGsAbIf4AMz//wDM//8AzP//AMz//wDM//8Auun/AK/b/wDM//8AzP//AMz//wDM//8AzP//AGyH+QAAAGsAAAAZAA0QtgC24/8AzP//AMz//wDM//8AzP//Ai86/wMLDf8AwvP/AMz//wDM//8AzP//ALfk/wAOEbgAAAAZAAAAAAAAAFAAT2LqAMz//wDM//8AzP//AMz//wF/n/8CYXn/AMv+/wDM//8AzP//AMz//wBRZesAAABSAAAAAAAAAAAAAAAIAAIDngCcw/8AzP//AMz//wDM//8AeZj/AHSR/wDM//8AzP//AMz//wCfx/8AAwShAAAACQAAAAAAAAAAAAAAAAAAADgAMDzYAMr8/wDM//8AzP//ACQt/wAbIv8AzP//AMz//wDL/f8ANEHbAAAAOwAAAAAAAAAAAAAAAAAAAAAAAAABAAAAfQB9nP4AzP//AMz//wAcI/8AFBj/AMz//wDM//8AgqP+AAAAggAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACMAGB7DAL/v/wDM//8AFBn/AA0Q/wDL/v8AwvL/ABwjyAAAACcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAXwBgePMAy/7/AA0Q/wAHCf8Ayfv/AGaA9gAAAGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABEABwisAKvV/wAPE/8ACgz/AK7Z/wAKDLIAAAAVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARgBCUuIAn8f/AJzD/wBLXecAAABNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAGRAI+y/wCZv/8AAQKbAAAABgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALwAlLtAALTnWAAAANgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABvAAAAeQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIABAACAAQAAwAMAAMADAADgBwAA8A8AAPAPAAD4HwAA+B8AAPw/AAD8PwAA/n8AAA==" rel="icon" type="image/x-icon">');
        }

        scanHash();
    });

    function scanHash() {
        var hash = window.location.hash,
            url = window.location.href,
            baseUrl = /https:\/\/scrap.tf\/raffles/;

        if (url.match(baseUrl) && isThereNewRaffles()) {
            scanRaffles();
        } else {
            console.info('Bot: Nothing to do, waiting ' + (interval / 1000) + ' sec before reloading…');

            setTimeout(function() {
                location.reload();
            }, interval);
        }

    }

    function scanRaffles() {
        //console.info('Bot: Loading all the raffles…');

        $.when(loadAllRaffles()).then(function() {
            var activePanel = $('div.panel');
            $(activePanel[activePanel.length - 1]).find('div.panel-raffle').each(function(id, item) {
                if ($(item).css('opacity') === '1') {
                    todoRaffleList.push($(item).find('div.raffle-name > a').attr('href'));
                }
            });

            if (todoRaffleList.length > 0) {
                //console.info('Bot: Start entering raffles.');

                $.when(enterRaffles()).then(function() {
                    //console.info('Bot: Done entering raffles, reloading…');
                    location.reload();
                });
            } else {
                console.info('Bot: No raffle to enter, waiting ' + (interval / 1000) + ' sec before reloading…');
                setTimeout(function() {
                    location.reload();
                }, interval);
            }
        });

    }

    function enterRaffles() {
        var deferred = jQuery.Deferred();

        function joinRaffle(url) {

            var id, hash;

            ScrapTF.Raffles.EnterRaffle = function(idArg, hashArg) {
                id = idArg;
                hash = hashArg;
            }

            $.get(url, function(responseData) {

                var request,
                    raffleDeferred = jQuery.Deferred(),
                    raffleKey = $(responseData).find("#raffle-key").val(),
                    enterButton = $(responseData).find('button#raffle-enter');

                if (enterButton.length > 0 && $(responseData).find('button#raffle-enter>i18n').html() === 'Enter Raffle') {
                    console.info('Bot: Entrering raffle: ' + (raffleIndex + 1) + '/' + todoRaffleList.length);

                    $(responseData).find('button#raffle-enter').click();

                    request = {
                        raffle: id,
                        captcha: '',
                        rafflekey: raffleKey,
                        password: '',
                        hash: hash
                    };

                    ScrapTF.Ajax('viewraffle/EnterRaffle', {
                        raffle: id,
                        captcha: '',
                        rafflekey: raffleKey,
                        password: '',
                        hash: hash
                    }, function() {
                        console.info('Bot: Done entering raffle');

                        raffleDeferred.resolve();
                    }, function() {
                        console.warn('Bot: Error when entering raffle: ' + (raffleIndex + 1) + '/' + todoRaffleList.length);

                        raffleDeferred.resolve();
                    });

                } else {
                    console.warn('Bot: Can\'t enter raffle: ' + (raffleIndex + 1) + '/' + todoRaffleList.length);
                    raffleDeferred.resolve();
                }

                $.when(raffleDeferred.promise()).then(function() {
                    raffleIndex++;
                    if (raffleIndex < todoRaffleList.length) {
                        setTimeout(function() {
                            joinRaffle(todoRaffleList[raffleIndex]);
                        }, randomInterval(ENTERING_DELAY));
                    } else {
                        deferred.resolve();
                    }
                });

            });

            /* var currentChildFrame = window.open(url);

             $(currentChildFrame.document).ready(function() {
             var waitInterval;
             console.log('Bot: Entrering raffle: ' + (raffleIndex + 1) + '/' + todoRaffleList.length);

             waitInterval = setInterval(function() {
             console.log('Bot: Waiting confirmation…');

             if ($(currentChildFrame.document).find('button#raffle-enter>i18n').html() === 'Leave Raffle' || $(currentChildFrame.document).find('div.alert-error').length > 0) {

             console.log('Bot: Closing raffle window');

             currentChildFrame.close();

             raffleIndex++;
             if (raffleIndex < todoRaffleList.length) {
             setTimeout(function() {
             joinRaffle(todoRaffleList[raffleIndex]);
             }, randomInterval(ENTERING_DELAY));
             } else {
             deferred.resolve();
             }

             clearInterval(waitInterval);

             } else if ($(currentChildFrame.document).find('button#raffle-enter>i18n').html() === 'Enter Raffle') {

             $(currentChildFrame.document).find('button#raffle-enter').trigger('click');

             }
             }, randomInterval(ENTERING_DELAY));

             });*/

        }

        joinRaffle(todoRaffleList[raffleIndex]);

        return deferred.promise();
    }

    function isThereNewRaffles() {

        var value = $('div.panel-body>div.text-center>i18n>var').text(),
            ar = value.match(/[0-9]+/gi),
            raffleToEnterNumber = (parseInt(ar[1]) - parseInt(ar[0]));

        console.info('Bot: ' + value + ', There is ' + raffleToEnterNumber + ' raffle(s) to enter.');

        return (ar.length > 1 && raffleToEnterNumber > 0);
    }

    function loadAllRaffles() {
        var deferred = jQuery.Deferred();

        var loadInterval = setInterval(function() {

            if (!ScrapTF.Raffles.Pagination.isDone) {
                ScrapTF.Raffles.Pagination.LoadNext();
            } else {
                deferred.resolve();
                clearInterval(loadInterval);
            }

        }, randomInterval());

        return deferred.promise();

    }

    function randomInterval(delay) {
        if (!delay) {
            delay = 0.5;
        }
        return Math.floor(delay * 1000) + Math.floor(Math.random() * (delay * 1000));
    }

})
();
<commit_msg>change icon for green one<commit_after>// ==UserScript==
// @name         CheckItForMe
// @version      0.20
// @match        https://scrap.tf/raffles
// @match        https://scrap.tf/raffles/ending
// @require      https://code.jquery.com/jquery-2.2.4.min.js#sha256=BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=
// @updateURL    https://raw.githubusercontent.com/GuilloOme/CheckThisForMe/master/checkItForMe.js
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    var RELOAD_DELAY = 10,
        ENTERING_DELAY = 2.5;

    var todoRaffleList = [],
        raffleIndex = 0,
        interval = randomInterval(RELOAD_DELAY);

    $(document).ready(function() {
        console.info('Bot: Started');

        if(parseInt($('.user-notices-count').html()) > 0){
            console.info('Bot: There is new message(s)!');
            $('link[rel*="icon"]').remove();
            // green icon
            $('head').append('<link href="data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAABILAAASCwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAG0QYXBtEGTQbRBk8G0QZPBtEGTwbRBk8G0QZPBtEGTwbRBkkG0QYKAAAAAAAAAAAAAAAAAAAAAAAAAAAG0QYQBtEG5wbRBv8G0Qb/BtEG/wbRBv8G0Qb/BtEG/wbRBv8G0Qb/BtEGwAXRBQAAAAAAAAAAAAAAAAAAAAAABtEGOQbRBv/J9cn/z/bP/6bvpv9/53//nO2c/53tnf/u/O7/l+yX/wbRBvkF0QUHAAAAAAAAAAAAAAAAAAAAAAbRBjoG0Qb/2/jb/yjXKP8G0Qb/EdMR/0zeTP9C3EL/6vvq/6TupP8G0Qb5BdEFCAAAAAAAAAAAAAAAAAAAAAAG0QY6BtEG/9v42/8l1yX/BtEG/xHTEf9M3kz/Nto2/7Xxtf+k7qT/BtEG+QXRBQgAAAAAAAAAAAAAAAAAAAAABtEGOgbRBv/b+Nv/jeqN/xjUGP8S0xL/TN5M/zfaN//F9MX/pO6k/wbRBvkF0QUIAAAAAAAAAAAAAAAAAAAAAAbRBjoG0Qb/2/jb//////+B6IH/FNQU/8X0xf+9873/9v32/6TupP8G0Qb5BdEFCAAAAAAAAAAAAAAAAAAAAAAG0QY6BtEG/9v42///////6vvq/w/TD//z/fP///////////+k7qT/BtEG+QXRBQgAAAAAAAAAAAAAAAAAAAAABtEGOQbRBv/T99P/+f75//n++f+b7Zv/9f31//n++f/5/vn/nu2e/wbRBvkF0QUIAAAAAAAAAAAAAAAAAAAAAAbRBhMG0QbtB9EH/wjRCP8I0Qj/CNEI/wjRCP8I0Qj/CNEI/wfRB/8G0QbHBdEFAQAAAAAAAAAAAAAAAAAAAAAAAAAABtEGHwbRBlsG0QZdBtEGXQbRBl0G0QZdBtEGXQbRBl0G0QZWBtEGDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAD//wAA4AcAAMADAADAAwAAwAMAAMADAADAAwAAwAMAAMADAADAAwAAwAMAAOAHAAD//wAA//8AAA==" rel="icon" type="image/x-icon">');
            //warning icon: $('head').append('<link href="data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAABILAAASCwAAAAAAAAAAAAAAAAADAAAABgAAAAYAAAAGAAAABgAAAAYAAAAGAAAABgAAAAYAAAAGAAAABgAAAAYAAAAGAAAABwAAAAcAAAADAAAAmwAHCcIACQvCAAkLwgAJC8IACQvCAAkLwgAJDMIACQzCAAkMwgAJDMIACQzCAAkMwgAJDMIACArDAAAAmwAAAGsAbIf4AMz//wDM//8AzP//AMz//wDM//8Auun/AK/b/wDM//8AzP//AMz//wDM//8AzP//AGyH+QAAAGsAAAAZAA0QtgC24/8AzP//AMz//wDM//8AzP//Ai86/wMLDf8AwvP/AMz//wDM//8AzP//ALfk/wAOEbgAAAAZAAAAAAAAAFAAT2LqAMz//wDM//8AzP//AMz//wF/n/8CYXn/AMv+/wDM//8AzP//AMz//wBRZesAAABSAAAAAAAAAAAAAAAIAAIDngCcw/8AzP//AMz//wDM//8AeZj/AHSR/wDM//8AzP//AMz//wCfx/8AAwShAAAACQAAAAAAAAAAAAAAAAAAADgAMDzYAMr8/wDM//8AzP//ACQt/wAbIv8AzP//AMz//wDL/f8ANEHbAAAAOwAAAAAAAAAAAAAAAAAAAAAAAAABAAAAfQB9nP4AzP//AMz//wAcI/8AFBj/AMz//wDM//8AgqP+AAAAggAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACMAGB7DAL/v/wDM//8AFBn/AA0Q/wDL/v8AwvL/ABwjyAAAACcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAXwBgePMAy/7/AA0Q/wAHCf8Ayfv/AGaA9gAAAGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABEABwisAKvV/wAPE/8ACgz/AK7Z/wAKDLIAAAAVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARgBCUuIAn8f/AJzD/wBLXecAAABNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAGRAI+y/wCZv/8AAQKbAAAABgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALwAlLtAALTnWAAAANgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABvAAAAeQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIABAACAAQAAwAMAAMADAADgBwAA8A8AAPAPAAD4HwAA+B8AAPw/AAD8PwAA/n8AAA==" rel="icon" type="image/x-icon">');
        }

        scanHash();
    });

    function scanHash() {
        var hash = window.location.hash,
            url = window.location.href,
            baseUrl = /https:\/\/scrap.tf\/raffles/;

        if (url.match(baseUrl) && isThereNewRaffles()) {
            scanRaffles();
        } else {
            console.info('Bot: Nothing to do, waiting ' + (interval / 1000) + ' sec before reloading…');

            setTimeout(function() {
                location.reload();
            }, interval);
        }

    }

    function scanRaffles() {
        //console.info('Bot: Loading all the raffles…');

        $.when(loadAllRaffles()).then(function() {
            var activePanel = $('div.panel');
            $(activePanel[activePanel.length - 1]).find('div.panel-raffle').each(function(id, item) {
                if ($(item).css('opacity') === '1') {
                    todoRaffleList.push($(item).find('div.raffle-name > a').attr('href'));
                }
            });

            if (todoRaffleList.length > 0) {
                //console.info('Bot: Start entering raffles.');

                $.when(enterRaffles()).then(function() {
                    //console.info('Bot: Done entering raffles, reloading…');
                    location.reload();
                });
            } else {
                console.info('Bot: No raffle to enter, waiting ' + (interval / 1000) + ' sec before reloading…');
                setTimeout(function() {
                    location.reload();
                }, interval);
            }
        });

    }

    function enterRaffles() {
        var deferred = jQuery.Deferred();

        function joinRaffle(url) {

            var id, hash;

            ScrapTF.Raffles.EnterRaffle = function(idArg, hashArg) {
                id = idArg;
                hash = hashArg;
            }

            $.get(url, function(responseData) {

                var request,
                    raffleDeferred = jQuery.Deferred(),
                    raffleKey = $(responseData).find("#raffle-key").val(),
                    enterButton = $(responseData).find('button#raffle-enter');

                if (enterButton.length > 0 && $(responseData).find('button#raffle-enter>i18n').html() === 'Enter Raffle') {
                    console.info('Bot: Entrering raffle: ' + (raffleIndex + 1) + '/' + todoRaffleList.length);

                    $(responseData).find('button#raffle-enter').click();

                    request = {
                        raffle: id,
                        captcha: '',
                        rafflekey: raffleKey,
                        password: '',
                        hash: hash
                    };

                    ScrapTF.Ajax('viewraffle/EnterRaffle', {
                        raffle: id,
                        captcha: '',
                        rafflekey: raffleKey,
                        password: '',
                        hash: hash
                    }, function() {
                        console.info('Bot: Done entering raffle');

                        raffleDeferred.resolve();
                    }, function() {
                        console.warn('Bot: Error when entering raffle: ' + (raffleIndex + 1) + '/' + todoRaffleList.length);

                        raffleDeferred.resolve();
                    });

                } else {
                    console.warn('Bot: Can\'t enter raffle: ' + (raffleIndex + 1) + '/' + todoRaffleList.length);
                    raffleDeferred.resolve();
                }

                $.when(raffleDeferred.promise()).then(function() {
                    raffleIndex++;
                    if (raffleIndex < todoRaffleList.length) {
                        setTimeout(function() {
                            joinRaffle(todoRaffleList[raffleIndex]);
                        }, randomInterval(ENTERING_DELAY));
                    } else {
                        deferred.resolve();
                    }
                });

            });

            /* var currentChildFrame = window.open(url);

             $(currentChildFrame.document).ready(function() {
             var waitInterval;
             console.log('Bot: Entrering raffle: ' + (raffleIndex + 1) + '/' + todoRaffleList.length);

             waitInterval = setInterval(function() {
             console.log('Bot: Waiting confirmation…');

             if ($(currentChildFrame.document).find('button#raffle-enter>i18n').html() === 'Leave Raffle' || $(currentChildFrame.document).find('div.alert-error').length > 0) {

             console.log('Bot: Closing raffle window');

             currentChildFrame.close();

             raffleIndex++;
             if (raffleIndex < todoRaffleList.length) {
             setTimeout(function() {
             joinRaffle(todoRaffleList[raffleIndex]);
             }, randomInterval(ENTERING_DELAY));
             } else {
             deferred.resolve();
             }

             clearInterval(waitInterval);

             } else if ($(currentChildFrame.document).find('button#raffle-enter>i18n').html() === 'Enter Raffle') {

             $(currentChildFrame.document).find('button#raffle-enter').trigger('click');

             }
             }, randomInterval(ENTERING_DELAY));

             });*/

        }

        joinRaffle(todoRaffleList[raffleIndex]);

        return deferred.promise();
    }

    function isThereNewRaffles() {

        var value = $('div.panel-body>div.text-center>i18n>var').text(),
            ar = value.match(/[0-9]+/gi),
            raffleToEnterNumber = (parseInt(ar[1]) - parseInt(ar[0]));

        console.info('Bot: ' + value + ', There is ' + raffleToEnterNumber + ' raffle(s) to enter.');

        return (ar.length > 1 && raffleToEnterNumber > 0);
    }

    function loadAllRaffles() {
        var deferred = jQuery.Deferred();

        var loadInterval = setInterval(function() {

            if (!ScrapTF.Raffles.Pagination.isDone) {
                ScrapTF.Raffles.Pagination.LoadNext();
            } else {
                deferred.resolve();
                clearInterval(loadInterval);
            }

        }, randomInterval());

        return deferred.promise();

    }

    function randomInterval(delay) {
        if (!delay) {
            delay = 0.5;
        }
        return Math.floor(delay * 1000) + Math.floor(Math.random() * (delay * 1000));
    }

})
();
<|endoftext|>


<commit_before>import { runQueue } from '../util/async'
import { isSameLocation } from '../util/location'

export class History {
  constructor (router) {
    this.router = router
    this.current = router.match('/')
    this.pending = null
    this.beforeHooks = []
    this.afterHooks = []
  }

  listen (cb) {
    this.cb = cb
  }

  before (fn) {
    this.beforeHooks.push(fn)
  }

  after (fn) {
    this.afterHooks.push(fn)
  }

  push (location) {
    location = this.router.match(location, this.current)
    this.confirmTransition(location, () => {
      this._push(location)
      this.updateLocation(location)
    })
  }

  replace (location) {
    location = this.router.match(location, this.current)
    this.confirmTransition(location, () => {
      this._replace(location)
      this.updateLocation(location)
    }, true)
  }

  confirmTransition (location, cb, replace) {
    if (isSameLocation(location, this.current)) {
      return
    }

    const redirect = location => this[replace ? 'replace' : 'push'](location)
    const queue = this.beforeHooks.concat(
      // route config canDeactivate hooks
      this.current.matched.map(m => m.canDeactivate).reverse(),
      // component canDeactivate hooks
      extractComponentHooks(this.current.matched, 'routeCanDeactivate').reverse(),
      // route config canActivate hooks
      location.matched.map(m => m.canActivate),
      // component canActivate hooks
      extractComponentHooks(location.matched, 'routeCanActivate')
    ).filter(_ => _)

    this.pending = location

    runQueue(
      queue,
      (hook, next) => { hook(location, redirect, next) },
      () => {
        if (isSameLocation(location, this.pending)) {
          this.pending = null
          cb(location)
        }
      }
    )
  }

  updateLocation (location) {
    this.current = location
    this.cb && this.cb(location)
    this.afterHooks.forEach(hook => {
      hook(location)
    })
  }
}

function extractComponentHooks (matched, name) {
  return Array.prototype.concat.apply([], matched.map(m => {
    return Object.keys(m.components).map(key => {
      const component = m.components[key]
      const instance = m.instances[key]
      const hook = typeof component === 'function'
        ? component.options[name]
        : component[name]
      if (hook) {
        return function routerHook () {
          return hook.apply(instance, arguments)
        }
      }
    })
  }))
}
<commit_msg>fix route hook context<commit_after>import { runQueue } from '../util/async'
import { isSameLocation } from '../util/location'

export class History {
  constructor (router) {
    this.router = router
    this.current = router.match('/')
    this.pending = null
    this.beforeHooks = []
    this.afterHooks = []
  }

  listen (cb) {
    this.cb = cb
  }

  before (fn) {
    this.beforeHooks.push(fn)
  }

  after (fn) {
    this.afterHooks.push(fn)
  }

  push (location) {
    location = this.router.match(location, this.current)
    this.confirmTransition(location, () => {
      this._push(location)
      this.updateLocation(location)
    })
  }

  replace (location) {
    location = this.router.match(location, this.current)
    this.confirmTransition(location, () => {
      this._replace(location)
      this.updateLocation(location)
    }, true)
  }

  confirmTransition (location, cb, replace) {
    if (isSameLocation(location, this.current)) {
      return
    }

    const redirect = location => this[replace ? 'replace' : 'push'](location)
    const queue = this.beforeHooks.concat(
      // route config canDeactivate hooks
      this.current.matched.map(m => m.canDeactivate).reverse(),
      // component canDeactivate hooks
      extractComponentHooks(this.current.matched, 'routeCanDeactivate').reverse(),
      // route config canActivate hooks
      location.matched.map(m => m.canActivate),
      // component canActivate hooks
      extractComponentHooks(location.matched, 'routeCanActivate')
    ).filter(_ => _)

    this.pending = location

    runQueue(
      queue,
      (hook, next) => { hook(location, redirect, next) },
      () => {
        if (isSameLocation(location, this.pending)) {
          this.pending = null
          cb(location)
        }
      }
    )
  }

  updateLocation (location) {
    this.current = location
    this.cb && this.cb(location)
    this.afterHooks.forEach(hook => {
      hook(location)
    })
  }
}

function extractComponentHooks (matched, name) {
  return Array.prototype.concat.apply([], matched.map(m => {
    return Object.keys(m.components).map(key => {
      const component = m.components[key]
      const instance = m.instances[key] && m.instances[key].child
      const hook = typeof component === 'function'
        ? component.options[name]
        : component[name]
      if (hook) {
        return function routerHook () {
          return hook.apply(instance, arguments)
        }
      }
    })
  }))
}
<|endoftext|>


<commit_before>/* incident.js
 * this file contains all the controllers for modify, add, delete for incidents
*/

// Includes
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var modules = require('./../../util/modules.js');

var router = express.Router();
var urlencodedParser = bodyParser.urlencoded({ extended: false })

router.get('/', function (req, res) {
    res.sendFile(path.resolve(__dirname + "/../views/addIncident.html"));
});

router.post('/addNew', urlencodedParser, function (req, res) {
    // Create the item for the db
    console.log('Adding new');
    item = {
        'id': req.body.id,
        'title':req.body.title,
        'type': req.body.type,
        'open': new Date().toISOString().replace('Z', ''),
        'geo': req.body.geo
    };

    // Get the database module and give it the item to push to the db
    db = modules.getModule('firebase');
    db.addNewItem(item);

    // Just give them the json that was submitted to the db
    res.end(JSON.stringify(item));
});

router.post('/update', urlencodedParser, function(req, res){
    var id = req.body.id;
    var values = req.body.values;

    db = modules.getModule('firebase');

    for(i in values){
        var value = JSON.parse(values[i]);

        db.setItem(value['path'] +'/'+ id, value['value']);
    }

    res.end('thanks');
});

router.post('/add', urlencodedParser, function(req, res){
    // Get the path to add
    // Get the vaule to add
    var path = req.body.path;
    var value = req.body.value;

    console.log('Add recieved');
    console.log(req);

    db = modules.getModule('firebase');
    //fb.addItem(path, value);

    res.end('thanks');

});

module.exports = router;<commit_msg>making a stupid form work<commit_after>/* incident.js
 * this file contains all the controllers for modify, add, delete for incidents
*/

// Includes
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var modules = require('./../../util/modules.js');

var router = express.Router();
var urlencodedParser = bodyParser.urlencoded({ extended: false })

router.get('/', function (req, res) {
    res.sendFile(path.resolve(__dirname + "/../views/addIncident.html"));
});

router.post('/addNew', urlencodedParser, function (req, res) {
    // Create the item for the db
    console.log('Adding new');
    item = {
        'id': '23456',//req.body.id,
        'title':req.body.title,
        'type': req.body.type,
        'open': new Date().toISOString().replace('Z', ''),
        'geo': req.body.geo
    };

    // Get the database module and give it the item to push to the db
    db = modules.getModule('firebase');
    db.addNewItem(item);

    // Just give them the json that was submitted to the db
    res.end(JSON.stringify(item));
});

router.post('/update', urlencodedParser, function(req, res){
    var id = req.body.id;
    var values = req.body.values;

    db = modules.getModule('firebase');

    for(i in values){
        var value = JSON.parse(values[i]);

        db.setItem(value['path'] +'/'+ id, value['value']);
    }

    res.end('thanks');
});

router.post('/add', urlencodedParser, function(req, res){
    // Get the path to add
    // Get the vaule to add
    var path = req.body.path;
    var value = req.body.value;

    console.log('Add recieved');
    console.log(req);

    db = modules.getModule('firebase');
    //fb.addItem(path, value);

    res.end('thanks');

});

module.exports = router;<|endoftext|>


<commit_before>/*
 * debugger.io: An interactive web scripting sandbox
 */

define([
  'module', 'path', 'underscore', 'q',
  'cjson', 'utils'
],
function(
  module, path, _, Q,
  cjson, utils
) {
  'use strict';

  var __dirname = path.dirname(module.uri);
  var appRoot = __dirname + '/../../';

  var config = { client: {} };

  var required_options = [
    'db.name',
    'db.user',
    'db.path',
    'db.host',
    'auth.secret'
  ];

  /**
   * Extend the config object with data from a JSON file, if available
   *
   * @param {String} prop - property to create (if needed) and extend
   * @param {String} filename - JSON filename, relative to `appRoot`
   */
  var extend_config_with_json = function(prop, filename) {
    var obj = prop ? (config[prop] || {}) : config;
    if (prop) { config[prop] = obj; }

    try {
      _.merge(obj, cjson.load(appRoot + filename));
    } catch(err) {
      // nothing to do
    }
  };

  extend_config_with_json(null, 'config.json');
  extend_config_with_json(null, 'deploy.json');
  extend_config_with_json('build', 'build.json');

  config.prod = config.client.prod = (process.env.NODE_ENV === 'production');

  // default theme goes last
  config.themes = ['light', 'dark'];
  config.themes[_.indexOf(config.themes, config.client.default_theme)] = null;
  config.themes.push(config.client.default_theme);
  config.themes = _.uniq(_.compact(config.themes));

  var invalids = _.filter(required_options, function(required) {
    var opt = utils.reduce(required, config);
    return _.isUndefined(opt) || _.isNull(opt);
  });

  if (invalids.length) {
    _.each(invalids, function(invalid) {
      console.error('Unset option: ' + invalid);
    });

    console.error('See `config.json`, `deploy.json`');
  }

  return config;
});
<commit_msg>Fix config typo<commit_after>/*
 * debugger.io: An interactive web scripting sandbox
 */

define([
  'module', 'path', 'underscore', 'q',
  'cjson', 'utils'
],
function(
  module, path, _, Q,
  cjson, utils
) {
  'use strict';

  var __dirname = path.dirname(module.uri);
  var appRoot = __dirname + '/../../';

  var config = { client: {} };

  var required_options = [
    'db.name',
    'db.user',
    'db.pass',
    'db.host',
    'auth.secret'
  ];

  /**
   * Extend the config object with data from a JSON file, if available
   *
   * @param {String} prop - property to create (if needed) and extend
   * @param {String} filename - JSON filename, relative to `appRoot`
   */
  var extend_config_with_json = function(prop, filename) {
    var obj = prop ? (config[prop] || {}) : config;
    if (prop) { config[prop] = obj; }

    try {
      _.merge(obj, cjson.load(appRoot + filename));
    } catch(err) {
      // nothing to do
    }
  };

  extend_config_with_json(null, 'config.json');
  extend_config_with_json(null, 'deploy.json');
  extend_config_with_json('build', 'build.json');

  config.prod = config.client.prod = (process.env.NODE_ENV === 'production');

  // default theme goes last
  config.themes = ['light', 'dark'];
  config.themes[_.indexOf(config.themes, config.client.default_theme)] = null;
  config.themes.push(config.client.default_theme);
  config.themes = _.uniq(_.compact(config.themes));

  var invalids = _.filter(required_options, function(required) {
    var opt = utils.reduce(required, config);
    return _.isUndefined(opt) || _.isNull(opt);
  });

  if (invalids.length) {
    _.each(invalids, function(invalid) {
      console.error('Unset option: ' + invalid);
    });

    console.error('See `config.json`, `deploy.json`');
  }

  return config;
});
<|endoftext|>


<commit_before>/**
 * uncomment.js - Strips comments out of JavaScript code.
 *
 * Copyright (c) 2011 - 2016 Juerg Lehni
 * http://scratchdisk.com/
 *
 * Distributed under the MIT license.
 */

function uncomment(str, options) {
	options = options || {};
	var length = str.length,
		parts = [],
		index = 0,
		quote = false,
		quoteChar,
		regularExpression = false,
		characterClass = false,
		blockComment = false,
		lineComment = false,
		preserveComment = false;

	for (var i = 0; i < length; i++) {
		// When checking for quote escaping, we also need to check that the
		// escape sign itself is not escaped, as otherwise '\\' would cause the
		// wrong impression of an unclosed string:
		var unescaped = str[i - 1] !== '\\' || str[i - 2] === '\\';

		if (quote) {
			if (str[i] === quoteChar && unescaped)
				quote = false;
		} else if (regularExpression) {
			// Make sure '/'' inside character classes is not considered the end
			// of the regular expression.
			if (str[i] === '[' && unescaped) {
				characterClass = true;
			} else if (str[i] === ']' && unescaped && characterClass) {
				characterClass = false;
			} else if (str[i] === '/' && unescaped && !characterClass) {
				regularExpression = false;
			}
		} else if (blockComment) {
			// Is the block comment closing?
			if (str[i] === '*' && str[i + 1] === '/') {
				// Increase by 1 to skip closing '/', as it would be mistaken
				// for a regexp otherwise.
				i++;
				if (!preserveComment) {
					// Next content starts after the comment.
					index = i + 1;
				}
				blockComment = preserveComment = false;
			}
		} else if (lineComment) {
			// One-line comments end with the line-break.
			if (/[\n\r]/.test(str[i + 1])) {
				lineComment = false;
				// Next content starts after the comment.
				index = i + 1;
			}
		} else {
			if (/['"]/.test(str[i])) {
				quote = true;
				// Remember the type of opening quote so we can match it.
				quoteChar = str[i];
			} else if (str[i] === '/') {
				var next = str[i + 1];
				if (next === '*') {
					// Do not filter out conditional comments /*@ ... */
					// and comments marked as protected /*! ... */
					preserveComment = /[@!]/.test(str[i + 2]);
					blockComment = true;
				} else if (next === '/') {
					lineComment = true;
				} else {
					// We need to make sure we don't count normal divisions as
					// regular expressions. Matching this properly is difficult,
					// but if we assume that normal division always have a space
					// after /, a simple check for white space or '='' (for /=)
					// is enough to distinguish divisions from regexps.
					// TODO: Develop a proper check for regexps.
					regularExpression = !/[\s=]/.test(next);
				}
				if (index < i && (lineComment ||
						blockComment && !preserveComment)) {
					// Insert valid content up to the comment.
					parts.push(str.substring(index, index = i));
				}
			}
		}
	}
	if (index < length && !lineComment && (!blockComment || preserveComment)) {
		// Insert valid content up to the end of the string.
		parts.push(str.substring(index, length));
	}
	// Convert back to one string, by concatenating the valid parts.
	str = parts.join('');

	if (options.removeEmptyLines || options.mergeEmptyLines) {
		// Strip empty lines that contain only white space and line breaks, as
		// they are left-overs from comment removal.
		str = str.replace(/^([ \t]+(?:\r\n|\n|\r))/gm, function(all) {
			return '';
		});

		// Replace a sequence of two or more line breaks with:
		// - One break, if removeEmptyLines is set.
		// - Two breaks, if mergeEmptyLines is set, meaning they all merge to
		//   one empty line.
		str = str.replace(/(\r\n|\n|\r){2,}/g, function(all, lineBreak) {
			return options.mergeEmptyLines ? lineBreak + lineBreak : lineBreak;
		});
	}

	return str;
}

// Export uncomment function for node
if (typeof module !== 'undefined')
	module.exports = uncomment;
<commit_msg>Improve regular expression parsing and add some performance improvements.<commit_after>/**
 * uncomment.js - Strips comments out of JavaScript code.
 *
 * Copyright (c) 2011 - 2016 Juerg Lehni
 * http://scratchdisk.com/
 *
 * Distributed under the MIT license.
 */

function uncomment(str, options) {
	options = options || {};
	var length = str.length,
		chr = str[0],
		prev,
		next,
		parts = [],
		index = 0,
		prevToken,
		quote = false,
		quoteChar,
		regularExpression = false,
		characterClass = false,
		blockComment = false,
		lineComment = false,
		preserveComment = false;

	for (var i = 0; i < length; i++) {
		next = str[i + 1];
		// When checking for quote escaping, we also need to check that the
		// escape sign itself is not escaped, as otherwise '\\' would cause the
		// wrong impression of an unclosed string:
		var unescaped = prev !== '\\' || str[i - 2] === '\\';
		if (quote) {
			if (chr === quoteChar && unescaped)
				quote = false;
		} else if (regularExpression) {
			// Make sure '/'' inside character classes is not considered the end
			// of the regular expression.
			if (chr === '[' && unescaped) {
				characterClass = true;
			} else if (chr === ']' && unescaped && characterClass) {
				characterClass = false;
			} else if (chr === '/' && unescaped && !characterClass) {
				regularExpression = false;
			}
		} else if (blockComment) {
			// Is the block comment closing?
			if (chr === '*' && next === '/') {
				// Increase by 1 to skip closing '/', as it would be mistaken
				// for a regexp otherwise.
				i++;
				if (!preserveComment) {
					// Next content starts after the comment.
					index = i + 1;
				}
				blockComment = preserveComment = false;
			}
		} else if (lineComment) {
			// One-line comments end with the line-break.
			if (/[\n\r]/.test(next)) {
				lineComment = false;
				// Next content starts after the comment.
				index = i + 1;
			}
		} else {
			if (/['"]/.test(chr)) {
				quote = true;
				// Remember the type of opening quote so we can match it.
				quoteChar = chr;
			} else if (chr === '/') {
				if (next === '*') {
					// Do not filter out conditional comments /*@ ... */
					// and comments marked as protected /*! ... */
					preserveComment = /[@!]/.test(str[i + 2]);
					blockComment = true;
				} else if (next === '/') {
					lineComment = true;
				} else {
					// We need to make sure we don't count normal divisions as
					// regular expressions. Look at the previous token in the
					// code to decide if this is a regular expression.
					// This check is based on code in JSLint:
					regularExpression = /[(,=:[!&|?{};\/]/.test(prevToken);
				}
				if (index < i && (lineComment ||
						blockComment && !preserveComment)) {
					// Insert valid content up to the comment.
					parts.push(str.substring(index, i));
					index = i;
				}
			}
		}
		// Keep track of the previous non-whitespace character, as required by
		// the regular expression check above.
		if (!/\s/.test(chr))
			prevToken = chr;
		prev = chr;
		chr = next;
	}
	if (index < length && !lineComment && (!blockComment || preserveComment)) {
		// Insert valid content up to the end of the string.
		parts.push(str.substring(index, length));
	}
	// Convert back to one string, by concatenating the valid parts.
	str = parts.join('');

	if (options.removeEmptyLines || options.mergeEmptyLines) {
		// Strip empty lines that contain only white space and line breaks, as
		// they are left-overs from comment removal.
		str = str.replace(/^([ \t]+(?:\r\n|\n|\r))/gm, function(all) {
			return '';
		});

		// Replace a sequence of two or more line breaks with:
		// - One break, if removeEmptyLines is set.
		// - Two breaks, if mergeEmptyLines is set, meaning they all merge to
		//   one empty line.
		str = str.replace(/(\r\n|\n|\r){2,}/g, function(all, lineBreak) {
			return options.mergeEmptyLines ? lineBreak + lineBreak : lineBreak;
		});
	}

	return str;
}

// Export uncomment function for node
if (typeof module !== 'undefined')
	module.exports = uncomment;
<|endoftext|>


<commit_before>/**
 * @file MS Script host adapter
 * @since 0.1.5
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GPF_HOST*/ // Host types
/*global _gpfBootImplByHost*/ // Boot host specific implementation per host
/*global _gpfConsoleGenerate*/ // Generate an object that can be used to simulate console methods
/*global _gpfExit:true*/ // Exit function
/*global _gpfMainContext*/ // Main context object
/*global _gpfMsFSO:true*/ // Scripting.FileSystemObject activeX
/*#endif*/

/*jshint wsh: true*/
/*eslint-env wsh*/
/*eslint-disable new-cap*/

/**
 * @namespace gpf.wscript
 * @description Root namespace for WScript specifics
 * @since 0.1.9
 */
gpf.wscript = {};

/* istanbul ignore next */ // WScript.Echo can't be bound to WScript and not testable
function _gpfWScriptEcho (text) {
    WScript.Echo(text);
}

_gpfBootImplByHost[_GPF_HOST.WSCRIPT] = function () {

    _gpfMsFSO = new ActiveXObject("Scripting.FileSystemObject");

    // Define console APIs
    _gpfMainContext.console = _gpfConsoleGenerate(_gpfWScriptEcho);

    /* istanbul ignore next */ // Not testable
    _gpfExit = function (code) {
        WScript.Quit(code);
    };

};
<commit_msg>Document coverage exceptions<commit_after>/**
 * @file MS Script host adapter
 * @since 0.1.5
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GPF_HOST*/ // Host types
/*global _gpfBootImplByHost*/ // Boot host specific implementation per host
/*global _gpfConsoleGenerate*/ // Generate an object that can be used to simulate console methods
/*global _gpfExit:true*/ // Exit function
/*global _gpfMainContext*/ // Main context object
/*global _gpfMsFSO:true*/ // Scripting.FileSystemObject activeX
/*#endif*/

/*jshint wsh: true*/
/*eslint-env wsh*/
/*eslint-disable new-cap*/

/**
 * @namespace gpf.wscript
 * @description Root namespace for WScript specifics
 * @since 0.1.9
 */
gpf.wscript = {};

/* istanbul ignore next */ // wscript.echo.1
function _gpfWScriptEcho (text) {
    WScript.Echo(text);
}

_gpfBootImplByHost[_GPF_HOST.WSCRIPT] = function () {

    _gpfMsFSO = new ActiveXObject("Scripting.FileSystemObject");

    // Define console APIs
    _gpfMainContext.console = _gpfConsoleGenerate(_gpfWScriptEcho);

    /* istanbul ignore next */ // exit.1
    _gpfExit = function (code) {
        WScript.Quit(code);
    };

};
<|endoftext|>


<commit_before>/*!
 * HTML Minifier v0.2
 * http://kangax.github.com/html-minifier/
 *
 * Copyright (c) 2010 Juriy "kangax" Zaytsev
 * Licensed under the MIT license.
 *
 */

(function(global){

  var log;
  if (global.console && global.console.log) {
    log = function(message) {
      // "preserving" `this`
      global.console.log(message);
    };
  }
  else {
    log = function(){ };
  }

  function trimWhitespace(str) {
    return (str.trim ? str.trim() : str.replace(/^\s+/, '').replace(/\s+$/, ''));
  }

  function collapseWhitespace(str) {
    return str.replace(/\s+/g, ' ');
  }

  function isConditionalComment(text) {
    return /\[if[^]+\]/.test(text);
  }

  function canRemoveAttributeQuotes(value) {
    // http://www.w3.org/TR/html4/intro/sgmltut.html#attributes
    // avoid \w, which could match unicode in some implementations
    return /^[a-zA-Z0-9-._:]+$/.test(value);
  }

  function attributesInclude(attributes, attribute) {
    for (var i = attributes.length; i--; ) {
      if (attributes[i].name.toLowerCase() === attribute) {
        return true;
      }
    }
    return false;
  }

  function isAttributeRedundant(tag, attrName, attrValue, attrs) {
    attrValue = trimWhitespace(attrValue.toLowerCase());
    return (
        (tag === 'script' &&
        attrName === 'language' &&
        attrValue === 'javascript') ||

        (tag === 'form' &&
        attrName === 'method' &&
        attrValue === 'get') ||

        (tag === 'input' &&
        attrName === 'type' &&
        attrValue === 'text') ||

        (tag === 'script' &&
        attrName === 'charset' &&
        !attributesInclude(attrs, 'src')) ||

        (tag === 'a' &&
        attrName === 'name' &&
        attributesInclude(attrs, 'id'))
    );
  }

  function isBooleanAttribute(attrName) {
    return /^(?:checked|disabled|selected|readonly)$/.test(attrName);
  }

  function cleanAttributeValue(tag, attrName, attrValue) {
    if (/^on[a-z]+/.test(attrName)) {
      return trimWhitespace(attrValue.replace(/^\s*javascript:\s*/i, ''));
    }
    if (attrName === 'class') {
      // trim and collapse whitesapce
      return collapseWhitespace(trimWhitespace(attrValue));
    }
    return attrValue;
  }

  var reEmptyAttribute = new RegExp(
    '^(?:class|id|style|title|lang|dir|on(?:focus|blur|change|click|dblclick|mouse(' +
      '?:down|up|over|move|out)|key(?:press|down|up)))$');

  function canDeleteEmptyAttribute(tag, attrName, attrValue) {
    var isValueEmpty = /^(["'])?\s*\1$/.test(attrValue);
    if (isValueEmpty) {
      log('empty attribute: ' + tag + ' :: ' + attrName);
      return (
        (tag === 'input' && attrName === 'value') ||
        reEmptyAttribute.test(attrName));
    }
    return false;
  }

  function canRemoveElement(tag) {
    return tag !== 'textarea';
  }

  function canCollapseWhitespace(tag) {
    return !(/^(?:script|style|pre|textarea)$/.test(tag));
  }

  function canTrimWhitespace(tag) {
    return !(/^(?:pre|textarea)$/.test(tag));
  }

  function normalizeAttribute(attr, attrs, tag, options) {

    var attrName = attr.name.toLowerCase(),
        attrValue = attr.escaped,
        attrFragment;

    if (options.removeRedundantAttributes &&
        isAttributeRedundant(tag, attrName, attrValue, attrs)) {
      return '';
    }

    attrValue = cleanAttributeValue(tag, attrName, attrValue);

    if (!options.removeAttributeQuotes ||
        !canRemoveAttributeQuotes(attrValue)) {
      attrValue = '"' + attrValue + '"';
    }

    if (options.removeEmptyAttributes &&
        canDeleteEmptyAttribute(tag, attrName, attrValue)) {
      return '';
    }

    if (options.collapseBooleanAttributes &&
        isBooleanAttribute(attrName)) {
      attrFragment = attrName;
    }
    else {
      attrFragment = attrName + '=' + attrValue;
    }

    return (' ' + attrFragment);
  }

  function minify(value, options) {

    options = options || { };
    value = trimWhitespace(value);

    var results = [ ],
        buffer = [ ],
        currentChars = '',
        currentTag = '',
        t = new Date();

    HTMLParser(value, {
      start: function( tag, attrs, unary ) {

        tag = tag.toLowerCase();
        currentTag = tag;

        buffer.push('<', tag);

        for ( var i = 0, len = attrs.length; i < len; i++ ) {
          buffer.push(normalizeAttribute(attrs[i], attrs, tag, options));
        }

        buffer.push('>');
      },
      end: function( tag ) {
        var isElementEmpty = currentChars === '' && tag === currentTag;
        if (options.removeEmptyElements && isElementEmpty && canRemoveElement(tag)) {
          // noop
        }
        else {
          buffer.push('</', tag.toLowerCase(), '>');
          results.push.apply(results, buffer);
        }
        buffer.length = 0;
        currentChars = '';
      },
      chars: function( text ) {
        if (currentTag === 'script' || currentTag === 'style') {
          if (options.removeCommentsFromCDATA) {
            text = text.replace(/^\s*<!--/, '').replace(/-->\s*$/, '');
          }
          if (options.removeCDATASectionsFromCDATA) {
            text = text
              // "/* <![CDATA[ */" or "// <![CDATA["
              .replace(/^(?:\s*\/\*\s*<!\[CDATA\[\s*\*\/|\s*\/\/\s*<!\[CDATA\[.*)/, '')
              // "/* ]]> */" or "// ]]>"
              .replace(/(?:\/\*\s*\]\]>\s*\*\/|\/\/\s*\]\]>)\s*$/, '');
          }
        }
        if (options.collapseWhitespace) {
          if (canTrimWhitespace(currentTag)) {
            text = trimWhitespace(text);
          }
          if (canCollapseWhitespace(currentTag)) {
            text = collapseWhitespace(text);
          }
        }
        currentChars = text;
        buffer.push(text);
      },
      comment: function( text ) {
        if (options.removeComments && !isConditionalComment(text)) {
          text = '';
        }
        else {
          text = '<!--' + text + '-->';
        }
        buffer.push(text);
      },
      doctype: function(doctype) {
        buffer.push(options.useShortDoctype ? '<!DOCTYPE html>' : collapseWhitespace(doctype));
      }
    });

    results.push.apply(results, buffer);

    var str = results.join('');

    log('minified in: ' + (new Date() - t) + 'ms');

    return str;
  }

  // export
  global.minify = minify;

})(this);<commit_msg>Slight refactoring.<commit_after>/*!
 * HTML Minifier v0.2
 * http://kangax.github.com/html-minifier/
 *
 * Copyright (c) 2010 Juriy "kangax" Zaytsev
 * Licensed under the MIT license.
 *
 */

(function(global){

  var log;
  if (global.console && global.console.log) {
    log = function(message) {
      // "preserving" `this`
      global.console.log(message);
    };
  }
  else {
    log = function(){ };
  }

  function trimWhitespace(str) {
    return (str.trim ? str.trim() : str.replace(/^\s+/, '').replace(/\s+$/, ''));
  }

  function collapseWhitespace(str) {
    return str.replace(/\s+/g, ' ');
  }

  function isConditionalComment(text) {
    return (/\[if[^\]]+\]/).test(text);
  }

  function canRemoveAttributeQuotes(value) {
    // http://www.w3.org/TR/html4/intro/sgmltut.html#attributes
    // avoid \w, which could match unicode in some implementations
    return (/^[a-zA-Z0-9-._:]+$/).test(value);
  }

  function attributesInclude(attributes, attribute) {
    for (var i = attributes.length; i--; ) {
      if (attributes[i].name.toLowerCase() === attribute) {
        return true;
      }
    }
    return false;
  }

  function isAttributeRedundant(tag, attrName, attrValue, attrs) {
    attrValue = trimWhitespace(attrValue.toLowerCase());
    return (
        (tag === 'script' &&
        attrName === 'language' &&
        attrValue === 'javascript') ||

        (tag === 'form' &&
        attrName === 'method' &&
        attrValue === 'get') ||

        (tag === 'input' &&
        attrName === 'type' &&
        attrValue === 'text') ||

        (tag === 'script' &&
        attrName === 'charset' &&
        !attributesInclude(attrs, 'src')) ||

        (tag === 'a' &&
        attrName === 'name' &&
        attributesInclude(attrs, 'id'))
    );
  }

  function isBooleanAttribute(attrName) {
    return (/^(?:checked|disabled|selected|readonly)$/).test(attrName);
  }

  function cleanAttributeValue(tag, attrName, attrValue) {
    if (/^on[a-z]+/.test(attrName)) {
      return trimWhitespace(attrValue.replace(/^\s*javascript:\s*/i, ''));
    }
    if (attrName === 'class') {
      // trim and collapse whitesapce
      return collapseWhitespace(trimWhitespace(attrValue));
    }
    return attrValue;
  }

  function removeCDATASections(text) {
    return text
      // "/* <![CDATA[ */" or "// <![CDATA["
      .replace(/^(?:\s*\/\*\s*<!\[CDATA\[\s*\*\/|\s*\/\/\s*<!\[CDATA\[.*)/, '')
      // "/* ]]> */" or "// ]]>"
      .replace(/(?:\/\*\s*\]\]>\s*\*\/|\/\/\s*\]\]>)\s*$/, '');
  }

  function removeComments(text) {
    return text.replace(/^\s*<!--/, '').replace(/-->\s*$/, '');
  }

  var reEmptyAttribute = new RegExp(
    '^(?:class|id|style|title|lang|dir|on(?:focus|blur|change|click|dblclick|mouse(' +
      '?:down|up|over|move|out)|key(?:press|down|up)))$');

  function canDeleteEmptyAttribute(tag, attrName, attrValue) {
    var isValueEmpty = /^(["'])?\s*\1$/.test(attrValue);
    if (isValueEmpty) {
      return (
        (tag === 'input' && attrName === 'value') ||
        reEmptyAttribute.test(attrName));
    }
    return false;
  }

  function canRemoveElement(tag) {
    return tag !== 'textarea';
  }

  function canCollapseWhitespace(tag) {
    return !(/^(?:script|style|pre|textarea)$/.test(tag));
  }

  function canTrimWhitespace(tag) {
    return !(/^(?:pre|textarea)$/.test(tag));
  }

  function normalizeAttribute(attr, attrs, tag, options) {

    var attrName = attr.name.toLowerCase(),
        attrValue = attr.escaped,
        attrFragment;

    if (options.removeRedundantAttributes &&
        isAttributeRedundant(tag, attrName, attrValue, attrs)) {
      return '';
    }

    attrValue = cleanAttributeValue(tag, attrName, attrValue);

    if (!options.removeAttributeQuotes ||
        !canRemoveAttributeQuotes(attrValue)) {
      attrValue = '"' + attrValue + '"';
    }

    if (options.removeEmptyAttributes &&
        canDeleteEmptyAttribute(tag, attrName, attrValue)) {
      return '';
    }

    if (options.collapseBooleanAttributes &&
        isBooleanAttribute(attrName)) {
      attrFragment = attrName;
    }
    else {
      attrFragment = attrName + '=' + attrValue;
    }

    return (' ' + attrFragment);
  }

  function minify(value, options) {

    options = options || { };
    value = trimWhitespace(value);

    var results = [ ],
        buffer = [ ],
        currentChars = '',
        currentTag = '',
        t = new Date();

    HTMLParser(value, {
      start: function( tag, attrs, unary ) {

        tag = tag.toLowerCase();
        currentTag = tag;

        buffer.push('<', tag);

        for ( var i = 0, len = attrs.length; i < len; i++ ) {
          buffer.push(normalizeAttribute(attrs[i], attrs, tag, options));
        }

        buffer.push('>');
      },
      end: function( tag ) {
        var isElementEmpty = currentChars === '' && tag === currentTag;
        if (options.removeEmptyElements && isElementEmpty && canRemoveElement(tag)) {
          // noop
        }
        else {
          buffer.push('</', tag.toLowerCase(), '>');
          results.push.apply(results, buffer);
        }
        buffer.length = 0;
        currentChars = '';
      },
      chars: function( text ) {
        if (currentTag === 'script' || currentTag === 'style') {
          if (options.removeCommentsFromCDATA) {
            text = removeComments(text);
          }
          if (options.removeCDATASectionsFromCDATA) {
            text = removeCDATASections(text);
          }
        }
        if (options.collapseWhitespace) {
          if (canTrimWhitespace(currentTag)) {
            text = trimWhitespace(text);
          }
          if (canCollapseWhitespace(currentTag)) {
            text = collapseWhitespace(text);
          }
        }
        currentChars = text;
        buffer.push(text);
      },
      comment: function( text ) {
        if (options.removeComments && !isConditionalComment(text)) {
          text = '';
        }
        else {
          text = '<!--' + text + '-->';
        }
        buffer.push(text);
      },
      doctype: function(doctype) {
        buffer.push(options.useShortDoctype ? '<!DOCTYPE html>' : collapseWhitespace(doctype));
      }
    });

    results.push.apply(results, buffer);

    var str = results.join('');

    log('minified in: ' + (new Date() - t) + 'ms');

    return str;
  }

  // export
  global.minify = minify;

})(this);<|endoftext|>


<commit_before>/*

The MIT License (MIT)

Copyright (c) 2013 Rémi Arnaud - Advanced Micro Devices, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
//
setViewer6Upload=function(upload){
    var header;
    var index;
    var buttonToReplace;
    upload.callOnClick(function(){
        header = upload.header();
        index=0;
    });
    var url = '/rest3d/upload',
        uploadButton = $('<button/>')
            .addClass('btn')
            .prop('disabled', true)
            .on('click', function (){
                var $this = $(this),
                    data = $this.data();
                $this
                    .off('click')
                    .on('click', function () {
                        $this.remove();
                        data.abort();
                    });
                data.submit();
                buttonToReplace=$(this);
                //.always(function () {
                //     $this.remove();
                // });
        }),
        // show the name of the file nicely
        formatName = function(data,file){
            var i = file.name.lastIndexOf('/');
            return file.name.substring(i+1);
        },
        convertButton = $('<button/>')
            .addClass('btn')
            .prop('disabled', true)
            .on('click', function () {
                var $this = $(this),
                    data = $this.data();
                $this
                    .off('click')
                    .prop('disabled',true)
                // user rest to convert dae into glTF
                var callback = function(data) {
                    $this.prop('disabled',true);
                    if(data.result.output){console.debug(data.result.output);}
                    if(data.result.code){console.debug("Exit code: "+data.result.code);}
                    if (data.error){
                        var span = $('
Error code='+data.error.code+' :: '+data.error.message+'
');
                        data.context.append(span);
                    } else {
                        // ennumerate all resulting files
                        var $conve = upload.header(data.file.name);
                        $.each(data.result.files, function (index, file) {
                            var href = $('');
                            upload.filesArea.append(href);
                            var $download = $("<button>Download</button>").on("click",function(){
                                href[0].click();
                            });

                        var url = decodeURIComponent(file.url);
                        var ext = url.match(/\.[^.]+$/);
                        if(ext==".json"){
                            var $dialog = $("<button>Launch your model</button>").on("click",function(){
                                glTF.load(url, viewer.parse_gltf);
                                window.notif(url);
                            });
                            var $preview = $("<button>Peview</button>").on("click",function(){
                                var gitHtml = '

';
                                gitPanel = $('body').append(gitHtml);
                                $("#dialog").dialog({
                                    autoOpen: true,
                                    width: 800,
                                    height: 600,
                                    open: function (ev, ui) {
                                        $('#myIframe').attr('src', '/viewer/easy-viewer.html?file=/rest3d/upload/'+decodeURIComponent(file.name));
                                    }
                                });
                            });
                                upload.convert($conve,formatName(data,file),$dialog,$download,$preview);
                        }
                        else{
                            upload.download($conve,formatName(data,file),$download);//
                        }
                        });
                    }
                }

                rest3d.convert(data,callback);
            });

    upload.object.on('fileuploadadd', function (e, data) {
        upload.object=$(this);
        data.context = header;
        $.each(data.files, function (index, file) {
            var ext = file.name.match(/\.[^.]+$/);
            if(ext=".dae"){
                var url =  'node.fl4re.com/rest3d/upload/'+decodeURIComponent(file.name);
                console.debug(url);
                var $dialog = $("<button>Launch your model</button>").on("click",function(){
                                COLLADA.load(url, viewer.parse_dae);
                                window.notif(url);
                            }).css("display","none");
                 var $preview = $("<button>Peview</button>").on("click",function(){
                                var gitHtml = '

';
                                gitPanel = $('body').append(gitHtml);
                                $("#dialog").dialog({
                                    autoOpen: true,
                                    width: 800,
                                    height: 600,
                                    open: function (ev, ui) {
                                        $('#myIframe').attr('src', '/viewer/easy-viewer.html?file=/rest3d/upload/'+decodeURIComponent(file.name));
                                    }//
                                });
                            }).css("display","none");
                array = []
                upload.upload(header,file.name,$preview,$dialog,uploadButton.clone(true).data(data));}
            else{this.upload(header,file.name);}
        });
    }).on('fileuploadprocessalways', function (e, data) {
            var indexI = data.index,
            file = data.files[indexI],
             node = $(data.context.children('div')[index+1]);//s
        if (file.preview) {
            node
                .prepend('
')
                .prepend(file.preview);
        }
        if (file.error) {//
          GUI.addTooltip({
                    parent: node.find('button'),
                    content: file.error,
                });//
        }
        if (indexI + 1 === data.files.length) {
            node.find('button')
                .prop('disabled', !!data.files.error);
        }
        index++;//
    }).on('fileuploadprogressall', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        upload.progress.setValue(progress);
    }).on('fileuploaddone', function (e, data) {//
        $.each(data.result.files, function (index, file) {
            file.assetName = data.result.files[index].name;
            var $node = convertButton.clone(true).data({file: file, context: data.context})
                .prop('disabled', !/dae$/i.test(file.url))
            buttonToReplace
                .replaceWith($node)
                .prop("id","nodeClose");//
            GUI.addIcon($node, "ui-icon-check", "", "before");
            $node.parent().parent().show();
        });
    }).on('fileuploadfail', function (e, data) {
        if (!data.result) {
            $(data.context.children()[0])
                .append('
')
                .append('error communicating with server')
                .find('button').remove();
        } else
        $.each(data.result.files, function (index, file) {
            var error = $('').text(file.error);
            $(data.context.children()[index])
                .append('
')
                .append(error)
                .find('button').remove();
        });
    });
}
<commit_msg>dasmpdas<commit_after>/*

The MIT License (MIT)

Copyright (c) 2013 Rémi Arnaud - Advanced Micro Devices, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
//
setViewer6Upload=function(upload){
    var header;
    var index;
    var buttonToReplace;
    upload.callOnClick(function(){
        header = upload.header();
        index=0;
    });
    var url = '/rest3d/upload',
        uploadButton = $('<button/>')
            .addClass('btn')
            .prop('disabled', true)
            .on('click', function (){
                var $this = $(this),
                    data = $this.data();
                $this
                    .off('click')
                    .on('click', function () {
                        $this.remove();
                        data.abort();
                    });
                data.submit();
                buttonToReplace=$(this);
                //.always(function () {
                //     $this.remove();
                // });
        }),
        // show the name of the file nicely
        formatName = function(data,file){
            var i = file.name.lastIndexOf('/');
            return file.name.substring(i+1);
        },
        convertButton = $('<button/>')
            .addClass('btn')
            .prop('disabled', true)
            .on('click', function () {
                var $this = $(this),
                    data = $this.data();
                $this
                    .off('click')
                    .prop('disabled',true)
                // user rest to convert dae into glTF
                var callback = function(data) {
                    $this.prop('disabled',true);
                    if(data.result.output){console.debug(data.result.output);}
                    if(data.result.code){console.debug("Exit code: "+data.result.code);}
                    if (data.error){
                        var span = $('
Error code='+data.error.code+' :: '+data.error.message+'
');
                        data.context.append(span);
                    } else {
                        // ennumerate all resulting files
                        var $conve = upload.header(data.file.name);
                        $.each(data.result.files, function (index, file) {
                            var href = $('');
                            upload.filesArea.append(href);
                            var $download = $("<button>Download</button>").on("click",function(){
                                href[0].click();
                            });

                        var url = decodeURIComponent(file.url);
                        var ext = url.match(/\.[^.]+$/);
                        if(ext==".json"){
                            var $dialog = $("<button>Launch your model</button>").on("click",function(){
                                glTF.load(url, viewer.parse_gltf);
                                window.notif(url);
                            });
                            var $preview = $("<button>Peview</button>").on("click",function(){
                                var gitHtml = '

';
                                gitPanel = $('body').append(gitHtml);
                                $("#dialog").dialog({
                                    autoOpen: true,
                                    width: 800,
                                    height: 600,
                                    open: function (ev, ui) {
                                        $('#myIframe').attr('src', '/viewer/easy-viewer.html?file=/rest3d/upload/'+decodeURIComponent(file.name));
                                    }
                                });
                            });
                                upload.convert($conve,formatName(data,file),$dialog,$download,$preview);
                        }
                        else{
                            upload.download($conve,formatName(data,file),$download);//
                        }
                        });
                    }
                }

                rest3d.convert(data,callback);
            });

    upload.object.on('fileuploadadd', function (e, data) {
        upload.object=$(this);
        data.context = header;
        $.each(data.files, function (index, file) {
            var ext = file.name.match(/\.[^.]+$/);
            if(ext=".dae"){
                var url =  'node.fl4re.com/rest3d/upload/'+decodeURIComponent(file.name);
                console.debug(url);
                var $dialog = $("<button>Launch your model</button>").on("click",function(){
                                COLLADA.load(url, viewer.parse_dae);
                                window.notif(url);
                            }).css("display","none");
                 var $preview = $("<button>Peview</button>").on("click",function(){
                                var gitHtml = '

';
                                gitPanel = $('body').append(gitHtml);
                                $("#dialog").dialog({
                                    autoOpen: true,
                                    width: 800,
                                    height: 600,
                                    open: function (ev, ui) {
                                        $('#myIframe').attr('src', '/viewer/easy-viewer.html?file=/rest3d/upload/'+decodeURIComponent(file.name));
                                    }//
                                });
                            }).css("display","none");
                array = []
                upload.upload(header,file.name,$preview,$dialog,uploadButton.clone(true).data(data));}
            else{this.upload(header,file.name);}
        });
    }).on('fileuploadprocessalways', function (e, data) {
            var indexI = data.index,
            file = data.files[indexI],
             node = $(data.context.children('div')[index+1]);
        if (file.preview) {
            node
                .prepend('
')
                .prepend(file.preview);
        }
        if (file.error) {//
          GUI.addTooltip({
                    parent: node.find('button'),
                    content: file.error,
                });//
        }
        if (indexI + 1 === data.files.length) {
            node.find('button')
                .prop('disabled', !!data.files.error);
        }
        index++;//
    }).on('fileuploadprogressall', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        upload.progress.setValue(progress);
    }).on('fileuploaddone', function (e, data) {//
        $.each(data.result.files, function (index, file) {
            file.assetName = data.result.files[index].name;
            var $node = convertButton.clone(true).data({file: file, context: data.context})
                .prop('disabled', !/dae$/i.test(file.url))
            buttonToReplace
                .replaceWith($node)
                .prop("id","nodeClose");//
            GUI.addIcon($node, "ui-icon-check", "", "before");
            $node.parent().parent().show();
        });
    }).on('fileuploadfail', function (e, data) {
        if (!data.result) {
            $(data.context.children()[0])
                .append('
')
                .append('error communicating with server')
                .find('button').remove();
        } else
        $.each(data.result.files, function (index, file) {
            var error = $('').text(file.error);
            $(data.context.children()[index])
                .append('
')
                .append(error)
                .find('button').remove();
        });
    });
}
<|endoftext|>


<commit_before>var log = require('/api/Log');
var utils = require('/api/Utils');
var Compression = require("ti.compression");
var assert = require('/api/Assert');
var io = require('/lib/socket.io');
var osname = Ti.Platform.osname;
var platform = (osname === 'ipad' || osname === 'iphone') ? 'ios' : osname;
var socket, room;

if (!Ti.App.Properties.hasProperty("tishadow:uuid")) {
  Ti.App.Properties.setString("tishadow:uuid",Ti.Platform.createUUID());
}

exports.currentApp;
exports.connect = function(o) {
  room = o.room;
  var version_property = "tishadow:" + room + ":version";
  if (socket) {
    exports.disconnect();
  }
  socket = io.connect((o.proto || "http") + "://" + o.host + ":"  + o.port, {'force new connection': true});

  socket.on("connect", function() {
    socket.emit("join", {
      name : o.name,
      uuid : Ti.App.Properties.getString("tishadow:uuid"),
      os_osname: Ti.Platform.osname,
      os_version: Ti.Platform.version,
      room : o.room,
      version: Ti.App.Properties.getString(version_property) || undefined
    });

    if(o.callback) {
      o.callback();
    }
  });
  socket.on("error", function(e) {
    if (o.onerror) {
      o.onerror(e);
    }
  });
  socket.on("connect_failed", function(e) {
    if(o.onerror) {
      o.onerror(e);
    }
  });

  // REPL messages
  socket.on('message', function(data) {
    if (!isTarget(data)) {
      return;
    }
    require('/api/PlatformRequire').eval(data);
  });

  socket.on('bundle', function(data) {
    if (!isTarget(data)) {
      return;
    }
    if(data.locale) {
      require("/api/Localisation").locale = data.locale;
    }
    loadRemoteZip(data.name, (o.proto || "http") + "://" + o.host + ":" + o.port + "/bundle", data, version_property);
  });

  socket.on('clear', function(data) {
    if (!isTarget(data)) {
      return;
    }
    exports.clearCache();
  });

  socket.on('close', function(data) {
    if (!isTarget(data)) {
      return;
    }
    exports.closeApp();
  });

  socket.on('screenshot', function(data) {
    if (!isTarget(data)) {
      return;
    }
    Ti.Media.takeScreenshot(function(o) {
      var image = o.media;
      if (data.scale) {
        var height = Ti.Platform.displayCaps.platformHeight * data.scale;
        var width = Ti.Platform.displayCaps.platformWidth * data.scale;
        image = image.imageAsResized(width, height);
      }
      var imgStr = Ti.Utils.base64encode(image).toString();
      socket.emit("screenshot_taken", {image: imgStr});
    });
  });

  socket.on('disconnect', function() {
    if(o.disconnected) {
      o.disconnected();
    }
  });

};

exports.emitLog = function(e) {
  if (socket) {
    socket.emit("log", e);
  }
};

exports.disconnect = function() {
  if (socket) {
    socket.disconnect();
  }
};

var bundle;
exports.closeApp = function(name) {
  require("/api/UI").closeApp(name || exports.currentApp);
  require("/api/App").clearAll();
  log.info("Previous bundle closed.");
};
exports.launchApp = function(name) {
  try {
    var p = require('/api/PlatformRequire');
    exports.closeApp();
    p.clearCache();
    require("/api/Localisation").clear();
    // Custom Fonts
    if (osname === "ipad" || osname === "iphone") {
      require("/api/Fonts").loadCustomFonts(name);
    }
    Ti.App.fireEvent("tishadow:refresh_list");
    exports.currentApp = name;
    bundle = p.include(null, "/app.js");
    log.info(exports.currentApp.replace(/_/g," ") + " launched.");
  } catch(e) {
    log.error(utils.extractExceptionData(e));
  }
};

exports.clearCache = function() {
  require("/api/UI").closeAll();

  Ti.App.Properties.listProperties().forEach(function(property) {
    if (!property.match("^tishadow:")) {
      Ti.App.Properties.removeProperty(property);
    }
  });

  var dirty_directories = [Ti.Filesystem.applicationDataDirectory];
  if (Ti.UI.iOS) {
    var applicationDatabaseDirectory = Ti.Filesystem.applicationDataDirectory.replace("Documents/","") + "Library/Private%20Documents/";
    if (Ti.Filesystem.getFile(applicationDatabaseDirectory).exists()) {
      dirty_directories.push(applicationDatabaseDirectory);
    }
  }

  try {
    dirty_directories.forEach(function(targetDirectory) {
      // Clear Applications
      var files = Ti.Filesystem.getFile(targetDirectory).getDirectoryListing();
      files.forEach(function(file_name) {
        var file = Ti.Filesystem.getFile(targetDirectory,file_name);
        if (Ti.Platform.osname === "android") {
          if (file.isFile()) {
            file.deleteFile();
          } else if (file.isDirectory()) {
            file.deleteDirectory(true);
          }
        } else {
          file.deleteFile();
          file.deleteDirectory(true);
        }
      });
    });
    Ti.App.fireEvent("tishadow:refresh_list");
  } catch (e) {
    log.error(utils.extractExceptionData(e));
  }
  log.info("Cache cleared");
};

function loadRemoteZip(name, url, data, version_property) {
  var xhr = Ti.Network.createHTTPClient();
  xhr.setTimeout(10000);
  xhr.onload=function(e) {
    try {
      log.info("Unpacking new bundle: " + name);

      var path_name = name.replace(/ /g,"_");
      // SAVE ZIP
      var zip_file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path_name + '.zip');
      zip_file.write(this.responseData);
      // Prepare path
      var target = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path_name);
      if (!target.exists()) {
        target.createDirectory();
      }
      // Extract
      var dataDir=Ti.Filesystem.applicationDataDirectory + "/";
      Compression.unzip(dataDir + path_name, dataDir + path_name + '.zip',true);
      if (data && data.version && version_property) {
        Ti.App.Properties.setString(version_property, data.version);
      } else {
        Ti.App.Properties.removeProperty(version_property);
      }
      // Launch
      if (data && data.spec && data.spec.run) {
        exports.currentApp = path_name;
        require("/api/Spec").run(path_name, data.spec.junitxml, data.spec.type);
      } else if (data && data.patch && data.patch.run) {
        require('/api/PlatformRequire').clearCache(data.patch.files);
      } else  {
        exports.launchApp(path_name);
      }
    } catch (e) {
      log.error(utils.extractExceptionData(e));
    }
  };
  xhr.onerror = function(e){
    Ti.UI.createAlertDialog({title:'XHR', message:'Error: ' + e.error}).show();
  };
  xhr.open('GET', url + "/" + room + "/" + Ti.App.Properties.getString("tishadow:uuid") );
  xhr.send();
}

function isTarget(data) {
  return (!data.platform || data.platform.indexOf(osname) !== -1 || data.platform.indexOf(platform) !== -1);
}

// FOR URL SCHEME - tishadow://
function loadRemoteBundle(url) {
  if (url.indexOf(".zip") === -1) {
    alert("Invalid Bundle");
  } else {
    var name_parts = url.split("/");
    var name = name_parts[name_parts.length -1].replace(".zip","");
    loadRemoteZip(name, url);
  }
}

function parseArguments() {
  cmd = Ti.App.getArguments();
  if ( (typeof cmd == 'object') && cmd.hasOwnProperty('url') ) {
    if ( cmd.url !== url ) {
      url = cmd.url;
      if (url.substring(0, 8) === 'tishadow') {
        loadRemoteBundle(url.replace("tishadow", "http"));
      }
    }
  }
}

var url = '';
if (osname !== "android") {
  parseArguments();
  Ti.App.addEventListener( 'resumed', parseArguments);
}
<commit_msg>Fixes multi platform compile for classic projects<commit_after>var log = require('/api/Log');
var utils = require('/api/Utils');
var Compression = require("ti.compression");
var assert = require('/api/Assert');
var io = require('/lib/socket.io');
var osname = Ti.Platform.osname;
var platform = (osname === 'ipad' || osname === 'iphone') ? 'ios' : osname;
var socket, room;

if (!Ti.App.Properties.hasProperty("tishadow:uuid")) {
  Ti.App.Properties.setString("tishadow:uuid",Ti.Platform.createUUID());
}

exports.currentApp;
exports.connect = function(o) {
  room = o.room;
  var version_property = "tishadow:" + room + ":version";
  if (socket) {
    exports.disconnect();
  }
  socket = io.connect((o.proto || "http") + "://" + o.host + ":"  + o.port, {'force new connection': true});

  socket.on("connect", function() {
    socket.emit("join", {
      name : o.name,
      uuid : Ti.App.Properties.getString("tishadow:uuid"),
      os_osname: Ti.Platform.osname,
      os_version: Ti.Platform.version,
      room : o.room,
      version: Ti.App.Properties.getString(version_property) || undefined
    });

    if(o.callback) {
      o.callback();
    }
  });
  socket.on("error", function(e) {
    if (o.onerror) {
      o.onerror(e);
    }
  });
  socket.on("connect_failed", function(e) {
    if(o.onerror) {
      o.onerror(e);
    }
  });

  // REPL messages
  socket.on('message', function(data) {
    if (!isTarget(data)) {
      return;
    }
    require('/api/PlatformRequire').eval(data);
  });

  socket.on('bundle', function(data) {
    if (!isTarget(data)) {
      return;
    }
    if(data.locale) {
      require("/api/Localisation").locale = data.locale;
    }
    loadRemoteZip(data.name, (o.proto || "http") + "://" + o.host + ":" + o.port + "/bundle", data, version_property);
  });

  socket.on('clear', function(data) {
    if (!isTarget(data)) {
      return;
    }
    exports.clearCache();
  });

  socket.on('close', function(data) {
    if (!isTarget(data)) {
      return;
    }
    exports.closeApp();
  });

  socket.on('screenshot', function(data) {
    if (!isTarget(data)) {
      return;
    }
    Ti.Media.takeScreenshot(function(o) {
      var image = o.media;
      if (data.scale) {
        var height = Ti.Platform.displayCaps.platformHeight * data.scale;
        var width = Ti.Platform.displayCaps.platformWidth * data.scale;
        image = image.imageAsResized(width, height);
      }
      var imgStr = Ti.Utils.base64encode(image).toString();
      socket.emit("screenshot_taken", {image: imgStr});
    });
  });

  socket.on('disconnect', function() {
    if(o.disconnected) {
      o.disconnected();
    }
  });

};

exports.emitLog = function(e) {
  if (socket) {
    socket.emit("log", e);
  }
};

exports.disconnect = function() {
  if (socket) {
    socket.disconnect();
  }
};

var bundle;
exports.closeApp = function(name) {
  require("/api/UI").closeApp(name || exports.currentApp);
  require("/api/App").clearAll();
  log.info("Previous bundle closed.");
};
exports.launchApp = function(name) {
  try {
    var p = require('/api/PlatformRequire');
    exports.closeApp();
    p.clearCache();
    require("/api/Localisation").clear();
    // Custom Fonts
    if (osname === "ipad" || osname === "iphone") {
      require("/api/Fonts").loadCustomFonts(name);
    }
    Ti.App.fireEvent("tishadow:refresh_list");
    exports.currentApp = name;
    bundle = p.include(null, "/app.js");
    log.info(exports.currentApp.replace(/_/g," ") + " launched.");
  } catch(e) {
    log.error(utils.extractExceptionData(e));
  }
};

exports.clearCache = function() {
  require("/api/UI").closeAll();

  Ti.App.Properties.listProperties().forEach(function(property) {
    if (!property.match("^tishadow:")) {
      Ti.App.Properties.removeProperty(property);
    }
  });

  var dirty_directories = [Ti.Filesystem.applicationDataDirectory];
  if (Ti.UI.iOS) {
    var applicationDatabaseDirectory = Ti.Filesystem.applicationDataDirectory.replace("Documents/","") + "Library/Private%20Documents/";
    if (Ti.Filesystem.getFile(applicationDatabaseDirectory).exists()) {
      dirty_directories.push(applicationDatabaseDirectory);
    }
  }

  try {
    dirty_directories.forEach(function(targetDirectory) {
      // Clear Applications
      var files = Ti.Filesystem.getFile(targetDirectory).getDirectoryListing();
      files.forEach(function(file_name) {
        var file = Ti.Filesystem.getFile(targetDirectory,file_name);
        if (Ti.Platform.osname === "android") {
          if (file.isFile()) {
            file.deleteFile();
          } else if (file.isDirectory()) {
            file.deleteDirectory(true);
          }
        } else {
          file.deleteFile();
          file.deleteDirectory(true);
        }
      });
    });
    Ti.App.fireEvent("tishadow:refresh_list");
  } catch (e) {
    log.error(utils.extractExceptionData(e));
  }
  log.info("Cache cleared");
};

function loadRemoteZip(name, url, data, version_property) {
  var xhr = Ti.Network.createHTTPClient();
  xhr.setTimeout(10000);
  xhr.onload=function(e) {
    try {
      log.info("Unpacking new bundle: " + name);

      var path_name = name.replace(/ /g,"_");
      // SAVE ZIP
      var zip_file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path_name + '.zip');
      zip_file.write(this.responseData);
      // Prepare path
      var target = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path_name);
      if (!target.exists()) {
        target.createDirectory();
      }
      // Extract
      var dataDir=Ti.Filesystem.applicationDataDirectory + "/";
      Compression.unzip(dataDir + path_name, dataDir + path_name + '.zip',true);
      if (data && data.version && version_property) {
        Ti.App.Properties.setString(version_property, data.version);
      } else {
        Ti.App.Properties.removeProperty(version_property);
      }
      // Launch
      if (data && data.spec && data.spec.run) {
        exports.currentApp = path_name;
        require("/api/Spec").run(path_name, data.spec.junitxml, data.spec.type);
      } else if (data && data.patch && data.patch.run) {
        require('/api/PlatformRequire').clearCache(data.patch.files);
      } else  {
        exports.launchApp(path_name);
      }
    } catch (e) {
      log.error(utils.extractExceptionData(e));
    }
  };
  xhr.onerror = function(e){
    Ti.UI.createAlertDialog({title:'XHR', message:'Error: ' + e.error}).show();
  };
  xhr.open('GET', url + "/" + room + "/" + Ti.App.Properties.getString("tishadow:uuid") );
  xhr.send();
}

function isTarget(data) {
  return (!data.platform || data.platform.length === 0 || data.platform.indexOf(osname) !== -1 || data.platform.indexOf(platform) !== -1);
}

// FOR URL SCHEME - tishadow://
function loadRemoteBundle(url) {
  if (url.indexOf(".zip") === -1) {
    alert("Invalid Bundle");
  } else {
    var name_parts = url.split("/");
    var name = name_parts[name_parts.length -1].replace(".zip","");
    loadRemoteZip(name, url);
  }
}

function parseArguments() {
  cmd = Ti.App.getArguments();
  if ( (typeof cmd == 'object') && cmd.hasOwnProperty('url') ) {
    if ( cmd.url !== url ) {
      url = cmd.url;
      if (url.substring(0, 8) === 'tishadow') {
        loadRemoteBundle(url.replace("tishadow", "http"));
      }
    }
  }
}

var url = '';
if (osname !== "android") {
  parseArguments();
  Ti.App.addEventListener( 'resumed', parseArguments);
}
<|endoftext|>


<commit_before>"use strict";

var FbStrategy = require('passport-facebook').Strategy;
var authConfig = require('../config/auth');
var rp = require('request-promise');
var url = require('../config/url').url;

module.exports = function (passport) {

  passport.serializeUser(function (user, done) {
    // todo
    console.log(user);
    done(null, user);
  })

  passport.deserializeUser(function (user, done) {
    // todo
    console.log(user);
    done(null, user);
  })

  passport.use(new FbStrategy(authConfig,
    function (accessToken, refreshToken, profile, done) {
      // save accessToke to user table
      rp({
        method: 'GET',
        uri: url + '/api/v1/users?fbid=' + profile.id,
        json: true
      }).then(function (result) {
        console.log(result);
        // user found, update token
        return rp({
          method: 'PUT',
          uri: url + '/api/v1/users/' + result.value + '/token',
          body: {
            token: accessToken
          },
          json: true
        });
      }).catch(function (err) {
        if (101 === err.error.status) {
          // user not found, create user
          console.log(JSON.stringify(profile));
          return rp({
            method: 'POST',
            uri: url + '/api/v1/users',
            form: {
              fbid: profile.id,
              name: profile.name,
              gender: profile.gender,
              email: profile.email,
              token: accessToken
            },
            json: true
          });
        } else {
          console.log(err.error);
          throw new Error('unexpected error has occured while creating user');
        }
      }).then(function (result) {
        console.log(result);
      }).catch(function (err) {
        console.log(err);
      });

      done(null, accessToken);
    }
  ));
}<commit_msg>field fix<commit_after>"use strict";

var FbStrategy = require('passport-facebook').Strategy;
var authConfig = require('../config/auth');
var rp = require('request-promise');
var url = require('../config/url').url;

module.exports = function (passport) {

  passport.serializeUser(function (user, done) {
    // todo
    console.log(user);
    done(null, user);
  })

  passport.deserializeUser(function (user, done) {
    // todo
    console.log(user);
    done(null, user);
  })

  passport.use(new FbStrategy(authConfig,
    function (accessToken, refreshToken, profile, done) {
      // save accessToke to user table
      rp({
        method: 'GET',
        uri: url + '/api/v1/users?fbid=' + profile.id,
        json: true
      }).then(function (result) {
        console.log(result);
        // user found, update token
        return rp({
          method: 'PUT',
          uri: url + '/api/v1/users/' + result.value + '/token',
          body: {
            token: accessToken
          },
          json: true
        });
      }).catch(function (err) {
        if (101 === err.error.status) {
          // user not found, create user
          console.log(JSON.stringify(profile));
          return rp({
            method: 'POST',
            uri: url + '/api/v1/users',
            form: {
              fbid: profile._json.id,
              name: profile._json.last_name + ' ' + profile._json.first_name,
              gender: profile._json.gender,
              email: profile._json.email,
              token: accessToken
            },
            json: true
          });
        } else {
          console.log(err.error);
          throw new Error('unexpected error has occured while creating user');
        }
      }).then(function (result) {
        console.log(result);
      }).catch(function (err) {
        console.log(err);
      });

      done(null, accessToken);
    }
  ));
}<|endoftext|>


<commit_before>// Start polling for preview and full render job status and take action when document is ready
$(document).ready(function(){
  // Poll for preview image
  $(".js-nopreview").each(function(){
    var jobId = this.id;
    var intervalTime = 1000;
    var windowLoc = $(location).attr('pathname');
    var intervalID = setInterval(function poll(){
      $.ajax({
        url: "/preview_poll/",
        data: {'jobid': jobId},
        dataType: "json"
      }).done(function(json){
        var info = json.job_info;
        var newid = '#'.concat(jobId);
        if(info.jobstatus != 'Done' && info.jobstatus != 'Failed'){
          // Display loading gif.
          $(newid).html(
            "

");
        }else{
          if(info.jobstatus != 'Failed'){
            // Stop polling on success
            if(windowLoc.indexOf('bands') == -1){
              $(newid).html(
                "" +

                  "
" +
                  "    " + info.band1 + "" +
                  "    " + info.band2 + "" +
                  "    " + info.band3 + "" +
                  "
" +
                  "");
            }else{
              $(newid).html(
                "
" +
                  "" +
                  "" +
                  "" +
                  "
");
            }
            clearInterval(intervalID);
          }else{
            // Stop polling on failure
            $(newid).html(
              "
Preview Failure
");
              clearInterval(intervalID);
          }
        }
      });
    }, intervalTime);
  });

  // Poll for full render job status
  $(".js-nofull").each(function(){
    var jobId = this.id;
    var intervalTime = 10000;
    if(jobId){
      var intervalID = setInterval(function poll(){
        $.ajax({
          url: "/status_poll/",
          data: {'jobid': jobId},
          dataType: "json"
        }).done(function(json){
          var info = json.job_info;
          var newid = '#'.concat(jobId);
          if(info.jobstatus != 'Done' && info.jobstatus != 'Failed'){
            // Update status and elapsed time.
            $(newid).find("#js-fullstatus").html("Status: " + info.jobstatus);
          }else{
            if(info.jobstatus != 'Failed'){
              // Stop polling on success
              $(newid).html(
                "Download full size image." +
                  "");
                clearInterval(intervalID);
            }else{
              // Stop polling on failure
              $(newid).html(
                "
Composite Failure
");
                clearInterval(intervalID);
            }
          }
        });
      }, intervalTime);
    }
  });
});

// Stop polling for a preview when
function stopPreviewPoll(data, intervalID){
  if(data.bool === false){
    clearInterval(intervalID);
  }
}

// Start polliing for preview status
function startPreviewPoll(jobId, intervalID){
  $.ajax({
    url: "/preview_poll/",
    dataType: "json"
  }).done(function(data){
    if(data.bool === false){
      clearInterval(intervalID);
    }
  });
}

// Stop polliing for full render status when
function stopStatusPoll(data, intervalID){
  if(data.bool === false){
    clearInterval(intervalID);
  }
}

// Start polliing for full render status
function startStatusPoll(jobId, intervalID){
  $.ajax({
    url: "/status_poll/",
    dataType: "json"
  }).done(function(data){
    if(data.bool === false){
      clearInterval(intervalID);
    }
  });
}
<commit_msg>#232 fix class styling for inserted element<commit_after>// Start polling for preview and full render job status and take action when document is ready
$(document).ready(function(){
  // Poll for preview image
  $(".js-nopreview").each(function(){
    var jobId = this.id;
    var intervalTime = 1000;
    var windowLoc = $(location).attr('pathname');
    var intervalID = setInterval(function poll(){
      $.ajax({
        url: "/preview_poll/",
        data: {'jobid': jobId},
        dataType: "json"
      }).done(function(json){
        var info = json.job_info;
        var newid = '#'.concat(jobId);
        if(info.jobstatus != 'Done' && info.jobstatus != 'Failed'){
          // Display loading gif.
          $(newid).html(
            "

");
        }else{
          if(info.jobstatus != 'Failed'){
            // Stop polling on success
            if(windowLoc.indexOf('bands') == -1){
              $(newid).html(
                "" +

                  "
" +
                  "    " + info.band1 + "" +
                  "    " + info.band2 + "" +
                  "    " + info.band3 + "" +
                  "
" +
                  "");
            }else{
              $(newid).html(
                "
" +
                  "" +
                  "" +
                  "" +
                  "
");
            }
            clearInterval(intervalID);
          }else{
            // Stop polling on failure
            $(newid).html(
              "
Preview Failure
");
              clearInterval(intervalID);
          }
        }
      });
    }, intervalTime);
  });

  // Poll for full render job status
  $(".js-nofull").each(function(){
    var jobId = this.id;
    var intervalTime = 10000;
    if(jobId){
      var intervalID = setInterval(function poll(){
        $.ajax({
          url: "/status_poll/",
          data: {'jobid': jobId},
          dataType: "json"
        }).done(function(json){
          var info = json.job_info;
          var newid = '#'.concat(jobId);
          if(info.jobstatus != 'Done' && info.jobstatus != 'Failed'){
            // Update status and elapsed time.
            $(newid).find("#js-fullstatus").html("Status: " + info.jobstatus);
          }else{
            if(info.jobstatus != 'Failed'){
              // Stop polling on success
              $(newid).html(
                "Download full size image." +
                  "");
                clearInterval(intervalID);
            }else{
              // Stop polling on failure
              $(newid).html(
                "
Composite Failure
");
                clearInterval(intervalID);
            }
          }
        });
      }, intervalTime);
    }
  });
});

// Stop polling for a preview when
function stopPreviewPoll(data, intervalID){
  if(data.bool === false){
    clearInterval(intervalID);
  }
}

// Start polliing for preview status
function startPreviewPoll(jobId, intervalID){
  $.ajax({
    url: "/preview_poll/",
    dataType: "json"
  }).done(function(data){
    if(data.bool === false){
      clearInterval(intervalID);
    }
  });
}

// Stop polliing for full render status when
function stopStatusPoll(data, intervalID){
  if(data.bool === false){
    clearInterval(intervalID);
  }
}

// Start polliing for full render status
function startStatusPoll(jobId, intervalID){
  $.ajax({
    url: "/status_poll/",
    dataType: "json"
  }).done(function(data){
    if(data.bool === false){
      clearInterval(intervalID);
    }
  });
}
<|endoftext|>