<commit_before>var watch = require('watch'),
	fs = require('fs'),
	path = require('path'),
	jade = require('jade'),
	express = require('express');

function compileTemplate(path, callback) {
	fs.readFile(path, 'utf-8', function(err, data) {
		if (err) throw err;
		callback(jade.compile(data));
	});
}

function removeRoute(route) {
	var routes = woods.express.routes;
	for (var i in routes.get) {
		if (routes.get[i].path + '' === route + '') {
			routes.get.splice(i, 1);
			break;
		}
	}
}

var Site = function(param) {
	this.directory = param.directory;
	woods.express.use(
		this.getUrl() + 'static/',
		express.static(param.assets || this.getUri('assets/'))
	);
	this.build();
	this.watchDirectory();
};

Site.prototype.build = function() {
	// TODO: remove static routes
	if (this.pageByUrl) {
		for (var i in this.pageByUrl) {
			removeRoute(i);
		}
	}
	this.pageByUrl = {};
	this.types = {};
	this.templateLocations = {};
	this.root = new Page(this, null, '');
	this.addType('default');
};

// TODO: moving this to woods makes sense:
Site.prototype.watchDirectory = function() {
	var directory = path.resolve(woods.directory, this.directory);
	var watch = require('watch');
	var that = this;
	watch.watchTree(directory, function (f, curr, prev) {
		// Finished walking the site:
		if (typeof f == "object" && prev === null && curr === null)
			return;
		var then = new Date();

		// TODO: rebuild the Page instead of the whole site
		// TODO: ignore changes in static directories?
		that.build();
		console.log(new Date());
		console.log('Rebuilding took', new Date() - then);
	});
};

Site.prototype.getPageByUrl = function(url) {
	return this.pageByUrl[path.join(this.getUrl() + url)];
};

Site.prototype.getUrl = function() {
	return '/' + this.directory;
};

Site.prototype.getUri = function(subfolder) {
	return path.resolve(woods.directory, this.directory, subfolder || '');
};

Site.prototype.getTemplateUri = function(type) {
	return this.getUri('templates/' + (type ? type + '/' : ''));
};

Site.prototype.addType = function(type) {
	if (!this.types[type]) {
		// Check for templates belonging to type and install them
		// TODO: make async
		var typeTemplates = this.types[type] = {},
			templateLocations = this.templateLocations[type] = {},
			templatesDir = this.getTemplateUri(type);
		if (!fs.existsSync(templatesDir))
			return;
		var files = fs.readdirSync(templatesDir);
		files.forEach(function(file) {
			if ((/jade$/).test(file)) {
				var templateName = path.basename(file, '.jade');
				var location = templateLocations[templateName] =
						path.join(templatesDir, file);
				compileTemplate(location, function(renderer) {
					typeTemplates[templateName] = renderer;
				});
			}
		});
	}
};

var Page = require('./Page'),
	woods = require('./woods');

module.exports = Site;
<commit_msg>Use path.join for path concatenation.<commit_after>var watch = require('watch'),
	fs = require('fs'),
	path = require('path'),
	jade = require('jade'),
	express = require('express');

function compileTemplate(path, callback) {
	fs.readFile(path, 'utf-8', function(err, data) {
		if (err) throw err;
		callback(jade.compile(data));
	});
}

function removeRoute(route) {
	var routes = woods.express.routes;
	for (var i in routes.get) {
		if (routes.get[i].path + '' === route + '') {
			routes.get.splice(i, 1);
			break;
		}
	}
}

var Site = function(param) {
	this.directory = param.directory;
	woods.express.use(
		path.join(this.getUrl(), 'static'),
		express.static(param.assets || this.getUri('assets/'))
	);
	this.build();
	this.watchDirectory();
};

Site.prototype.build = function() {
	// TODO: remove static routes
	if (this.pageByUrl) {
		for (var i in this.pageByUrl) {
			removeRoute(i);
		}
	}
	this.pageByUrl = {};
	this.types = {};
	this.templateLocations = {};
	this.root = new Page(this, null, '');
	this.addType('default');
};

// TODO: moving this to woods makes sense:
Site.prototype.watchDirectory = function() {
	var directory = path.resolve(woods.directory, this.directory);
	var watch = require('watch');
	var that = this;
	watch.watchTree(directory, function (f, curr, prev) {
		// Finished walking the site:
		if (typeof f == "object" && prev === null && curr === null)
			return;
		var then = new Date();

		// TODO: rebuild the Page instead of the whole site
		// TODO: ignore changes in static directories?
		that.build();
		console.log(new Date());
		console.log('Rebuilding took', new Date() - then);
	});
};

Site.prototype.getPageByUrl = function(url) {
	return this.pageByUrl[path.join(this.getUrl(), url || '')];
};

Site.prototype.getUrl = function() {
	return '/' + this.directory;
};

Site.prototype.getUri = function(subfolder) {
	return path.resolve(woods.directory, this.directory, subfolder || '');
};

Site.prototype.getTemplateUri = function(type) {
	return this.getUri(path.join('templates', type || ''));
};

Site.prototype.addType = function(type) {
	if (!this.types[type]) {
		// Check for templates belonging to type and install them
		// TODO: make async
		var typeTemplates = this.types[type] = {},
			templateLocations = this.templateLocations[type] = {},
			templatesDir = this.getTemplateUri(type);
		if (!fs.existsSync(templatesDir))
			return;
		var files = fs.readdirSync(templatesDir);
		files.forEach(function(file) {
			if ((/jade$/).test(file)) {
				var templateName = path.basename(file, '.jade');
				var location = templateLocations[templateName] =
						path.join(templatesDir, file);
				compileTemplate(location, function(renderer) {
					typeTemplates[templateName] = renderer;
				});
			}
		});
	}
};

var Page = require('./Page'),
	woods = require('./woods');

module.exports = Site;
<|endoftext|>


<commit_before>$( document ).ready(function() {

 $.getJSON('/api/v1/assts', {"usersId": '1'}).then( (data) => {
  console.log('get assts ', data)
  let tbody = $('#assignments tbody')
  data.forEach( (item) => {
  tbody.append($(`

    ${item.title}
    ${item.description}
<<<<<<< HEAD
    ${item.title}
    Submit Here
=======
    ${item.title}
    Submit Here
>>>>>>> FirstPage

`))
  })
})

})

  // $("this").click(function(){
  //   console.log("helloworld")
  // });
<commit_msg>deleted conflicts<commit_after>$( document ).ready(function() {

 $.getJSON('/api/v1/assts', {"usersId": '1'}).then( (data) => {
  console.log('get assts ', data)
  let tbody = $('#assignments tbody')
  data.forEach( (item) => {
  tbody.append($(`

    ${item.title}
    ${item.description}
    ${item.title}
    Submit Here

`))
  })
})

})

  // $("this").click(function(){
  //   console.log("helloworld")
  // });
<|endoftext|>


<commit_before>/**
 * index.js - Main library for index page/view.
 * Authors: Ian McGaunn; Dave Zimmelman
 * Modified: 09 Mar 15
 */
(function (window, $) {
    'use strict';

    window.load_splash_view = function () {
        $.get('/api/view/splash', function (data) {

            $('#left-col').html(data);

            $.get('/api/castcat/0', function (data) {
                insertPodcasts(data.podcasts, '#pc-0 > .panel-body', false, false);
            });

            $('#left-col .genre-panel').each(function () {
                var i, el = $(this).find('.panel-body'), gid = $(this).data('genreid');
                $.get('/api/castcat/' + gid, function (data) {
                    el.html('');
                    if (data.favorites) {
                        insertPodcasts(data.favorites, el, false, true);
                    }
                    insertPodcasts(data.podcasts, el, false, false);
                });
            });

            $('#podcast-search-input').on('change keyup paste', function (e) {
                if (e.type == "keyup" && e.which == 13) {
                    // Enter key pressed
                    submitSearch();
                }
                else if ($(this).val().trim() !== "" &&
                         $(this).val().trim() !== window.lastTickSearch &&
                         window.searchBoxTH === null) {
                    window.quicksearch();
                    window.searchBoxTH = setInterval(window.quicksearch, 250);
                }
                else if ($(this).val().trim() === "") {
                    clearInterval(window.searchBoxTH);
                    window.searchBoxTH = null;
                    searchResults({});
                }
            });
            // Search button press
            $('#podcast-search-button').click(function () {
                submitSearch();
            });
        });
    };

    window.load_podcast_view = function (id) {
        $.get('/api/view/podcast/'+ id, function (data) {
            $('#left-col').html(data);

            // Reformat URL to reflect appropriate title.
            window.history.replaceState({}, document.title, '/podcast/' + window.safetitle);
        });
    };

    function insertPodcasts(pcasts, selector, append, fav) {
        var i;
        if (!append) $(selector).html('');
        for (i in pcasts) {
            var classes = (fav) ? "castnail favorite" : "castnail";
            $(selector).append('

');
        }
    }

    /**
     * Populate results table with search data.
     * @param {Object} data - The JSON object returned from iTunes query.
     */
    function searchResults(results) {
        var podcast, row, count;
        // Update table title with result count.
        if (results.length > 0) {
            $('#result-counter').html(results.length + " Results");
            $('#search-results').css('height', '120px');
            $('#search-results').css('padding', '10px');
        } else {
            $('#result-counter').html("No Results");
            $('#search-results').css('height', '0px');
            $('#search-results').css('padding', '0px');
        }
        insertPodcasts(results, '#search-results');
    }

    /* When document is finished loading, execute following code: */
    $().ready(function () {

        window.searchBoxTH = null;
        window.lastTickSearch = "";
        // Submit search query
        var submitSearch = function () {
            clearInterval(window.searchBoxTH);
            window.searchBoxTH = null;
            var searchTerm = $('#podcast-search-input').val();
            // Get search data from API.
            $.get('/api/search/?term=' + searchTerm, function (data) {
                // Parse results and add to table.
                searchResults(data);
                // Push new URL state.
                //window.history.pushState({}, document.title, '/search/' + searchTerm);
            });
        };
        // Search box change
        var quicksearch = function () {
            var s = $('#podcast-search-input').val().trim();
            if (s == window.lastTickSearch) {
                clearInterval(window.searchBoxTH);
                window.searchBoxTH = null;
                return;
            }
            if (s != "") {
                window.lastTickSearch = s;
                $.get('/api/quicksearch/?term=' + s, function (data) {
                    searchResults(data);
                });
            }
        };
        if (window['preload_cast']) {
            window.load_podcast_view(window.preload_cast);
        }
        else {
            window.load_splash_view();
        }

    });
}(window, jQuery));
<commit_msg>Cleaned up window history states<commit_after>/**
 * index.js - Main library for index page/view.
 * Authors: Ian McGaunn; Dave Zimmelman
 * Modified: 09 Mar 15
 */
(function (window, $) {
    'use strict';

    window.load_splash_view = function (first) {
        $.get('/api/view/splash', function (data) {

            if (!first) window.history.pushState({}, document.title, '/');

            $('#left-col').html(data);

            $.get('/api/castcat/0', function (data) {
                insertPodcasts(data.podcasts, '#pc-0 > .panel-body', false, false);
            });

            $('#left-col .genre-panel').each(function () {
                var i, el = $(this).find('.panel-body'), gid = $(this).data('genreid');
                $.get('/api/castcat/' + gid, function (data) {
                    el.html('');
                    if (data.favorites) {
                        insertPodcasts(data.favorites, el, false, true);
                    }
                    insertPodcasts(data.podcasts, el, false, false);
                });
            });

            $('#podcast-search-input').on('change keyup paste', function (e) {
                if (e.type == "keyup" && e.which == 13) {
                    // Enter key pressed
                    submitSearch();
                }
                else if ($(this).val().trim() !== "" &&
                         $(this).val().trim() !== window.lastTickSearch &&
                         window.searchBoxTH === null) {
                    window.quicksearch();
                    window.searchBoxTH = setInterval(window.quicksearch, 250);
                }
                else if ($(this).val().trim() === "") {
                    clearInterval(window.searchBoxTH);
                    window.searchBoxTH = null;
                    searchResults({});
                }
            });
            // Search button press
            $('#podcast-search-button').click(function () {
                submitSearch();
            });
        });
    };

    window.load_podcast_view = function (id) {
        $.get('/api/view/podcast/'+ id, function (data) {
            $('#left-col').html(data);

            // Reformat URL to reflect appropriate title.
            if (window['preload_cast']) {
                window.history.replaceState({}, document.title, '/podcast/' + window.safetitle);
                delete window['preload_cast'];
            } else {
                window.history.pushState({}, document.title, '/podcast/' + window.safetitle);
            }
        });
    };

    function insertPodcasts(pcasts, selector, append, fav) {
        var i;
        if (!append) $(selector).html('');
        for (i in pcasts) {
            var classes = (fav) ? "castnail favorite" : "castnail";
            $(selector).append('

');
        }
    }

    /**
     * Populate results table with search data.
     * @param {Object} data - The JSON object returned from iTunes query.
     */
    function searchResults(results) {
        var podcast, row, count;
        // Update table title with result count.
        if (results.length > 0) {
            $('#result-counter').html(results.length + " Results");
            $('#search-results').css('height', '120px');
            $('#search-results').css('padding', '10px');
        } else {
            $('#result-counter').html("No Results");
            $('#search-results').css('height', '0px');
            $('#search-results').css('padding', '0px');
        }
        insertPodcasts(results, '#search-results');
    }

    /* When document is finished loading, execute following code: */
    $().ready(function () {

        window.searchBoxTH = null;
        window.lastTickSearch = "";
        // Submit search query
        var submitSearch = function () {
            clearInterval(window.searchBoxTH);
            window.searchBoxTH = null;
            var searchTerm = $('#podcast-search-input').val();
            // Get search data from API.
            $.get('/api/search/?term=' + searchTerm, function (data) {
                // Parse results and add to table.
                searchResults(data);
                // Push new URL state.
                //window.history.pushState({}, document.title, '/search/' + searchTerm);
            });
        };
        // Search box change
        var quicksearch = function () {
            var s = $('#podcast-search-input').val().trim();
            if (s == window.lastTickSearch) {
                clearInterval(window.searchBoxTH);
                window.searchBoxTH = null;
                return;
            }
            if (s != "") {
                window.lastTickSearch = s;
                $.get('/api/quicksearch/?term=' + s, function (data) {
                    searchResults(data);
                });
            }
        };
        if (window['preload_cast']) {
            window.load_podcast_view(window.preload_cast);
        }
        else {
            window.load_splash_view(true);
        }

    });
}(window, jQuery));
<|endoftext|>


<commit_before>// $(function() {
//     $("#print").on('click', function() {
//        // console.log("asdfasdfasd asdfasdf asdasdf");
//         $.print("#content-box");
//     });

    var doc = new jsPDF();
        var specialElementHandlers = {
            '#editor': function (element, renderer) {
                return true;
            }
        };

        $('#pdf').click(function () {
           // alert("asdfasdf");
            doc.fromHTML($('#content-box').html(), 15, 15, {
                'width': 600,
                    'elementHandlers': specialElementHandlers
            });
            doc.save('sample-file.pdf');
    });

      $(function() {
    $("#message").on('click', function() {
        alert("asdfasdf");
       // $.message("#formdata");
    });
     });

});<commit_msg>change data<commit_after>// $(function() {
//     $("#print").on('click', function() {
//        // console.log("asdfasdfasd asdfasdf asdasdf");
//         $.print("#content-box");
//     });

    var doc = new jsPDF();
        var specialElementHandlers = {
            '#editor': function (element, renderer) {
                return true;
            }
        };

        $('#pdf').click(function () {
           // alert("asdfasdf");
            doc.fromHTML($('#content-box').html(), 15, 15, {
                'width': 170,
                    'elementHandlers': specialElementHandlers
            });
            doc.save('sample-file.pdf');
    });

      $(function() {
    $("#message").on('click', function() {
        alert("asdfasdf");
       // $.message("#formdata");
    });
     });

});<|endoftext|>


<commit_before>// $(function() {
//     $("#print").on('click', function() {
//        // console.log("asdfasdfasd asdfasdf asdasdf");
//         $.print("#content-box");
//     });
var imageSrc;
$(document).ready(function(){
    imageSrc = $('#image').attr('src');
    //console.log(imageSrc);

    var doc = new jsPDF();
    var dataURL;
    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }

    };

    $('#pdf').click(function () {
        //image converet to base 64 open
        var imageUrl = $('#image').attr('src');
        var imageUrl1 = $('#image1').attr('src');
        var imageUrl2 = $('#image2').attr('src');
        var imageUrl3 = $('#image3').attr('src');

        var imageArr = [imageUrl,imageUrl1,imageUrl2,imageUrl3];
        var dataURLArr = [];
        var precount = imageArr.length;
        //trim the imageArray to remove undefined if less than 4 images.
        for(var i=0; i< precount; i++) {
            if(imageArr[i] == 'undefined' || imageArr[i] == null) {
                var index = imageArr.indexOf(imageArr[i]);
                if (index > -1) {
                    imageArr.splice(index, 1);
                }
            }
        }
        for (var i=0; i< imageArr.length; i++) {
            convertImgToBase64(imageArr[i], i); // pass index of current element
        }
            //createPdf();
            //console.log(dataURLArr[i] + "" + "" + "num" + i);

        //var data = $('#content-box').html();
        console.log('imageUrl', imageUrl);

        function convertImgToBase64(url, imageCount){
            var canvas = document.createElement('CANVAS');
            var ctx = canvas.getContext('2d');
            var img = new Image;
            img.crossOrigin = 'Anonymous';
            img.src = url;
            img.onload = function(){
                canvas.height = img.height;
                canvas.width = img.width;
                ctx.drawImage(img,0,0);
                dataURL = canvas.toDataURL('image/jpeg');
                dataURLArr.push(dataURL);
                if(imageCount == imageArr.length-1) { // check if it is last index of array
                    createPdf();
                }
                console.log('dataUrl',dataURL);
                //callback.call(this, dataURL);
                // Clean up
                canvas = null;
            };

        }
                // image convert base64 close
        function createPdf() {
            //console.log('dataUrl in createPdf',dataURL);
            if (dataURLArr.length > 0) {
                var doc = new jsPDF('p','mm',[297,210],pt','a4');
               // console.log(imageSrc);
                var imgData;
                for (var i=0; i<dataURLArr.length; i++) {
                    imgData = dataURLArr[i];
                   doc.addImage(imgData, 'JPEG', 15, 50*(i+1), 60, 40);
                }
                doc.fromHTML($('#content-data').html(), 80,30,  {
                    'width': 450,'elementHandlers': specialElementHandlers
                });
                doc.save('sample-file.pdf');
            }
        };
    });
});
<commit_msg>added content data id<commit_after>// $(function() {
//     $("#print").on('click', function() {
//        // console.log("asdfasdfasd asdfasdf asdasdf");
//         $.print("#content-box");
//     });
var imageSrc;
$(document).ready(function(){
    imageSrc = $('#image').attr('src');
    //console.log(imageSrc);

    var doc = new jsPDF();
    var dataURL;
    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }

    };

    $('#pdf').click(function () {
        //image converet to base 64 open
        var imageUrl = $('#image').attr('src');
        var imageUrl1 = $('#image1').attr('src');
        var imageUrl2 = $('#image2').attr('src');
        var imageUrl3 = $('#image3').attr('src');

        var imageArr = [imageUrl,imageUrl1,imageUrl2,imageUrl3];
        var dataURLArr = [];
        var precount = imageArr.length;
        //trim the imageArray to remove undefined if less than 4 images.
        for(var i=0; i< precount; i++) {
            if(imageArr[i] == 'undefined' || imageArr[i] == null) {
                var index = imageArr.indexOf(imageArr[i]);
                if (index > -1) {
                    imageArr.splice(index, 1);
                }
            }
        }
        for (var i=0; i< imageArr.length; i++) {
            convertImgToBase64(imageArr[i], i); // pass index of current element
        }
            //createPdf();
            //console.log(dataURLArr[i] + "" + "" + "num" + i);

        //var data = $('#content-box').html();
        console.log('imageUrl', imageUrl);

        function convertImgToBase64(url, imageCount){
            var canvas = document.createElement('CANVAS');
            var ctx = canvas.getContext('2d');
            var img = new Image;
            img.crossOrigin = 'Anonymous';
            img.src = url;
            img.onload = function(){
                canvas.height = img.height;
                canvas.width = img.width;
                ctx.drawImage(img,0,0);
                dataURL = canvas.toDataURL('image/jpeg');
                dataURLArr.push(dataURL);
                if(imageCount == imageArr.length-1) { // check if it is last index of array
                    createPdf();
                }
                console.log('dataUrl',dataURL);
                //callback.call(this, dataURL);
                // Clean up
                canvas = null;
            };

        }
                // image convert base64 close
        function createPdf() {
            //console.log('dataUrl in createPdf',dataURL);
            if (dataURLArr.length > 0) {
                var doc = new jsPDF('p','mm',[297,210],'pt','a4');
               // console.log(imageSrc);
                var imgData;
                for (var i=0; i<dataURLArr.length; i++) {
                    imgData = dataURLArr[i];
                   doc.addImage(imgData, 'JPEG', 15, 50*(i+1), 60, 40);
                }
                doc.fromHTML($('#content-data').html(), 80,30,  {
                    'width': 450,'elementHandlers': specialElementHandlers
                });
                doc.save('sample-file.pdf');
            }
        };
    });
});
<|endoftext|>


<commit_before>const inputs = {
  performanceName: $('.performanceName'),
  performanceDate: $('.performanceDate'),
  openAt: $('.openAt'),
  closeAt: $('.closeAt'),
  current: $('.current')
};

$('.newPerformanceSubmit').on('click', () => {
  if (validInput()) {
    fetch('/performances/create', {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      credentials: 'same-origin',
      method: 'post',
      body: JSON.stringify({
        performanceName: inputs.performanceName.val(),
        performanceDate: inputs.performanceDate.val(),
        openAt: inputs.openAt.val(),
        closeAt: inputs.closeAt.val(),
        current: inputs.current.is(':checked')
      })
    })
    .then(() => {
      banner(`Successfully Created ${inputs.performanceName.val()}!`);
      clearInput();
    })
    .catch(err => console.error(err));

  } else {
    console.log('Bad data');
  }
});

const clearInput = () => {
  inputs.performanceName.val('');
  inputs.performanceDate.val('');
  inputs.openAt.val('');
  inputs.closeAt.val('');
};

const banner = (message) => {
  $('.navbar').after(`<h2>${message}</h2>`);
};

const validInput = () => {
  const { performanceName, performanceDate, openAt, closeAt } = inputs;

  return performanceName.val().length > 0 &&
    !isNaN(Date.parse(performanceDate.val())) &&
    !isNaN(Date.parse(openAt.val())) &&
    !isNaN(Date.parse(closeAt.val()));
};
<commit_msg>Banner message for new performance errors<commit_after>const inputs = {
  performanceName: $('.performanceName'),
  performanceDate: $('.performanceDate'),
  openAt: $('.openAt'),
  closeAt: $('.closeAt'),
  current: $('.current')
};

$('.newPerformanceSubmit').on('click', () => {
  if (validInput()) {
    fetch('/performances/create', {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      credentials: 'same-origin',
      method: 'post',
      body: JSON.stringify({
        performanceName: inputs.performanceName.val(),
        performanceDate: inputs.performanceDate.val(),
        openAt: inputs.openAt.val(),
        closeAt: inputs.closeAt.val(),
        current: inputs.current.is(':checked')
      })
    })
    .then(() => {
      banner(`Successfully Created ${inputs.performanceName.val()}!`);
      clearInput();
    })
    .catch(err => {
      banner('We\'re sorry! There was an error creating your performance');
      console.error(err);
    });

  } else {
    banner('We couldn\'t create your new performance. Please format your input like the suggestions');
  }
});

const clearInput = () => {
  inputs.performanceName.val('');
  inputs.performanceDate.val('');
  inputs.openAt.val('');
  inputs.closeAt.val('');
};

const banner = (message) => {
  $('.bannerMessage').remove();
  $('.navbar').after(`<h3 class="bannerMessage">${message}</h3>`);
};

const validInput = () => {
  const { performanceName, performanceDate, openAt, closeAt } = inputs;

  return performanceName.val().length > 0 &&
    !isNaN(Date.parse(performanceDate.val())) &&
    !isNaN(Date.parse(openAt.val())) &&
    !isNaN(Date.parse(closeAt.val()));
};
<|endoftext|>


<commit_before>'use strict'

const common = require('./webpack.common')

const webpack = require('webpack')
const webpackTargetElectronRenderer = require('webpack-target-electron-renderer')

const config = {
  devtool: 'cheap-module-eval-source-map',
  entry: Object.assign({}, common.entry, {
    renderer: ['webpack-hot-middleware/client?path=http://localhost:3000/__webpack_hmr', ...common.entry.renderer],
    shared: ['webpack-hot-middleware/client?path=http://localhost:3000/__webpack_hmr', ...common.entry.shared]
  }),
  output: {
    filename: common.output.filename,
    path: common.output.path,
    libraryTarget: common.output.libraryTarget,
    publicPath: 'http://localhost:3000/build/'
  },
  plugins: [
    ...common.plugins,
    new webpack.HotModuleReplacementPlugin(),
    new webpack.DefinePlugin(Object.assign({}, {
      __DEV__: true,
      __RELEASE_ENV__: 'development'
    }, common.replacements))
  ],
  module: common.module,
  resolve: common.resolve,
  target: 'electron',
  externals: common.externals,
  node: common.node
}

// This will cause the compiled CSS (and sourceMap) to be
// embedded within the compiled javascript bundle and added
// as a blob:// uri at runtime.
config.module.loaders.push({
  test: /\.(scss|css)$/,
  loaders: ['style', 'css?sourceMap', 'sass?sourceMap']
})

config.target = webpackTargetElectronRenderer(config)

module.exports = config
<commit_msg>Stringify so it remains a string<commit_after>'use strict'

const common = require('./webpack.common')

const webpack = require('webpack')
const webpackTargetElectronRenderer = require('webpack-target-electron-renderer')

const config = {
  devtool: 'cheap-module-eval-source-map',
  entry: Object.assign({}, common.entry, {
    renderer: ['webpack-hot-middleware/client?path=http://localhost:3000/__webpack_hmr', ...common.entry.renderer],
    shared: ['webpack-hot-middleware/client?path=http://localhost:3000/__webpack_hmr', ...common.entry.shared]
  }),
  output: {
    filename: common.output.filename,
    path: common.output.path,
    libraryTarget: common.output.libraryTarget,
    publicPath: 'http://localhost:3000/build/'
  },
  plugins: [
    ...common.plugins,
    new webpack.HotModuleReplacementPlugin(),
    new webpack.DefinePlugin(Object.assign({}, {
      __DEV__: true,
      __RELEASE_ENV__: JSON.stringify('development')
    }, common.replacements))
  ],
  module: common.module,
  resolve: common.resolve,
  target: 'electron',
  externals: common.externals,
  node: common.node
}

// This will cause the compiled CSS (and sourceMap) to be
// embedded within the compiled javascript bundle and added
// as a blob:// uri at runtime.
config.module.loaders.push({
  test: /\.(scss|css)$/,
  loaders: ['style', 'css?sourceMap', 'sass?sourceMap']
})

config.target = webpackTargetElectronRenderer(config)

module.exports = config
<|endoftext|>


<commit_before>define(function (require) {
	/*
	 TODO: Remove jquery dependency
	 */
	var transport = require('jquery').ajax,
		placeholder = /^{(.+)}$/;

	function request(method, url, data, headers) {
		return transport({
			url: url,
			type: method,
			data: data,
			headers: headers,
			xhrFields: {
				withCredentials: true
			}
		});
	}

	function result(value) {
		if (value.indexOf('=') === -1)
			return value;

		parts = value.split('=');
		value = new String(parts[0]);
		value.variable = parts[1];
		return value
	}

	return function apic(desc, ssl, options) {
		options = options || {};

		var base = desc.base,
			safeMethods = { 'GET': true, 'HEAD': true, 'OPTIONS': true },
			tokenHeader = options.tokenHeader || 'X-Security-Token',
			aliases = options.aliases || {
				'PUT': ['save'],
				'POST': ['add'],
				'DELETE': ['remove']
			};

		var token, variables = {};

		function last(arr) {
			return typeof arr[arr.length - 1];
		}

		function method(verb, uri, res, params, secure) {
			var safe = safeMethods[verb] || false,
				protocol = ssl || (secure = secure || !safe) ? 'https:' : 'http:';

			return function () {
				var args = Array.prototype.slice.call(arguments),
					callback = last(args) === 'function' ? args.pop() : undefined,
					query = last(args) === 'object' ? args.pop() : {},
					path = uri,
					headers = {}
					;

				/*
				 Check if all necessary arguments passed in arguments or query object or have default variable value
				 */
				if (params.reduce(function (a, b) {
					return a - +(query.hasOwnProperty(b) || !!variables[b.variable]);
				}, params.length) > args.length)
					throw new Error([
						params.length, ' argument', (params.length === 1 ? '' : 's'),
						params.length ? ' (' + params.join(', ') + ')' : '',
						' expected ', args.length, ' given',
						args.length ? ' (' + args.join(', ') + ')' : ''
					].join(''));

				params.forEach(function (name, i) {
					if (query[name] !== undefined && args[i] !== undefined)
						throw new Error('Duplicate key (' + name + ')');

					if (query[name] === undefined) {
						query[name] = args[i] === undefined
							? (name.variable && variables[name.variable])
							: args[i];
					}

					if (name.template) {
						var _ = '{' + name + '}',
							value = args[i] || query[name];

						path.indexOf(_) === -1
							? (path += '/' + value)
							: (path = path.replace(_, value));

						delete query[name];
					}
				});

				secure && (headers[tokenHeader] = token);

				var err, resp;

				return request(verb, protocol + base + path, query, headers)
					.done(function (data, code, xhr) {
						res.variable && (variables[res.variable] = data[res]);

						resp = data[res];

					})
					.fail(function (xhr) {
						err = {};

						if (xhr.responseText) {
							try {
								err = JSON.parse(xhr.responseText)['error'] || {};
							}
							catch (e) {
							}
						}

						err.status = xhr.status;
					})
					.always(function(a, status, b) {
						var xhr = status === 'success' ? b : a; // WTF

						secure && (token = xhr.getResponseHeader(tokenHeader) || token);

						callback && (callback.length > 1
							? callback(err, resp)
							: (err || callback(resp))
							);
					});
			};
		}

		return function generate(map, url, res) {
			var key,
				value,
				parts,
				secure,
				transparent,
				tree,
				_;

			res = res || {};

			for (key in map)
				if (map.hasOwnProperty(key) && key !== '@') {
					value = map[key];

					transparent = key.match(placeholder);

					key = (parts = key.split('#')).shift();

					parts = parts.map(function (name) {
						var template, variable, match;

						if (name.charAt(0) === '/') {
							template = true;
							name = name.substr(1);
						}

						if (match = name.match(placeholder)) {
							parts = match[1].split('=');

							name = parts[0];
							variable = parts[1];
						}

						name = new String(name);
						name.template = template;
						name.variable = variable;

						return name;
					});

					if (key.charAt(key.length - 1) === '*')
						secure = !!(key = key.substring(0, key.length - 1));

					if (key.charAt(0) !== ':') {
						_ = key.toLowerCase();

						tree = typeof value === 'string'
							? method(key, url || '/', result(value), parts, secure)
							: generate(value, (url || '') + '/' + (value['@'] || key), transparent && res);

						transparent || (res[_] = tree);

						aliases[key] && aliases[key].forEach(function (alias) {
							res[alias] || (res[alias] = res[_]);
						});
					} else
						res[key.substr(1)] = res[value.toLowerCase()];
				}

			return res;
		}(desc.resources);
	};
});<commit_msg>Добавлена возможность передачи представлений<commit_after>define(function (require) {
	/*
	 TODO: Remove jquery dependency
	 */
	var transport = require('jquery').ajax,
		urlencode = require('jquery').param,
		placeholder = /^{(.+)}$/;

	function request(method, uri, query, representation, headers) {
		var params = urlencode(query);

		/*
		TODO: configurable media-type
		 */

		return transport({
			url: uri + (params ? (uri.indexOf('?') === -1 ? '?' : '&') + params : params),
			type: method,
			data: JSON.stringify(representation),
			contentType: 'application/json',
			headers: headers,
			xhrFields: {
				withCredentials: true
			}
		});
	}

	function result(value) {
		if (value.indexOf('=') === -1)
			return value;

		parts = value.split('=');
		value = new String(parts[0]);
		value.variable = parts[1];
		return value
	}

	return function apic(desc, ssl, options) {
		options = options || {};

		var base = desc.base,
			safeMethods = { 'GET': true, 'HEAD': true, 'OPTIONS': true },
			tokenHeader = options.tokenHeader || 'X-Security-Token',
			aliases = options.aliases || {
				'PUT': ['save'],
				'POST': ['add'],
				'DELETE': ['remove']
			};

		var token, variables = {};

		function last(arr) {
			return typeof arr[arr.length - 1];
		}

		function method(verb, uri, res, params, secure) {
			var safe = safeMethods[verb] || false,
				protocol = ssl || (secure = secure || !safe) ? 'https:' : 'http:';

			return function () {
				var args = Array.prototype.slice.call(arguments),
					callback = last(args) === 'function' ? args.pop() : undefined,
					representation = last(args) === 'object' ? args.pop() : {},
					path = uri,
					headers = {},
					query = {};

				/*
				 Check if all necessary arguments passed in arguments or have default variable value
				 */
				if (params.reduce(function (a, b) {
					return a - +(variables[b.variable] !== undefined);
				}, params.length) > args.length)
					throw new Error([
						params.length, ' argument', (params.length === 1 ? '' : 's'),
						params.length ? ' (' + params.join(', ') + ')' : '',
						' expected ', args.length, ' given',
						args.length ? ' (' + args.join(', ') + ')' : ''
					].join(''));

				params.forEach(function (name, i) {
					query[name] = args[i] === undefined
						? (name.variable && variables[name.variable])
						: args[i];

					if (name.template) {
						var _ = '{' + name + '}',
							value = args[i] || query[name];

						path.indexOf(_) === -1
							? (path += '/' + value)
							: (path = path.replace(_, value));

						delete query[name];
					}
				});

				secure && (headers[tokenHeader] = token);

				var err, resp;

				return request(verb, protocol + base + path, query, representation, headers)
					.done(function (data, code, xhr) {
						res.variable && (variables[res.variable] = data[res]);

						resp = data[res];

					})
					.fail(function (xhr) {
						err = {};

						if (xhr.responseText) {
							try {
								err = JSON.parse(xhr.responseText)['error'] || {};
							}
							catch (e) {
							}
						}

						err.status = xhr.status;
					})
					.always(function(a, status, b) {
						var xhr = status === 'success' ? b : a; // WTF

						secure && (token = xhr.getResponseHeader(tokenHeader) || token);

						callback && (callback.length > 1
							? callback(err, resp)
							: (err || callback(resp))
							);
					});
			};
		}

		return function generate(map, uri, res) {
			var key,
				value,
				parts,
				secure,
				transparent,
				tree,
				_;

			res = res || {};

			for (key in map)
				if (map.hasOwnProperty(key) && key !== '@') {
					value = map[key];

					transparent = key.match(placeholder);

					key = (parts = key.split('#')).shift();

					parts = parts.map(function (name) {
						var template, variable, match;

						if (name.charAt(0) === '/') {
							template = true;
							name = name.substr(1);
						}

						if (match = name.match(placeholder)) {
							parts = match[1].split('=');

							name = parts[0];
							variable = parts[1];
						}

						name = new String(name);
						name.template = template;
						name.variable = variable;

						return name;
					});

					if (key.charAt(key.length - 1) === '*')
						secure = !!(key = key.substring(0, key.length - 1));

					if (key.charAt(0) !== ':') {
						_ = key.toLowerCase();

						tree = typeof value === 'string'
							? method(key, uri || '/', result(value), parts, secure)
							: generate(value, (uri || '') + '/' + (value['@'] || key), transparent && res);

						transparent || (res[_] = tree);

						aliases[key] && aliases[key].forEach(function (alias) {
							res[alias] || (res[alias] = res[_]);
						});
					} else
						res[key.substr(1)] = res[value.toLowerCase()];
				}

			return res;
		}(desc.resources);
	};
});<|endoftext|>


<commit_before>define(['underscore', 'require', 'backbone'],
  function(_, require, Backbone, MainAppView) {

  var Router = Backbone.Router.extend({
    routes: {
      'landing': 'landing',

      'feedback': 'feedback',

      'buy/:uid': 'buyParking',
      'sell/:uid': 'sellParking',

      'getstarted': 'getStarted',
      'getstarted/:email': 'getStarted',
      'login': 'login',
      'login/:email': 'login',

      'users': '',
      'users/:uid': 'sellParking',
      'users/:uid/feedback': 'userFeedback',
      'users/:uid/settings': 'userSettings',
      'users/:uid/settings/credit-card': 'addCard',

      '': 'main',

      'image' : 'imageUploader'
    },

    main: function() {
      this.navigate('landing', {trigger: true});
    },

    landing: function(){
      require(['views/application/main'], function(MainAppView) {
        MainAppView.sharedInstance().showLanding();
      });
    },

    feedback: function() {
      require(['views/application/main'], function(MainAppView) {
        MainAppView.sharedInstance().showFeedback();
      });
    },

    buyParking: function(uid){
      require(['views/application/main'], function(MainAppView) {
        MainAppView.sharedInstance().showBuyParking(uid);
      });
    },

    sellParking: function(uid){
      require(['views/application/main'], function(MainAppView) {
        MainAppView.sharedInstance().showSellParking(uid);
      });
    },

    getStarted: function(email){
      require(['views/application/main'], function(MainAppView){
        MainAppView.sharedInstance().showGetStarted(email);
      });
    },

    login: function(email){
      require(['views/application/main'], function(MainAppView){
        MainAppView.sharedInstance().showLogin(email);
      });
    },

    userFeedback: function(uid) {
      require(['views/application/main'], function(MainAppView){
        MainAppView.sharedInstance().showUserFeedback(uid);
      });
    },

    userSettings: function(uid){
      require(['views/application/main'], function(MainAppView) {
        MainAppView.sharedInstance().showUserSettings(uid);
      });
    },

    // addCard: function(uid) {
    //   require(['views/application/main'], function(MainAppView) {
    //     MainAppView.sharedInstance().showAddCard(uid);
    // },

    imageUploader: function(){
       require(['views/application/main'], function(MainAppView) {
         MainAppView.sharedInstance().showImageUploader();
       });
    },

    // call start when the application is ready to begin routing
    start: function() {
      var router = this;

      // Set up browser history
      Backbone.history.start({ pushState: true });

      // Router fix so that internal links do not all have to begin with hashes
      // Or rather so that the browser doesn't always refersh the page

      $(document).on("click", "a[href^='/']", function(evt) {
        var href = $(this).attr('href');
        var protocol = this.protocol + '//';

        if (href.slice(protocol.length) !== protocol) {
          evt.preventDefault();
          router.navigate(href, true);
        }
      });
    }

  });

  Router.sharedInstance = _.once(function() {
    return new Router();
  });

  return Router;
});
<commit_msg>add card<commit_after>define(['underscore', 'require', 'backbone'],
  function(_, require, Backbone, MainAppView) {

  var Router = Backbone.Router.extend({
    routes: {
      'landing': 'landing',

      'feedback': 'feedback',

      'buy/:uid': 'buyParking',
      'sell/:uid': 'sellParking',

      'getstarted': 'getStarted',
      'getstarted/:email': 'getStarted',
      'login': 'login',
      'login/:email': 'login',

      'users': '',
      'users/:uid': 'sellParking',
      'users/:uid/feedback': 'userFeedback',
      'users/:uid/settings': 'userSettings',
      'users/:uid/settings/credit-card': 'addCard',

      '': 'main',

      'image' : 'imageUploader'
    },

    main: function() {
      this.navigate('landing', {trigger: true});
    },

    landing: function(){
      require(['views/application/main'], function(MainAppView) {
        MainAppView.sharedInstance().showLanding();
      });
    },

    feedback: function() {
      require(['views/application/main'], function(MainAppView) {
        MainAppView.sharedInstance().showFeedback();
      });
    },

    buyParking: function(uid){
      require(['views/application/main'], function(MainAppView) {
        MainAppView.sharedInstance().showBuyParking(uid);
      });
    },

    sellParking: function(uid){
      require(['views/application/main'], function(MainAppView) {
        MainAppView.sharedInstance().showSellParking(uid);
      });
    },

    getStarted: function(email){
      require(['views/application/main'], function(MainAppView){
        MainAppView.sharedInstance().showGetStarted(email);
      });
    },

    login: function(email){
      require(['views/application/main'], function(MainAppView){
        MainAppView.sharedInstance().showLogin(email);
      });
    },

    userFeedback: function(uid) {
      require(['views/application/main'], function(MainAppView){
        MainAppView.sharedInstance().showUserFeedback(uid);
      });
    },

    userSettings: function(uid){
      require(['views/application/main'], function(MainAppView) {
        MainAppView.sharedInstance().showUserSettings(uid);
      });
    },

    addCard: function(uid) {
       require(['views/application/main'], function(MainAppView) {
         MainAppView.sharedInstance().showAddCard(uid);
       });
    },

    imageUploader: function(){
       require(['views/application/main'], function(MainAppView) {
         MainAppView.sharedInstance().showImageUploader();
       });
    },

    // call start when the application is ready to begin routing
    start: function() {
      var router = this;

      // Set up browser history
      Backbone.history.start({ pushState: true });

      // Router fix so that internal links do not all have to begin with hashes
      // Or rather so that the browser doesn't always refersh the page

      $(document).on("click", "a[href^='/']", function(evt) {
        var href = $(this).attr('href');
        var protocol = this.protocol + '//';

        if (href.slice(protocol.length) !== protocol) {
          evt.preventDefault();
          router.navigate(href, true);
        }
      });
    }

  });

  Router.sharedInstance = _.once(function() {
    return new Router();
  });

  return Router;
});
<|endoftext|>


<commit_before>function logError(error) {
    console.log(error.name + ': ' + error.message);
    console.error(error);
}

var Visio = {
    from: null,
    id: null,
    withVideo: false,

    localVideo: null,
    remoteVideo: null,
    localAudio: null,
    remoteAudio: null,
    screenSharing: null,

    calling: false,

    videoSelect: undefined,
    switchCamera: undefined,

    inboundStream: null,

    services: [],

    tracksTypes: [],

    init: function() {
        Visio.from = MovimUtils.urlParts().params[0];

        if (MovimUtils.urlParts().params[1] !== undefined) {
            Visio.from += '/' + MovimUtils.urlParts().params[1];
        }

        if (Visio.withVideo) {
            Visio.localVideo = document.getElementById('video');
            Visio.remoteVideo = document.getElementById('remote_video');
            Visio.screenSharing = document.getElementById('screen_sharing_video');
        }

        Visio.localAudio = document.getElementById('audio');
        Visio.remoteAudio = document.getElementById('remote_audio');

        var configuration = {
            'iceServers': Visio.services
        };

        Visio.pc = new RTCPeerConnection(configuration);

        Visio.pc.ontrack = event => {
            if (Visio.withVideo) {
                if (event.streams && event.streams[0]) {
                    Visio.remoteVideo.srcObject = event.streams[0];
                } else {
                    if (!Visio.inboundStream) {
                        Visio.inboundStream = new MediaStream();
                        Visio.remoteVideo.srcObject = Visio.inboundStream;
                    }
                    Visio.inboundStream.addTrack(event.track);
                }

                VisioUtils.setRemoteAudioState('mic');
                VisioUtils.setRemoteVideoState('videocam');
            } else {
                if (event.streams && event.streams[0]) {
                    Visio.remoteAudio.srcObject = event.streams[0];
                } else {
                    if (!Visio.inboundStream) {
                        Visio.inboundStream = new MediaStream();
                        Visio.remoteAudio.srcObject = Visio.inboundStream;
                    }
                    Visio.inboundStream.addTrack(event.track);
                }
                VisioUtils.handleRemoteAudio();
                VisioUtils.setRemoteAudioState('mic');
            }

            Visio.tracksTypes['mid'+event.transceiver.mid] = event.track.kind;
        };

        Visio.pc.onicecandidate = event => {
            let candidate = event.candidate;
            if (candidate && candidate.candidate && candidate.candidate.length > 0) {
                Visio_ajaxCandidate(event.candidate, Visio.from, Visio.id);
            }
        };

        Visio.pc.oniceconnectionstatechange = () => VisioUtils.toggleMainButton();

        Visio.pc.onicegatheringstatechange = function (event) {
            // When we didn't receive the WebRTC termination before Jingle
            if (Visio.pc.iceConnectionState == 'disconnected') {
                Visio.onTerminate();
            }

            VisioUtils.toggleMainButton();
        };

        VisioUtils.toggleMainButton();

        if (Visio.withVideo) {
            VisioUtils.switchCameraSetup();
        }

        Visio.getStream();
    },

    onMute: function(name) {
        if (Visio.tracksTypes[name]) {
            if (Visio.tracksTypes[name] == 'audio') {
                VisioUtils.setRemoteAudioState('mic_off');
            }

            if (Visio.tracksTypes[name] == 'video') {
                document.querySelector('#remote_video').classList.add('muted');
                VisioUtils.setRemoteVideoState('videocam_off');
            }
        }
    },

    onUnmute: function(name) {
        if (Visio.tracksTypes[name]) {
            if (Visio.tracksTypes[name] == 'audio') {
                VisioUtils.setRemoteAudioState('mic');
            }

            if (Visio.tracksTypes[name] == 'video') {
                document.querySelector('#remote_video').classList.remove('muted');
                VisioUtils.setRemoteVideoState('videocam');
            }
        }
    },

    setServices: function(services) {
        Visio.services = services;
    },

    getStream: function() {
        if (Visio.withVideo) {
            // On Android where you can't have both camera enabled at the same time
            var videoTrack = Visio.pc.getSenders().find(rtc => rtc.track && rtc.track.kind == 'video');
            if (videoTrack) videoTrack.track.stop();

            Visio.switchCamera.classList.add('disabled');
        }

        var constraints = {
            audio: true,
            video: false
        };

        const videoSource = Visio.videoSelect.value;

        if (Visio.withVideo) {
            constraints.video = {
                deviceId: videoSource ? {exact: videoSource} : undefined,
                facingMode: 'user',
                width: { ideal: 4096 },
                height: { ideal: 4096 }
            };
        }

        navigator.mediaDevices.getUserMedia(constraints).then(stream => {
            if (!Visio.withVideo) {
                Visio.localAudio.srcObject = stream;
            } else {
                Visio.switchCamera.classList.remove('disabled');
                Visio.localVideo.srcObject = stream;

                // Toggle video icon
                var cameraIcon = document.querySelector('#toggle_video i');
                cameraIcon.innerText = 'videocam';

                // Switch camera
                VisioUtils.pcReplaceTrack(stream);
                VisioUtils.enableScreenSharingButton();
            }

            VisioUtils.handleAudio();
            VisioUtils.toggleMainButton();

            // For the first time we attach all the tracks and we launch the call
            if (Visio.pc.getSenders().length == 0) {
                stream.getTracks().forEach(track => Visio.pc.addTrack(track, stream));

                if (Visio.id) {
                    Visio_ajaxAccept(Visio.from, Visio.id);
                } else {
                    // TODO launch when button pressed
                    Visio.id = Math.random().toString(36).substr(2, 9);
                    Visio.calling = true;
                    VisioUtils.toggleMainButton();
                    Visio_ajaxPropose(Visio.from, Visio.id, Visio.withVideo);
                }
            }
        }, logError);
    },

    gotQuickStream: function() {
        VisioUtils.pcReplaceTrack(Visio.localVideo.srcObject);
    },

    gotScreen: function() {
        VisioUtils.pcReplaceTrack(Visio.screenSharing.srcObject);
    },

    onCandidate: function(candidate, mid, mlineindex) {
        // filter the a=candidate lines
        var filtered = candidate.split(/\n/).filter(line => {
            return line.startsWith('a=candidate');
        });

        Visio.pc.addIceCandidate(new RTCIceCandidate({
            'candidate': filtered.join('').substr(2),
            'sdpMid': mid,
            'sdpMLineIndex' : mlineindex
        }), () => {}, logError);
    },

    onProceed: function(from, id) {
        if (from.substring(0, Visio.from.length) == Visio.from && Visio.id == id) {
            // We set the remote resource
            Visio.from = from;

            Visio.pc.createOffer().then(function(offer) {
                Visio.calling = false;
                VisioUtils.toggleMainButton();
                return Visio.pc.setLocalDescription(offer);
            })
            .then(function() {
                Visio_ajaxSessionInitiate(Visio.pc.localDescription, Visio.from, Visio.id);
            });
        } else {
            console.error('Wrong call')
        }
    },

    onInitiateSDP: function(sdp) {
        Visio.pc.setRemoteDescription(new RTCSessionDescription({'sdp': sdp + "\n", 'type': 'offer'}), () => {
            Visio.pc.createAnswer().then(function(answer) {
                return Visio.pc.setLocalDescription(answer);
            }).then(function() {
                Visio_ajaxSessionAccept(Visio.pc.localDescription, Visio.from, Visio.id);
            }).catch(logError);
        }, logError);
    },

    onAcceptSDP: function(sdp) {
        Visio.pc.setRemoteDescription(
            new RTCSessionDescription({'sdp': sdp + "\n", 'type': 'answer'}), () => {},
            (error) => {
                Visio.goodbye('incompatible-parameters');
                logError(error)
            }
        );
    },

    onTerminate: (reason) => {
        if (!Visio.withVideo) {
            let localStream = Visio.localAudio.srcObject;

            if (localStream) {
                localStream.getTracks().forEach(track => track.stop());
            }

            let remoteStream = Visio.remoteAudio.srcObject;

            if (remoteStream) {
                remoteStream.getTracks().forEach(track => track.stop());
            }

            Visio.localAudio.srcObject = null;
            Visio.remoteAudio.srcObject = null;
        } else {
            let localStream = Visio.localVideo.srcObject;

            if (localStream) {
                localStream.getTracks().forEach(track => track.stop());
            }

            let remoteStream = Visio.remoteVideo.srcObject;

            if (remoteStream) {
                remoteStream.getTracks().forEach(track => track.stop());
            }

            Visio.localVideo.srcObject = null;
            Visio.remoteVideo.srcObject = null;

            Visio.localVideo.classList.add('hide');
        }

        if (Visio.pc) Visio.pc.close();

        document.querySelector('p.state').innerText = reason == 'decline'
            ? Visio.states.declined
            : Visio.states.ended;
        button = document.querySelector('#main');

        button.className = 'button action color red';
        button.querySelector('i').className = 'material-icons';
        button.querySelector('i').innerText = 'close';

        button.onclick = () => {
            window.close();

            if (typeof Android !== 'undefined') {
                Android.closePopUpWebview();
            }
        }

        // And we force close the window after 2sec
        window.setTimeout(() => {
            window.close();

            if (typeof Android !== 'undefined') {
                Android.closePopUpWebview();
            }
        }, 2000);
    },

    goodbye: (reason) => {
        Visio.onTerminate(reason);
        Visio_ajaxTerminate(Visio.from, reason, Visio.id);
    },
}

MovimWebsocket.attach(() => {
    if (MovimUtils.urlParts().params[2] !== undefined) {
        Visio.id = MovimUtils.urlParts().params[2];
    }

    if (MovimUtils.urlParts().page == 'visio') {
        Visio.withVideo = true;
    }

    Visio_ajaxResolveServices();
});

window.onbeforeunload = () => {
    Visio.goodbye();
}
<commit_msg>Fix audio calls<commit_after>function logError(error) {
    console.log(error.name + ': ' + error.message);
    console.error(error);
}

var Visio = {
    from: null,
    id: null,
    withVideo: false,

    localVideo: null,
    remoteVideo: null,
    localAudio: null,
    remoteAudio: null,
    screenSharing: null,

    calling: false,

    videoSelect: undefined,
    switchCamera: undefined,

    inboundStream: null,

    services: [],

    tracksTypes: [],

    init: function() {
        Visio.from = MovimUtils.urlParts().params[0];

        if (MovimUtils.urlParts().params[1] !== undefined) {
            Visio.from += '/' + MovimUtils.urlParts().params[1];
        }

        if (Visio.withVideo) {
            Visio.localVideo = document.getElementById('video');
            Visio.remoteVideo = document.getElementById('remote_video');
            Visio.screenSharing = document.getElementById('screen_sharing_video');
        }

        Visio.localAudio = document.getElementById('audio');
        Visio.remoteAudio = document.getElementById('remote_audio');

        var configuration = {
            'iceServers': Visio.services
        };

        Visio.pc = new RTCPeerConnection(configuration);

        Visio.pc.ontrack = event => {
            if (Visio.withVideo) {
                if (event.streams && event.streams[0]) {
                    Visio.remoteVideo.srcObject = event.streams[0];
                } else {
                    if (!Visio.inboundStream) {
                        Visio.inboundStream = new MediaStream();
                        Visio.remoteVideo.srcObject = Visio.inboundStream;
                    }
                    Visio.inboundStream.addTrack(event.track);
                }

                VisioUtils.setRemoteAudioState('mic');
                VisioUtils.setRemoteVideoState('videocam');
            } else {
                if (event.streams && event.streams[0]) {
                    Visio.remoteAudio.srcObject = event.streams[0];
                } else {
                    if (!Visio.inboundStream) {
                        Visio.inboundStream = new MediaStream();
                        Visio.remoteAudio.srcObject = Visio.inboundStream;
                    }
                    Visio.inboundStream.addTrack(event.track);
                }
                VisioUtils.handleRemoteAudio();
                VisioUtils.setRemoteAudioState('mic');
            }

            Visio.tracksTypes['mid'+event.transceiver.mid] = event.track.kind;
        };

        Visio.pc.onicecandidate = event => {
            let candidate = event.candidate;
            if (candidate && candidate.candidate && candidate.candidate.length > 0) {
                Visio_ajaxCandidate(event.candidate, Visio.from, Visio.id);
            }
        };

        Visio.pc.oniceconnectionstatechange = () => VisioUtils.toggleMainButton();

        Visio.pc.onicegatheringstatechange = function (event) {
            // When we didn't receive the WebRTC termination before Jingle
            if (Visio.pc.iceConnectionState == 'disconnected') {
                Visio.onTerminate();
            }

            VisioUtils.toggleMainButton();
        };

        VisioUtils.toggleMainButton();

        if (Visio.withVideo) {
            VisioUtils.switchCameraSetup();
        }

        Visio.getStream();
    },

    onMute: function(name) {
        if (Visio.tracksTypes[name]) {
            if (Visio.tracksTypes[name] == 'audio') {
                VisioUtils.setRemoteAudioState('mic_off');
            }

            if (Visio.tracksTypes[name] == 'video') {
                document.querySelector('#remote_video').classList.add('muted');
                VisioUtils.setRemoteVideoState('videocam_off');
            }
        }
    },

    onUnmute: function(name) {
        if (Visio.tracksTypes[name]) {
            if (Visio.tracksTypes[name] == 'audio') {
                VisioUtils.setRemoteAudioState('mic');
            }

            if (Visio.tracksTypes[name] == 'video') {
                document.querySelector('#remote_video').classList.remove('muted');
                VisioUtils.setRemoteVideoState('videocam');
            }
        }
    },

    setServices: function(services) {
        Visio.services = services;
    },

    getStream: function() {
        if (Visio.withVideo) {
            // On Android where you can't have both camera enabled at the same time
            var videoTrack = Visio.pc.getSenders().find(rtc => rtc.track && rtc.track.kind == 'video');
            if (videoTrack) videoTrack.track.stop();

            Visio.switchCamera.classList.add('disabled');
        }

        var constraints = {
            audio: true,
            video: false
        };

        if (Visio.withVideo) {
            const videoSource = Visio.videoSelect.value;

            constraints.video = {
                deviceId: videoSource ? {exact: videoSource} : undefined,
                facingMode: 'user',
                width: { ideal: 4096 },
                height: { ideal: 4096 }
            };
        }

        navigator.mediaDevices.getUserMedia(constraints).then(stream => {
            if (!Visio.withVideo) {
                Visio.localAudio.srcObject = stream;
            } else {
                Visio.switchCamera.classList.remove('disabled');
                Visio.localVideo.srcObject = stream;

                // Toggle video icon
                var cameraIcon = document.querySelector('#toggle_video i');
                cameraIcon.innerText = 'videocam';

                // Switch camera
                VisioUtils.pcReplaceTrack(stream);
                VisioUtils.enableScreenSharingButton();
            }

            VisioUtils.handleAudio();
            VisioUtils.toggleMainButton();

            // For the first time we attach all the tracks and we launch the call
            if (Visio.pc.getSenders().length == 0) {
                stream.getTracks().forEach(track => Visio.pc.addTrack(track, stream));

                if (Visio.id) {
                    Visio_ajaxAccept(Visio.from, Visio.id);
                } else {
                    // TODO launch when button pressed
                    Visio.id = Math.random().toString(36).substr(2, 9);
                    Visio.calling = true;
                    VisioUtils.toggleMainButton();
                    Visio_ajaxPropose(Visio.from, Visio.id, Visio.withVideo);
                }
            }
        }, logError);
    },

    gotQuickStream: function() {
        VisioUtils.pcReplaceTrack(Visio.localVideo.srcObject);
    },

    gotScreen: function() {
        VisioUtils.pcReplaceTrack(Visio.screenSharing.srcObject);
    },

    onCandidate: function(candidate, mid, mlineindex) {
        // filter the a=candidate lines
        var filtered = candidate.split(/\n/).filter(line => {
            return line.startsWith('a=candidate');
        });

        Visio.pc.addIceCandidate(new RTCIceCandidate({
            'candidate': filtered.join('').substr(2),
            'sdpMid': mid,
            'sdpMLineIndex' : mlineindex
        }), () => {}, logError);
    },

    onProceed: function(from, id) {
        if (from.substring(0, Visio.from.length) == Visio.from && Visio.id == id) {
            // We set the remote resource
            Visio.from = from;

            Visio.pc.createOffer().then(function(offer) {
                Visio.calling = false;
                VisioUtils.toggleMainButton();
                return Visio.pc.setLocalDescription(offer);
            })
            .then(function() {
                Visio_ajaxSessionInitiate(Visio.pc.localDescription, Visio.from, Visio.id);
            });
        } else {
            console.error('Wrong call')
        }
    },

    onInitiateSDP: function(sdp) {
        Visio.pc.setRemoteDescription(new RTCSessionDescription({'sdp': sdp + "\n", 'type': 'offer'}), () => {
            Visio.pc.createAnswer().then(function(answer) {
                return Visio.pc.setLocalDescription(answer);
            }).then(function() {
                Visio_ajaxSessionAccept(Visio.pc.localDescription, Visio.from, Visio.id);
            }).catch(logError);
        }, logError);
    },

    onAcceptSDP: function(sdp) {
        Visio.pc.setRemoteDescription(
            new RTCSessionDescription({'sdp': sdp + "\n", 'type': 'answer'}), () => {},
            (error) => {
                Visio.goodbye('incompatible-parameters');
                logError(error)
            }
        );
    },

    onTerminate: (reason) => {
        if (!Visio.withVideo) {
            let localStream = Visio.localAudio.srcObject;

            if (localStream) {
                localStream.getTracks().forEach(track => track.stop());
            }

            let remoteStream = Visio.remoteAudio.srcObject;

            if (remoteStream) {
                remoteStream.getTracks().forEach(track => track.stop());
            }

            Visio.localAudio.srcObject = null;
            Visio.remoteAudio.srcObject = null;
        } else {
            let localStream = Visio.localVideo.srcObject;

            if (localStream) {
                localStream.getTracks().forEach(track => track.stop());
            }

            let remoteStream = Visio.remoteVideo.srcObject;

            if (remoteStream) {
                remoteStream.getTracks().forEach(track => track.stop());
            }

            Visio.localVideo.srcObject = null;
            Visio.remoteVideo.srcObject = null;

            Visio.localVideo.classList.add('hide');
        }

        if (Visio.pc) Visio.pc.close();

        document.querySelector('p.state').innerText = reason == 'decline'
            ? Visio.states.declined
            : Visio.states.ended;
        button = document.querySelector('#main');

        button.className = 'button action color red';
        button.querySelector('i').className = 'material-icons';
        button.querySelector('i').innerText = 'close';

        button.onclick = () => {
            window.close();

            if (typeof Android !== 'undefined') {
                Android.closePopUpWebview();
            }
        }

        // And we force close the window after 2sec
        window.setTimeout(() => {
            window.close();

            if (typeof Android !== 'undefined') {
                Android.closePopUpWebview();
            }
        }, 2000);
    },

    goodbye: (reason) => {
        Visio.onTerminate(reason);
        Visio_ajaxTerminate(Visio.from, reason, Visio.id);
    },
}

MovimWebsocket.attach(() => {
    if (MovimUtils.urlParts().params[2] !== undefined) {
        Visio.id = MovimUtils.urlParts().params[2];
    }

    if (MovimUtils.urlParts().page == 'visio') {
        Visio.withVideo = true;
    }

    Visio_ajaxResolveServices();
});

window.onbeforeunload = () => {
    Visio.goodbye();
}
<|endoftext|>


<commit_before>var userTitle = "MESH USERS";
var counter = 0;

$(document).ready(function(){
  var socket = io();
  var names = ["David", "Tom"]
  socket.emit("join", names.pop());

  var ready = true;

  $("#name").focus().fadeIn(1000);
  $("form").submit(function(event){
    event.preventDefault();
  });

  $("#send").click(function(){
    var company = $("#company").val();
    var market = $("#market").val();
    var shareAmount = $("#share-amount").val();
    var price = $("#price").val();
    socket.emit("message", company, market, shareAmount, price);
    $("#msg").val("");
  });

  $("#send-comment").click(function(event){
    event.preventDefault();
    var comment = $("#new-comment").val();
    var ticketID = $('#comment-ticket').val();
    socket.emit("comment", comment, ticketID);
    $("#msg").val("");
  });

  socket.on("update", function(user){
    socket.emit("user-list", name);
    if(ready === true) {
      $("#users").html("
" + name + "
");
    }
  });

  socket.on("update", function(msg) {
    if(ready) {
      $("#msgs").append("
" + msg + "
");
    }
  });

  socket.on("update-disconnect", function(user) {
    socket.emit("user-list", name);
    if(ready === true) {
      $("#users").html("
" + name + "
");
    }
  });

  socket.on("update-disconnect", function(user) {
    if(ready === true) {
      $("#msgs").append("
" + user + "
");
    }
  })

  socket.on("comment", function(who, comment, ticketID) {
    if(ready) {
      if(comment != null) {
        $("#comments").append("
" + comment + "
");
      }
    }
  });

  socket.on("chat", function(who, company, market, shareAmount, price){
    if(ready) {
      if (company != null) {
        $("#msgs").append("
" +

          "
" +
            "
" + company + "
" +
            "
" + market +  "
" +
            "
" + shareAmount + "@" + price + "
" +
            "" +
            "
" +
              "
" +
                "" +
              "
" +
              "
" +
                "" +
              "
" +
              "
" +
                "" +
              "
" +
            "
" +
          "
" +

          "<form id='3' class='form-inline'>" +
            "<input type='text' class='input' placeholder='Comment' id='new-comment'>" +
            "<input type='hidden' value=" + "ticket" + counter + "id='comment-ticket'" + ">" +
            "<button type='button' name='send' id='send-comment' value='Send' class='btn btn-success'>Comment</button>" +
          "</form>" +

          "
");
        $('#ticket' + counter).fadeIn();
        counter += 1;
      }
    }
  });

  socket.on("disconnect", function(){
    $("#msgs").append("
The server is not available
");
    $("#msg").attr("disabled", "disabled");
    $("#send").attr("disabled", "disabled");
  });

  socket.on("logged-in-users", function(who){
    if(ready === true){
      var users = '';
      $.each(who, function(index, person) {
        users += '
' + person + '
'
      })
      $('#users').append(users);
    }
  });

});
<commit_msg>Updated socketHandlers to handle comments<commit_after>var userTitle = "MESH USERS";
var counter = 0;

$(document).ready(function(){
  var socket = io();
  var names = ["David", "Tom"]
  socket.emit("join", names.pop());

  var ready = true;

  $("#name").focus().fadeIn(1000);
  $("form").submit(function(event){
    event.preventDefault();
  });

  $("#send").click(function(){
    var company = $("#company").val();
    var market = $("#market").val();
    var shareAmount = $("#share-amount").val();
    var price = $("#price").val();
    socket.emit("message", company, market, shareAmount, price);
    $("#msg").val("");
  });

  $("body").on('click', '#send-comment', function(event){
    event.preventDefault();
    var comment = $("#new-comment").val();
    var ticketID = this.value;
    console.log(ticketID);
    socket.emit("comment", comment, ticketID);
    $("#msg").val("");
  });

  socket.on("update", function(user){
    socket.emit("user-list", name);
    if(ready === true) {
      $("#users").html("
" + name + "
");
    }
  });

  socket.on("update", function(msg) {
    if(ready) {
      $("#msgs").append("
" + msg + "
");
    }
  });

  socket.on("update-disconnect", function(user) {
    socket.emit("user-list", name);
    if(ready === true) {
      $("#users").html("
" + name + "
");
    }
  });

  socket.on("update-disconnect", function(user) {
    if(ready === true) {
      $("#msgs").append("
" + user + "
");
    }
  })

  socket.on("comment", function(who, comment, ticketID) {
    if(ready) {
      if(comment != null) {
        $("#ticket" + ticketID).append("
" + comment + "
");
      }
    }
  });

  socket.on("chat", function(who, company, market, shareAmount, price){
    if(ready) {
      if (company != null) {
        $("#msgs").append("
" +

          "
" +
            "
" + company + "
" +
            "
" + market +  "
" +
            "
" + shareAmount + "@" + price + "
" +
            "" +
            "
" +
              "
" +
                "" +
              "
" +
              "
" +
                "" +
              "
" +
              "
" +
                "" +
              "
" +
            "
" +
          "
" +

          "<form id='3' class='form-inline'>" +
            "<input type='text' class='input' placeholder='Comment' id='new-comment'>" +
            "<input type='hidden' value='ticket" + counter + "\'" +  "id='comment-ticket'" + ">" +
            "<button type='button' name='send' id='send-comment' value='" + counter + "\'" + "class='btn btn-success'>Comment</button>" +
          "</form>" +

          "
");
        $('#ticket' + counter).fadeIn();
        counter += 1;
      }
    }
  });

  socket.on("disconnect", function(){
    $("#msgs").append("
The server is not available
");
    $("#msg").attr("disabled", "disabled");
    $("#send").attr("disabled", "disabled");
  });

  socket.on("logged-in-users", function(who){
    if(ready === true){
      var users = '';
      $.each(who, function(index, person) {
        users += '
' + person + '
'
      })
      $('#users').append(users);
    }
  });

});
<|endoftext|>


<commit_before>/**
 * Created by apizzimenti on 12/29/15.
 */

var http = require('http'),
    https = require('https'),
    clc = require('cli-color'),
    Format = require('./Format');

function weatherRequest(location, units) {
    var weather_options = {
        host: 'api.forecast.io',
        path: '/forecast/d399f7331297381cd6b95106add0d22d/' + location.lat + ',' + location.long + '?units=' + units.type,
        method: 'GET'
    };

    https.get(weather_options, function(res) {
        var json  = '';
        res
            .on('data', function (chunk) {
                json += chunk;
            })
            .on('end', function() {
                console.log(clc.green('✓ got data from weather server'));

                var weather = Format(json, units);
                console.log(weather.currentWeather);
                console.log(weather.tabled());
                process.exit();
            })
    });
}

function address(address, callback, units) {

    var location_options = {
        host: 'maps.googleapis.com',
        path: '/maps/api/geocode/json?address=' + encodeURIComponent(address.toString()),
        method: 'GET'
    };

    http.get(location_options, function (res) {
        var text = '',
            position = {};
        res
            .on('data', function (chunk) {
                text +=  chunk.toString();
            })
            .on('end', function () {
                var json = JSON.parse(text);
                if (json.status == "OK" && json.results[0]) {
                    console.log(clc.green('✓ got geo location server response'));
                    console.log(clc.green('✓ got location: ') + clc.bgBlack.white(json.results[0].formatted_address));
                    position.lat = json.results[0].geometry.location.lat;
                    position.long = json.results[0].geometry.location.lng;
                    callback(position, units);
                } else {
                    console.log(clc.red('✗ address not found'));
                }
            })
    });
}

function automatic(ip, callback, units) {

    var location_options = {
        host: 'freegeoip.net',
        path: '/json/' + ip,
        method: 'GET'
    };

    http.get(location_options, function (res) {
        var text = '',
            position = {};
        res
            .on('data', function (chunk) {
                console.log(clc.green('✓ got location server response'));
                text +=  chunk.toString();
            })
            .on('end', function () {
                var json = JSON.parse(text),
                    location = json.city + ', ' + json.region_name + ', ' + json.country_name;
                position.lat = json.latitude;
                position.long = json.longitude;
                console.log(clc.green('✓ got location: ') + clc.bgBlack.white(location));
                callback(position, units);
            })
    });
}

module.exports = {
    weatherRequest: weatherRequest,
    address: address,
    automatic: automatic
};<commit_msg>I did something but I don't know what it was<commit_after>/**
 * Created by apizzimenti on 12/29/15.
 */

var http = require('http'),
    https = require('https'),
    clc = require('cli-color'),
    Format = require('./format');

function weatherRequest(location, units) {
    var weather_options = {
        host: 'api.forecast.io',
        path: '/forecast/d399f7331297381cd6b95106add0d22d/' + location.lat + ',' + location.long + '?units=' + units.type,
        method: 'GET'
    };

    https.get(weather_options, function(res) {
        var json  = '';
        res
            .on('data', function (chunk) {
                json += chunk;
            })
            .on('end', function() {
                console.log(clc.green('✓ got data from weather server'));

                var weather = Format(json, units);
                console.log(weather.currentWeather);
                console.log(weather.tabled());
                process.exit();
            })
    });
}

function address(address, callback, units) {

    var location_options = {
        host: 'maps.googleapis.com',
        path: '/maps/api/geocode/json?address=' + encodeURIComponent(address.toString()),
        method: 'GET'
    };

    http.get(location_options, function (res) {
        var text = '',
            position = {};
        res
            .on('data', function (chunk) {
                text +=  chunk.toString();
            })
            .on('end', function () {
                var json = JSON.parse(text);
                if (json.status == "OK" && json.results[0]) {
                    console.log(clc.green('✓ got geo location server response'));
                    console.log(clc.green('✓ got location: ') + clc.bgBlack.white(json.results[0].formatted_address));
                    position.lat = json.results[0].geometry.location.lat;
                    position.long = json.results[0].geometry.location.lng;
                    callback(position, units);
                } else {
                    console.log(clc.red('✗ address not found'));
                }
            })
    });
}

function automatic(ip, callback, units) {

    var location_options = {
        host: 'freegeoip.net',
        path: '/json/' + ip,
        method: 'GET'
    };

    http.get(location_options, function (res) {
        var text = '',
            position = {};
        res
            .on('data', function (chunk) {
                console.log(clc.green('✓ got location server response'));
                text +=  chunk.toString();
            })
            .on('end', function () {
                var json = JSON.parse(text),
                    location = json.city + ', ' + json.region_name + ', ' + json.country_name;
                position.lat = json.latitude;
                position.long = json.longitude;
                console.log(clc.green('✓ got location: ') + clc.bgBlack.white(location));
                callback(position, units);
            })
    });
}

module.exports = {
    weatherRequest: weatherRequest,
    address: address,
    automatic: automatic
};<|endoftext|>


<commit_before>'use strict';

(function() {
  window.diana = window.diana || {};
  window.diana.views = window.diana.views || {};
  var diana = window.diana;

  /**
   * Displays the <table> into which result sets are rendered. Automatically
   * fetches the result set based on router options passed via initialize().
   */
  diana.views.Timeline = Backbone.View.extend({
    // Track the most recent event ID seen by initial fetch() and automatic updates.
    newestEventId: null,

    // socket.io connection.
    socket: null,

    initialize: function(options) {
      var view = this;

      $.when(
        diana.helpers.View.deferRender(
          'timeline_table',
          null,
          function(err, out) {
            view.$el.html(out);
          }
        )
      ).done(function() {
        view.fetchTimeline.call(view, view.renderTimeline);
      });
    },

    onClose: function() {
      if (this.socket) {
        this.socket.disconnect();
        this.socket = null;
      }
    },

    events: {
      'click #timeline-open-search': 'openSearch'
    },

    /**
     * Open search modal.
     *
     * @param event {Object} jQuery event object.
     */
    openSearch: function(event) {
      diana.helpers.Widget.closeDropdown(event);
      new diana.views.TimelineSearch({
        el: $('#timeline-search-modal'),
        searchArgs: this.options.searchArgs
      });
    },

    /**
     * Fetch all log events matching the search arguments passed to the view.
     *
     * @param callback {Function} Fires on success/error.
     * - Receives an array with zero or more event objects.
     */
    fetchTimeline: function(callback) {
      var view = this;

      // Supply search filters/options for the collection's URL generation.
      view.collection = new diana.collections.Timeline(
        null, {searchArgs: view.options.searchArgs}
      );

      view.collection.fetch({
        success: function(collection, response) {
          if (!response.length) {
            dust.render('timeline_no_results', null, function(err, out) {
              view.$el.html(out);
            });
            return;
          }
          callback.call(view, response);
        },

        error: function(collection, response) {
          diana.helpers.Event.trigger('CritFetchError', response);
          callback.call(view, []);
        }
      });
    },

    /**
     * Render a set of events.
     *
     * - Used for both the intiial fetch and socket.io update payloads.
     *
     * @param events {Array}
     * @param options {Object}
      * - prepend {Boolean} If true, row is prepended (default=false).
      * - highlight {Boolean} If true, row receives styled class (default=false).
     */
    renderTimeline: function(events, options) {
      if (!events.length) {
        return;
      }

      options = options || {
        prepend: false,
        highlight: false
      };

      var view = this;

      // This function is used for both initial fetch and automatic updates.
      // Initial <tbody> is built off-screen and appended as a whole.
      // Automatic updates' <tr> nodes are added individually to an existing <tbody>.
      var existingTbody = $('#timeline-table tbody');
      var tbody = (existingTbody.length ? existingTbody : null) || $('<tbody>');

      // Deferred dust.render() calls later executed by $.when().
      var renderPromises = [];

      // Add empty <tr> nodes to the off-screen or live <tbody>.
      _.each(events, function(event) {
        var tr = $('<tr>');
        if (options.prepend) {
          if (options.highlight) {
            tr.addClass('timeline-update');
          }
          tbody.prepend(tr);
        } else {
          tbody.append(tr);
        }
        renderPromises.push(view.renderEvent(event, tr));
      });

      $.when(renderPromises).done(function() {
        if (existingTbody.length) {
          // tbody was already part of the DOM, so above rows were added live.
        } else {
          $('#timeline-table').append(tbody);
          view.startTimelineUpdate.call(view, events[0]._id);
        }
      });
    },

    /**
     * Render a single event in the timeline table.
     *
     * @param event {Object}
     * @param tr {Object} <tr> parent element.
     * @return {Object} jQuery Promise.
     */
    renderEvent: function(event, tr) {
      event.time = moment(event.time * 1000).fromNow();

      return diana.helpers.View.deferRender(
        'timeline_table_row',
        event,
        function(err, out) {
          $(tr).append(out);
        }
      );
    },

    /**
     * Creates the automatic updates socket. Also handles reconnection and diverts
     * update payloads.
     *
     * @param initialId {String} All updates (if any) will be newer than this ID.
     */
    startTimelineUpdate: function(initialId) {
      if (!diana.features.timelineUpdate) {
        return;
      }

      var view = this;
      view.newestEventId = initialId;

      this.socket = diana.helpers.Socket.create({
        event: {
          connect: function() {
            // Start/restart automatic updates.
            view.socket.emit('startTimelineUpdate', {
              newestEventId: view.newestEventId,
              searchArgs: view.options.searchArgs
            });
          }
        }
      });

      // Update the view with events fresher than newestEventId.
      this.socket.on('timelineUpdate', function(data) {
        view.onTimelineUpdate.call(view, data);
      });
    },

    /**
     * Fires on received responses from the automatic updates socket.
     *
     * @param data {Array|Object} List of event objects on success.
     * - On error, __socket_error string is set.
     */
    onTimelineUpdate: function(data) {
      if (!data || !data.length) {
        return;
      }

      // Advance the manual cursor.
      this.newestEventId = data[0]._id;

      // Un-highlight any past updates.
      $('.timeline-update').removeClass('timeline-update');

      this.renderTimeline(data.reverse(), {prepend: true, highlight: true});
    }
  });
})();
<commit_msg>Reuse search view after modal is hidden.<commit_after>'use strict';

(function() {
  window.diana = window.diana || {};
  window.diana.views = window.diana.views || {};
  var diana = window.diana;

  /**
   * Displays the <table> into which result sets are rendered. Automatically
   * fetches the result set based on router options passed via initialize().
   */
  diana.views.Timeline = Backbone.View.extend({
    // Track the most recent event ID seen by initial fetch() and automatic updates.
    newestEventId: null,

    // socket.io connection.
    socket: null,

    // Modal sub-view.
    searchView: null,

    initialize: function(options) {
      var view = this;

      $.when(
        diana.helpers.View.deferRender(
          'timeline_table',
          null,
          function(err, out) {
            view.$el.html(out);
          }
        )
      ).done(function() {
        view.fetchTimeline.call(view, view.renderTimeline);
      });
    },

    onClose: function() {
      if (this.socket) {
        this.socket.disconnect();
        this.socket = null;
      }
    },

    events: {
      'click #timeline-open-search': 'openSearch'
    },

    /**
     * Open search modal.
     *
     * @param event {Object} jQuery event object.
     */
    openSearch: function(event) {
      diana.helpers.Widget.closeDropdown(event);
      if (this.searchView) {
          $('#timeline-search-modal').modal('show');
      } else {
        this.searchView = new diana.views.TimelineSearch({
          el: $('#timeline-search-modal'),
          searchArgs: this.options.searchArgs
        });
      }
    },

    /**
     * Fetch all log events matching the search arguments passed to the view.
     *
     * @param callback {Function} Fires on success/error.
     * - Receives an array with zero or more event objects.
     */
    fetchTimeline: function(callback) {
      var view = this;

      // Supply search filters/options for the collection's URL generation.
      view.collection = new diana.collections.Timeline(
        null, {searchArgs: view.options.searchArgs}
      );

      view.collection.fetch({
        success: function(collection, response) {
          if (!response.length) {
            dust.render('timeline_no_results', null, function(err, out) {
              view.$el.html(out);
            });
            return;
          }
          callback.call(view, response);
        },

        error: function(collection, response) {
          diana.helpers.Event.trigger('CritFetchError', response);
          callback.call(view, []);
        }
      });
    },

    /**
     * Render a set of events.
     *
     * - Used for both the intiial fetch and socket.io update payloads.
     *
     * @param events {Array}
     * @param options {Object}
      * - prepend {Boolean} If true, row is prepended (default=false).
      * - highlight {Boolean} If true, row receives styled class (default=false).
     */
    renderTimeline: function(events, options) {
      if (!events.length) {
        return;
      }

      options = options || {
        prepend: false,
        highlight: false
      };

      var view = this;

      // This function is used for both initial fetch and automatic updates.
      // Initial <tbody> is built off-screen and appended as a whole.
      // Automatic updates' <tr> nodes are added individually to an existing <tbody>.
      var existingTbody = $('#timeline-table tbody');
      var tbody = (existingTbody.length ? existingTbody : null) || $('<tbody>');

      // Deferred dust.render() calls later executed by $.when().
      var renderPromises = [];

      // Add empty <tr> nodes to the off-screen or live <tbody>.
      _.each(events, function(event) {
        var tr = $('<tr>');
        if (options.prepend) {
          if (options.highlight) {
            tr.addClass('timeline-update');
          }
          tbody.prepend(tr);
        } else {
          tbody.append(tr);
        }
        renderPromises.push(view.renderEvent(event, tr));
      });

      $.when(renderPromises).done(function() {
        if (existingTbody.length) {
          // tbody was already part of the DOM, so above rows were added live.
        } else {
          $('#timeline-table').append(tbody);
          view.startTimelineUpdate.call(view, events[0]._id);
        }
      });
    },

    /**
     * Render a single event in the timeline table.
     *
     * @param event {Object}
     * @param tr {Object} <tr> parent element.
     * @return {Object} jQuery Promise.
     */
    renderEvent: function(event, tr) {
      event.time = moment(event.time * 1000).fromNow();

      return diana.helpers.View.deferRender(
        'timeline_table_row',
        event,
        function(err, out) {
          $(tr).append(out);
        }
      );
    },

    /**
     * Creates the automatic updates socket. Also handles reconnection and diverts
     * update payloads.
     *
     * @param initialId {String} All updates (if any) will be newer than this ID.
     */
    startTimelineUpdate: function(initialId) {
      if (!diana.features.timelineUpdate) {
        return;
      }

      var view = this;
      view.newestEventId = initialId;

      this.socket = diana.helpers.Socket.create({
        event: {
          connect: function() {
            // Start/restart automatic updates.
            view.socket.emit('startTimelineUpdate', {
              newestEventId: view.newestEventId,
              searchArgs: view.options.searchArgs
            });
          }
        }
      });

      // Update the view with events fresher than newestEventId.
      this.socket.on('timelineUpdate', function(data) {
        view.onTimelineUpdate.call(view, data);
      });
    },

    /**
     * Fires on received responses from the automatic updates socket.
     *
     * @param data {Array|Object} List of event objects on success.
     * - On error, __socket_error string is set.
     */
    onTimelineUpdate: function(data) {
      if (!data || !data.length) {
        return;
      }

      // Advance the manual cursor.
      this.newestEventId = data[0]._id;

      // Un-highlight any past updates.
      $('.timeline-update').removeClass('timeline-update');

      this.renderTimeline(data.reverse(), {prepend: true, highlight: true});
    }
  });
})();
<|endoftext|>


<commit_before>// ==UserScript==
// @name         Extrai Stats Totalcorner
// @namespace    http://aposte.me
// @version      0.1.5
// @description  Extrai Stats Totalcorner
// @author       Ronlado Araújo de Farias
// @match        http://www.totalcorner.com/match/today
// @grant        GM_xmlhttpRequest
// ==/UserScript==

$(document).ready(function(){
	//Se não estiver aparecendo a columa "on target", define as colunas corretas
	$.post('http://www.totalcorner.com/user/select_match_list_columns','asian_handicap=on&corner_score=on&total_corners=on&total_goals=on&dangerous_attack=on&shoot_on=on&shoot_off=on&events=on&save=today', function(){
	   window.location.reload();
	});

	$( document ).ajaxComplete(function( event, res, settings) {
		if (!settings.url.includes('api_ongoing_matches') ) return;

		var TABELA_JOGOS={};
		$('[data-match_id]').each(function(i,e){
			TABELA_JOGOS[$(e).attr('data-match_id')]={
				home: $(e).find('.match_home a').text(),
				away: $(e).find('.match_away a').text()
			};
		});

		var DATA=[];
		$(res.responseJSON).each(function(i,j){

			HA=$(j.han.split(',')).size()==2 ? (Number(j.han.split(',')[0]) + Number(j.han.split(',')[1]))/2.0 : Number(j.han.split(',')[0]);
			try{
				DATA.push({
						id:   j.id,
						time_:j.sta,
						home: TABELA_JOGOS[j.id].home,
						away: TABELA_JOGOS[j.id].away,
						HA:   HA,
						gH:   Number(j.hg),
						gA:   Number(j.ag),
						daH:  Number(j.hda),
						daA:  Number(j.ada),
						soH:  Number(j.ho),
						soA:  Number(j.ao),
						sfH:  Number(j.hf),
						sfA:  Number(j.af)
				});
			} catch(e){
				window.location.reload();
			}

		});

		//$.post('http://aposte.me/live/atualiza_live_bet365_REST.php', JSON.stringify(DATA), function(data) {console.log(data) });
		GM_xmlhttpRequest({
			method: "POST",
			url: "http://aposte.me/live/atualiza_live_bet365_REST.php",
			data:  JSON.stringify(DATA),
			onload: function(res){
				console.log(res.responseText);
			}
		});

	});
});<commit_msg>coloca o document ready - bug<commit_after>// ==UserScript==
// @name         Extrai Stats Totalcorner
// @namespace    http://aposte.me
// @version      0.1.5.1
// @description  Extrai Stats Totalcorner
// @author       Ronlado Araújo de Farias
// @match        http://www.totalcorner.com/match/today
// @grant        GM_xmlhttpRequest
// ==/UserScript==

$(document).ready(function(){
	//Se não estiver aparecendo a columa "on target", define as colunas corretas
    if( $('th:contains(on target)').size()<1 ) {
        $.post('http://www.totalcorner.com/user/select_match_list_columns','asian_handicap=on&corner_score=on&total_corners=on&total_goals=on&dangerous_attack=on&shoot_on=on&shoot_off=on&events=on&save=today', function(){
           window.location.reload();
        });
    }

	$( document ).ajaxComplete(function( event, res, settings) {
		if (!settings.url.includes('api_ongoing_matches') ) return;

		var TABELA_JOGOS={};
		$('[data-match_id]').each(function(i,e){
			TABELA_JOGOS[$(e).attr('data-match_id')]={
				home: $(e).find('.match_home a').text(),
				away: $(e).find('.match_away a').text()
			};
		});

		var DATA=[];
		$(res.responseJSON).each(function(i,j){

			HA=$(j.han.split(',')).size()==2 ? (Number(j.han.split(',')[0]) + Number(j.han.split(',')[1]))/2.0 : Number(j.han.split(',')[0]);
			try{
				DATA.push({
						id:   j.id,
						time_:j.sta,
						home: TABELA_JOGOS[j.id].home,
						away: TABELA_JOGOS[j.id].away,
						HA:   HA,
						gH:   Number(j.hg),
						gA:   Number(j.ag),
						daH:  Number(j.hda),
						daA:  Number(j.ada),
						soH:  Number(j.ho),
						soA:  Number(j.ao),
						sfH:  Number(j.hf),
						sfA:  Number(j.af)
				});
			} catch(e){
				window.location.reload();
			}

		});

		//$.post('http://aposte.me/live/atualiza_live_bet365_REST.php', JSON.stringify(DATA), function(data) {console.log(data) });
		GM_xmlhttpRequest({
			method: "POST",
			url: "http://aposte.me/live/atualiza_live_bet365_REST.php",
			data:  JSON.stringify(DATA),
			onload: function(res){
				console.log(res.responseText);
			}
		});

	});
});<|endoftext|>