<commit_before>
$(function(){
    var themes = [
        ["Default",  "//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css"],
        ["Amelia",   "//bootswatch.com/amelia/bootstrap.min.css"],
        ["Cerulean", "//bootswatch.com/cerulean/bootstrap.min.css"],
        ["Cosmo",    "//bootswatch.com/cosmo/bootstrap.min.css"],
        ["Cyborg",   "//bootswatch.com/cyborg/bootstrap.min.css"],
        ["Flatly",   "//bootswatch.com/flatly/bootstrap.min.css"],
        ["Journal",  "//bootswatch.com/journal/bootstrap.min.css"],
        ["Lumen",    "//bootswatch.com/lumen/bootstrap.min.css"],
        ["Readable", "//bootswatch.com/readable/bootstrap.min.css"],
        ["Simplex",  "//bootswatch.com/simplex/bootstrap.min.css"],
        ["Slate",    "//bootswatch.com/slate/bootstrap.min.css"],
        ["Spacelab", "//bootswatch.com/spacelab/bootstrap.min.css"],
        ["United",   "//bootswatch.com/united/bootstrap.min.css"],
        ["Yeti",     "//bootswatch.com/yeti/bootstrap.min.css"]
    ];

    var sheet = $('<link href="' + themes[0][1] + '" rel="stylesheet" />'),
        list  = $('#theme-list');
    sheet.prependTo('head');

    if (!list.length)
        return;

    var i, n = themes.length, name, href;
    for (i = 0; i < n; i++) {
        name = themes[i][0];
        href = themes[i][1];
        $('
' + name + '
')
            .appendTo(list).find('a').click(function() {
                sheet.attr('href', $(this).attr('data-href'));
            });
    }
});

$(document).ready(generateButtons);

function generateButtons() {
    var i = 0, sheet, sheets = document.styleSheets;
    while ((sheet = sheets[i++]) && ('showcase' !== sheet.href.split('?').pop())); // !
    if (!sheet)
        return;

    var rules = sheet.cssRules, n = rules.length, j = -1,
        re = /\.([\w-]+)(:hover)/, selector, prevSelector,
        container = $('#showcase'),
        header    = $('

'),
        button    = $('<button type="button" class="btn btn-lg"></button>'),
        groupClass = [
            "btn-info",
            "btn-success",
            "btn-danger",
            "btn-warning",
            "btn-primary",
            "btn-default"
        ];

    for (i = 0; i < n; i++) {
        if (rules[i].type !== 1
            || !(selector = re.exec(rules[i].selectorText))
            || (prevSelector === (selector = selector[1])))
                continue;
        prevSelector = selector;
        if (!selector.search("md-group")) {
            header.clone().appendTo(container)
                .text(rules[i].style.getPropertyValue('content').replace(/['"]/g, ''));
            j = (j + 1) % groupClass.length;
        } else {
            button.clone().appendTo(container)
                .addClass(groupClass[j]).addClass(selector).text(selector);
        }
    }
}<commit_msg>Added more themes for demo.<commit_after>
$(function(){
    var themes = [
        ["Default",  "//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css"],
        ["Amelia",   "//bootswatch.com/amelia/bootstrap.min.css"],
        ["Cerulean", "//bootswatch.com/cerulean/bootstrap.min.css"],
        ["Cosmo",    "//bootswatch.com/cosmo/bootstrap.min.css"],
        ["Cupid",    "//bootswatch.com/cupid/bootstrap.min.css"],
        ["Cyborg",   "//bootswatch.com/cyborg/bootstrap.min.css"],
        ["Flatly",   "//bootswatch.com/flatly/bootstrap.min.css"],
        ["Journal",  "//bootswatch.com/journal/bootstrap.min.css"],
        ["Lumen",    "//bootswatch.com/lumen/bootstrap.min.css"],
        ["Readable", "//bootswatch.com/readable/bootstrap.min.css"],
        ["Simplex",  "//bootswatch.com/simplex/bootstrap.min.css"],
        ["Slate",    "//bootswatch.com/slate/bootstrap.min.css"],
        ["Spacelab", "//bootswatch.com/spacelab/bootstrap.min.css"],
        ["United",   "//bootswatch.com/united/bootstrap.min.css"],
        ["Yeti",     "//bootswatch.com/yeti/bootstrap.min.css"]
    ];

    var sheet = $('<link href="' + themes[0][1] + '" rel="stylesheet" />'),
        list  = $('#theme-list');
    sheet.prependTo('head');

    if (!list.length)
        return;

    var i, n = themes.length, name, href;
    for (i = 0; i < n; i++) {
        name = themes[i][0];
        href = themes[i][1];
        $('
' + name + '
')
            .appendTo(list).find('a').click(function() {
                sheet.attr('href', $(this).attr('data-href'));
            });
    }
});

$(document).ready(generateButtons);

var element_;

function generateButtons() {
    var i = 0, sheet, sheets = document.styleSheets;
    while ((sheet = sheets[i++]) && ('showcase' !== sheet.href.split('?').pop())); // !
    if (!sheet)
        return;

    var rules = sheet.cssRules, n = rules.length, j = -1,
        re = /\.([\w-]+)(:hover)/, selector, prevSelector,
        container = $('#showcase'),
        header    = $('

'),
        element   = $(element_ || '<button type="button" class="btn btn-lg"></button>'),
        groupClass = [
            "btn-info",
            "btn-success",
            "btn-danger",
            "btn-warning",
            "btn-primary",
            "btn-default"
        ];

    for (i = 0; i < n; i++) {
        if (rules[i].type !== 1
            || !(selector = re.exec(rules[i].selectorText))
            || (prevSelector === (selector = selector[1])))
                continue;
        prevSelector = selector;
        if (!selector.search("md-group")) {
            header.clone().appendTo(container)
                .text(rules[i].style.getPropertyValue('content').replace(/['"]/g, ''));
            j = (j + 1) % groupClass.length;
        } else {
            element.clone().appendTo(container)
                .addClass(groupClass[j]).addClass(selector).text(selector);
        }
    }
}
<|endoftext|>


<commit_before>import axios from 'axios';

import { library } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import { faExclamationTriangle } from '@fortawesome/free-solid-svg-icons';
library.add(faExclamationTriangle);

import { mount } from '@vue/test-utils';
import { createLocalVue } from './helper';

import Vuex from 'vuex';
import hfs from '../vuex/store/hfs';

import UwCard from '../components/_templates/card.vue';
import HuskyCard from '../components/accounts/husky.vue';
import mockJaverageHfs from './mock_data/hfs.json';

const localVue = createLocalVue(Vuex);
localVue.component('font-awesome-icon', FontAwesomeIcon);
localVue.component('uw-card', UwCard);

jest.mock('axios');

describe('Husky Card', () => {
  let store;

  beforeEach(() => {
    store = new Vuex.Store({
      modules: {
        hfs,
      },
      state: {
        user: {
          affiliations: {
            student: false,
            past_stud: false,
            employee: false,
            past_employee: false,
          }
        }
      }
    });
  });

  it('Display card to student', async () => {
    axios.get.mockResolvedValue({data: mockJaverageHfs, status: 200});
    store.state.user.affiliations.student = true;
    const wrapper = mount(HuskyCard, {store, localVue});
    await new Promise((r) => setTimeout(r, 10));
    expect(wrapper.vm.isReady).toBeTruthy();
    expect(
      wrapper.findComponent(UwCard).exists()
    ).toBe(true);
    expect(
      wrapper.findAll('h3').at(0).text()
    ).toBe('Husky Card');
    expect(
      wrapper.findAll('h4').at(0).text()
    ).toBe('Student Husky Account');
    expect(
      wrapper.findAll('h4').at(1).text()
    ).toBe('Employee Husky Account');
    expect(wrapper.findAll('span').at(0).text()
    ).toBe('$1.23');
    expect(wrapper.findAll('span').at(2).text()
    ).toBe('$1.00');
    expect(wrapper.findAll('a').length).toBe(1);
  });

  it('Hide card if not the right user type', async () => {
    const wrapper = mount(HuskyCard, { store, localVue });
    expect(wrapper.vm.showCard).toBe(false);
    expect(wrapper.findComponent(UwCard).exists()).toBe(false);
  });

  it('Hide card if api returns 404', async () => {
    axios.get.mockResolvedValue(Promise.reject({response: {status: 404}}));
    const wrapper = mount(HuskyCard, {store, localVue});
    await new Promise((r) => setTimeout(r, 10));
    expect(wrapper.vm.isErrored).toBe(true);
    expect(wrapper.vm.showError).toBe(false);
    expect(wrapper.findComponent(UwCard).exists()).toBe(false);
  });

  it('Show error msg if api returns 543', async () => {
    axios.get.mockResolvedValue(Promise.reject({response: {status: 543}}));
    const wrapper = mount(HuskyCard, {store, localVue});
    await new Promise((r) => setTimeout(r, 10));
    expect(wrapper.vm.isErrored).toBe(true);
    expect(wrapper.vm.showError).toBe(true);
    expect(wrapper.findAll('a').length).toBe(1);
    expect(wrapper.findAll('a').at(0).attributes().href
    ).toBe('https://hfs.uw.edu/olco/Secure/AccountSummary.aspx');
  });
});
<commit_msg>add await<commit_after>import axios from 'axios';

import { library } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import { faExclamationTriangle } from '@fortawesome/free-solid-svg-icons';
library.add(faExclamationTriangle);

import { mount } from '@vue/test-utils';
import { createLocalVue } from './helper';

import Vuex from 'vuex';
import hfs from '../vuex/store/hfs';

import UwCard from '../components/_templates/card.vue';
import HuskyCard from '../components/accounts/husky.vue';
import mockJaverageHfs from './mock_data/hfs.json';

const localVue = createLocalVue(Vuex);
localVue.component('font-awesome-icon', FontAwesomeIcon);
localVue.component('uw-card', UwCard);

jest.mock('axios');

describe('Husky Card', () => {
  let store;

  beforeEach(() => {
    store = new Vuex.Store({
      modules: {
        hfs,
      },
      state: {
        user: {
          affiliations: {
            student: false,
            past_stud: false,
            employee: false,
            past_employee: false,
          }
        }
      }
    });
  });

  it('Display card to student', async () => {
    axios.get.mockResolvedValue({data: mockJaverageHfs, status: 200});
    store.state.user.affiliations.student = true;
    const wrapper = mount(HuskyCard, {store, localVue});
    await new Promise((r) => setTimeout(r, 10));
    expect(wrapper.vm.isReady).toBeTruthy();
    expect(
      wrapper.findComponent(UwCard).exists()
    ).toBe(true);
    expect(
      wrapper.findAll('h3').at(0).text()
    ).toBe('Husky Card');
    expect(
      wrapper.findAll('h4').at(0).text()
    ).toBe('Student Husky Account');
    expect(
      wrapper.findAll('h4').at(1).text()
    ).toBe('Employee Husky Account');
    expect(wrapper.findAll('span').at(0).text()
    ).toBe('$1.23');
    expect(wrapper.findAll('span').at(2).text()
    ).toBe('$1.00');
    expect(wrapper.findAll('a').length).toBe(1);
  });

  it('Hide card if not the right user type', async () => {
    const wrapper = mount(HuskyCard, { store, localVue });
    await new Promise((r) => setTimeout(r, 10));
    expect(wrapper.vm.showCard).toBe(false);
    expect(wrapper.findComponent(UwCard).exists()).toBe(false);
  });

  it('Hide card if api returns 404', async () => {
    axios.get.mockResolvedValue(Promise.reject({response: {status: 404}}));
    const wrapper = mount(HuskyCard, {store, localVue});
    await new Promise((r) => setTimeout(r, 10));
    expect(wrapper.vm.isErrored).toBe(true);
    expect(wrapper.vm.showError).toBe(false);
    expect(wrapper.findComponent(UwCard).exists()).toBe(false);
  });

  it('Show error msg if api returns 543', async () => {
    axios.get.mockResolvedValue(Promise.reject({response: {status: 543}}));
    const wrapper = mount(HuskyCard, {store, localVue});
    await new Promise((r) => setTimeout(r, 10));
    expect(wrapper.vm.isErrored).toBe(true);
    expect(wrapper.vm.showError).toBe(true);
    expect(wrapper.findAll('a').length).toBe(1);
    expect(wrapper.findAll('a').at(0).attributes().href
    ).toBe('https://hfs.uw.edu/olco/Secure/AccountSummary.aspx');
  });
});
<|endoftext|>


<commit_before>(function (enyo, scope) {

	/**
	* Features a variety of commonly used widgets, including toolbars, text inputs, checkboxes, groups
	* and multiple types of buttons.
	*
	* @namespace onyx
	*/

	if (enyo && enyo.version) {
		enyo.version.onyx = "2.6.0-zzz.1";
	}

})(enyo, this);
<commit_msg>Update version string to 2.6.0-zzz.1.dev<commit_after>(function (enyo, scope) {

	/**
	* Features a variety of commonly used widgets, including toolbars, text inputs, checkboxes, groups
	* and multiple types of buttons.
	*
	* @namespace onyx
	*/

	if (enyo && enyo.version) {
		enyo.version.onyx = "2.6.0-zzz.1.dev";
	}

})(enyo, this);
<|endoftext|>


<commit_before>/* This module uses a give ip to visit the whole urls in the bucket assigned to it
*/
module.exports = function(bucketExplorer , database) {
	//
    var ObjectId = require('mongodb').ObjectId;
	var Spooky = require('spooky');
	var bucket;
    var ipQueue = [];
    var ipQueueIndex = 0;
    var visiting = 0;

    var exitFlag = false;

    //
    var Buckets = database.model('Buckets');

    //
    var setBucket =  function(bucketObj){
    	 bucket = bucketObj;
         if(bucket.urls.length>0){
            for(var i=0; i<bucket.urls.length; i++){
                bucket.urls[i].visited = 0;
                bucket.urls[i].statusText = 'No status yet';
            };
         }

    	 console.log(bucket);
    	 console.log('bucket set in visitor');
         startUpdateDaemon();
    };

    var getBucket = function(){
    	return bucket;
    };

    var updateBucket = function(bucketObj , meta){
    	console.log(meta);
    	if(bucket){
            if(bucketObj._id+'' == bucket._id){
	           if(meta.action == 0){
	           	   console.log('Deleting url in this bucket');
                   bucket.urls.splice(meta.index , 1);
	           }
	           else if(meta.action == 1) {
                   console.log('Updating url in this bucket');
                   bucket = bucketObj;
	           }
	    	}
	    	else{
	    	   console.log('Just passing by');
	    	}
    	}
    	else{
    		 console.log('Bucket empty here');
    	}
    }

    //updateBucket after every 100 secs of activity
    function startUpdateDaemon(){
        console.log('Starting cron daemon');
        setInterval(function(){
            bucket.lastActive = Date.now()+'';
            Buckets.update(
                {_id : ObjectId(bucket._id)},
                bucket,
                function(err , result){
                    if(err){
                        console.log(err);
                        res.status(500).send('Database error during cron update in visitor');
                    }
                    else {
                        console.log('bucket updated in cron job');
                    }
                }
          );
        } , 100000);
    }

    //
    function startVisitingDaemon(){
       var interval = 10000;
       setInterval(function(){
           if(visiting<3 && ipQueueIndex < ipQueue.length){
               interval = 10000;
               for(var i=0; i<bucket.urls.length; i++){
                    runGhostProxy (ipQueue[ipQueueIndex] , bucket.urls[i] , i , function(){
                        visiting--;
                        console.log('visiting complete '+(visiting)+' currently running');
                        if(exitFlag && visiting == 0){
                            console.log('All ips have been visited exiting process...');
                            process.exit(0);
                        }
                    });
              }
              ipQueueIndex++;
           }
           else{
               if(interval < 60000){
                   interval+=5000;
               }

               if(visiting>=5){
                   console.log('Maximum limit of '+visiting+' reached');
               }
               else{
                   //console.log('No more ip in queue yet');
               }
           }

       } , interval);

    }

    //
    var visitWith = function(ip){
        console.log('Adding ip to queue');
        if(ipQueue.indexOf(ip)<0){
            ipQueue.push(ip);
        }
        else{
            console.log('ip alredy used or currently in use');
        }

        if(ipQueue.length == 1){
            startVisitingDaemon();
        }
    }

    //
    var exitWhenDone = function(){
         exitFlag = true;
    }

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	function runGhostProxy (ip , url , index , callback){
        visiting++;
		console.log('starting ghost');
		console.log('process starting '+ip+' '+url.urlName+' '+url.selector);

	    var spooky = new Spooky({
			child: {
				transport: 'http',
				proxy: ip
			},
			casper: {
				logLevel: 'debug',
				verbose: true,
				options: {
				   clientScripts: ['http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'],
				   pageSettings: {
				        Referer: 'https://www.google.com.ng'
				    }
				}
			}
		 },
		 function(err){
		   if (err) {
				e = new Error('Failed to initialize SpookyJS');
				e.details = err;
				throw e;
			}

			//
			spooky.start(url.urlName);
			spooky.then([{url:url.urlName , selector:url.selector} , function(){
                 this.viewport(1024, 768, function() {//
					  console.log('Viewport size changed');

			          //General case
                      if(selector=='none'){
                           this.then(function(){
                                this.wait(15000 , function(){
                                    this.emit('done', 'Hello, from ' + this.getCurrentUrl());
                                    phantom.clearCookies();
                                });
                            });
						}

						else{
						   this.then(function(){
						   	   this.waitForSelector(selector , function(){
						   	   	  this.thenClick(selector , function() {
                                        this.emit('done', 'Hello, from ' + this.getCurrentUrl());
								        phantom.clearCookies();
                                   });

						   	   } , function(){
						   	   	     this.emit('done', 'The selector was not found');
								        phantom.clearCookies();
						   	   } , 20000);
						   });
						}

				    });
			}]);

            //
			spooky.run();
		});

		//logs and listeners
		spooky.on('error', function (e, stack) {
			console.log('here');//
			console.error(e);
			Greeting = e;

			if (stack) {
				console.log(stack);
				Greeting = stack;
			}

            console.log('This round done visiting with '+ip);
            bucket.urls[index].statusText = e;
            bucket.urls[index].visited++;
            spooky.destroy();
            return callback();

		});

		//
		spooky.on('console', function (line) {
			console.log(line);
		});

		//
		spooky.on('done', function (greeting) {
			bucket.urls[index].statusText = greeting;
            bucket.urls[index].visited++;

			console.log('This round done visiting with '+ip);
            spooky.destroy();
            return callback();

		});
	};

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	return {
	    visitWith:visitWith,
	    getBucket:getBucket,
	    setBucket:setBucket,
	    updateBucket:updateBucket,
	    exitWhenDone:exitWhenDone
	}

};<commit_msg>update<commit_after>/* This module uses a give ip to visit the whole urls in the bucket assigned to it
*/
module.exports = function(bucketExplorer , database) {
	//
    var ObjectId = require('mongodb').ObjectId;
	var Spooky = require('spooky');
	var bucket;
    var ipQueue = [];
    var ipQueueIndex = 0;
    var visiting = 0;
    var limit =  5;

    var exitFlag = false;

    //
    var Buckets = database.model('Buckets');

    //
    var setBucket =  function(bucketObj){
    	 bucket = bucketObj;
         if(bucket.urls.length>0){
            for(var i=0; i<bucket.urls.length; i++){
                bucket.urls[i].visited = 0;
                bucket.urls[i].statusText = 'No status yet';
            };
         }

    	 console.log(bucket);
    	 console.log('bucket set in visitor');
         startUpdateDaemon();
    };

    var getBucket = function(){
    	return bucket;
    };

    var updateBucket = function(bucketObj , meta){
    	console.log(meta);
    	if(bucket){
            if(bucketObj._id+'' == bucket._id){
	           if(meta.action == 0){
	           	   console.log('Deleting url in this bucket');
                   bucket.urls.splice(meta.index , 1);
	           }
	           else if(meta.action == 1) {
                   console.log('Updating url in this bucket');
                   bucket = bucketObj;
	           }
	    	}
	    	else{
	    	   console.log('Just passing by');
	    	}
    	}
    	else{
    		 console.log('Bucket empty here');
    	}
    }

    //updateBucket after every 100 secs of activity
    function startUpdateDaemon(){
        console.log('Starting cron daemon');
        setInterval(function(){
            bucket.lastActive = Date.now()+'';
            Buckets.update(
                {_id : ObjectId(bucket._id)},
                bucket,
                function(err , result){
                    if(err){
                        console.log(err);
                        res.status(500).send('Database error during cron update in visitor');
                    }
                    else {
                        console.log('bucket updated in cron job');
                    }
                }
          );
        } , 100000);
    }

    //
    function startVisitingDaemon(){
       var interval = 10000;
       setInterval(function(){
           if(visiting<limit && ipQueueIndex < ipQueue.length){
               interval = 10000;
               for(var i=0; i<bucket.urls.length; i++){
                    runGhostProxy (ipQueue[ipQueueIndex] , bucket.urls[i] , i , function(){
                        visiting--;
                        console.log('visiting complete '+(visiting)+' currently running');
                        if(exitFlag && visiting == 0){
                            console.log('All ips have been visited exiting process...');
                            process.exit(0);
                        }
                    });
              }
              ipQueueIndex++;
           }
           else{
               if(interval < 60000){
                   interval+=5000;
               }

               if(visiting>=limit){
                   console.log('Maximum limit of '+visiting+' reached');
                    limit++;
               }
               else{
                   //console.log('No more ip in queue yet');
               }
           }

       } , interval);

    }

    //
    var visitWith = function(ip){
        console.log('Adding ip to queue');
        if(ipQueue.indexOf(ip)<0){
            ipQueue.push(ip);
        }
        else{
            console.log('ip alredy used or currently in use');
        }

        if(ipQueue.length == 1){
            startVisitingDaemon();
        }
    }

    //
    var exitWhenDone = function(){
         exitFlag = true;
    }

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	function runGhostProxy (ip , url , index , callback){
        visiting++;
		console.log('starting ghost');
		console.log('process starting '+ip+' '+url.urlName+' '+url.selector);

	    var spooky = new Spooky({
			child: {
				transport: 'http',
				proxy: ip
			},
			casper: {
				logLevel: 'debug',
				verbose: true,
				options: {
				   clientScripts: ['http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'],
				   pageSettings: {
				        Referer: 'https://www.google.com.ng'
				    }
				}
			}
		 },
		 function(err){
		   if (err) {
				e = new Error('Failed to initialize SpookyJS');
				e.details = err;
				throw e;
			}

			//
			spooky.start(url.urlName);
			spooky.then([{url:url.urlName , selector:url.selector} , function(){
                 this.viewport(1024, 768, function() {//
					  console.log('Viewport size changed');

			          //General case
                      if(selector=='none'){
                           this.then(function(){
                                this.wait(15000 , function(){
                                    this.emit('done', 'Hello, from ' + this.getCurrentUrl());
                                    phantom.clearCookies();
                                });
                            });
						}

						else{
						   this.then(function(){
						   	   this.waitForSelector(selector , function(){
						   	   	  this.thenClick(selector , function() {
                                        this.emit('done', 'Hello, from ' + this.getCurrentUrl());
								        phantom.clearCookies();
                                   });

						   	   } , function(){
						   	   	     this.emit('done', 'The selector was not found');
								        phantom.clearCookies();
						   	   } , 20000);
						   });
						}

				    });
			}]);

            //
			spooky.run();
		});

		//logs and listeners
		spooky.on('error', function (e, stack) {
			console.log('here');//
			console.error(e);
			Greeting = e;

			if (stack) {
				console.log(stack);
				Greeting = stack;
			}

            console.log('This round done visiting with '+ip);
            bucket.urls[index].statusText = e;
            bucket.urls[index].visited++;
            spooky.destroy();
            return callback();

		});

		//
		spooky.on('console', function (line) {
			console.log(line);
		});

		//
		spooky.on('done', function (greeting) {
			bucket.urls[index].statusText = greeting;
            bucket.urls[index].visited++;

			console.log('This round done visiting with '+ip);
            spooky.destroy();
            return callback();

		});
	};

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	return {
	    visitWith:visitWith,
	    getBucket:getBucket,
	    setBucket:setBucket,
	    updateBucket:updateBucket,
	    exitWhenDone:exitWhenDone
	}

};<|endoftext|>


<commit_before>/* This module uses a give ip to visit the whole urls in the bucket assigned to it
*/
'use strict';

module.exports = function(bucketExplorer , database) {
	//
    var ObjectId = require('mongodb').ObjectId;
	var Spooky = require('spooky');
    var EventEmitter = require('events').EventEmitter;

	var bucket;
    var ipQueue = [];
    var ipQueueIndex = 0;

    var exitFlag = false;

    //
    var Buckets = database.model('Buckets');

    //
    var setBucket =  function(bucketObj){
    	 bucket = bucketObj;
         if(bucket.urls.length>0){
            for(var i=0; i<bucket.urls.length; i++){
                bucket.urls[i].visited = 0;
                bucket.urls[i].statusText = 'No status yet';
            };
         }

    	 console.log(bucket);
    	 console.log('bucket set in visitor');
         startUpdateDaemon();
    };

    //
    var getBucket = function(){
    	return bucket;
    };

    //
    var updateBucket = function(bucketObj , meta){
    	console.log(meta);
    	if(bucket){
            if(bucketObj._id+'' == bucket._id){
	           if(meta.action == 0){
	           	   console.log('Deleting url in this bucket');
                   bucket.urls.splice(meta.index , 1);
	           }
	           else if(meta.action == 1) {
                   console.log('Updating url in this bucket');
                   bucket = bucketObj;
	           }
	    	}
	    	else{
	    	   console.log('Just passing by');
	    	}
    	}
    	else{
    		 console.log('Bucket empty here');
    	}
    }

    //
    var notifyDelete = function(_id){
         console.log('Bucket with'+ _id +'deleted');
         if(bucket){
             if(bucket._id == _id){
                console.log('This bucket was deleted');
                setTimeout(function(){
                    process.exit(0);
                } , 10000);
             }
             else{
                 console.log('Not this one 1..');
             }

         }
         else{
            console.log('Not this one..');
         }
    }

    //
    var visitWith = function(ip){
        console.log('Adding ip to queue');
        if(ipQueue.indexOf(ip)<0){
            ipQueue.push(ip);
        }
        else{
            console.log('ip alredy used or currently in use');
        }

        if(ipQueue.length == 1){
            startVisitingDaemon();
        }
    }

    //
    var exitWhenDone = function(){
         exitFlag = true;
    }

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    var V_WORKER = function(){
        var workerEvents = new EventEmitter;

        var visit = function(ip , urlsArr){
            console.log('visit starting with '+ip+' and '+urlsArr.length+' urls');

            var spooky = new Spooky({
                child: {
                    transport: 'http',
                    proxy: ip
                },
                casper: {
                    logLevel: 'debug',
                    verbose: true,
                    options: {
                        pageSettings: {
                            webSecurityEnabled: false
                        }
                    }
                }
            },
            function(err){
            if (err) {
                    e = new Error('Failed to initialize SpookyJS');
                    e.details = err;
                    throw e;
                }

                var worker = function(url , selector , index){
                    //
                    spooky.start(url);
                    spooky.then([{url:url , selector:selector , urlIndex:index} , function(){
                        //General case
                        this.done = function(err , status){
                            if(err){
                                this.emit('done', {status:this.getCurrentUrl() , index:urlIndex});
                                return phantom.clearCookies();
                            }
                            else{
                                this.emit('done', {status:this.getCurrentUrl() , index:urlIndex});
                                return phantom.clearCookies();
                            }
                        }

                        if(selector=='none'){
                            this.then(function(){
                                this.wait(15000 , function(){
                                    this.done(null , true);
                                });
                            });
                        }

                        else{
                            this.then(function(){
                                this.waitForSelector(selector , function(){
                                    this.thenClick(selector , function() {
                                       this.done();
                                    });

                                } , function(){
                                      this.done(true , null);
                                } , 20000);
                            });
                        }
                    }]);
                }

                //
                for(var i=0; i < urlsArr.length; i++){
                    worker(urlsArr[i].urlName , urlsArr[i].selector , i);
                }

                //
                spooky.run();
            });

            //
            spooky.on('console', function (line) {
                console.log(line);
            });

            //
            spooky.on('error', function (e, stack) {
                console.error(stack||e);
                workerEvents.emit('done' , {status:stack?stack:e , index:0});
            });

            //
            spooky.on('done', function (status) {
                workerEvents.emit('done' , status);
            });

            //self destruct this instance in 15 minutes
            setTimeout(function(){
                console.log('Instance destroyed');
                spooky.destroy();
            } , 15*60000);
        };

        return {
            visit:visit,
            status:workerEvents
        }
    }
    //++++++++++++++++++++++++++++++++END++++++++++++++++++++++++++++++++++++++++++

    //updateBucket after every 120 secs of activity
    function startUpdateDaemon(){
        var timer = 0;
        console.log('Starting cron daemon');
        setInterval(function(){
            bucket.lastActive = Date.now()+'';
            Buckets.update(
                {_id : ObjectId(bucket._id)},
                bucket,
                function(err , result){
                    if(err){
                        console.log(err);
                        res.status(500).send('Database error during cron update in visitor');
                    }
                    else {
                        timer+=2;
                        if(timer >= 162){
                            console.log('Maximum uptime of two hours exceeded exiting....');
                            process.exit(0);
                        }
                        console.log('bucket updated in cron job');
                    }
                }
          );
        } , 120000);
    }

    //
    function startVisitingDaemon(){
       let visiting = 0;
       let limit =  20;
       let v_worker = V_WORKER();

       setInterval(function(){
          if(ipQueueIndex < ipQueue.length){
               v_worker.visit(ipQueue[ipQueueIndex] , bucket.urls);
               ipQueueIndex++;
               visiting+= bucket.urls.length;
          }
          else{
              if(limit < visiting){
                  console.log('Visiting urls have exceeded the limit');
                  limit+=100;
              }
              else{
                  //console.log('Good ip shortage');
              }

          }

       } , 10000);

       //
       v_worker.status.on('done' , function(status){
            console.log(status);
            bucket.urls[status.index].statusText = status.status;
            bucket.urls[status.index].visited++;
            visiting--;
            limit--;

            if(exitFlag && ipQueueIndex >= ipQueue.length){
                console.log('All ips have been visited exiting process...');
                process.exit(0);
            }
        });
    }

	return {
	    visitWith:visitWith,
	    getBucket:getBucket,
	    setBucket:setBucket,
	    updateBucket:updateBucket,
        notifyDelete:notifyDelete,
	    exitWhenDone:exitWhenDone
	}
};<commit_msg>update merge revert<commit_after>/* This module uses a give ip to visit the whole urls in the bucket assigned to it
*/
'use strict';

module.exports = function(bucketExplorer , database) {
	//
    var ObjectId = require('mongodb').ObjectId;
	var Spooky = require('spooky');
    var EventEmitter = require('events').EventEmitter;

	var bucket;
    var ipQueue = [];
    var ipQueueIndex = 0;

    var exitFlag = false;

    //
    var Buckets = database.model('Buckets');

    //
    var setBucket =  function(bucketObj){
    	 bucket = bucketObj;
         if(bucket.urls.length>0){
            for(var i=0; i<bucket.urls.length; i++){
                bucket.urls[i].visited = 0;
                bucket.urls[i].statusText = 'No status yet';
            };
         }

    	 console.log(bucket);
    	 console.log('bucket set in visitor');
         startUpdateDaemon();
    };

    //
    var getBucket = function(){
    	return bucket;
    };

    //
    var updateBucket = function(bucketObj , meta){
    	console.log(meta);
    	if(bucket){
            if(bucketObj._id+'' == bucket._id){
	           if(meta.action == 0){
	           	   console.log('Deleting url in this bucket');
                   bucket.urls.splice(meta.index , 1);
	           }
	           else if(meta.action == 1) {
                   console.log('Updating url in this bucket');
                   bucket = bucketObj;
	           }
	    	}
	    	else{
	    	   console.log('Just passing by');
	    	}
    	}
    	else{
    		 console.log('Bucket empty here');
    	}
    }

    //
    var notifyDelete = function(_id){
         console.log('Bucket with'+ _id +'deleted');
         if(bucket){
             if(bucket._id == _id){
                console.log('This bucket was deleted');
                setTimeout(function(){
                    process.exit(0);
                } , 10000);
             }
             else{
                 console.log('Not this one 1..');
             }

         }
         else{
            console.log('Not this one..');
         }
    }

    //
    var visitWith = function(ip){
        console.log('Adding ip to queue');
        if(ipQueue.indexOf(ip)<0){
            ipQueue.push(ip);
        }
        else{
            console.log('ip alredy used or currently in use');
        }

        if(ipQueue.length == 1){
            startVisitingDaemon();
        }
    }

    //
    var exitWhenDone = function(){
         exitFlag = true;
    }

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    var V_WORKER = function(){
        var workerEvents = new EventEmitter;

        var visit = function(ip , urlsArr){
            console.log('visit starting with '+ip+' and '+urlsArr.length+' urls');

            var spooky = new Spooky({
                child: {
                    transport: 'http',
                    proxy: ip
                },
                casper: {
                    logLevel: 'debug',
                    verbose: true,
                    options: {
                        pageSettings: {
                            webSecurityEnabled: false
                        }
                    }
                }
            },
            function(err){
            if (err) {
                    e = new Error('Failed to initialize SpookyJS');
                    e.details = err;
                    throw e;
                }

                var worker = function(url , selector , index){
                    //
                    spooky.start(url);
                    spooky.then([{url:url , selector:selector , urlIndex:index} , function(){
                        //General case
                        this.done = function(err , status){
                            if(err){
                                this.emit('done', {status:this.getCurrentUrl() , index:urlIndex});
                                return phantom.clearCookies();
                            }
                            else{
                                this.emit('done', {status:this.getCurrentUrl() , index:urlIndex});
                                return phantom.clearCookies();
                            }
                        }

                        if(selector=='none'){
                            this.then(function(){
                                this.wait(15000 , function(){
                                    this.done(null , true);
                                });
                            });
                        }

                        else{
                            this.then(function(){
                                this.waitForSelector(selector , function(){
                                    this.thenClick(selector , function() {
                                       this.done();
                                    });

                                } , function(){
                                      this.done(true , null);
                                } , 20000);
                            });
                        }
                    }]);
                }

                //
                for(var i=0; i < urlsArr.length; i++){
                    worker(urlsArr[i].urlName , urlsArr[i].selector , i);
                }

                //
                spooky.run();
            });

            //
            spooky.on('console', function (line) {
                console.log(line);
            });

            //
            spooky.on('error', function (e, stack) {
                console.error(stack||e);
                workerEvents.emit('done' , {status:stack?stack:e , index:0});
            });

            //
            spooky.on('done', function (status) {
                workerEvents.emit('done' , status);
            });

            //self destruct this instance in 15 minutes
            setTimeout(function(){
                console.log('Instance destroyed');
                spooky.destroy();
            } , 15*60000);
        };

        return {
            visit:visit,
            status:workerEvents
        }
    }
    //++++++++++++++++++++++++++++++++END++++++++++++++++++++++++++++++++++++++++++

    //updateBucket after every 120 secs of activity
    function startUpdateDaemon(){
        var timer = 0;
        console.log('Starting cron daemon');
        setInterval(function(){
            bucket.lastActive = Date.now()+'';
            Buckets.update(
                {_id : ObjectId(bucket._id)},
                bucket,
                function(err , result){
                    if(err){
                        console.log(err);
                        res.status(500).send('Database error during cron update in visitor');
                    }
                    else {
                        timer+=2;
                        if(timer >= 162){
                            console.log('Maximum uptime of two hours exceeded exiting....');
                            process.exit(0);
                        }
                        console.log('bucket updated in cron job');
                    }
                }
          );
        } , 120000);
    }

    //
    function startVisitingDaemon(){
       let visiting = 0;
       let limit =  20;
       let v_worker = V_WORKER();

       setInterval(function(){
          if(ipQueueIndex < ipQueue.length){
               v_worker.visit(ipQueue[ipQueueIndex] , bucket.urls);
               ipQueueIndex++;
               visiting+= bucket.urls.length;
          }
          else{
              if(limit < visiting){
                  console.log('Visiting urls have exceeded the limit');
                  limit+=100;
              }
              else{
                  //console.log('Good ip shortage');
              }

          }

       } , 10000);

       //
       v_worker.status.on('done' , function(status){
            console.log(status);
            bucket.urls[status.index].statusText = status.status;
            bucket.urls[status.index].visited++;
            visiting--;
            limit--;

            if(exitFlag && ipQueueIndex >= ipQueue.length){
                console.log('All ips have been visited exiting process...');
                process.exit(0);
            }//
        });
    }

	return {
	    visitWith:visitWith,
	    getBucket:getBucket,
	    setBucket:setBucket,
	    updateBucket:updateBucket,
        notifyDelete:notifyDelete,
	    exitWhenDone:exitWhenDone
	}
};<|endoftext|>


<commit_before>class Tile
{
    constructor(x, y, s)
    {
        this.x = x;
        this.y = y;
        this.s = s;
        this.state = 0;
    }

    draw()
    {
        switch( this.state )
        {
            case 0:
                fill( 'white' );
                break;
            case -1:
                fill( 'gray' );
                break;
            case 1:
                fill( 'blue' );
                break;
        }
        rect(this.x, this.y, this.s, this.s );
    }
}<commit_msg>change draw to return color based on state<commit_after>class Tile
{
    constructor(r, c, s)
    {
        this.r = r;
        this.c = c;
        this.s = s;
        this.state = 0;
    }

    getColor()
    {
        switch( this.state )
        {
            case -1:
                return 'gray' ;
            case 1:
                return 'blue' ;
            default:
                return 'white';
        }
        let x = padding + this.c * this.s;
        let y = padding + this.r * this.s;
        text(`(${this.r},${this.c})`, x, y + textSize() )
        rect(x, y, this.s, this.s );
    }
}<|endoftext|>


<commit_before> /*
 * Watcher v1.2.0 - 11-23-2015, https://github.com/davegillem/watcher-pubsub
 * ===================================
 * A jQuery plugin for enabling publish/subscribe (Observer) functionality
 *
 * (c) Copyright 2015 Dave Gillem, http://davegillem.com
 * MIT Licensed
 */

;(function ($, window) {
	"use strict";

	var watchers			= {},
		watcherID			= -1,

		_addWatcher			= function(event, callback) {
			if(!watchers[event]){
				watchers[event] = [];
			}

			var whichWatcher, watcherRef,
				isCopy = false,
				currEvent = watchers[event];
			// check for duplicates
			for(var i=0, loopcount=currEvent.length; i<loopcount; i++){
				whichWatcher = currEvent[i];
				if(whichWatcher.callback === callback) {
					isCopy = true;
					watcherRef = whichWatcher.id;
				}
			}
			if(!isCopy){
				++watcherID;
				watchers[event].push({
							callback	: callback,
							id			: watcherID
				});
				watcherRef = watcherID;
			}
			return watcherRef;
	    },
	    _removeWatcher		= function(event, id) {
			var whichWatcher,
				isRemoved = false,
				currEvent = watchers[event];
			for(var i=0, loopcount=currEvent.length; i<loopcount; i++){
				whichWatcher = currEvent[i];
				if(whichWatcher.id == id) {
					currEvent.splice(i, 1);
					isRemoved = true;
				}
			}
			return isRemoved;
	    },
	    _removeAllWatchers	= function(event) {
			delete watchers[event];
	    },
		_notifyWatchers		= function(event, data) {
			var whichEvent = watchers[event];
			if(whichEvent){
				whichEvent && $.each(whichEvent, function() {
					this.callback.call($, data);
				});
			}
	    },
	    _getWatchers		= function (event){
		    	return event ? watchers[event] : watchers;
	    },
		_pubMap				= {
								'getWatchers'	: _getWatchers,
								'publish'		: _notifyWatchers,
								'subscribe'		: _addWatcher,
								'unsubscribe'	: _removeWatcher,
								'unsubscribeAll': _removeAllWatchers
							};

	$.watcher 			= function(method, event, data) {
		var methodCall = _pubMap[method];
		if (methodCall) {
			return methodCall(event, data);
		}else{
			throw new Error("There is not a "+method+" that can be called for $.watcher");
		}
	};

})(jQuery, this);<commit_msg>updated patch version<commit_after> /*
 * Watcher v1.2.1 - 11-23-2015, https://github.com/davegillem/watcher-pubsub
 * ===================================
 * A jQuery plugin for enabling publish/subscribe (Observer) functionality
 *
 * (c) Copyright 2015 Dave Gillem, http://davegillem.com
 * MIT Licensed
 */

;(function ($, window) {
	"use strict";

	var watchers			= {},
		watcherID			= -1,

		_addWatcher			= function(event, callback) {
			if(!watchers[event]){
				watchers[event] = [];
			}

			var whichWatcher, watcherRef,
				isCopy = false,
				currEvent = watchers[event];
			// check for duplicates
			for(var i=0, loopcount=currEvent.length; i<loopcount; i++){
				whichWatcher = currEvent[i];
				if(whichWatcher.callback === callback) {
					isCopy = true;
					watcherRef = whichWatcher.id;
				}
			}
			if(!isCopy){
				++watcherID;
				watchers[event].push({
							callback	: callback,
							id			: watcherID
				});
				watcherRef = watcherID;
			}
			return watcherRef;
	    },
	    _removeWatcher		= function(event, id) {
			var whichWatcher,
				isRemoved = false,
				currEvent = watchers[event];
			for(var i=0, loopcount=currEvent.length; i<loopcount; i++){
				whichWatcher = currEvent[i];
				if(whichWatcher.id == id) {
					currEvent.splice(i, 1);
					isRemoved = true;
				}
			}
			return isRemoved;
	    },
	    _removeAllWatchers	= function(event) {
			delete watchers[event];
	    },
		_notifyWatchers		= function(event, data) {
			var whichEvent = watchers[event];
			if(whichEvent){
				whichEvent && $.each(whichEvent, function() {
					this.callback.call($, data);
				});
			}
	    },
	    _getWatchers		= function (event){
		    	return event ? watchers[event] : watchers;
	    },
		_pubMap				= {
								'getWatchers'	: _getWatchers,
								'publish'		: _notifyWatchers,
								'subscribe'		: _addWatcher,
								'unsubscribe'	: _removeWatcher,
								'unsubscribeAll': _removeAllWatchers
							};

	$.watcher 			= function(method, event, data) {
		var methodCall = _pubMap[method];
		if (methodCall) {
			return methodCall(event, data);
		}else{
			throw new Error("There is not a "+method+" that can be called for $.watcher");
		}
	};

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


<commit_before>var fs = require('fs');
var request = require('request');
var Slack = require('slack-node');

var slack_token = process.argv[2];
var weather_code = process.argv[3];
var slack_channel = process.argv[4];

var url = "http://weather.gc.ca/wxlink/site_js/" + weather_code + ".js"

webhookUri = "https://hooks.slack.com/services/" + slack_token;
slack = new Slack();
slack.setWebhook(webhookUri);

request(url, function(error, response, html){
    if(!error){
        eval (html);

        send_to_slack (
            "WeatherBot: Currently",
            obIconCode,
            obTemperature + "°C " + obCondition + "(" + obWindSpeed + " km/h " + obWindDir + ")",
            function (err, response) {
                display_forecast(html, 0);
            }
        );
    }
})

function display_forecast (html, i) {
    eval (html);
    var high = forecastHighs[i] != "" ? forecastHighs[i] + "°C" : "";
    var low = forecastLows[i] != "" ? forecastLows[i] + "°C" : "";

    send_to_slack (
        forecastPeriods[i],
        forecastIconCodes[i],
        " " + forecastConditions[i] + " " + high + "/" + low + "\n",
        function (err, response) {
            if (i < 2) {
                display_forecast (html, i + 1);
            }
        }
    );
}

function get_icon (icon_code) {
    return "http://weather.gc.ca/weathericons/small/" + icon_code +".png";
}

function send_to_slack (username, icon_code, text, call_back) {
    slack.webhook({
      channel: slack_channel,
      username: username,
      icon_emoji: get_icon (icon_code),
      text: text
    }, function(err, response) {
        if (err) {
            console.log (err);
        } else {
            console.log(response);
        }

        call_back(err, response);
    });
}
<commit_msg>refactor is_tempature_set<commit_after>var fs = require('fs');
var request = require('request');
var Slack = require('slack-node');

var slack_token = process.argv[2];
var weather_code = process.argv[3];
var slack_channel = process.argv[4];

var url = "http://weather.gc.ca/wxlink/site_js/" + weather_code + ".js"

webhookUri = "https://hooks.slack.com/services/" + slack_token;
slack = new Slack();
slack.setWebhook(webhookUri);

request(url, function(error, response, html){
    if(!error){
        eval (html);

        send_to_slack (
            "WeatherBot: Currently",
            obIconCode,
            obTemperature + "°C " + obCondition + "(" + obWindSpeed + " km/h " + obWindDir + ")",
            function (err, response) {
                display_forecast(html, 0);
            }
        );
    }
})

function display_forecast (html, i) {
    eval (html);
    var high = is_tempature_set (forecastHighs[i]);
    var low = is_tempature_set (forecastLows[i]);

    send_to_slack (
        forecastPeriods[i],
        forecastIconCodes[i],
        " " + forecastConditions[i] + " " + high + "/" + low + "\n",
        function (err, response) {
            if (i < 2) {
                display_forecast (html, i + 1);
            }
        }
    );
}

function is_tempature_set (temperature) {
    return temperature !== "" ? temperature + "°C" : "";
}

function get_icon (icon_code) {
    return "http://weather.gc.ca/weathericons/small/" + icon_code +".png";
}

function send_to_slack (username, icon_code, text, call_back) {
    slack.webhook({
      channel: slack_channel,
      username: username,
      icon_emoji: get_icon (icon_code),
      text: text
    }, function(err, response) {
        if (err) {
            console.log (err);
        } else {
            console.log(response);
        }

        call_back(err, response);
    });
}
<|endoftext|>


<commit_before>//***** baseline (begin) *******************************************************************************************************************
function afterLoadIpJSP() {
    //switch to different tab
    $("#tab_details").bind("click", function(event){
        $(this).removeClass("off").addClass("on");
        $("#tab_port_forwarding, #tab_load_balancer").removeClass("on").addClass("off");
        $("#tab_content_details").show();
        $("#tab_content_port_forwarding, #tab_content_load_balancer").hide();
        return false;
    });
    $("#tab_port_forwarding").bind("click", function(event){
        $(this).removeClass("off").addClass("on");
        $("#tab_details, #tab_load_balancer").removeClass("on").addClass("off");
        $("#tab_content_port_forwarding").show();
        $("#tab_content_details, #tab_content_load_balancer").hide();
        return false;
    });
    $("#tab_load_balancer").bind("click", function(event){
        $(this).removeClass("off").addClass("on");
        $("#tab_details, #tab_port_forwarding").removeClass("on").addClass("off");
        $("#tab_content_load_balancer").show();
        $("#tab_content_details, #tab_content_port_forwarding").hide();
        return false;
    });

    //Port Fowording tab
    var $createPortForwardingRow = $("#create_port_forwarding_row");

    $createPortForwardingRow.find("#add_link").bind("click", function(event){
		var isValid = true;
		isValid &= validateNumber("Public Port", $createPortForwardingRow.find("#public_port"), $createPortForwardingRow.find("#public_port_errormsg"), 1, 65535);
		isValid &= validateNumber("Private Port", $createPortForwardingRow.find("#private_port"), $createPortForwardingRow.find("#private_port_errormsg"), 1, 65535);
		if (!isValid) return;

	    var $template = $("#port_forwarding_template").clone();
	    $("#tab_content_port_forwarding #grid_container").append($template.show());

	    var $spinningWheel = $template.find("row_container").find("#spinning_wheel");
	    $spinningWheel.find("#description").text("Adding....");
        $spinningWheel.show();

	    var $detailsTab = $("#right_panel_content #tab_content_details");
        var jsonObj = $detailsTab.data("jsonObj");
		var ipAddress = jsonObj.ipaddress;
	    var publicPort = $createPortForwardingRow.find("#public_port").val();
	    var privatePort = $createPortForwardingRow.find("#private_port").val();
	    var protocol = $createPortForwardingRow.find("#protocol").val();
	    var virtualMachineId = $createPortForwardingRow.find("#vm").val();

	    var array1 = [];
        array1.push("&ipaddress="+ipAddress);
        array1.push("&privateport="+privatePort);
        array1.push("&publicport="+publicPort);
        array1.push("&protocol="+protocol);
        array1.push("&virtualmachineid=" + virtualMachineId);
        $.ajax({
	        data: createURL("command=createPortForwardingRule"+array1.join("")),
	        dataType: "json",
	        success: function(json) {
	            var items = json.createportforwardingruleresponse.portforwardingrule;
	            portForwardingJsonToTemplate(items[0],$template);
	            $spinningWheel.hide();
	            refreshCreatePortForwardingRow();
	        },
		    error: function(XMLHttpResponse) {
			    handleError(XMLHttpResponse);
			    $template.slideUp("slow", function() {
					$(this).remove();
				});
		    }
        });

	    return false;
	});

}

function ipGetMidmenuId(jsonObj) {
    return "midmenuItem_" + jsonObj.ipaddress.replace(/\./g, "_");   //e.g. "192.168.33.108" => "192_168_33_108"
}

function ipToMidmenu(jsonObj, $midmenuItem1) {
    var id = ipGetMidmenuId(jsonObj);
    $midmenuItem1.attr("id", id);
    $midmenuItem1.data("jsonObj", jsonObj);

    var $iconContainer = $midmenuItem1.find("#icon_container").show();
    $iconContainer.find("#icon").attr("src", "images/midmenuicon_network_networkgroup.png");

    $midmenuItem1.find("#first_row").text(jsonObj.ipaddress.substring(0,25));
    $midmenuItem1.find("#second_row").text(fromdb(jsonObj.account).substring(0,25));
}

function ipToRigntPanel($midmenuItem1) {
    var jsonObj = $midmenuItem1.data("jsonObj");

    //Details tab
    ipJsonToDetailsTab(jsonObj);

    //Port Forwarding tab
    listPortForwardingRules();
    refreshCreatePortForwardingRow();
}

function ipJsonToDetailsTab(jsonObj) {
    var $detailsTab = $("#right_panel_content #tab_content_details");
    $detailsTab.data("jsonObj", jsonObj);

    $detailsTab.find("#ipaddress").text(fromdb(jsonObj.ipaddress));
    $detailsTab.find("#zonename").text(fromdb(jsonObj.zonename));
    $detailsTab.find("#vlanname").text(fromdb(jsonObj.vlanname));
    setSourceNatField(jsonObj.issourcenat, $detailsTab.find("#source_nat"));
    setNetworkTypeField(jsonObj.forvirtualnetwork, $detailsTab.find("#network_type"));

    $detailsTab.find("#domain").text(fromdb(jsonObj.domain));
    $detailsTab.find("#account").text(fromdb(jsonObj.account));
    $detailsTab.find("#allocated").text(fromdb(jsonObj.allocated));
}
//***** baseline (end) *********************************************************************************************************************

//***** Details tab (begin) ****************************************************************************************************************
function setSourceNatField(value, $field) {
    if(value == "true")
        $field.text("Yes");
    else if(value == "false")
        $field.text("No");
    else
        $field.text("");
}

function setNetworkTypeField(value, $field) {
    if(value == "true")
        $field.text("Public");
    else if(value == "false")
        $field.text("Direct");
    else
        $field.text("");
}
//***** Details tab (end) ******************************************************************************************************************

//***** Port Forwarding tab (begin) ********************************************************************************************************

//var portForwardingIndex = 0;
function portForwardingJsonToTemplate(jsonObj, template) {
    //(portForwardingIndex++ % 2 == 0)? template.find("#row_container").addClass("smallrow_even"): template.find("#row_container").addClass("smallrow_odd");
    template.attr("id", "portForwarding_" + jsonObj.id).data("portForwardingId", jsonObj.id);

    template.find("#row_container #public_port").text(jsonObj.publicport);
    template.find("#row_container_edit #public_port").text(jsonObj.publicport);

    template.find("#row_container #private_port").text(jsonObj.privateport);
    template.find("#row_container_edit #private_port").val(jsonObj.privateport);

    template.find("#row_container #protocol").text(jsonObj.protocol);
    template.find("#row_container_edit #protocol").text(jsonObj.protocol);

    template.find("#row_container #vm_name").text(jsonObj.vmname);
    var virtualMachineId = jsonObj.virtualmachineid;

    var $detailsTab = $("#right_panel_content #tab_content_details");
    var jsonObj = $detailsTab.data("jsonObj");
    var IpDomainid = jsonObj.domainid;
    var IpAccount = jsonObj.account;

    $.ajax({
	   data: createURL("command=listVirtualMachines&domainid="+IpDomainid+"&account="+IpAccount+maxPageSize),
	    dataType: "json",
	    success: function(json) {
		    var instances = json.listvirtualmachinesresponse.virtualmachine;
		    var vmSelect = template.find("#row_container_edit #vm").empty();
		    if (instances != null && instances.length > 0) {
			    for (var i = 0; i < instances.length; i++) {
			        var html = $("<option value='" + instances[i].id + "'>" +  getVmName(instances[i].name, instances[i].displayname) + "</option>");
		            vmSelect.append(html);
			    }
			    vmSelect.val(virtualMachineId);
		    }
	    }
    });

   	//???
    var $rowContainer = template.find("#row_container");
    var $rowContainerEdit = template.find("#row_container_edit");

    template.find("#delete_link").unbind("click").bind("click", function(event){
        var $spinningWheel = $rowContainer.find("#spinning_wheel");
        $spinningWheel.find("#description").text("Deleting....");
        $spinningWheel.show();
        $.ajax({
	       data: createURL("command=deletePortForwardingRule&id="+jsonObj.id),
            dataType: "json",
            success: function(json) {
                template.slideUp("slow", function(){
                    $(this).remove();
                });
            },
            error: function(XMLHttpResponse) {
                handleError(XMLHttpResponse);
                $spinningWheel.hide();
            }
        });
        return false;
    });

    template.find("#edit_link").unbind("click").bind("click", function(event){
        $rowContainer.hide();
        $rowContainerEdit.show();
    });

    template.find("#cancel_link").unbind("click").bind("click", function(event){
        $rowContainer.show();
        $rowContainerEdit.hide();
    });

    template.find("#save_link").unbind("click").bind("click", function(event){
        // validate values
	    var isValid = true;
	    isValid &= validateNumber("Private Port", $rowContainerEdit.find("#private_port"), $rowContainerEdit.find("#private_port_errormsg"), 1, 65535);
	    if (!isValid) return;

        var $spinningWheel = $rowContainerEdit.find("#spinning_wheel");
        $spinningWheel.find("#description").text("Saving....");
        $spinningWheel.show();

	    var jsonObj = $("#right_panel_content #tab_content_details").data("jsonObj");
	    var ipAddress = jsonObj.ipaddress;

        var publicPort = $rowContainerEdit.find("#public_port").text();
        var privatePort = $rowContainerEdit.find("#private_port").val();
        var protocol = $rowContainerEdit.find("#protocol").text();
        var virtualMachineId = $rowContainerEdit.find("#vm").val();

        var array1 = [];
        array1.push("&publicip="+ipAddress);
        array1.push("&privateport="+privatePort);
        array1.push("&publicport="+publicPort);
        array1.push("&protocol="+protocol);
        array1.push("&virtualmachineid=" + virtualMachineId);

        $.ajax({
             data: createURL("command=updatePortForwardingRule"+array1.join("")),
			 dataType: "json",
			 success: function(json) {
				var jobId = json.updateportforwardingruleresponse.jobid;
		        var timerKey = "updateportforwardingruleJob"+jobId;

                $("body").everyTime(2000, timerKey, function() {
				    $.ajax({
					   data: createURL("command=queryAsyncJobResult&jobId="+jobId),
					    dataType: "json",
					    success: function(json) {
						    var result = json.queryasyncjobresultresponse;
						    if (result.jobstatus == 0) {
							    return; //Job has not completed
						    } else {
							    $("body").stopTime(timerKey);
							    if (result.jobstatus == 1) { // Succeeded
								    var items = result.portforwardingrule;
                                    portForwardingJsonToTemplate(items[0],template);
                                    $spinningWheel.hide();
                                    $rowContainerEdit.hide();
                                    $rowContainer.show();
							    } else if (result.jobstatus == 2) { //Fail
							        $spinningWheel.hide();
						            $("#dialog_alert").html("<p>" + sanitizeXSS(result.jobresult) + "</p>").dialog("open");
							    }
						    }
					    },
					    error: function(XMLHttpResponse) {
					        handleError(XMLHttpResponse);
						    $("body").stopTime(timerKey);
						    $spinningWheel.hide();
					    }
				    });
			    }, 0);
			 },
			 error: function(XMLHttpResponse) {
			     handleError(XMLHttpResponse);
			     $spinningWheel.hide();
			 }
		 });
    });
    //???
}

function listPortForwardingRules() {
    var jsonObj = $("#right_panel_content #tab_content_details").data("jsonObj");
	var ipAddress = jsonObj.ipaddress;
    if(ipAddress == null || ipAddress.length == 0)
        return;
    $.ajax({
        data: createURL("command=listPortForwardingRules&ipaddress=" + ipAddress),
        dataType: "json",
        success: function(json) {
            var items = json.listportforwardingrulesresponse.portforwardingrule;
            var $portForwardingGrid = $("#tab_content_port_forwarding #grid_container #grid_content");
            $portForwardingGrid.empty();
            if (items != null && items.length > 0) {
                for (var i = 0; i < items.length; i++) {
	                var $template = $("#port_forwarding_template").clone(true);
	                portForwardingJsonToTemplate(items[i], $template);
	                $portForwardingGrid.append($template.show());
                }
            }
        }
    });
}

function refreshCreatePortForwardingRow() {
    var $createPortForwardingRow = $("#create_port_forwarding_row");
    $createPortForwardingRow.find("#public_port").val("");
    $createPortForwardingRow.find("#private_port").val("");
    $createPortForwardingRow.find("#protocol").val("TCP");

    var $detailsTab = $("#right_panel_content #tab_content_details");
    var jsonObj = $detailsTab.data("jsonObj");
    var IpDomainid = jsonObj.domainid;
    var IpAccount = jsonObj.account;

    $.ajax({
	    data: createURL("command=listVirtualMachines&domainid="+IpDomainid+"&account="+IpAccount+maxPageSize),
	    dataType: "json",
	    success: function(json) {
		    var instances = json.listvirtualmachinesresponse.virtualmachine;
		    var vmSelect = $createPortForwardingRow.find("#vm").empty();
		    if (instances != null && instances.length > 0) {
			    for (var i = 0; i < instances.length; i++) {
			        var html = $("<option value='" + instances[i].id + "'>" +  getVmName(instances[i].name, instances[i].displayname) + "</option>");
		            vmSelect.append(html);
			    }
		    }
	    }
    });
}

//***** Port Forwarding tab (end) **********************************************************************************************************<commit_msg>new UI - ip address page - implement delete port forwarding rule.<commit_after>//***** baseline (begin) *******************************************************************************************************************
function afterLoadIpJSP() {
    //switch to different tab
    $("#tab_details").bind("click", function(event){
        $(this).removeClass("off").addClass("on");
        $("#tab_port_forwarding, #tab_load_balancer").removeClass("on").addClass("off");
        $("#tab_content_details").show();
        $("#tab_content_port_forwarding, #tab_content_load_balancer").hide();
        return false;
    });
    $("#tab_port_forwarding").bind("click", function(event){
        $(this).removeClass("off").addClass("on");
        $("#tab_details, #tab_load_balancer").removeClass("on").addClass("off");
        $("#tab_content_port_forwarding").show();
        $("#tab_content_details, #tab_content_load_balancer").hide();
        return false;
    });
    $("#tab_load_balancer").bind("click", function(event){
        $(this).removeClass("off").addClass("on");
        $("#tab_details, #tab_port_forwarding").removeClass("on").addClass("off");
        $("#tab_content_load_balancer").show();
        $("#tab_content_details, #tab_content_port_forwarding").hide();
        return false;
    });

    //Port Fowording tab
    var $createPortForwardingRow = $("#create_port_forwarding_row");

    $createPortForwardingRow.find("#add_link").bind("click", function(event){
		var isValid = true;
		isValid &= validateNumber("Public Port", $createPortForwardingRow.find("#public_port"), $createPortForwardingRow.find("#public_port_errormsg"), 1, 65535);
		isValid &= validateNumber("Private Port", $createPortForwardingRow.find("#private_port"), $createPortForwardingRow.find("#private_port_errormsg"), 1, 65535);
		if (!isValid) return;

	    var $template = $("#port_forwarding_template").clone();
	    $("#tab_content_port_forwarding #grid_container").append($template.show());

	    var $spinningWheel = $template.find("row_container").find("#spinning_wheel");
	    $spinningWheel.find("#description").text("Adding....");
        $spinningWheel.show();

	    var $detailsTab = $("#right_panel_content #tab_content_details");
        var jsonObj = $detailsTab.data("jsonObj");
		var ipAddress = jsonObj.ipaddress;
	    var publicPort = $createPortForwardingRow.find("#public_port").val();
	    var privatePort = $createPortForwardingRow.find("#private_port").val();
	    var protocol = $createPortForwardingRow.find("#protocol").val();
	    var virtualMachineId = $createPortForwardingRow.find("#vm").val();

	    var array1 = [];
        array1.push("&ipaddress="+ipAddress);
        array1.push("&privateport="+privatePort);
        array1.push("&publicport="+publicPort);
        array1.push("&protocol="+protocol);
        array1.push("&virtualmachineid=" + virtualMachineId);
        $.ajax({
	        data: createURL("command=createPortForwardingRule"+array1.join("")),
	        dataType: "json",
	        success: function(json) {
	            var items = json.createportforwardingruleresponse.portforwardingrule;
	            portForwardingJsonToTemplate(items[0],$template);
	            $spinningWheel.hide();
	            refreshCreatePortForwardingRow();
	        },
		    error: function(XMLHttpResponse) {
			    handleError(XMLHttpResponse);
			    $template.slideUp("slow", function() {
					$(this).remove();
				});
		    }
        });

	    return false;
	});

}

function ipGetMidmenuId(jsonObj) {
    return "midmenuItem_" + jsonObj.ipaddress.replace(/\./g, "_");   //e.g. "192.168.33.108" => "192_168_33_108"
}

function ipToMidmenu(jsonObj, $midmenuItem1) {
    var id = ipGetMidmenuId(jsonObj);
    $midmenuItem1.attr("id", id);
    $midmenuItem1.data("jsonObj", jsonObj);

    var $iconContainer = $midmenuItem1.find("#icon_container").show();
    $iconContainer.find("#icon").attr("src", "images/midmenuicon_network_networkgroup.png");

    $midmenuItem1.find("#first_row").text(jsonObj.ipaddress.substring(0,25));
    $midmenuItem1.find("#second_row").text(fromdb(jsonObj.account).substring(0,25));
}

function ipToRigntPanel($midmenuItem1) {
    var jsonObj = $midmenuItem1.data("jsonObj");

    //Details tab
    ipJsonToDetailsTab(jsonObj);

    //Port Forwarding tab
    listPortForwardingRules();
    refreshCreatePortForwardingRow();
}

function ipJsonToDetailsTab(jsonObj) {
    var $detailsTab = $("#right_panel_content #tab_content_details");
    $detailsTab.data("jsonObj", jsonObj);

    $detailsTab.find("#ipaddress").text(fromdb(jsonObj.ipaddress));
    $detailsTab.find("#zonename").text(fromdb(jsonObj.zonename));
    $detailsTab.find("#vlanname").text(fromdb(jsonObj.vlanname));
    setSourceNatField(jsonObj.issourcenat, $detailsTab.find("#source_nat"));
    setNetworkTypeField(jsonObj.forvirtualnetwork, $detailsTab.find("#network_type"));

    $detailsTab.find("#domain").text(fromdb(jsonObj.domain));
    $detailsTab.find("#account").text(fromdb(jsonObj.account));
    $detailsTab.find("#allocated").text(fromdb(jsonObj.allocated));
}
//***** baseline (end) *********************************************************************************************************************

//***** Details tab (begin) ****************************************************************************************************************
function setSourceNatField(value, $field) {
    if(value == "true")
        $field.text("Yes");
    else if(value == "false")
        $field.text("No");
    else
        $field.text("");
}

function setNetworkTypeField(value, $field) {
    if(value == "true")
        $field.text("Public");
    else if(value == "false")
        $field.text("Direct");
    else
        $field.text("");
}
//***** Details tab (end) ******************************************************************************************************************

//***** Port Forwarding tab (begin) ********************************************************************************************************

//var portForwardingIndex = 0;
function portForwardingJsonToTemplate(jsonObj, template) {
    //(portForwardingIndex++ % 2 == 0)? template.find("#row_container").addClass("smallrow_even"): template.find("#row_container").addClass("smallrow_odd");
    template.attr("id", "portForwarding_" + jsonObj.id).data("portForwardingId", jsonObj.id);

    template.find("#row_container #public_port").text(jsonObj.publicport);
    template.find("#row_container_edit #public_port").text(jsonObj.publicport);

    template.find("#row_container #private_port").text(jsonObj.privateport);
    template.find("#row_container_edit #private_port").val(jsonObj.privateport);

    template.find("#row_container #protocol").text(jsonObj.protocol);
    template.find("#row_container_edit #protocol").text(jsonObj.protocol);

    template.find("#row_container #vm_name").text(jsonObj.vmname);
    var virtualMachineId = jsonObj.virtualmachineid;

    var $detailsTab = $("#right_panel_content #tab_content_details");
    var ipObj = $detailsTab.data("jsonObj");
    var ipAddress = jsonObj.ipaddress;
    var IpDomainid = ipObj.domainid;
    var IpAccount = ipObj.account;

    $.ajax({
	   data: createURL("command=listVirtualMachines&domainid="+IpDomainid+"&account="+IpAccount+maxPageSize),
	    dataType: "json",
	    success: function(json) {
		    var instances = json.listvirtualmachinesresponse.virtualmachine;
		    var vmSelect = template.find("#row_container_edit #vm").empty();
		    if (instances != null && instances.length > 0) {
			    for (var i = 0; i < instances.length; i++) {
			        var html = $("<option value='" + instances[i].id + "'>" +  getVmName(instances[i].name, instances[i].displayname) + "</option>");
		            vmSelect.append(html);
			    }
			    vmSelect.val(virtualMachineId);
		    }
	    }
    });

    var $rowContainer = template.find("#row_container");
    var $rowContainerEdit = template.find("#row_container_edit");

    template.find("#delete_link").unbind("click").bind("click", function(event){
        var $spinningWheel = $rowContainer.find("#spinning_wheel");
        $spinningWheel.find("#description").text("Deleting....");
        $spinningWheel.show();
        $.ajax({
	       data: createURL("command=deletePortForwardingRule&id="+jsonObj.id),
            dataType: "json",
            success: function(json) {
                template.slideUp("slow", function(){
                    $(this).remove();
                });
            },
            error: function(XMLHttpResponse) {
                handleError(XMLHttpResponse);
                $spinningWheel.hide();
            }
        });
        return false;
    });

    template.find("#edit_link").unbind("click").bind("click", function(event){
        $rowContainer.hide();
        $rowContainerEdit.show();
    });

    template.find("#cancel_link").unbind("click").bind("click", function(event){
        $rowContainer.show();
        $rowContainerEdit.hide();
    });

    template.find("#save_link").unbind("click").bind("click", function(event){
        // validate values
	    var isValid = true;
	    isValid &= validateNumber("Private Port", $rowContainerEdit.find("#private_port"), $rowContainerEdit.find("#private_port_errormsg"), 1, 65535);
	    if (!isValid) return;

        var $spinningWheel = $rowContainerEdit.find("#spinning_wheel");
        $spinningWheel.find("#description").text("Saving....");
        $spinningWheel.show();

        var publicPort = $rowContainerEdit.find("#public_port").text();
        var privatePort = $rowContainerEdit.find("#private_port").val();
        var protocol = $rowContainerEdit.find("#protocol").text();
        var virtualMachineId = $rowContainerEdit.find("#vm").val();

        var array1 = [];
        array1.push("&publicip="+ipAddress);
        array1.push("&privateport="+privatePort);
        array1.push("&publicport="+publicPort);
        array1.push("&protocol="+protocol);
        array1.push("&virtualmachineid=" + virtualMachineId);

        $.ajax({
             data: createURL("command=updatePortForwardingRule"+array1.join("")),
			 dataType: "json",
			 success: function(json) {
				var jobId = json.updateportforwardingruleresponse.jobid;
		        var timerKey = "updateportforwardingruleJob"+jobId;

                $("body").everyTime(2000, timerKey, function() {
				    $.ajax({
					   data: createURL("command=queryAsyncJobResult&jobId="+jobId),
					    dataType: "json",
					    success: function(json) {
						    var result = json.queryasyncjobresultresponse;
						    if (result.jobstatus == 0) {
							    return; //Job has not completed
						    } else {
							    $("body").stopTime(timerKey);
							    if (result.jobstatus == 1) { // Succeeded
								    var items = result.portforwardingrule;
                                    portForwardingJsonToTemplate(items[0],template);
                                    $spinningWheel.hide();
                                    $rowContainerEdit.hide();
                                    $rowContainer.show();
							    } else if (result.jobstatus == 2) { //Fail
							        $spinningWheel.hide();
						            $("#dialog_alert").html("<p>" + sanitizeXSS(result.jobresult) + "</p>").dialog("open");
							    }
						    }
					    },
					    error: function(XMLHttpResponse) {
					        handleError(XMLHttpResponse);
						    $("body").stopTime(timerKey);
						    $spinningWheel.hide();
					    }
				    });
			    }, 0);
			 },
			 error: function(XMLHttpResponse) {
			     handleError(XMLHttpResponse);
			     $spinningWheel.hide();
			 }
		 });
    });
}

function listPortForwardingRules() {
    var jsonObj = $("#right_panel_content #tab_content_details").data("jsonObj");
	var ipAddress = jsonObj.ipaddress;
    if(ipAddress == null || ipAddress.length == 0)
        return;
    $.ajax({
        data: createURL("command=listPortForwardingRules&ipaddress=" + ipAddress),
        dataType: "json",
        success: function(json) {
            var items = json.listportforwardingrulesresponse.portforwardingrule;
            var $portForwardingGrid = $("#tab_content_port_forwarding #grid_container #grid_content");
            $portForwardingGrid.empty();
            if (items != null && items.length > 0) {
                for (var i = 0; i < items.length; i++) {
	                var $template = $("#port_forwarding_template").clone(true);
	                portForwardingJsonToTemplate(items[i], $template);
	                $portForwardingGrid.append($template.show());
                }
            }
        }
    });
}

function refreshCreatePortForwardingRow() {
    var $createPortForwardingRow = $("#create_port_forwarding_row");
    $createPortForwardingRow.find("#public_port").val("");
    $createPortForwardingRow.find("#private_port").val("");
    $createPortForwardingRow.find("#protocol").val("TCP");

    var $detailsTab = $("#right_panel_content #tab_content_details");
    var jsonObj = $detailsTab.data("jsonObj");
    var IpDomainid = jsonObj.domainid;
    var IpAccount = jsonObj.account;

    $.ajax({
	    data: createURL("command=listVirtualMachines&domainid="+IpDomainid+"&account="+IpAccount+maxPageSize),
	    dataType: "json",
	    success: function(json) {
		    var instances = json.listvirtualmachinesresponse.virtualmachine;
		    var vmSelect = $createPortForwardingRow.find("#vm").empty();
		    if (instances != null && instances.length > 0) {
			    for (var i = 0; i < instances.length; i++) {
			        var html = $("<option value='" + instances[i].id + "'>" +  getVmName(instances[i].name, instances[i].displayname) + "</option>");
		            vmSelect.append(html);
			    }
		    }
	    }
    });
}

//***** Port Forwarding tab (end) **********************************************************************************************************<|endoftext|>


<commit_before>/*
 * Copyright © 2016-2020 The Thingsboard Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* eslint-disable import/no-unresolved, import/default */

import eventErrorDialogTemplate from './event-content-dialog.tpl.html';

import eventRowLcEventTemplate from './event-row-lc-event.tpl.html';
import eventRowStatsTemplate from './event-row-stats.tpl.html';
import eventRowErrorTemplate from './event-row-error.tpl.html';
import eventRowDebugRuleNodeTemplate from './event-row-debug-rulenode.tpl.html';
import eventRowEdgeEventTemplate from './event-row-edge-event.tpl.html';

/* eslint-enable import/no-unresolved, import/default */

/*@ngInject*/
export default function EventRowDirective($compile, $templateCache, $mdDialog, $document, $translate,
                                          types, utils, toast, entityService, ruleChainService) {

    var linker = function (scope, element, attrs) {

        var getTemplate = function(eventType) {
            var template = '';
            switch(eventType) {
                case types.eventType.lcEvent.value:
                    template = eventRowLcEventTemplate;
                    break;
                case types.eventType.stats.value:
                    template = eventRowStatsTemplate;
                    break;
                case types.eventType.error.value:
                    template = eventRowErrorTemplate;
                    break;
                case types.debugEventType.debugRuleNode.value:
                    template = eventRowDebugRuleNodeTemplate;
                    break;
                case types.debugEventType.debugRuleChain.value:
                    template = eventRowDebugRuleNodeTemplate;
                    break;
                case types.eventType.edgeEvent.value:
                    template = eventRowEdgeEventTemplate;
                    break;
            }
            return $templateCache.get(template);
        }

        scope.loadTemplate = function() {
            element.html(getTemplate(attrs.eventType));
            $compile(element.contents())(scope);
        }

        attrs.$observe('eventType', function() {
            scope.loadTemplate();
        });

        scope.types = types;

        scope.event = attrs.event;

        scope.showContent = function($event, content, title, contentType) {
            var onShowingCallback = {
                onShowing: function(){}
            }
            if (!contentType) {
                contentType = null;
            }
            var sortedContent;
            try {
                sortedContent = angular.toJson(utils.sortObjectKeys(angular.fromJson(content)));
            }
            catch(err) {
                sortedContent = content;
            }
            $mdDialog.show({
                controller: 'EventContentDialogController',
                controllerAs: 'vm',
                templateUrl: eventErrorDialogTemplate,
                locals: {content: sortedContent, title: title, contentType: contentType, showingCallback: onShowingCallback},
                parent: angular.element($document[0].body),
                fullscreen: true,
                targetEvent: $event,
                multiple: true,
                onShowing: function(scope, element) {
                    onShowingCallback.onShowing(scope, element);
                }
            });
        }

        scope.showEdgeEntityContent = function($event, title, contentType) {
            var onShowingCallback = {
                onShowing: function(){}
            }
            if (!contentType) {
                contentType = null;
            }
            var content = '';
            switch(scope.event.type) {
                case types.edgeEventType.relation:
                    content = angular.toJson(scope.event.body);
                    showDialog();
                    break;
                case types.edgeEventType.ruleChainMetaData:
                    content = ruleChainService.getRuleChainMetaData(scope.event.entityId, {ignoreErrors: true}).then(
                        function success(info) {
                            showDialog();
                            return angular.toJson(info);
                        }, function fail() {
                            showError();
                        });
                    break;
                default:
                    content = entityService.getEntity(scope.event.type, scope.event.entityId, {ignoreErrors: true}).then(
                        function success(info) {
                            showDialog();
                            return angular.toJson(info);
                        }, function fail() {
                            showError();
                        });
                    break;
            }
            function showDialog() {
                $mdDialog.show({
                    controller: 'EventContentDialogController',
                    controllerAs: 'vm',
                    templateUrl: eventErrorDialogTemplate,
                    locals: {content: content, title: title, contentType: contentType, showingCallback: onShowingCallback},
                    parent: angular.element($document[0].body),
                    fullscreen: true,
                    targetEvent: $event,
                    multiple: true,
                    onShowing: function(scope, element) {
                        onShowingCallback.onShowing(scope, element);
                    }
                });
            }
            function showError() {
                toast.showError($translate.instant('edge.load-entity-error'));
            }
        }

        scope.checkEdgeEventType = function (edgeEventType) {
            return !(edgeEventType === types.edgeEventType.widgetType ||
                edgeEventType === types.edgeEventType.adminSettings ||
                edgeEventType === types.edgeEventType.widgetsBundle );
        }

        scope.checkTooltip = function($event) {
            var el = $event.target;
            var $el = angular.element(el);
            if(el.offsetWidth < el.scrollWidth && !$el.attr('title')){
                $el.attr('title', $el.text());
            }
        }

        $compile(element.contents())(scope);

        scope.updateStatus = function(eventCreatedTime) {
            if (scope.queueStartTs) {
                var status;
                if (eventCreatedTime < scope.queueStartTs) {
                    status = $translate.instant('edge.success');
                    scope.isPending = false;
                } else {
                    status = $translate.instant('edge.failed');
                    scope.isPending = true;
                }
                return status;
            }
        }
    }

    return {
        restrict: "A",
        replace: false,
        link: linker,
        scope: false
    };
}
<commit_msg>Edge events refactored<commit_after>/*
 * Copyright © 2016-2020 The Thingsboard Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* eslint-disable import/no-unresolved, import/default */

import eventErrorDialogTemplate from './event-content-dialog.tpl.html';

import eventRowLcEventTemplate from './event-row-lc-event.tpl.html';
import eventRowStatsTemplate from './event-row-stats.tpl.html';
import eventRowErrorTemplate from './event-row-error.tpl.html';
import eventRowDebugRuleNodeTemplate from './event-row-debug-rulenode.tpl.html';
import eventRowEdgeEventTemplate from './event-row-edge-event.tpl.html';

/* eslint-enable import/no-unresolved, import/default */

/*@ngInject*/
export default function EventRowDirective($compile, $templateCache, $mdDialog, $document, $translate,
                                          types, utils, toast, entityService, ruleChainService) {

    var linker = function (scope, element, attrs) {

        var getTemplate = function(eventType) {
            var template = '';
            switch(eventType) {
                case types.eventType.lcEvent.value:
                    template = eventRowLcEventTemplate;
                    break;
                case types.eventType.stats.value:
                    template = eventRowStatsTemplate;
                    break;
                case types.eventType.error.value:
                    template = eventRowErrorTemplate;
                    break;
                case types.debugEventType.debugRuleNode.value:
                    template = eventRowDebugRuleNodeTemplate;
                    break;
                case types.debugEventType.debugRuleChain.value:
                    template = eventRowDebugRuleNodeTemplate;
                    break;
                case types.eventType.edgeEvent.value:
                    template = eventRowEdgeEventTemplate;
                    break;
            }
            return $templateCache.get(template);
        }

        scope.loadTemplate = function() {
            element.html(getTemplate(attrs.eventType));
            $compile(element.contents())(scope);
        }

        attrs.$observe('eventType', function() {
            scope.loadTemplate();
        });

        scope.types = types;

        scope.event = attrs.event;

        scope.showContent = function($event, content, title, contentType) {
            var onShowingCallback = {
                onShowing: function(){}
            }
            if (!contentType) {
                contentType = null;
            }
            var sortedContent;
            try {
                sortedContent = angular.toJson(utils.sortObjectKeys(angular.fromJson(content)));
            }
            catch(err) {
                sortedContent = content;
            }
            $mdDialog.show({
                controller: 'EventContentDialogController',
                controllerAs: 'vm',
                templateUrl: eventErrorDialogTemplate,
                locals: {content: sortedContent, title: title, contentType: contentType, showingCallback: onShowingCallback},
                parent: angular.element($document[0].body),
                fullscreen: true,
                targetEvent: $event,
                multiple: true,
                onShowing: function(scope, element) {
                    onShowingCallback.onShowing(scope, element);
                }
            });
        }

        scope.showEdgeEntityContent = function($event, title, contentType) {
            var onShowingCallback = {
                onShowing: function(){}
            }
            if (!contentType) {
                contentType = null;
            }
            var content = '';
            switch(scope.event.type) {
                case types.edgeEventType.relation:
                    content = angular.toJson(scope.event.body);
                    showDialog();
                    break;
                case types.edgeEventType.ruleChainMetaData:
                    content = ruleChainService.getRuleChainMetaData(scope.event.entityId, {ignoreErrors: true}).then(
                        function success(info) {
                            showDialog();
                            return angular.toJson(info);
                        }, function fail() {
                            showError();
                        });
                    break;
                default:
                    content = entityService.getEntity(scope.event.type, scope.event.entityId, {ignoreErrors: true}).then(
                        function success(info) {
                            showDialog();
                            return angular.toJson(info);
                        }, function fail() {
                            showError();
                        });
                    break;
            }
            function showDialog() {
                $mdDialog.show({
                    controller: 'EventContentDialogController',
                    controllerAs: 'vm',
                    templateUrl: eventErrorDialogTemplate,
                    locals: {content: content, title: title, contentType: contentType, showingCallback: onShowingCallback},
                    parent: angular.element($document[0].body),
                    fullscreen: true,
                    targetEvent: $event,
                    multiple: true,
                    onShowing: function(scope, element) {
                        onShowingCallback.onShowing(scope, element);
                    }
                });
            }
            function showError() {
                toast.showError($translate.instant('edge.load-entity-error'));
            }
        }

        scope.checkEdgeEventType = function (type) {
            return !(type === types.edgeEventType.widgetType ||
                type === types.edgeEventType.adminSettings ||
                type === types.edgeEventType.widgetsBundle );
        }

        scope.checkTooltip = function($event) {
            var el = $event.target;
            var $el = angular.element(el);
            if(el.offsetWidth < el.scrollWidth && !$el.attr('title')){
                $el.attr('title', $el.text());
            }
        }

        $compile(element.contents())(scope);

        scope.updateStatus = function(eventCreatedTime) {
            if (scope.queueStartTs) {
                var status;
                if (eventCreatedTime < scope.queueStartTs) {
                    status = $translate.instant('edge.success');
                    scope.isPending = false;
                } else {
                    status = $translate.instant('edge.failed');
                    scope.isPending = true;
                }
                return status;
            }
        }
    }

    return {
        restrict: "A",
        replace: false,
        link: linker,
        scope: false
    };
}
<|endoftext|>