<commit_before>
var url = require('url');
var util = require('util');

var stitcher = require('../../bin/TsStitcher.node');
require('../adIntegration/KalturaAdIntegrationHandler');

var kaltura = module.exports = require('../KalturaManager');

/**
 * @service media
 */
var KalturaMediaManager = function(){
};
util.inherits(KalturaMediaManager, kaltura.KalturaManager);

KalturaMediaManager.TS_PACKET_LENGTH = 188;
KalturaMediaManager.FILE_CHUNK_SIZE = 2500 * KalturaMediaManager.TS_PACKET_LENGTH;

KalturaMediaManager.PBA_CALL_AGAIN = 0;
KalturaMediaManager.PBA_GET_NEXT_CHUNK = 1;
KalturaMediaManager.PBA_CLONE_CURRENT_CHUNK = 2;

KalturaMediaManager.ALIGN_LEFT = 0;
KalturaMediaManager.ALIGN_MIDDLE =	1;
KalturaMediaManager.ALIGN_RIGHT = 	2;

KalturaMediaManager.CHUNK_TYPE_INVALID  =	-1;
KalturaMediaManager.CHUNK_TYPE_TS_HEADER = 0;
KalturaMediaManager.CHUNK_TYPE_PRE_AD = 	 1;
KalturaMediaManager.CHUNK_TYPE_POST_AD = 	 2;

KalturaMediaManager.CHUNK_TYPE_AD = 		 5;
KalturaMediaManager.CHUNK_TYPE_BLACK = 	 4;

KalturaMediaManager.prototype.outputStitchedSegment = function(outputLayout, outputState, curChunk, preAdKey, adKeys, blackKey, postAdKey, response) {
	if (!curChunk) {
		// not much to do about this since we already returned the response headers
		response.log('failed to get chunk from memcache');
		response.end();
		return;
	}

	do {
		var processResult = stitcher.processChunk(
			outputLayout,
			curChunk,
			outputState);

		if (processResult.chunkOutputEnd > 0) {
			response.log('Writing ' + processResult.chunkOutputStart + '..' + processResult.chunkOutputEnd);
			var curSlice = curChunk.slice(processResult.chunkOutputStart, processResult.chunkOutputEnd);
			response.write(curSlice);
		}

		if (processResult.outputBuffer) {
			response.log('Writing extra buffer of size ' + processResult.outputBuffer.length);
			response.write(processResult.outputBuffer);
		}

		if (processResult.action == KalturaMediaManager.PBA_CLONE_CURRENT_CHUNK)
		{
			response.log('Cloning chunk buffer');
			chunkClone = new Buffer(curChunk.length);
			curChunk.copy(chunkClone);
			curChunk = chunkClone;
		}
	} while (processResult.action != KalturaMediaManager.PBA_GET_NEXT_CHUNK);

	curChunk = null;		// no longer need the chunk

	var chunkIndex = Math.floor(outputState.chunkStartOffset / KalturaMediaManager.FILE_CHUNK_SIZE);
	var videoKey = null;

	switch (outputState.chunkType) {
	case KalturaMediaManager.CHUNK_TYPE_PRE_AD:
		videoKey = preAdKey + '-' + chunkIndex;
		break;
	case KalturaMediaManager.CHUNK_TYPE_BLACK:
		videoKey = blackKey + '-' + chunkIndex;
		break;
	case KalturaMediaManager.CHUNK_TYPE_POST_AD:
		videoKey = postAdKey + '-' + chunkIndex;
		break;
	case KalturaMediaManager.CHUNK_TYPE_TS_HEADER:
		videoKey = preAdKey + '-header';
		break;
	default:
		for(var i=0; i<adKeys.length; i++){
			if(KalturaMediaManager.CHUNK_TYPE_AD + i == outputState.chunkType){
				videoKey = adKeys[i] + '-' + chunkIndex;
				break;
			}
		}
		if(!videoKey){
			response.log('Request completed');
			response.end();
			return;
		}
	}

	response.log('Getting ' + videoKey);
	var This = this;
	KalturaCache.getBinary(videoKey, function (curChunk) {
		outputState.chunkStartOffset = chunkIndex * KalturaMediaManager.FILE_CHUNK_SIZE;
		This.outputStitchedSegment(outputLayout, outputState, curChunk, preAdKey, adKeys, blackKey, postAdKey, response);
	});
};

KalturaMediaManager.prototype.get = function(request, response, params){
	// TODO verify the call is from the CDN
	if (!params.e) {
		response.dir(params);
		response.error('Missing arguments [e]');
		this.errorMissingParameter(response);
		return;
	}

	params = this.decrypt(params);
	this.serve(request, response, params.serverAdId, params.cuePointId, params.renditionId, params.encodingId, parseInt(params.segmentIndex), parseInt(params.outputStart), parseInt(params.outputEnd));
};

KalturaMediaManager.prototype.serve = function(request, response, serverAdId, cuePointId, renditionId, encodingId, segmentIndex, outputStart, outputEnd){
	var This = this;

	var preSegmentId = KalturaCache.getPreSegmentId(cuePointId, renditionId);
	var postSegmentId = KalturaCache.getPostSegmentId(cuePointId, renditionId);
	var preAdMetadataKey = KalturaCache.getSegmentMediaMetadata(preSegmentId);
	var blackMetadataKey = KalturaCache.getBlackMediaMetadata(encodingId);
	var postAdMetadataKey = KalturaCache.getSegmentMediaMetadata(postSegmentId);
	var adMetadataKeys = [];
	serverAdId = JSON.parse(serverAdId);
	var adKeys = [];
	for(var i=0; i<serverAdId.length; i++){
		adMetadataKeys.push(KalturaCache.getAdMediaMetadata(serverAdId[i].id));
		adKeys.push(KalturaCache.getAdMedia(serverAdId[i].id));
	}

	var cacheKeys = adMetadataKeys.concat([preAdMetadataKey, blackMetadataKey, postAdMetadataKey]);
	KalturaCache.getMultiBinary(cacheKeys, function(data){
		preAdMetadata = data[preAdMetadataKey];
		blackMetadata = data[blackMetadataKey];
		postAdMetadata = data[postAdMetadataKey];

		adsMetadata = [];
		for(var i=0; i<adMetadataKeys.length; i++){
			if(data[adMetadataKeys[i]]){
				var adMetadata =
				{
					adChunkType: KalturaMediaManager.CHUNK_TYPE_AD + i,
					ad: data[adMetadataKeys[i]],
					fillerChunkType: KalturaMediaManager.CHUNK_TYPE_BLACK,
					filler: blackMetadata,
					startPos: serverAdId[i].startPos,
					endPos: serverAdId[i].endPos,
					alignment: KalturaMediaManager.ALIGN_LEFT
				};
				adsMetadata.push(adMetadata);
				response.log('Added ad metadata: adChunkType [' + adMetadata.adChunkType + '], startPos [' + serverAdId[i].startPos + '] endPos [' + serverAdId[i].endPos + ']');
			}
			else{
				delete adKeys[i];
			}
		}

		if (!preAdMetadata){
			response.log('Pre-Ad metadata is null');
		}
		else{
			response.log('Pre-Ad metadata length ' + preAdMetadata.length);
		}

		if (!adsMetadata.length){
			response.log('Ad metadata is null');
			//set black ad as a dummy ad metadata
			var adMetadata =
			{
				adChunkType: KalturaMediaManager.CHUNK_TYPE_BLACK,
				ad: blackMetadata,
				fillerChunkType: KalturaMediaManager.CHUNK_TYPE_BLACK,
				filler: blackMetadata,
				startPos: 0,
				endPos: 0,
				alignment: KalturaMediaManager.ALIGN_LEFT
			};
			adsMetadata.push(adMetadata);
		}
		else{
			response.log('Ad metadata length ' + adsMetadata.length);
		}

		// build the layout of the output TS
		var outputLayout = stitcher.buildLayout(
				preAdMetadata,
				postAdMetadata,
				adsMetadata,
				segmentIndex,
				outputStart,
				outputEnd);

		// free the metadata buffers, we don't need them anymore
		preAdMetadata = null;
		adsMetadata = null;
		blackMetadata = null;
		postAdMetadata = null;

		var preAdKey = KalturaCache.getSegmentMedia(preSegmentId);
		var blackKey = KalturaCache.getBlackMedia(encodingId);
		var postAdKey = KalturaCache.getSegmentMedia(postSegmentId);

		// output the TS
		response.writeHead(200, {
			'Content-Type': 'video/MP2T',
			'Cache-Control': KalturaConfig.config.media.cdnCacheScope + ', max-age=' + KalturaConfig.config.media.cdnMaxAge + ', max-stale=0'
			});

		This.outputStitchedSegment(outputLayout, {}, new Buffer(0), preAdKey, adKeys, blackKey, postAdKey, response);
	});
};

/**
 * Returns the segment media from cache
 *
 * @action media.segment
 */
KalturaMediaManager.prototype.segment = function(request, response, params){
	var This = this;
	if (!params.e) {
		response.dir(params);
		response.error('Missing arguments [e]');
		this.errorMissingParameter(response);
		return;
	}

	params = this.decrypt(params);
	response.dir(params);

	var requiredParams = [
		'cuePointId',
		'renditionId',
		'encodingId',
		'segmentIndex',
		'outputStart',
		'outputEnd',
		'sessionId',
		'adStart',
		'originalUrl'
	];

	var missingParams = this.getMissingParams(params, requiredParams);
	if(missingParams.length){
		response.error('Missing arguments [' + missingParams.join(', ') + ']');
		this.errorMissingParameter(response);
		return;
	}

	var serverAdIdKey = KalturaCache.getServerAdId(params.cuePointId, params.encodingId, params.sessionId);

	KalturaCache.get(serverAdIdKey, function(serverAdIds){
		if(!serverAdIds){
			response.log('No ad found, redirecting to original ts');
			response.writeHead(302, {'Location' : params.originalUrl});
			response.end();
		}
		else{
			var outputStart = parseInt(params.outputStart);
			var outputEnd = parseInt(params.outputEnd);
			var adStart = parseInt(params.adStart);
			var serverAdId = [];
			var adsSequence = [];
			var currentAdsIdx = [];
			var sequenceDuration = adStart;
			var startSequenceIndex = 0;
			var startPos = adStart;
			var endPos = adStart;
			for(var i = 0; i<= serverAdIds.length; i++){
				if(!serverAdIds[i]){
					continue;
				}
				if(sequenceDuration + serverAdIds[i].duration <= outputStart){
					sequenceDuration += serverAdIds[i].duration;
					startSequenceIndex = i;
				}
				startPos = endPos;
				endPos += serverAdIds[i].duration;
				adsSequence.push({id:serverAdIds[i].id, startPos:startPos, endPos:endPos, sequence:i});
			}

			for(var j = startSequenceIndex; adsSequence[j] && (adsSequence[j].startPos <= outputEnd || !outputEnd); j++){
				currentAdsIdx.push(adsSequence[j].sequence);
				serverAdId.push({id:adsSequence[j].id, startPos:adsSequence[j].startPos, endPos:adsSequence[j].endPos});
			}

			response.log('Handling server ad Ids: ' + JSON.stringify(serverAdId));
			params.serverAdId = JSON.stringify(serverAdId);

			var trackingKey = KalturaCache.getAdTrackingId(params.cuePointId, params.sessionId);
			KalturaAdIntegrationHandler.sendBeacon(trackingKey, currentAdsIdx, sequenceDuration, outputStart, outputEnd, adStart);

			delete params.sessionId;
			response.dir(params);

			var redirectUrl = This.getPlayServerUrl('media', 'get', params.partnerId, null, params);
			response.writeHead(302, {'Location' : redirectUrl});
			response.end();
		}

	}, function(err){
		response.log('No ad found, redirecting to original ts');
		response.writeHead(302, {'Location' : params.originalUrl});
		response.end();
	});
};

module.exports.KalturaMediaManager = KalturaMediaManager;
<commit_msg>Print out params when getting media<commit_after>
var url = require('url');
var util = require('util');

var stitcher = require('../../bin/TsStitcher.node');
require('../adIntegration/KalturaAdIntegrationHandler');

var kaltura = module.exports = require('../KalturaManager');

/**
 * @service media
 */
var KalturaMediaManager = function(){
};
util.inherits(KalturaMediaManager, kaltura.KalturaManager);

KalturaMediaManager.TS_PACKET_LENGTH = 188;
KalturaMediaManager.FILE_CHUNK_SIZE = 2500 * KalturaMediaManager.TS_PACKET_LENGTH;

KalturaMediaManager.PBA_CALL_AGAIN = 0;
KalturaMediaManager.PBA_GET_NEXT_CHUNK = 1;
KalturaMediaManager.PBA_CLONE_CURRENT_CHUNK = 2;

KalturaMediaManager.ALIGN_LEFT = 0;
KalturaMediaManager.ALIGN_MIDDLE =	1;
KalturaMediaManager.ALIGN_RIGHT = 	2;

KalturaMediaManager.CHUNK_TYPE_INVALID  =	-1;
KalturaMediaManager.CHUNK_TYPE_TS_HEADER = 0;
KalturaMediaManager.CHUNK_TYPE_PRE_AD = 	 1;
KalturaMediaManager.CHUNK_TYPE_POST_AD = 	 2;

KalturaMediaManager.CHUNK_TYPE_AD = 		 5;
KalturaMediaManager.CHUNK_TYPE_BLACK = 	 4;

KalturaMediaManager.prototype.outputStitchedSegment = function(outputLayout, outputState, curChunk, preAdKey, adKeys, blackKey, postAdKey, response) {
	if (!curChunk) {
		// not much to do about this since we already returned the response headers
		response.log('failed to get chunk from memcache');
		response.end();
		return;
	}

	do {
		var processResult = stitcher.processChunk(
			outputLayout,
			curChunk,
			outputState);

		if (processResult.chunkOutputEnd > 0) {
			response.log('Writing ' + processResult.chunkOutputStart + '..' + processResult.chunkOutputEnd);
			var curSlice = curChunk.slice(processResult.chunkOutputStart, processResult.chunkOutputEnd);
			response.write(curSlice);
		}

		if (processResult.outputBuffer) {
			response.log('Writing extra buffer of size ' + processResult.outputBuffer.length);
			response.write(processResult.outputBuffer);
		}

		if (processResult.action == KalturaMediaManager.PBA_CLONE_CURRENT_CHUNK)
		{
			response.log('Cloning chunk buffer');
			chunkClone = new Buffer(curChunk.length);
			curChunk.copy(chunkClone);
			curChunk = chunkClone;
		}
	} while (processResult.action != KalturaMediaManager.PBA_GET_NEXT_CHUNK);

	curChunk = null;		// no longer need the chunk

	var chunkIndex = Math.floor(outputState.chunkStartOffset / KalturaMediaManager.FILE_CHUNK_SIZE);
	var videoKey = null;

	switch (outputState.chunkType) {
	case KalturaMediaManager.CHUNK_TYPE_PRE_AD:
		videoKey = preAdKey + '-' + chunkIndex;
		break;
	case KalturaMediaManager.CHUNK_TYPE_BLACK:
		videoKey = blackKey + '-' + chunkIndex;
		break;
	case KalturaMediaManager.CHUNK_TYPE_POST_AD:
		videoKey = postAdKey + '-' + chunkIndex;
		break;
	case KalturaMediaManager.CHUNK_TYPE_TS_HEADER:
		videoKey = preAdKey + '-header';
		break;
	default:
		for(var i=0; i<adKeys.length; i++){
			if(KalturaMediaManager.CHUNK_TYPE_AD + i == outputState.chunkType){
				videoKey = adKeys[i] + '-' + chunkIndex;
				break;
			}
		}
		if(!videoKey){
			response.log('Request completed');
			response.end();
			return;
		}
	}

	response.log('Getting ' + videoKey);
	var This = this;
	KalturaCache.getBinary(videoKey, function (curChunk) {
		outputState.chunkStartOffset = chunkIndex * KalturaMediaManager.FILE_CHUNK_SIZE;
		This.outputStitchedSegment(outputLayout, outputState, curChunk, preAdKey, adKeys, blackKey, postAdKey, response);
	});
};

KalturaMediaManager.prototype.get = function(request, response, params){
	// TODO verify the call is from the CDN
	if (!params.e) {
		response.dir(params);
		response.error('Missing arguments [e]');
		this.errorMissingParameter(response);
		return;
	}

	params = this.decrypt(params);
	response.dir(params);
	this.serve(request, response, params.serverAdId, params.cuePointId, params.renditionId, params.encodingId, parseInt(params.segmentIndex), parseInt(params.outputStart), parseInt(params.outputEnd));
};

KalturaMediaManager.prototype.serve = function(request, response, serverAdId, cuePointId, renditionId, encodingId, segmentIndex, outputStart, outputEnd){
	var This = this;

	var preSegmentId = KalturaCache.getPreSegmentId(cuePointId, renditionId);
	var postSegmentId = KalturaCache.getPostSegmentId(cuePointId, renditionId);
	var preAdMetadataKey = KalturaCache.getSegmentMediaMetadata(preSegmentId);
	var blackMetadataKey = KalturaCache.getBlackMediaMetadata(encodingId);
	var postAdMetadataKey = KalturaCache.getSegmentMediaMetadata(postSegmentId);
	var adMetadataKeys = [];
	serverAdId = JSON.parse(serverAdId);
	var adKeys = [];
	for(var i=0; i<serverAdId.length; i++){
		adMetadataKeys.push(KalturaCache.getAdMediaMetadata(serverAdId[i].id));
		adKeys.push(KalturaCache.getAdMedia(serverAdId[i].id));
	}

	var cacheKeys = adMetadataKeys.concat([preAdMetadataKey, blackMetadataKey, postAdMetadataKey]);
	KalturaCache.getMultiBinary(cacheKeys, function(data){
		preAdMetadata = data[preAdMetadataKey];
		blackMetadata = data[blackMetadataKey];
		postAdMetadata = data[postAdMetadataKey];

		adsMetadata = [];
		for(var i=0; i<adMetadataKeys.length; i++){
			if(data[adMetadataKeys[i]]){
				var adMetadata =
				{
					adChunkType: KalturaMediaManager.CHUNK_TYPE_AD + i,
					ad: data[adMetadataKeys[i]],
					fillerChunkType: KalturaMediaManager.CHUNK_TYPE_BLACK,
					filler: blackMetadata,
					startPos: serverAdId[i].startPos,
					endPos: serverAdId[i].endPos,
					alignment: KalturaMediaManager.ALIGN_LEFT
				};
				adsMetadata.push(adMetadata);
				response.log('Added ad metadata: adChunkType [' + adMetadata.adChunkType + '], startPos [' + serverAdId[i].startPos + '] endPos [' + serverAdId[i].endPos + ']');
			}
			else{
				delete adKeys[i];
			}
		}

		if (!preAdMetadata){
			response.log('Pre-Ad metadata is null');
		}
		else{
			response.log('Pre-Ad metadata length ' + preAdMetadata.length);
		}

		if (!adsMetadata.length){
			response.log('Ad metadata is null');
			//set black ad as a dummy ad metadata
			var adMetadata =
			{
				adChunkType: KalturaMediaManager.CHUNK_TYPE_BLACK,
				ad: blackMetadata,
				fillerChunkType: KalturaMediaManager.CHUNK_TYPE_BLACK,
				filler: blackMetadata,
				startPos: 0,
				endPos: 0,
				alignment: KalturaMediaManager.ALIGN_LEFT
			};
			adsMetadata.push(adMetadata);
		}
		else{
			response.log('Ad metadata length ' + adsMetadata.length);
		}

		// build the layout of the output TS
		var outputLayout = stitcher.buildLayout(
				preAdMetadata,
				postAdMetadata,
				adsMetadata,
				segmentIndex,
				outputStart,
				outputEnd);

		// free the metadata buffers, we don't need them anymore
		preAdMetadata = null;
		adsMetadata = null;
		blackMetadata = null;
		postAdMetadata = null;

		var preAdKey = KalturaCache.getSegmentMedia(preSegmentId);
		var blackKey = KalturaCache.getBlackMedia(encodingId);
		var postAdKey = KalturaCache.getSegmentMedia(postSegmentId);

		// output the TS
		response.writeHead(200, {
			'Content-Type': 'video/MP2T',
			'Cache-Control': KalturaConfig.config.media.cdnCacheScope + ', max-age=' + KalturaConfig.config.media.cdnMaxAge + ', max-stale=0'
			});

		This.outputStitchedSegment(outputLayout, {}, new Buffer(0), preAdKey, adKeys, blackKey, postAdKey, response);
	});
};

/**
 * Returns the segment media from cache
 *
 * @action media.segment
 */
KalturaMediaManager.prototype.segment = function(request, response, params){
	var This = this;
	if (!params.e) {
		response.dir(params);
		response.error('Missing arguments [e]');
		this.errorMissingParameter(response);
		return;
	}

	params = this.decrypt(params);
	response.dir(params);

	var requiredParams = [
		'cuePointId',
		'renditionId',
		'encodingId',
		'segmentIndex',
		'outputStart',
		'outputEnd',
		'sessionId',
		'adStart',
		'originalUrl'
	];

	var missingParams = this.getMissingParams(params, requiredParams);
	if(missingParams.length){
		response.error('Missing arguments [' + missingParams.join(', ') + ']');
		this.errorMissingParameter(response);
		return;
	}

	var serverAdIdKey = KalturaCache.getServerAdId(params.cuePointId, params.encodingId, params.sessionId);

	KalturaCache.get(serverAdIdKey, function(serverAdIds){
		if(!serverAdIds){
			response.log('No ad found, redirecting to original ts');
			response.writeHead(302, {'Location' : params.originalUrl});
			response.end();
		}
		else{
			var outputStart = parseInt(params.outputStart);
			var outputEnd = parseInt(params.outputEnd);
			var adStart = parseInt(params.adStart);
			var serverAdId = [];
			var adsSequence = [];
			var currentAdsIdx = [];
			var sequenceDuration = adStart;
			var startSequenceIndex = 0;
			var startPos = adStart;
			var endPos = adStart;
			for(var i = 0; i<= serverAdIds.length; i++){
				if(!serverAdIds[i]){
					continue;
				}
				if(sequenceDuration + serverAdIds[i].duration <= outputStart){
					sequenceDuration += serverAdIds[i].duration;
					startSequenceIndex = i;
				}
				startPos = endPos;
				endPos += serverAdIds[i].duration;
				adsSequence.push({id:serverAdIds[i].id, startPos:startPos, endPos:endPos, sequence:i});
			}

			for(var j = startSequenceIndex; adsSequence[j] && (adsSequence[j].startPos <= outputEnd || !outputEnd); j++){
				currentAdsIdx.push(adsSequence[j].sequence);
				serverAdId.push({id:adsSequence[j].id, startPos:adsSequence[j].startPos, endPos:adsSequence[j].endPos});
			}

			response.log('Handling server ad Ids: ' + JSON.stringify(serverAdId));
			params.serverAdId = JSON.stringify(serverAdId);

			var trackingKey = KalturaCache.getAdTrackingId(params.cuePointId, params.sessionId);
			KalturaAdIntegrationHandler.sendBeacon(trackingKey, currentAdsIdx, sequenceDuration, outputStart, outputEnd, adStart);

			delete params.sessionId;
			response.dir(params);

			var redirectUrl = This.getPlayServerUrl('media', 'get', params.partnerId, null, params);
			response.writeHead(302, {'Location' : redirectUrl});
			response.end();
		}

	}, function(err){
		response.log('No ad found, redirecting to original ts');
		response.writeHead(302, {'Location' : params.originalUrl});
		response.end();
	});
};

module.exports.KalturaMediaManager = KalturaMediaManager;
<|endoftext|>


<commit_before>new Vue({
    el: 'body',
    data: {
        show: false,
        submit: false,
        error: false,
        finals: false,
        select: ['String', 'date', 'longText', 'integer', 'biginteger', 'boolean', 'float'],
        selected: '0',
        baseUrl: baseUrl,
        OneToMany: scaffoldList,
        attributes: [],
        OneToManyRows: 0,
        rows: 0,
    },
    methods: {
        increment: function() {
            this.error = false;
            this.rows += 1;
        },
        decrement: function() {
            if (this.rows == 0 && this.OneToManyRows == 0) {
                this.error = true;
            } else {
                if (this.OneToManyRows != 0) {
                    this.OneToManyRows -= 1;
                    return;
                }
                this.rows -= 1;
            }
        },
        addOneToMany: function() {
            this.OneToManyRows += 1;
        },
        getAttr: function(index) {
            console.log(index);
            this.selected = $('#tbl' + index).val();
            console.log(this.baseUrl + '/scaffold/getAttributes/' + this.selected);
            $.getJSON(this.baseUrl + '/scaffold/getAttributes/' + this.selected, function(response) {
                this.attributes = response
            }.bind(this));
        }
    }
})<commit_msg>update script<commit_after>Vue.component("ola-bola", {
    template: "
Hello World
"
});
new Vue({
    el: 'body',
    data: {
        show: false,
        submit: false,
        error: false,
        finals: false,
        select: ['String', 'date', 'longText', 'integer', 'biginteger', 'boolean', 'float'],
        selected: '0',
        baseUrl: baseUrl,
        OneToMany: scaffoldList,
        attributes: [],
        OneToManyRows: 0,
        rows: 0,
        table: '',
        OneToManyData: [],
        OneToManyBool: false
    },
    methods: {
        increment: function() {
            this.error = false;
            this.rows += 1;
        },
        decrement: function() {
            if (this.rows == 0 && this.OneToManyRows == 0) {
                this.error = true;
            } else {
                if (this.OneToManyRows != 0) {
                    this.OneToManyRows -= 1;
                    return;
                }
                this.rows -= 1;
            }
        },
        addOneToMany: function() {
            this.OneToManyRows += 1;
            this.OneToManyBool = true;
        },
        getAttr: function(index) {
            console.log(index);
            this.selected = $('#tbl').val();
            console.log(this.baseUrl + '/scaffold/getAttributes/' + this.selected);
            $.getJSON(this.baseUrl + '/scaffold/getAttributes/' + this.selected, function(response) {
                this.attributes = response

                this.table = this.selected;

            }.bind(this));
        },

        getOnData: function(index)
        {
            var onData = $('#on').val();
            console.log(onData);
            this.OneToManyData.push({table: this.table},{onData: onData});
            console.log(this.OneToManyData);
        }
    }
})<|endoftext|>


<commit_before>define([
  'intern!bdd',
  'intern/chai!expect',
  '../src/farbs'
], function (bdd, expect, farbs) {

  var opts = {}.toString;

  bdd.describe('The farbs module', function () {

    bdd.it('should return an object', function () {

      expect(opts.call(farbs)).to.equal('[object Object]');

    });

  });

  bdd.describe('registry ops', function () {

    [
      {
        registry: 'classRegistry',
        method: 'registerClass'
      },
      {
        registry: 'instRegistry',
        method: 'registerInstance'
      },
      {
        registry: 'methodRegistry',
        method: 'registerMethod'
      }

    ].forEach(function (registryType) {

        bdd.describe(registryType.registry, function () {

          bdd.it('should be an object', function () {

            expect(opts.call(farbs[registryType.registry])).to.equal('[object Object]');

          });

        });

        bdd.describe(registryType.method + '()', function () {

          bdd.beforeEach(function () {
            farbs[registryType.registry] = {};
          });

          bdd.it('should add anything at the given id to the registry', function () {

            var itemId = '__ITEM_ID',
                item = '__ITEM__';

            farbs[registryType.method](itemId, item);

            expect(farbs[registryType.registry][itemId]).to.equal(item);

          });

          bdd.it('should overwrite anything with the same id', function () {

            var itemId = '__ITEM_ID',
                item = '__ITEM__',
                item2 = '__ITEM2__';

            farbs[registryType.method](itemId, item);
            farbs[registryType.method](itemId, item2);

            expect(farbs[registryType.registry][itemId]).to.equal(item2);

          });

        });

      });

  });

  bdd.describe('pub/sub', function () {

    bdd.it('continue here', function(){

      expect(false).to.be.true;

    });

  });

});
<commit_msg>Start with pub/sub tests<commit_after>define([
  'intern!bdd',
  'intern/chai!expect',
  '../src/farbs'
], function (bdd, expect, farbs) {

  var opts = {}.toString;

  bdd.describe('The farbs module', function () {

    bdd.it('should return an object', function () {

      expect(opts.call(farbs)).to.equal('[object Object]');

    });

  });

  bdd.describe('registry ops', function () {

    [
      {
        registry: 'classRegistry',
        method: 'registerClass'
      },
      {
        registry: 'instRegistry',
        method: 'registerInstance'
      },
      {
        registry: 'methodRegistry',
        method: 'registerMethod'
      }

    ].forEach(function (registryType) {

        bdd.describe(registryType.registry, function () {

          bdd.it('should be an object', function () {

            expect(opts.call(farbs[registryType.registry])).to.equal('[object Object]');

          });

        });

        bdd.describe(registryType.method + '()', function () {

          bdd.beforeEach(function () {
            farbs[registryType.registry] = {};
          });

          bdd.it('should add anything at the given id to the registry', function () {

            var itemId = '__ITEM_ID',
                item = '__ITEM__';

            farbs[registryType.method](itemId, item);

            expect(farbs[registryType.registry][itemId]).to.equal(item);

          });

          bdd.it('should overwrite anything with the same id', function () {

            var itemId = '__ITEM_ID',
                item = '__ITEM__',
                item2 = '__ITEM2__';

            farbs[registryType.method](itemId, item);
            farbs[registryType.method](itemId, item2);

            expect(farbs[registryType.registry][itemId]).to.equal(item2);

          });

        });

      });

  });

  bdd.describe('pub/sub', function () {

    bdd.describe('listeners registry', function() {

      bdd.it('should be an object', function () {

        expect(opts.call(farbs.listeners)).to.equal('[object Object]');

      });

    });

    bdd.describe('subscribe()', function(){

      bdd.beforeEach(function () {
        farbs.listerns = {};
      });

      bdd.it('should create an array in the listeners object for the give topic', function(){

        var topic = '__TOPIC__',
            listener = '__LISTENER__';

        farbs.subscribe(topic, listener);

        expect(opts.call(farbs.listeners[topic])).to.equal('[object Array]');

      });

    });

  });

});
<|endoftext|>


<commit_before>function inArray(needle, haystack) {
    var length = haystack.length;
    for (var i = 0; i < length; i++) {
        if (haystack[i].onData == needle) return true;
    }
    return false;
}
var vm = new Vue({
    el: '.container',
    data: {
        show: false,
        submit: false,
        error: false,
        errorMsg: '',
        finals: false,
        more: false,
        select: ['String', 'date', 'longText', 'integer', 'biginteger', 'boolean', 'float'],
        selected: '0',
        rows: 0,
        baseUrl: baseUrl,
        OneToMany: scaffoldList,
        attributes: [],
        OneToManyRows: 0,
        table: '',
        OneToManyData: [],
        OneToManyBool: false,
        OpenClose: false
    },
    methods: {
        increment: function() {
            this.error = false;
            this.rows += 1;
        },
        decrement: function() {
            if (this.rows == 0 && this.OneToManyRows == 0) {
                this.errorMsg = 'Cannot remove More'
                this.error = true;
            } else {
                if (this.OneToManyRows != 0) {
                    this.OneToManyData.$remove(this.OneToManyRows);
                    this.OneToManyRows -= 1;
                    return;
                }
                this.rows -= 1;
            }
        },
        addOneToMany: function() {
            this.OneToManyBool = true;
            if (this.OpenClose) {
                var onData = $('#on').val();
                if (inArray(onData, this.OneToManyData) && onData == 'scfld#01') {
                    this.errorMsg = "Something is going wrong";
                    this.error = true
                    return;
                }
                var onData = $('#on').val();
                this.OneToManyData.push({
                    id: this.OneToManyRows,
                    table: this.table,
                    onData: onData
                });
                this.OneToManyRows += 1;
            }
            this.error = false;
        },
        getAttr: function(index) {
            console.log(index);
            this.selected = $('#tbl').val();
            console.log(this.baseUrl + '/scaffold/getAttributes/' + this.selected);
            $.getJSON(this.baseUrl + '/scaffold/getAttributes/' + this.selected, function(response) {
                this.attributes = response
                this.table = this.selected;
                this.OpenClose = true;
            }.bind(this)).error(function(response) {
                vm.errorMsg = 'Field not founds or the tabel does not migrated';
                vm.error = true
            });
        },
        lastStep: function() {
            this.submit = false;
            this.more = false;
            this.OneToManyBool = false;
        },
        lastOne: function() {
            this.submit = !this.submit;
            this.OneToManyBool = false;
        },
        removeRelation: function(item) {
            this.OneToManyData.$remove(item);
        }
    }
})<commit_msg>add some vue transitions<commit_after>function inArray(needle, haystack) {
    var length = haystack.length;
    for (var i = 0; i < length; i++) {
        if (haystack[i].onData == needle) return true;
    }
    return false;
}

Vue.transition('fade',{
    enterClass: 'fadeInRight',
    leaveClass: 'fadeOutLeft'
});
Vue.transition('actions',{
    enterClass: 'fadeInRight',
    leaveClass: 'fadeOutLeft'
});
var vm = new Vue({
    el: '.container',
    data: {
        show: false,
        submit: false,
        error: false,
        errorMsg: '',
        finals: false,
        more: false,
        select: ['String', 'date', 'longText', 'integer', 'biginteger', 'boolean', 'float'],
        selected: '0',
        rows: 0,
        baseUrl: baseUrl,
        OneToMany: scaffoldList,
        attributes: [],
        OneToManyRows: 0,
        table: '',
        OneToManyData: [],
        OneToManyBool: false,
        OpenClose: false
    },
    methods: {
        increment: function() {
            this.error = false;
            this.rows += 1;
        },
        decrement: function() {
            if (this.rows == 0 && this.OneToManyRows == 0) {
                this.errorMsg = 'Cannot remove More'
                this.error = true;
            } else {
                if (this.OneToManyRows != 0) {
                    this.OneToManyData.$remove(this.OneToManyRows);
                    this.OneToManyRows -= 1;
                    return;
                }
                this.rows -= 1;
            }
        },
        addOneToMany: function() {
            this.OneToManyBool = true;
            if (this.OpenClose) {
                var onData = $('#on').val();
                if (inArray(onData, this.OneToManyData) || onData == null) {
                    this.errorMsg = "Something is going wrong";
                    this.error = true
                    return;
                }
                this.OneToManyData.push({
                    id: this.OneToManyRows,
                    table: this.table,
                    onData: onData
                });
                this.OneToManyRows += 1;
            }
            this.error = false;
        },
        getAttr: function(index) {
            console.log(index);
            this.selected = $('#tbl').val();
            console.log(this.baseUrl + '/scaffold/getAttributes/' + this.selected);
            $.getJSON(this.baseUrl + '/scaffold/getAttributes/' + this.selected, function(response) {
                this.attributes = response
                this.table = this.selected;
                this.OpenClose = true;
            }.bind(this)).error(function(response) {
                vm.errorMsg = 'Field not founds or the tabel does not migrated';
                vm.error = true
            });
        },
        lastStep: function() {
            this.submit = false;
            this.more = false;
            this.OneToManyBool = false;
        },
        lastOne: function() {
            this.submit = !this.submit;
            this.OneToManyBool = false;
        },
        removeRelation: function(item) {
            this.OneToManyData.$remove(item);
        }
    }
})<|endoftext|>


<commit_before>define(function(require, exports, module){
    var Achievement = require('./achievement'),
        config = require('../config'),
        _ = require('../vendor/lodash.min'),
        locale = require('../services/locale'),
        ExtensionsService = require('../services/extensions');

    function AdobeAchievement(){
        this.calculate = function(extensions){
            var regexp = /adobe/;
                _.each(extensions, _.bind(function(extension){
                if (regexp.test(extension.homepage) || extension.author.toLowerCase().indexOf('adobe') >= 0){
                    this.writeBadge(null, extension);
                }
            }, this));
        }

        this.getTag = function(rating, element){
            return _.template('${badge}',{
                badge: locale.get('badgeAdobe'),
                title: locale.get('badgeAdobeTitle')
            });
        }
    }

    AdobeAchievement.prototype = Achievement;
    module.exports = AdobeAchievement;
});
<commit_msg>check extension.author field in adobe badges calculator<commit_after>define(function(require, exports, module){
    var Achievement = require('./achievement'),
        config = require('../config'),
        _ = require('../vendor/lodash.min'),
        locale = require('../services/locale'),
        ExtensionsService = require('../services/extensions');

    function AdobeAchievement(){
        this.calculate = function(extensions){
            var regexp = /adobe/;
                _.each(extensions, _.bind(function(extension){
                if (regexp.test(extension.homepage) ||
                    (typeof extension.author === 'string' && extension.author.toLowerCase().indexOf('adobe') >= 0)
                   ){
                    this.writeBadge(null, extension);
                }
            }, this));
        }

        this.getTag = function(rating, element){
            return _.template('${badge}',{
                badge: locale.get('badgeAdobe'),
                title: locale.get('badgeAdobeTitle')
            });
        }
    }

    AdobeAchievement.prototype = Achievement;
    module.exports = AdobeAchievement;
});
<|endoftext|>


<commit_before>/*
Copyright (c) 2011, Chris Umbel

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

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

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

var  fs = require('fs'),
  path = require('path'),
  util = require('util');

function appendLineChar(fd, pos, buffPos, buff, callback) {
  if(buffPos >= buff.length) {
    var newBuff = new Buffer(buff.length * 2);
    buff.copy(newBuff, 0, 0, buff.length);
    buff = newBuff;
  }

  fs.read(fd, buff, buffPos, 1, pos, function(err, count) {
    if(err)
      console.log(err);
    else {
      if(buff[buffPos] == 10 || buffPos == buff.length)
        callback(buff.slice(0, buffPos).toString('UTF-8'));
      else {
        appendLineChar(fd, pos + 1, buffPos + 1, buff, callback);
      }
    }
  });
}

function open(callback) {
  var filePath = this.filePath;

  fs.open(filePath, 'r', null, function(err, fd) {
    if (err) {
        console.log('Unable to open %s', filePath);
        return;
    }
    callback(err, fd, function() {fs.close(fd)});
  });
}

var WordNetFile = function(dataDir, fileName) {
  this.dataDir = dataDir;
  this.fileName = fileName;
  this.filePath = require('path').join(this.dataDir, this.fileName);
};

WordNetFile.prototype.open = open;
WordNetFile.appendLineChar = appendLineChar;

module.exports = WordNetFile;
<commit_msg>fix(wordnet): add callback to fs.close call<commit_after>/*
Copyright (c) 2011, Chris Umbel

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

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

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

var  fs = require('fs'),
  path = require('path'),
  util = require('util');

function appendLineChar(fd, pos, buffPos, buff, callback) {
  if(buffPos >= buff.length) {
    var newBuff = new Buffer(buff.length * 2);
    buff.copy(newBuff, 0, 0, buff.length);
    buff = newBuff;
  }

  fs.read(fd, buff, buffPos, 1, pos, function(err, count) {
    if(err)
      console.log(err);
    else {
      if(buff[buffPos] == 10 || buffPos == buff.length)
        callback(buff.slice(0, buffPos).toString('UTF-8'));
      else {
        appendLineChar(fd, pos + 1, buffPos + 1, buff, callback);
      }
    }
  });
}

function open(callback) {
  var filePath = this.filePath;

  fs.open(filePath, 'r', null, function(err, fd) {
    if (err) {
        console.log('Unable to open %s', filePath);
        return;
    }
    callback(err, fd, function() {
      fs.close(fd, function(error) {
        if (error) {
          throw error;
        }
      })
    });
  });
}

var WordNetFile = function(dataDir, fileName) {
  this.dataDir = dataDir;
  this.fileName = fileName;
  this.filePath = require('path').join(this.dataDir, this.fileName);
};

WordNetFile.prototype.open = open;
WordNetFile.appendLineChar = appendLineChar;

module.exports = WordNetFile;
<|endoftext|>


<commit_before>document.getElementById("ayuda").setAttribute("aria-current", "page");

var aside = document.getElementById("complementario");
var button = document.createElement("BUTTON");
button.setAttribute("id", "addonsButton");
var buttonText = document.createTextNode("Información sobre complementos de nvdaes");
button.appendChild(buttonText);
aside.appendChild(button);

addons = [
	"clipContentsDesigner",
	"emoticons",
	"eMule",
	"placeMarkers",
	"readFeeds",
	"reportSymbols",
]

var addonsLength = addons.length;

$(document).ready(function () {
	$("#addonsButton").click(function () {
		for (var i = 0; i < addonsLength; i++) {
			var details = document.createElement("DETAILS");
			var summary = document.createElement("SUMMARY");
			var t = document.createTextNode(addons[i]);
			summary.appendChild(t);
			// details.appendChild(summary);
			$.getJSON("https://api.github.com/repos/nvdaes/" + addons[i] + "/releases/latest", function(json) {
				var t = document.createTextNode(json.name);
				details.appendChild(summary);
			});
			aside.appendChild(details);
		}
	});
});
<commit_msg>Update script<commit_after>document.getElementById("ayuda").setAttribute("aria-current", "page");

var aside = document.getElementById("complementario");
var button = document.createElement("BUTTON");
button.setAttribute("id", "addonsButton");
var buttonText = document.createTextNode("Información sobre complementos de nvdaes");
button.appendChild(buttonText);
aside.appendChild(button);

addons = [
	"clipContentsDesigner",
	"emoticons",
	"eMule",
	"placeMarkers",
	"readFeeds",
	"reportSymbols",
]

var addonsLength = addons.length;

$(document).ready(function () {
	$("#addonsButton").click(function () {
		for (var i = 0; i < addonsLength; i++) {
			var details = document.createElement("DETAILS");
			var summary = document.createElement("SUMMARY");
			var t = document.createTextNode(addons[i]);
			summary.appendChild(t);
			// details.appendChild(summary);
			$.getJSON("https://api.github.com/repos/nvdaes/" + addons[i] + "/releases/latest", function(json) {
				var t = document.createTextNode(json.name);
				this.details.appendChild(this.summary);
			});
			aside.appendChild(details);
		}
	});
});
<|endoftext|>


<commit_before>'use strict';

var util = require('util'),
  XModule = require('../../../core/XModule'),
  ltx = require('ltx'),
  Iq = require('node-xmpp-core').Stanza.Iq,
  NS = require('../namespace'),
  mucutil = require('../Util'),
  logger = require('../../../core/Logger')('xep-0045:admin');

function Admin(storage) {
  XModule.call(this);
  this.storage = storage;
}

util.inherits(Admin, XModule);

Admin.prototype.name = 'XEP-0045: Admin';

Admin.prototype.match = function (stanza) {
  // membership
  return (stanza.is('iq') && stanza.getChild('query', NS.MUC_ADMIN));
};

/**
 * returs the affiliations for each members of the room
 *
 * <iq from='kinghenryv@shakespeare.lit/throne'
 *     id='ban2'
 *     to='southampton@chat.shakespeare.lit'
 *     type='get'>
 *   <query xmlns='http://jabber.org/protocol/muc#admin'>
 *     <item affiliation='outcast'/>
 *   </query>
 * </iq>
 *
 * <iq from='southampton@chat.shakespeare.lit'
 *     id='ban2'
 *     to='kinghenryv@shakespeare.lit/throne'
 *     type='result'>
 *   <query xmlns='http://jabber.org/protocol/muc#admin'>
 *     <item affiliation='outcast'
 *           jid='earlofcambridge@shakespeare.lit'>
 *       <reason>Treason</reason>
 *     </item>
 *   </query>
 * </iq>
 */
Admin.prototype.list = function (room, stanza, affiliation) {
  var self = this;

  var iq = new Iq({
    from: stanza.attrs.to,
    to: stanza.attrs.from,
    id: stanza.attrs.id,
    type: 'result'
  });

  var query = new ltx.Element('query', {
    'xmlns': NS.MUC_ADMIN,
    'to': stanza.attrs.from,
    'id': stanza.attrs.id,
    'type': 'result'
  });
  iq.cnode(query);

  var affiliationSet = [];

  switch (affiliation) {
  case NS.MUC_AFFILIATION_ADMIN:
    affiliationSet.push(this.storage.RoomMember.Affiliation.Admin);
    break;
  case NS.MUC_AFFILIATION_MEMBER:
    affiliationSet.push(this.storage.RoomMember.Affiliation.Member);
    break;
  case NS.MUC_AFFILIATION_OWNER:
    affiliationSet.push(this.storage.RoomMember.Affiliation.Owner);
    break;
  case NS.MUC_AFFILIATION_OUTCAST:
    affiliationSet.push(this.storage.RoomMember.Affiliation.Outcast);
    break;
  }

  // checkout if the current user is member
  room.getMembers({
    where: {
      affiliation: affiliationSet
    }
  }).then(function (members) {

    logger.debug('members with affiliation ' + affiliation + ': ' + JSON.stringify(members));

    // iterate over items and send them to the client
    members.forEach(function (member) {
      logger.debug(member);
      var itemEl = new ltx.Element('item', {
        'affiliation': member.RoomMember.affiliation,
        'jid': member.jid
      });

      // if we found a reason
      /*if (item.affiliation && item.affiliation.reason) {
          itemEl.c('reason').t(item.affiliation.reason);
      }*/

      // add item
      query.cnode(itemEl);
    });

    self.send(iq);
  }).catch(function (err) {
    logger.error(err);
    self.sendError(stanza);
  });
};

Admin.prototype.handleAdminRequests = function (stanza) {
  logger.debug('handleAdminRequests');
  var self = this;
  var storage = this.storage;

  // determine type of request
  var method = null;

  var query = stanza.getChild('query', NS.MUC_ADMIN);
  var item = query.getChild('item');

  if (item && (
      (item.attrs.affiliation === NS.MUC_AFFILIATION_ADMIN) ||
      (item.attrs.affiliation === NS.MUC_AFFILIATION_MEMBER) ||
      (item.attrs.affiliation === NS.MUC_AFFILIATION_OWNER) ||
      (item.attrs.affiliation === NS.MUC_AFFILIATION_OUTCAST)
    )) {

    // get room name
    var roomname = mucutil.determineRoomname(stanza);

    storage.findRoom(roomname).then(
        function (room) {
          logger.debug('found room: ' + JSON.stringify(room) + ' and ' + method);
          self.list(room, stanza, item.attrs.affiliation);
        })
      .
    catch(function (err) {
      logger.error(err);
      self.sendError(stanza);
    });
  } else {
    this.sendError(stanza);
  }

  return true;
};

Admin.prototype.handle = function (stanza) {
  var handled = false;

  // admin request
  if (stanza.is('iq') && stanza.getChild('query', NS.MUC_ADMIN)) {
    handled = this.handleAdminRequests(stanza);
  }

  return handled;
};

module.exports = Admin;
<commit_msg>bugfix: fix associations table<commit_after>'use strict';

var util = require('util'),
  XModule = require('../../../core/XModule'),
  ltx = require('ltx'),
  Iq = require('node-xmpp-core').Stanza.Iq,
  NS = require('../namespace'),
  mucutil = require('../Util'),
  logger = require('../../../core/Logger')('xep-0045:admin');

function Admin(storage) {
  XModule.call(this);
  this.storage = storage;
}

util.inherits(Admin, XModule);

Admin.prototype.name = 'XEP-0045: Admin';

Admin.prototype.match = function (stanza) {
  // membership
  return (stanza.is('iq') && stanza.getChild('query', NS.MUC_ADMIN));
};

/**
 * returs the affiliations for each members of the room
 *
 * <iq from='kinghenryv@shakespeare.lit/throne'
 *     id='ban2'
 *     to='southampton@chat.shakespeare.lit'
 *     type='get'>
 *   <query xmlns='http://jabber.org/protocol/muc#admin'>
 *     <item affiliation='outcast'/>
 *   </query>
 * </iq>
 *
 * <iq from='southampton@chat.shakespeare.lit'
 *     id='ban2'
 *     to='kinghenryv@shakespeare.lit/throne'
 *     type='result'>
 *   <query xmlns='http://jabber.org/protocol/muc#admin'>
 *     <item affiliation='outcast'
 *           jid='earlofcambridge@shakespeare.lit'>
 *       <reason>Treason</reason>
 *     </item>
 *   </query>
 * </iq>
 */
Admin.prototype.list = function (room, stanza, affiliation) {
  var self = this;

  var iq = new Iq({
    from: stanza.attrs.to,
    to: stanza.attrs.from,
    id: stanza.attrs.id,
    type: 'result'
  });

  var query = new ltx.Element('query', {
    'xmlns': NS.MUC_ADMIN,
    'to': stanza.attrs.from,
    'id': stanza.attrs.id,
    'type': 'result'
  });
  iq.cnode(query);

  var affiliationSet = [];

  switch (affiliation) {
  case NS.MUC_AFFILIATION_ADMIN:
    affiliationSet.push(this.storage.RoomMember.Affiliation.Admin);
    break;
  case NS.MUC_AFFILIATION_MEMBER:
    affiliationSet.push(this.storage.RoomMember.Affiliation.Member);
    break;
  case NS.MUC_AFFILIATION_OWNER:
    affiliationSet.push(this.storage.RoomMember.Affiliation.Owner);
    break;
  case NS.MUC_AFFILIATION_OUTCAST:
    affiliationSet.push(this.storage.RoomMember.Affiliation.Outcast);
    break;
  }

  // checkout if the current user is member
  room.getMembers({
    where: {
      'RoomMember.affiliation': affiliationSet
    }
  }).then(function (members) {

    logger.debug('members with affiliation ' + affiliation + ': ' + JSON.stringify(members));

    // iterate over items and send them to the client
    members.forEach(function (member) {
      logger.debug(member);
      var itemEl = new ltx.Element('item', {
        'affiliation': member.RoomMember.affiliation,
        'jid': member.jid
      });

      // if we found a reason
      /*if (item.affiliation && item.affiliation.reason) {
          itemEl.c('reason').t(item.affiliation.reason);
      }*/

      // add item
      query.cnode(itemEl);
    });

    self.send(iq);
  }).catch(function (err) {
    logger.error(err);
    self.sendError(stanza);
  });
};

Admin.prototype.handleAdminRequests = function (stanza) {
  logger.debug('handleAdminRequests');
  var self = this;
  var storage = this.storage;

  // determine type of request
  var method = null;

  var query = stanza.getChild('query', NS.MUC_ADMIN);
  var item = query.getChild('item');

  if (item && (
      (item.attrs.affiliation === NS.MUC_AFFILIATION_ADMIN) ||
      (item.attrs.affiliation === NS.MUC_AFFILIATION_MEMBER) ||
      (item.attrs.affiliation === NS.MUC_AFFILIATION_OWNER) ||
      (item.attrs.affiliation === NS.MUC_AFFILIATION_OUTCAST)
    )) {

    // get room name
    var roomname = mucutil.determineRoomname(stanza);

    storage.findRoom(roomname).then(function (room) {
      logger.debug('found room: ' + JSON.stringify(room) + ' and ' + method);
      self.list(room, stanza, item.attrs.affiliation);
    }).catch(function (err) {
      logger.error(err);
      self.sendError(stanza);
    });
  } else {
    this.sendError(stanza);
  }

  return true;
};

Admin.prototype.handle = function (stanza) {
  var handled = false;

  // admin request
  if (stanza.is('iq') && stanza.getChild('query', NS.MUC_ADMIN)) {
    handled = this.handleAdminRequests(stanza);
  }

  return handled;
};

module.exports = Admin;
<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  /* DEPENDENCIES */

  var Tree = require('./tree');
  var Sunstone = require('sunstone');
  var OpenNebula = require('opennebula');
  var Locale = require('utils/locale');
  var Notifier = require('utils/notifier');
  var TemplateUtils = require('utils/template-utils');

  var LABELS_ATTR = 'LABELS';

  return {
    'labelsStr': _labelsStr,
    'deserializeLabels': _deserializeLabels,
    'makeTree': _makeTree,
    'insertLabelsMenu': _insertLabelsMenu,
    'insertLabelsDropdown': _insertLabelsDropdown,
    'clearLabelsFilter': _clearLabelsFilter,
    'setLabelsFilter': _setLabelsFilter,
    'getLabelsFilter': _getLabelsFilter,
    'getLabels': _getLabels,
    'getLabel': _getLabel
  };

  /* FUNCTION DEFINITIONS */

  /**
   * Add labels tree to the left menu
   * @param {Object}        opts - Options
   * @param {string}        opts.tabName - Tab Name to retrieve the rest of the opts
   * @param {jQuery Object} [opts.context] - jQuery object to insert the menu, if not
   *                          provided the link of the tab in the left menu will be used
   * @param {DataTable}     [opts.dataTable] - Datatable to apply the filter, if not
   *                          provided the one defined in the Sunstone tab will be used
   * @param {Number}        [opts.labelsColumn] - Column of the labels in the datatable,
   *                          if not provided the one defined in the Sunstone tab datatable
   *                          will be used
   * @param {string}        [opts.labelsPath] - Path of the labels attr, this value will be
   *                          used if the datatable uses aData object instead of an array w
   *                          ith the values
   * @param {string}        [opts.placeholder] - Message to be shown in no labels are defined
   */
  function _insertLabelsMenu(opts) {
    var context = opts.context || $('#li_' + opts.tabName);
    var dataTable = opts.dataTable || Sunstone.getDataTable(opts.tabName).dataTable;
    var labelsColumn = opts.labelsColumn || Sunstone.getDataTable(opts.tabName).labelsColumn;
    var labelsPath = opts.labelsPath;

    var labels = _getLabels(dataTable, labelsColumn, labelsPath);
    $('.labels-tree', context).remove();
    if ($.isEmptyObject(labels)) {
      if (opts.placeholder) {
        context.html('
' + opts.placeholder + '
');
      }
    } else {
      context.append(Tree.html(_makeTree(labels), true));

      context.off('click', '.labeltree-line');

      Tree.setup($('.labels-tree', context));

      var currentLabel = $('span[one-label-full-name="'+_getLabelsFilter(dataTable)+'"]', context);

      if (currentLabel.length == 0){
        _clearLabelsFilter(dataTable, labelsColumn);
      }else{
        currentLabel.parent(".labeltree-line").click();
        currentLabel.parentsUntil(".labels-tree", "li").children(".tree-toggle").click();
      }
    }

    /*
      Filter datatable when a label in the left menu is clicked
     */
    context.off('click', '.labeltree-line');
    context.on('click', '.labeltree-line', function() {
      var span = $(".one-label", this);

      if($(span).hasClass("active")){
        if (opts.tabName && !Sunstone.rightListVisible($('#' + opts.tabName))) {
          Sunstone.showTab(opts.tabName);
        }

        var label = $(span).attr('one-label-full-name');

        _setLabelsFilter(dataTable, labelsColumn, label);
      } else {
        _clearLabelsFilter(dataTable, labelsColumn);
      }
    });
  }

  /*
    Generate labels dropdown
   */
  function _insertLabelsDropdown(tabName) {
    var tabTable = Sunstone.getDataTable(tabName);
    var dataTable = tabTable.dataTable;
    var labelsColumn = tabTable.labelsColumn;

    var labelsDropdown = $('#' + tabName + 'LabelsDropdown');

    var labels = _getLabels(dataTable, labelsColumn);
    labelsDropdown.html(
      '
' +
      '
' + Locale.tr('Edit Labels') + '
' +
      '
' +
        Tree.html(_makeTree(labels), false) +
      '
' +
      '
' +
        '<input type="text" class="newLabelInput" placeholder="' + Locale.tr("Add Label") + '"/>' +
      '
' +
      '
');

    Tree.setup(labelsDropdown);

    /*
      Update Dropdown with selected items
      [v] If all the selected items has a label
      [-] If any of the selected items has a label
      [ ] If no selected item has an existing label
     */
    function recountLabels() {
      // Generate Hash with labels and number of items
      var labelsStr, labelsIndexed = {};

      var selectedItems = tabTable.elements();
      $.each(selectedItems, function(index, resourceId) {
        labelsStr = _getLabel(tabName, dataTable, labelsColumn, resourceId);
        if (labelsStr != '') {
          $.each(labelsStr.split(','), function(){
            if (labelsIndexed[this]) {
              labelsIndexed[this] += 1
            } else {
              labelsIndexed[this] = 1
            }
          })
        }
      });

      // Set checkboxes (check|minus) depending on the number of items

      // Reset label checkboxes
      $('.labelsCheckbox', labelsDropdown)
        .removeClass('fa-minus-square-o')
        .removeClass('fa-check-square-o')
        .addClass('fa-square-o');

      var labelsCheckbox;
      $.each(labelsIndexed, function(labelName, numberOfItems) {
        labelsCheckbox = $('.labelsCheckbox',
          $('[one-label-full-name="' + labelName + '"]', labelsDropdown).closest('li'));
        if (labelsCheckbox.length > 0) {
          if (numberOfItems == selectedItems.length) {
            $(labelsCheckbox[0])
              .removeClass('fa-square-o')
              .addClass('fa-check-square-o');
          } else {
            $(labelsCheckbox[0])
              .removeClass('fa-square-o')
              .addClass('fa-minus-square-o');
          }
        }
      });

      $('.newLabelInput', labelsDropdown).focus();
    }

    recountLabels();
    $('[data-toggle="' + tabName + 'LabelsDropdown"]').off('click');
    $('[data-toggle="' + tabName + 'LabelsDropdown"]').on('click', function(){
      recountLabels();
    });

    /*
      Check/Uncheck label & Update Templates
     */
    labelsDropdown.off('click', '.labeltree-line');
    labelsDropdown.on('click', '.labeltree-line', function() {
      var action;
      var that = $(".labelsCheckbox", this);

      if ($(that).hasClass('fa-square-o')) {
        action = 'add';
        $(that).removeClass('fa-square-o').addClass('fa-check-square-o');
      } else {
        action = 'remove';
        $(that).removeClass('fa-check-square-o fa-minus-square-o').addClass('fa-square-o');
      }

      var labelName = $('.one-label', $(that).closest('li')).attr('one-label-full-name');
      var labelsArray, labelIndex;
      var selectedItems = tabTable.elements();
      $.each(selectedItems, function(index, resourceId) {
        labelsStr = _getLabel(tabName, dataTable, labelsColumn, resourceId);
        if (labelsStr != '') {
          labelsArray = labelsStr.split(',')
        } else {
          labelsArray = []
        }

        labelIndex = $.inArray(labelName, labelsArray);
        if (action == 'add' && labelIndex == -1) {
          labelsArray.push(labelName)
          _updateResouceLabels(tabName, resourceId, labelsArray);
        } else if (action == 'remove' && labelIndex != -1) {
          labelsArray.splice(labelIndex, 1);
          _updateResouceLabels(tabName, resourceId, labelsArray);
        }
      });
    });

    /*
      Add a new label when ENTER is presed in the input
     */
    labelsDropdown.off('keypress', '.newLabelInput');
    labelsDropdown.on('keypress', '.newLabelInput', function(e) {
      var ev = e || window.event;
      var key = ev.keyCode;
      var labelName = $(this).val();

      if (key == 13 && !ev.altKey && labelName != '') {
        var labelsArray, labelIndex;
        var selectedItems = tabTable.elements();
        $.each(selectedItems, function(index, resourceId) {
          labelsStr = _getLabel(tabName, dataTable, labelsColumn, resourceId);
          if (labelsStr != '') {
            labelsArray = labelsStr.split(',')
          } else {
            labelsArray = []
          }

          labelIndex = $.inArray(labelName, labelsArray);
          if (labelIndex == -1) {
            labelsArray.push(labelName);
            _updateResouceLabels(tabName, resourceId, labelsArray);
          }
        });

        ev.preventDefault();
      }
    });
  }

  function _updateResouceLabels(tabName, resourceId, labelsArray) {
    var templateStr = LABELS_ATTR + '="' + labelsArray.join(',') + '"';
    var resource = Sunstone.getResource(tabName);
    var tabTable = Sunstone.getDataTable(tabName);

    OpenNebula[resource].append({
      timeout: true,
      data : {
          id: resourceId,
          extra_param: templateStr
      },
      success: function(request) {
        OpenNebula[resource].show({
          timeout: true,
          data : {
              id: resourceId
          },
          success: function(request, response) {
            tabTable.updateElement(request, response);
            if (Sunstone.rightInfoVisible($('#' + tabName))) {
              Sunstone.insertPanels(tabName, response);
            }

            _insertLabelsMenu({'tabName': tabName});
            _insertLabelsDropdown(tabName);
          },
          error: Notifier.onError
        });
      },
      error: Notifier.onError
    })
  }

  function _labelsStr(elementTemplate) {
    return elementTemplate[LABELS_ATTR];
  }

  function _deserializeLabels(labelsStr) {
    var indexedLabels = {};

    if (labelsStr) {
      var parent;
      $.each(labelsStr.split(','), function() {
        parent = indexedLabels;
        $.each(this.split('/'), function() {
          if (parent[this] == undefined) {
            parent[this] = {};
          }
          parent = parent[this];
        });
      });
    }

    return indexedLabels;
  }

  function _makeTree(indexedLabels, currentLabel) {
    var treeRoot = {
      htmlStr : '',
      subTree : []
    };

    var keys = Object.keys(indexedLabels).sort();
    for (var i = 0; i < keys.length; i++){
      var folderName = keys[i];
      var childs = indexedLabels[folderName];
      treeRoot.subTree.push(_makeSubTree('', folderName, childs, currentLabel));
    }

    return treeRoot;
  }

  function _makeSubTree(parentName, folderName, childs, currentLabel) {
    var fullName = parentName + folderName;
    var htmlStr =
      '' +
        TemplateUtils.htmlEncode(folderName) +
      '';

    var tree = {
      htmlStr: htmlStr,
      subTree: []
    };

    var keys = Object.keys(childs).sort();
    for (var i = 0; i < keys.length; i++){
      var subFolderName = keys[i];
      var subChilds = childs[subFolderName];
      tree.subTree.push(_makeSubTree(fullName + '/', subFolderName, subChilds, currentLabel));
    }

    return tree;
  }

  /*
    dataTable Filters
   */

  function _setLabelsFilter(dataTable, labelsColumn, label) {

    // Make the label safe, it may contain regexp special characters. Source:
    // https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
    var escapedLabel = label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

    var regExp =  '^' + escapedLabel + '$|'+
                  ',' + escapedLabel + '$|'+
                  '^' + escapedLabel + ',|'+
                  ',' + escapedLabel + ','

    dataTable.data("sunstone-label-filter", label);
    dataTable.fnFilter(regExp, labelsColumn, true, false);
  }

  function _clearLabelsFilter(dataTable, labelsColumn) {
    dataTable.removeData("sunstone-label-filter");
    dataTable.fnFilter('', labelsColumn, true, false);
  }

  function _getLabelsFilter(dataTable) {
    return dataTable.data("sunstone-label-filter");
  }

  function _getLabels(dataTable, labelsColumn, labelsPath) {
    var labels = [];
    var tmp;
    $.each(dataTable.fnGetData(), function() {
      if (labelsPath) {
        tmp = this;
        $.each(labelsPath.split('.'), function() {
          if (tmp) {
            tmp = tmp[this];
          }
        });
        if (tmp && tmp != '') {
          labels.push(tmp);
        }
      } else {
        if (this[labelsColumn] != '') {
          labels.push(this[labelsColumn]);
        }
      }
    })
    return _deserializeLabels(labels.join(','));
  }

  function _getLabel(tabName, dataTable, labelsColumn, resourceId) {
    if (Sunstone.rightInfoVisible($('#' + tabName))) {
      var element = Sunstone.getElementRightInfo(tabName);
      if (element) {
        var template;
        if (element.USER_TEMPLATE) {
          template = element.USER_TEMPLATE;
        } else {
          template = element.TEMPLATE;
        }
        return template[LABELS_ATTR]||'';
      } else {
        return '';
      }
    } else {
      var nodes = dataTable.fnGetNodes();
      var tr = $('.check_item[value="' + resourceId + '"]', nodes).closest('tr');
      var aData = dataTable.fnGetData(tr);
      return aData[labelsColumn];
    }
  }
});
<commit_msg>B #4780: Fix label rendering when <> is used<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  /* DEPENDENCIES */

  var Tree = require('./tree');
  var Sunstone = require('sunstone');
  var OpenNebula = require('opennebula');
  var Locale = require('utils/locale');
  var Notifier = require('utils/notifier');
  var TemplateUtils = require('utils/template-utils');

  var LABELS_ATTR = 'LABELS';

  return {
    'labelsStr': _labelsStr,
    'deserializeLabels': _deserializeLabels,
    'makeTree': _makeTree,
    'insertLabelsMenu': _insertLabelsMenu,
    'insertLabelsDropdown': _insertLabelsDropdown,
    'clearLabelsFilter': _clearLabelsFilter,
    'setLabelsFilter': _setLabelsFilter,
    'getLabelsFilter': _getLabelsFilter,
    'getLabels': _getLabels,
    'getLabel': _getLabel
  };

  /* FUNCTION DEFINITIONS */

  /**
   * Add labels tree to the left menu
   * @param {Object}        opts - Options
   * @param {string}        opts.tabName - Tab Name to retrieve the rest of the opts
   * @param {jQuery Object} [opts.context] - jQuery object to insert the menu, if not
   *                          provided the link of the tab in the left menu will be used
   * @param {DataTable}     [opts.dataTable] - Datatable to apply the filter, if not
   *                          provided the one defined in the Sunstone tab will be used
   * @param {Number}        [opts.labelsColumn] - Column of the labels in the datatable,
   *                          if not provided the one defined in the Sunstone tab datatable
   *                          will be used
   * @param {string}        [opts.labelsPath] - Path of the labels attr, this value will be
   *                          used if the datatable uses aData object instead of an array w
   *                          ith the values
   * @param {string}        [opts.placeholder] - Message to be shown in no labels are defined
   */
  function _insertLabelsMenu(opts) {
    var context = opts.context || $('#li_' + opts.tabName);
    var dataTable = opts.dataTable || Sunstone.getDataTable(opts.tabName).dataTable;
    var labelsColumn = opts.labelsColumn || Sunstone.getDataTable(opts.tabName).labelsColumn;
    var labelsPath = opts.labelsPath;

    var labels = _getLabels(dataTable, labelsColumn, labelsPath);
    $('.labels-tree', context).remove();
    if ($.isEmptyObject(labels)) {
      if (opts.placeholder) {
        context.html('
' + opts.placeholder + '
');
      }
    } else {
      context.append(Tree.html(_makeTree(labels), true));

      context.off('click', '.labeltree-line');

      Tree.setup($('.labels-tree', context));

      var currentLabel = $('span[one-label-full-name="'+_getLabelsFilter(dataTable)+'"]', context);

      if (currentLabel.length == 0){
        _clearLabelsFilter(dataTable, labelsColumn);
      }else{
        currentLabel.parent(".labeltree-line").click();
        currentLabel.parentsUntil(".labels-tree", "li").children(".tree-toggle").click();
      }
    }

    /*
      Filter datatable when a label in the left menu is clicked
     */
    context.off('click', '.labeltree-line');
    context.on('click', '.labeltree-line', function() {
      var span = $(".one-label", this);

      if($(span).hasClass("active")){
        if (opts.tabName && !Sunstone.rightListVisible($('#' + opts.tabName))) {
          Sunstone.showTab(opts.tabName);
        }

        var label = $(span).attr('one-label-full-name');

        _setLabelsFilter(dataTable, labelsColumn, label);
      } else {
        _clearLabelsFilter(dataTable, labelsColumn);
      }
    });
  }

  /*
    Generate labels dropdown
   */
  function _insertLabelsDropdown(tabName) {
    var tabTable = Sunstone.getDataTable(tabName);
    var dataTable = tabTable.dataTable;
    var labelsColumn = tabTable.labelsColumn;

    var labelsDropdown = $('#' + tabName + 'LabelsDropdown');

    var labels = _getLabels(dataTable, labelsColumn);
    labelsDropdown.html(
      '
' +
      '
' + Locale.tr('Edit Labels') + '
' +
      '
' +
        Tree.html(_makeTree(labels), false) +
      '
' +
      '
' +
        '<input type="text" class="newLabelInput" placeholder="' + Locale.tr("Add Label") + '"/>' +
      '
' +
      '
');

    Tree.setup(labelsDropdown);

    /*
      Update Dropdown with selected items
      [v] If all the selected items has a label
      [-] If any of the selected items has a label
      [ ] If no selected item has an existing label
     */
    function recountLabels() {
      // Generate Hash with labels and number of items
      var labelsStr, labelsIndexed = {};

      var selectedItems = tabTable.elements();
      $.each(selectedItems, function(index, resourceId) {
        labelsStr = _getLabel(tabName, dataTable, labelsColumn, resourceId);
        if (labelsStr != '') {
          $.each(labelsStr.split(','), function(){
            if (labelsIndexed[this]) {
              labelsIndexed[this] += 1
            } else {
              labelsIndexed[this] = 1
            }
          })
        }
      });

      // Set checkboxes (check|minus) depending on the number of items

      // Reset label checkboxes
      $('.labelsCheckbox', labelsDropdown)
        .removeClass('fa-minus-square-o')
        .removeClass('fa-check-square-o')
        .addClass('fa-square-o');

      var labelsCheckbox;
      $.each(labelsIndexed, function(labelName, numberOfItems) {
        labelsCheckbox = $('.labelsCheckbox',
          $('[one-label-full-name="' + labelName + '"]', labelsDropdown).closest('li'));
        if (labelsCheckbox.length > 0) {
          if (numberOfItems == selectedItems.length) {
            $(labelsCheckbox[0])
              .removeClass('fa-square-o')
              .addClass('fa-check-square-o');
          } else {
            $(labelsCheckbox[0])
              .removeClass('fa-square-o')
              .addClass('fa-minus-square-o');
          }
        }
      });

      $('.newLabelInput', labelsDropdown).focus();
    }

    recountLabels();
    $('[data-toggle="' + tabName + 'LabelsDropdown"]').off('click');
    $('[data-toggle="' + tabName + 'LabelsDropdown"]').on('click', function(){
      recountLabels();
    });

    /*
      Check/Uncheck label & Update Templates
     */
    labelsDropdown.off('click', '.labeltree-line');
    labelsDropdown.on('click', '.labeltree-line', function() {
      var action;
      var that = $(".labelsCheckbox", this);

      if ($(that).hasClass('fa-square-o')) {
        action = 'add';
        $(that).removeClass('fa-square-o').addClass('fa-check-square-o');
      } else {
        action = 'remove';
        $(that).removeClass('fa-check-square-o fa-minus-square-o').addClass('fa-square-o');
      }

      var labelName = $('.one-label', $(that).closest('li')).attr('one-label-full-name');
      var labelsArray, labelIndex;
      var selectedItems = tabTable.elements();
      $.each(selectedItems, function(index, resourceId) {
        labelsStr = _getLabel(tabName, dataTable, labelsColumn, resourceId);
        if (labelsStr != '') {
          labelsArray = labelsStr.split(',')
        } else {
          labelsArray = []
        }

        labelIndex = $.inArray(labelName, labelsArray);
        if (action == 'add' && labelIndex == -1) {
          labelsArray.push(labelName)
          _updateResouceLabels(tabName, resourceId, labelsArray);
        } else if (action == 'remove' && labelIndex != -1) {
          labelsArray.splice(labelIndex, 1);
          _updateResouceLabels(tabName, resourceId, labelsArray);
        }
      });
    });

    /*
      Add a new label when ENTER is presed in the input
     */
    labelsDropdown.off('keypress', '.newLabelInput');
    labelsDropdown.on('keypress', '.newLabelInput', function(e) {
      var ev = e || window.event;
      var key = ev.keyCode;
      var labelName = $(this).val();

      if (key == 13 && !ev.altKey && labelName != '') {
        var labelsArray, labelIndex;
        var selectedItems = tabTable.elements();
        $.each(selectedItems, function(index, resourceId) {
          labelsStr = _getLabel(tabName, dataTable, labelsColumn, resourceId);
          if (labelsStr != '') {
            labelsArray = labelsStr.split(',')
          } else {
            labelsArray = []
          }

          labelIndex = $.inArray(labelName, labelsArray);
          if (labelIndex == -1) {
            labelsArray.push(labelName);
            _updateResouceLabels(tabName, resourceId, labelsArray);
          }
        });

        ev.preventDefault();
      }
    });
  }

  function _updateResouceLabels(tabName, resourceId, labelsArray) {
    var templateStr = LABELS_ATTR + '="' + labelsArray.join(',') + '"';
    var resource = Sunstone.getResource(tabName);
    var tabTable = Sunstone.getDataTable(tabName);

    OpenNebula[resource].append({
      timeout: true,
      data : {
          id: resourceId,
          extra_param: templateStr
      },
      success: function(request) {
        OpenNebula[resource].show({
          timeout: true,
          data : {
              id: resourceId
          },
          success: function(request, response) {
            tabTable.updateElement(request, response);
            if (Sunstone.rightInfoVisible($('#' + tabName))) {
              Sunstone.insertPanels(tabName, response);
            }

            _insertLabelsMenu({'tabName': tabName});
            _insertLabelsDropdown(tabName);
          },
          error: Notifier.onError
        });
      },
      error: Notifier.onError
    })
  }

  function _labelsStr(elementTemplate) {
    return TemplateUtils.htmlEncode( elementTemplate[LABELS_ATTR] );
  }

  function _deserializeLabels(labelsStr) {
    var indexedLabels = {};

    if (labelsStr) {
      var parent;
      $.each(labelsStr.split(','), function() {
        parent = indexedLabels;
        $.each(this.split('/'), function() {
          if (parent[this] == undefined) {
            parent[this] = {};
          }
          parent = parent[this];
        });
      });
    }

    return indexedLabels;
  }

  function _makeTree(indexedLabels, currentLabel) {
    var treeRoot = {
      htmlStr : '',
      subTree : []
    };

    var keys = Object.keys(indexedLabels).sort();
    for (var i = 0; i < keys.length; i++){
      var folderName = keys[i];
      var childs = indexedLabels[folderName];
      treeRoot.subTree.push(_makeSubTree('', folderName, childs, currentLabel));
    }

    return treeRoot;
  }

  function _makeSubTree(parentName, folderName, childs, currentLabel) {
    var fullName = parentName + folderName;
    var htmlStr =
      '' +
        folderName +
      '';

    var tree = {
      htmlStr: htmlStr,
      subTree: []
    };

    var keys = Object.keys(childs).sort();
    for (var i = 0; i < keys.length; i++){
      var subFolderName = keys[i];
      var subChilds = childs[subFolderName];
      tree.subTree.push(_makeSubTree(fullName + '/', subFolderName, subChilds, currentLabel));
    }

    return tree;
  }

  /*
    dataTable Filters
   */

  function _setLabelsFilter(dataTable, labelsColumn, label) {

    // Make the label safe, it may contain regexp special characters. Source:
    // https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
    var escapedLabel = label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

    var regExp =  '^' + escapedLabel + '$|'+
                  ',' + escapedLabel + '$|'+
                  '^' + escapedLabel + ',|'+
                  ',' + escapedLabel + ','

    dataTable.data("sunstone-label-filter", label);
    dataTable.fnFilter(regExp, labelsColumn, true, false);
  }

  function _clearLabelsFilter(dataTable, labelsColumn) {
    dataTable.removeData("sunstone-label-filter");
    dataTable.fnFilter('', labelsColumn, true, false);
  }

  function _getLabelsFilter(dataTable) {
    return dataTable.data("sunstone-label-filter");
  }

  function _getLabels(dataTable, labelsColumn, labelsPath) {
    var labels = [];
    var tmp;
    $.each(dataTable.fnGetData(), function() {
      if (labelsPath) {
        tmp = this;
        $.each(labelsPath.split('.'), function() {
          if (tmp) {
            tmp = tmp[this];
          }
        });
        if (tmp && tmp != '') {
          labels.push(tmp);
        }
      } else {
        if (this[labelsColumn] != '') {
          labels.push(this[labelsColumn]);
        }
      }
    })
    return _deserializeLabels(labels.join(','));
  }

  function _getLabel(tabName, dataTable, labelsColumn, resourceId) {
    if (Sunstone.rightInfoVisible($('#' + tabName))) {
      var element = Sunstone.getElementRightInfo(tabName);
      if (element) {
        var template;
        if (element.USER_TEMPLATE) {
          template = element.USER_TEMPLATE;
        } else {
          template = element.TEMPLATE;
        }
        return template[LABELS_ATTR]||'';
      } else {
        return '';
      }
    } else {
      var nodes = dataTable.fnGetNodes();
      var tr = $('.check_item[value="' + resourceId + '"]', nodes).closest('tr');
      var aData = dataTable.fnGetData(tr);
      return aData[labelsColumn];
    }
  }
});
<|endoftext|>