<commit_before>$("#max-peers").text(localStorage.maxPeers);
$("#spinner").val(localStorage.maxPeers);
$("#def-folder").text(localStorage.tmpDir);
if (localStorage.libDir == "Temp") {
	$("#lib-folder").text("same as Download Folder");
} else $("#lib-folder").text(localStorage.libDir);
if (localStorage.clickPause == 'fullscreen') {
	$("#click-pause").text("only in Fullscreen");
} else $("#click-pause").text("Fullscreen + Windowed");
$('#open-url').css('top', Math.round(($(window).height() - 187) / 2)+'px');

$('#magnetLink').mousedown(function(event) {
    if (event.which == 3) {
		var clipboard = gui.Clipboard.get();
		$('#magnetLink').val(clipboard.get('text')).select();
    }
});

$(document).ready(function() {
	// initiate progress bars
    $('.progress .progress-bar').progressbar({display_text: 'center'});

	// initiate max peers selector (settings)
	$('#spinner').spinner({
		min: 10,
		max: 10000,
		step: 10
	});
	$('.ui-spinner').css("display","none");

});

function getReadableFileSizeString(fileSizeInBytes) {
    var i = -1;
    var byteUnits = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
    do {
        fileSizeInBytes = fileSizeInBytes / 1024;
        i++;
    } while (fileSizeInBytes > 1024);
    return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
}

function changeClickPause() {
	if (localStorage.clickPause == 'fullscreen') {
		$("#click-pause").text("Fullscreen + Windowed");
		localStorage.clickPause = "both";
		wjs().emitJsMessage("[pause-policy]both");
	} else {
		$("#click-pause").text("only in Fullscreen");
		localStorage.clickPause = "fullscreen";
		wjs().emitJsMessage("[pause-policy]fullscreen");
	}
}

function openPeerSelector() {
	if($('#max-peers').is(':visible')) $('#max-peers').hide(0,function() { $('.ui-spinner').show(0); })
}

$('#max-peers-hov').hover(function() { }, function() {
	if ($('.ui-spinner').is(":hover") === false) if ($('.ui-spinner').is(':visible')) $('.ui-spinner').hide(0,function() {
		$('#max-peers').text($('#spinner').val()).show(0);
		localStorage.maxPeers = parseInt($('#spinner').val());
	})
});

function playEl(kj) {
	if ($("#action"+kj).hasClass("play")) {
		$("#action"+kj).removeClass("play").addClass("pause").css("background-color","#F6BC24").attr("onClick","pauseEl("+kj+")");
		powGlobals.engine.files[powGlobals.files[kj].index].select();
	}
}

function pauseEl(kj) {
	if ($("#action"+kj).hasClass("pause")) {
		$("#action"+kj).removeClass("pause").addClass("play").css("background-color","#FF704A").attr("onClick","playEl("+kj+")");
		powGlobals.engine.files[powGlobals.files[kj].index].deselect();
	}
}

function settingsEl(kj) {
	if (parseInt($("#progressbar"+kj).attr("data-transitiongoal")) > 0) {
		$("#openAction").attr("onClick","gui.Shell.openItem(powGlobals['engine'].path+'\\\\'+powGlobals['engine'].files[powGlobals['files']["+kj+"].index].path); $('#closeAction').trigger('click'); playEl("+kj+")");
		$("#openFolderAction").attr("onClick","gui.Shell.showItemInFolder(powGlobals['engine'].path+'\\\\'+powGlobals['engine'].files[powGlobals['files']["+kj+"].index].path); $('#closeAction').trigger('click')");
		$("#openAction").show(0);
		$("#openFolderAction").show(0);
	} else {
		$("#openAction").hide(0);
		$("#openFolderAction").hide(0);
	}
	if (supportedVideo.indexOf($("#file"+kj).find(".filenames").text().split(".").pop().toLowerCase()) > -1) {
		// if the item is a video
		powGlobals.videos.some(function(el,ij) {
			if (el.index == powGlobals.files[kj].index) {
				$("#playAction").attr("onClick","wjs().playItem("+ij+"); $('#closeAction').trigger('click'); $('html, body').animate({ scrollTop: 0 }, 'slow'); playEl("+kj+"); $('body').css('overflow-y','hidden')");
				$("#copyStream").attr("onClick","gui.Clipboard.get().set('http://localhost:'+powGlobals['engine'].server.address().port+'/"+powGlobals.files[kj].index+"','text'); $('#closeAction').trigger('click')");
				$("#playAction").show(0);
				$("#copyStream").show(0);
				return false;
			}
		});
	} else {
		$("#playAction").hide(0);
		$("#copyStream").hide(0);
	}
	$("#open-file-settings").trigger("click");
}

function goBack(nextTorrent) {
	if (peerInterval) clearInterval(peerInterval);
	savedHistory = 0;
	pitem["#webchimera"] = 0;
	if (typeof nextTorrent === 'undefined') {
		window.scrollTo(0, 0);
		wjs().setOpeningText("Stopping");
		wjs().emitJsMessage("[tor-data-but]0");
		wjs().emitJsMessage("[refresh-disabled]");
		wjs().fullscreen(false);
		$("#header_container").css("display","none");
		$("body").css("overflow-y","hidden");
		if (parseInt($("#main").css("opacity")) == 0) $("#main").css("opacity","1");
		$('#main').css("display","table");
		document.getElementById('magnetLink').value = "";
		$('#player_wrapper').css("width","1px").css("min-height","1px");
		win.setMinimumSize(530, 440);

		if ((win.width < 530 && win.height < 440) || (win.width < 530 || win.height < 440)) {
			win.width = 530;
			win.height = 440;
		}

		if (onTop) {
			onTop = false;
			win.setAlwaysOnTop(false);
			wjs().emitJsMessage("[on-top]"+onTop);
		}

		if ($(window).height() < $("#main").height() && win.zoomLevel == 0) {
			if (win.zoomLevel > -1) win.zoomLevel = -1;
		} else if ($(window).width() < $("#main").width() && win.zoomLevel == 0) {
			if (win.zoomLevel > -1) win.zoomLevel = -1;
		} else if ($(window).width() > 730 && $(window).height() > 650 && win.zoomLevel == -1) {
			if (win.zoomLevel < 0) win.zoomLevel = 0;
		}
		$('#open-url').css('top', Math.round(($(window).height() - 187) / 2)+'px');
		wjs().clearPlaylist();
	} else {
		wjs().setOpeningText("Loading resource");
		wjs().emitJsMessage("[temp-splash]");
	}
	wjs().setDownloaded(0);
	if (powGlobals.engine) {
		isReady = 0;
		clearTimeout(downSpeed);
		powGlobals.engine.swarm.removeListener('wire', onmagnet)
		powGlobals.engine.server.close(function() {
			powGlobals.engine.remove(function() {
				powGlobals.engine.destroy();
				powGlobals = [];
				if (typeof nextTorrent !== 'undefined') {
					resetPowGlobals();
					runURL(nextTorrent,false);
				}
			});
		});
	} else {
		if (typeof nextTorrent !== 'undefined') {
			resetPowGlobals();
			runURL(nextTorrent);
		}
	}

	firstTime = 0;
	firstTimeEver = 1;
	if (typeof nextTorrent === 'undefined') win.title = "Powder Player";
}

function printHistory() {
	$("#history-list").html("");
	historyObject = JSON.parse(localStorage.history);
	oi = 0;
	if (historyObject[oi.toString()]) {
		generateHistory = "";
		for (oi = 0; historyObject[oi.toString()]; oi++) {
			generateHistory += '
'+historyObject[oi.toString()].title+'
';
		}
		if (oi < 7) $("#history-list").css('overflowY', 'auto');
		else $("#history-list").css('overflowY', 'scroll');
		$("#history-list").html(generateHistory);
	} else {
		generateHistory = "
Your history is empty, watch something first.";
		$("#history-list").css('overflowY', 'auto');
		$("#history-list").html(generateHistory);
	}
}<commit_msg>Stop Sending Cache When Changing Torrents<commit_after>$("#max-peers").text(localStorage.maxPeers);
$("#spinner").val(localStorage.maxPeers);
$("#def-folder").text(localStorage.tmpDir);
if (localStorage.libDir == "Temp") {
	$("#lib-folder").text("same as Download Folder");
} else $("#lib-folder").text(localStorage.libDir);
if (localStorage.clickPause == 'fullscreen') {
	$("#click-pause").text("only in Fullscreen");
} else $("#click-pause").text("Fullscreen + Windowed");
$('#open-url').css('top', Math.round(($(window).height() - 187) / 2)+'px');

$('#magnetLink').mousedown(function(event) {
    if (event.which == 3) {
		var clipboard = gui.Clipboard.get();
		$('#magnetLink').val(clipboard.get('text')).select();
    }
});

$(document).ready(function() {
	// initiate progress bars
    $('.progress .progress-bar').progressbar({display_text: 'center'});

	// initiate max peers selector (settings)
	$('#spinner').spinner({
		min: 10,
		max: 10000,
		step: 10
	});
	$('.ui-spinner').css("display","none");

});

function getReadableFileSizeString(fileSizeInBytes) {
    var i = -1;
    var byteUnits = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
    do {
        fileSizeInBytes = fileSizeInBytes / 1024;
        i++;
    } while (fileSizeInBytes > 1024);
    return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
}

function changeClickPause() {
	if (localStorage.clickPause == 'fullscreen') {
		$("#click-pause").text("Fullscreen + Windowed");
		localStorage.clickPause = "both";
		wjs().emitJsMessage("[pause-policy]both");
	} else {
		$("#click-pause").text("only in Fullscreen");
		localStorage.clickPause = "fullscreen";
		wjs().emitJsMessage("[pause-policy]fullscreen");
	}
}

function openPeerSelector() {
	if($('#max-peers').is(':visible')) $('#max-peers').hide(0,function() { $('.ui-spinner').show(0); })
}

$('#max-peers-hov').hover(function() { }, function() {
	if ($('.ui-spinner').is(":hover") === false) if ($('.ui-spinner').is(':visible')) $('.ui-spinner').hide(0,function() {
		$('#max-peers').text($('#spinner').val()).show(0);
		localStorage.maxPeers = parseInt($('#spinner').val());
	})
});

function playEl(kj) {
	if ($("#action"+kj).hasClass("play")) {
		$("#action"+kj).removeClass("play").addClass("pause").css("background-color","#F6BC24").attr("onClick","pauseEl("+kj+")");
		powGlobals.engine.files[powGlobals.files[kj].index].select();
	}
}

function pauseEl(kj) {
	if ($("#action"+kj).hasClass("pause")) {
		$("#action"+kj).removeClass("pause").addClass("play").css("background-color","#FF704A").attr("onClick","playEl("+kj+")");
		powGlobals.engine.files[powGlobals.files[kj].index].deselect();
	}
}

function settingsEl(kj) {
	if (parseInt($("#progressbar"+kj).attr("data-transitiongoal")) > 0) {
		$("#openAction").attr("onClick","gui.Shell.openItem(powGlobals['engine'].path+'\\\\'+powGlobals['engine'].files[powGlobals['files']["+kj+"].index].path); $('#closeAction').trigger('click'); playEl("+kj+")");
		$("#openFolderAction").attr("onClick","gui.Shell.showItemInFolder(powGlobals['engine'].path+'\\\\'+powGlobals['engine'].files[powGlobals['files']["+kj+"].index].path); $('#closeAction').trigger('click')");
		$("#openAction").show(0);
		$("#openFolderAction").show(0);
	} else {
		$("#openAction").hide(0);
		$("#openFolderAction").hide(0);
	}
	if (supportedVideo.indexOf($("#file"+kj).find(".filenames").text().split(".").pop().toLowerCase()) > -1) {
		// if the item is a video
		powGlobals.videos.some(function(el,ij) {
			if (el.index == powGlobals.files[kj].index) {
				$("#playAction").attr("onClick","wjs().playItem("+ij+"); $('#closeAction').trigger('click'); $('html, body').animate({ scrollTop: 0 }, 'slow'); playEl("+kj+"); $('body').css('overflow-y','hidden')");
				$("#copyStream").attr("onClick","gui.Clipboard.get().set('http://localhost:'+powGlobals['engine'].server.address().port+'/"+powGlobals.files[kj].index+"','text'); $('#closeAction').trigger('click')");
				$("#playAction").show(0);
				$("#copyStream").show(0);
				return false;
			}
		});
	} else {
		$("#playAction").hide(0);
		$("#copyStream").hide(0);
	}
	$("#open-file-settings").trigger("click");
}

function goBack(nextTorrent) {
	if (peerInterval) clearInterval(peerInterval);
	if (delaySetDownload) clearTimeout(delaySetDownload);
	savedHistory = 0;
	pitem["#webchimera"] = 0;
	if (typeof nextTorrent === 'undefined') {
		window.scrollTo(0, 0);
		wjs().setOpeningText("Stopping");
		wjs().emitJsMessage("[tor-data-but]0");
		wjs().emitJsMessage("[refresh-disabled]");
		wjs().fullscreen(false);
		$("#header_container").css("display","none");
		$("body").css("overflow-y","hidden");
		if (parseInt($("#main").css("opacity")) == 0) $("#main").css("opacity","1");
		$('#main').css("display","table");
		document.getElementById('magnetLink').value = "";
		$('#player_wrapper').css("width","1px").css("min-height","1px");
		win.setMinimumSize(530, 440);

		if ((win.width < 530 && win.height < 440) || (win.width < 530 || win.height < 440)) {
			win.width = 530;
			win.height = 440;
		}

		if (onTop) {
			onTop = false;
			win.setAlwaysOnTop(false);
			wjs().emitJsMessage("[on-top]"+onTop);
		}

		if ($(window).height() < $("#main").height() && win.zoomLevel == 0) {
			if (win.zoomLevel > -1) win.zoomLevel = -1;
		} else if ($(window).width() < $("#main").width() && win.zoomLevel == 0) {
			if (win.zoomLevel > -1) win.zoomLevel = -1;
		} else if ($(window).width() > 730 && $(window).height() > 650 && win.zoomLevel == -1) {
			if (win.zoomLevel < 0) win.zoomLevel = 0;
		}
		$('#open-url').css('top', Math.round(($(window).height() - 187) / 2)+'px');
		wjs().clearPlaylist();
	} else {
		wjs().setOpeningText("Loading resource");
		wjs().emitJsMessage("[temp-splash]");
	}
	wjs().setDownloaded(0);
	if (powGlobals.engine) {
		isReady = 0;
		clearTimeout(downSpeed);
		powGlobals.engine.swarm.removeListener('wire', onmagnet)
		powGlobals.engine.server.close(function() {
			powGlobals.engine.remove(function() {
				powGlobals.engine.destroy();
				powGlobals = [];
				if (typeof nextTorrent !== 'undefined') {
					resetPowGlobals();
					runURL(nextTorrent,false);
				}
			});
		});
	} else {
		if (typeof nextTorrent !== 'undefined') {
			resetPowGlobals();
			runURL(nextTorrent);
		}
	}

	firstTime = 0;
	firstTimeEver = 1;
	if (typeof nextTorrent === 'undefined') win.title = "Powder Player";
}

function printHistory() {
	$("#history-list").html("");
	historyObject = JSON.parse(localStorage.history);
	oi = 0;
	if (historyObject[oi.toString()]) {
		generateHistory = "";
		for (oi = 0; historyObject[oi.toString()]; oi++) {
			generateHistory += '
'+historyObject[oi.toString()].title+'
';
		}
		if (oi < 7) $("#history-list").css('overflowY', 'auto');
		else $("#history-list").css('overflowY', 'scroll');
		$("#history-list").html(generateHistory);
	} else {
		generateHistory = "
Your history is empty, watch something first.";
		$("#history-list").css('overflowY', 'auto');
		$("#history-list").html(generateHistory);
	}
}<|endoftext|>


<commit_before>//  ██████╗ ██╗   ██╗███╗   ██╗     ██████╗ ██╗   ██╗███████╗██████╗ ██╗   ██╗
//  ██╔══██╗██║   ██║████╗  ██║    ██╔═══██╗██║   ██║██╔════╝██╔══██╗╚██╗ ██╔╝
//  ██████╔╝██║   ██║██╔██╗ ██║    ██║   ██║██║   ██║█████╗  ██████╔╝ ╚████╔╝
//  ██╔══██╗██║   ██║██║╚██╗██║    ██║▄▄ ██║██║   ██║██╔══╝  ██╔══██╗  ╚██╔╝
//  ██║  ██║╚██████╔╝██║ ╚████║    ╚██████╔╝╚██████╔╝███████╗██║  ██║   ██║
//  ╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═══╝     ╚══▀▀═╝  ╚═════╝ ╚══════╝╚═╝  ╚═╝   ╚═╝
//
// Send a Native Query to the datastore and gracefully handle errors.

var _ = require('lodash');
var PG = require('machinepack-postgresql');
var releaseConnection = require('../connection/release-connection');

module.exports = function runQuery(options, cb) {
  //  ╦  ╦╔═╗╦  ╦╔╦╗╔═╗╔╦╗╔═╗  ┌─┐┌─┐┌┬┐┬┌─┐┌┐┌┌─┐
  //  ╚╗╔╝╠═╣║  ║ ║║╠═╣ ║ ║╣   │ │├─┘ │ ││ ││││└─┐
  //   ╚╝ ╩ ╩╩═╝╩═╩╝╩ ╩ ╩ ╚═╝  └─┘┴   ┴ ┴└─┘┘└┘└─┘
  if (_.isUndefined(options) || !_.isPlainObject(options)) {
    throw new Error('Invalid options argument. Options must contain: connection, nativeQuery, and leased.');
  }

  if (!_.has(options, 'connection') || !_.isObject(options.connection)) {
    throw new Error('Invalid option used in options argument. Missing or invalid connection.');
  }

  if (!_.has(options, 'nativeQuery')) {
    throw new Error('Invalid option used in options argument. Missing or invalid nativeQuery.');
  }

  //  ╦═╗╦ ╦╔╗╔  ┌┐┌┌─┐┌┬┐┬┬  ┬┌─┐  ┌─┐ ┬ ┬┌─┐┬─┐┬ ┬
  //  ╠╦╝║ ║║║║  │││├─┤ │ │└┐┌┘├┤   │─┼┐│ │├┤ ├┬┘└┬┘
  //  ╩╚═╚═╝╝╚╝  ┘└┘┴ ┴ ┴ ┴ └┘ └─┘  └─┘└└─┘└─┘┴└─ ┴
  PG.sendNativeQuery({
    connection: options.connection,
    nativeQuery: options.nativeQuery
  })
  .exec({
    // If there was an error, check if the connection should be
    // released back into the pool automatically.
    error: function error(err) {
      if (!options.disconnectOnError) {
        return cb(err);
      }

      releaseConnection(options.connection, options.leased, function releaseConnectionCb(err) {
        return cb(err);
      });
    },
    // If the query failed, try and parse it into a normalized format and
    // release the connection if needed.
    queryFailed: function queryFailed(report) {
      // Parse the native query error into a normalized format
      var parsedError;
      try {
        parsedError = PG.parseNativeQueryError({
          nativeQueryError: report.error
        }).execSync();
      } catch (e) {
        if (!options.disconnectOnError) {
          return cb(e);
        }

        releaseConnection(options.connection, function releaseConnectionCb() {
          return cb(e);
        });
        return;
      }

      // If the catch all error was used, return an error instance instead of
      // the footprint.
      var catchAllError = false;

      if (parsedError.footprint.identity === 'catchall') {
        catchAllError = true;
      }

      if (!options.disconnectOnError) {
        if (catchAllError) {
          return cb(report.error);
        }

        return cb(parsedError);
      }

      // If this shouldn't disconnect the connection, just return the normalized
      // error with the footprint.
      if (!options.disconnectOnError) {
        if (catchAllError) {
          return cb(report.error);
        }

        return cb(parsedError);
      }

      releaseConnection(options.connection, false, function releaseConnectionCb() {
        if (catchAllError) {
          return cb(report.error);
        }

        return cb(parsedError);
      });
    },
    success: function success(report) {
      //  ╔═╗╔═╗╦═╗╔═╗╔═╗  ┌─┐ ┬ ┬┌─┐┬─┐┬ ┬  ┬─┐┌─┐┌─┐┬ ┬┬ ┌┬┐┌─┐
      //  ╠═╝╠═╣╠╦╝╚═╗║╣   │─┼┐│ │├┤ ├┬┘└┬┘  ├┬┘├┤ └─┐│ ││  │ └─┐
      //  ╩  ╩ ╩╩╚═╚═╝╚═╝  └─┘└└─┘└─┘┴└─ ┴   ┴└─└─┘└─┘└─┘┴─┘┴ └─┘
      // If there was a query type given, parse the results.
      var queryResults = report.result;
      if (options.queryType) {
        try {
          queryResults = PG.parseNativeQueryResult({
            queryType: options.queryType,
            nativeQueryResult: report.result
          }).execSync();
        } catch (e) {
          return cb(e);
        }
      }

      return cb(null, queryResults);
    }
  });
};
<commit_msg>remove duplicate logic<commit_after>//  ██████╗ ██╗   ██╗███╗   ██╗     ██████╗ ██╗   ██╗███████╗██████╗ ██╗   ██╗
//  ██╔══██╗██║   ██║████╗  ██║    ██╔═══██╗██║   ██║██╔════╝██╔══██╗╚██╗ ██╔╝
//  ██████╔╝██║   ██║██╔██╗ ██║    ██║   ██║██║   ██║█████╗  ██████╔╝ ╚████╔╝
//  ██╔══██╗██║   ██║██║╚██╗██║    ██║▄▄ ██║██║   ██║██╔══╝  ██╔══██╗  ╚██╔╝
//  ██║  ██║╚██████╔╝██║ ╚████║    ╚██████╔╝╚██████╔╝███████╗██║  ██║   ██║
//  ╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═══╝     ╚══▀▀═╝  ╚═════╝ ╚══════╝╚═╝  ╚═╝   ╚═╝
//
// Send a Native Query to the datastore and gracefully handle errors.

var _ = require('lodash');
var PG = require('machinepack-postgresql');
var releaseConnection = require('../connection/release-connection');

module.exports = function runQuery(options, cb) {
  //  ╦  ╦╔═╗╦  ╦╔╦╗╔═╗╔╦╗╔═╗  ┌─┐┌─┐┌┬┐┬┌─┐┌┐┌┌─┐
  //  ╚╗╔╝╠═╣║  ║ ║║╠═╣ ║ ║╣   │ │├─┘ │ ││ ││││└─┐
  //   ╚╝ ╩ ╩╩═╝╩═╩╝╩ ╩ ╩ ╚═╝  └─┘┴   ┴ ┴└─┘┘└┘└─┘
  if (_.isUndefined(options) || !_.isPlainObject(options)) {
    throw new Error('Invalid options argument. Options must contain: connection, nativeQuery, and leased.');
  }

  if (!_.has(options, 'connection') || !_.isObject(options.connection)) {
    throw new Error('Invalid option used in options argument. Missing or invalid connection.');
  }

  if (!_.has(options, 'nativeQuery')) {
    throw new Error('Invalid option used in options argument. Missing or invalid nativeQuery.');
  }

  //  ╦═╗╦ ╦╔╗╔  ┌┐┌┌─┐┌┬┐┬┬  ┬┌─┐  ┌─┐ ┬ ┬┌─┐┬─┐┬ ┬
  //  ╠╦╝║ ║║║║  │││├─┤ │ │└┐┌┘├┤   │─┼┐│ │├┤ ├┬┘└┬┘
  //  ╩╚═╚═╝╝╚╝  ┘└┘┴ ┴ ┴ ┴ └┘ └─┘  └─┘└└─┘└─┘┴└─ ┴
  PG.sendNativeQuery({
    connection: options.connection,
    nativeQuery: options.nativeQuery
  })
  .exec({
    // If there was an error, check if the connection should be
    // released back into the pool automatically.
    error: function error(err) {
      if (!options.disconnectOnError) {
        return cb(err);
      }

      releaseConnection(options.connection, options.leased, function releaseConnectionCb(err) {
        return cb(err);
      });
    },
    // If the query failed, try and parse it into a normalized format and
    // release the connection if needed.
    queryFailed: function queryFailed(report) {
      // Parse the native query error into a normalized format
      var parsedError;
      try {
        parsedError = PG.parseNativeQueryError({
          nativeQueryError: report.error
        }).execSync();
      } catch (e) {
        if (!options.disconnectOnError) {
          return cb(e);
        }

        releaseConnection(options.connection, function releaseConnectionCb() {
          return cb(e);
        });
        return;
      }

      // If the catch all error was used, return an error instance instead of
      // the footprint.
      var catchAllError = false;

      if (parsedError.footprint.identity === 'catchall') {
        catchAllError = true;
      }

      // If this shouldn't disconnect the connection, just return the normalized
      // error with the footprint.
      if (!options.disconnectOnError) {
        if (catchAllError) {
          return cb(report.error);
        }

        return cb(parsedError);
      }

      releaseConnection(options.connection, false, function releaseConnectionCb() {
        if (catchAllError) {
          return cb(report.error);
        }

        return cb(parsedError);
      });
    },
    success: function success(report) {
      //  ╔═╗╔═╗╦═╗╔═╗╔═╗  ┌─┐ ┬ ┬┌─┐┬─┐┬ ┬  ┬─┐┌─┐┌─┐┬ ┬┬ ┌┬┐┌─┐
      //  ╠═╝╠═╣╠╦╝╚═╗║╣   │─┼┐│ │├┤ ├┬┘└┬┘  ├┬┘├┤ └─┐│ ││  │ └─┐
      //  ╩  ╩ ╩╩╚═╚═╝╚═╝  └─┘└└─┘└─┘┴└─ ┴   ┴└─└─┘└─┘└─┘┴─┘┴ └─┘
      // If there was a query type given, parse the results.
      var queryResults = report.result;
      if (options.queryType) {
        try {
          queryResults = PG.parseNativeQueryResult({
            queryType: options.queryType,
            nativeQueryResult: report.result
          }).execSync();
        } catch (e) {
          return cb(e);
        }
      }

      return cb(null, queryResults);
    }
  });
};
<|endoftext|>


<commit_before>let status_label = {running: 'success', 'shut off': 'danger', 'paused': 'info'};

function enum_virsh() {
    $('.computer').each(function(i, a) {
        ws.emit('enum virsh', {device: a.id});
    });
}

function buttons(device) {
    let btn = '
';
    btn += '<button id="{}:start" type="button" class="btn btn-sm btn-success vm-control">Start</button>';
    btn += '<button id="{}:shutdown" type="button" class="btn btn-sm btn-danger vm-control">Stop</button>';
    btn += '<button id="{}:restart" type="button" class="btn btn-sm btn-warning vm-control">Restart</button>';
    btn += '<button id="{}:save" type="button" class="btn btn-sm btn-primary vm-control">Save</button>';
    btn += '<button id="{}:restore" type="button" class="btn btn-sm btn-info vm-control">Restore</button>';
    btn += '<button id="{}:suspend" type="button" class="btn btn-sm btn-default vm-control">Pause</button>';
    btn += '<button id="{}:resume" type="button" class="btn btn-sm btn-primary vm-control">Resume</button>';
    btn += '
';
    return btn.replace(/{}/g, device);
}

$('body').on('click', 'button.vm-control', function(a) {
    let s = a.target.id.split(':');
    ws.emit('vm ctrl', {
        device: s[0],
        vm: s[1],
        action: s[2]
    });
    setInterval(enum_virsh, 3000);
    setInterval(enum_virsh, 5000);
});

ws.on('vms', function(data) {
    let device = $('#' + data.device + '-table');
    device.html('');
    $.each(data.vms, function(a, b) {
        let status = '' + b[1] + '';
        device.append('
' + b[0] + '	' + status + '	' + buttons(data.device + ':' + b[0]) + '
');
    });
});

$('.refresh-vms').click(function() {
    enum_virsh();
    message({content: 'Refreshing...', class: 'alert-info'});
});

enum_virsh();
setInterval(enum_virsh, 15000);
<commit_msg>Fixes to virsh<commit_after>let status_label = {running: 'success', 'shut off': 'danger', 'paused': 'info'};

function enum_virsh() {
    $('.computer').each(function(i, a) {
        ws.emit('enum virsh', {device: a.id});
    });
}

function buttons(device, state) {
    let btn = '
';
    if (state == "running") {
        btn += '<button id="{}:save" type="button" class="btn btn-sm btn-primary vm-control">Save</button>';
        btn += '<button id="{}:suspend" type="button" class="btn btn-sm btn-default vm-control">Pause</button>';
    } else if (state == "paused") {
        btn += '<button id="{}:resume" type="button" class="btn btn-sm btn-primary vm-control">Resume</button>';
    } else {
        btn += '<button id="{}:start" type="button" class="btn btn-sm btn-success vm-control">Start</button>';
        btn += '<button id="{}:restore" type="button" class="btn btn-sm btn-info vm-control">Restore</button>';
    }
    btn += '<button id="{}:shutdown" type="button" class="btn btn-sm btn-danger vm-control">Stop</button>';
    btn += '<button id="{}:restart" type="button" class="btn btn-sm btn-warning vm-control">Restart</button>';
    btn += '
';
    return btn.replace(/{}/g, device);
}

$('body').on('click', 'button.vm-control', function(a) {
    let s = a.target.id.split(':');
    ws.emit('vm ctrl', {
        device: s[0],
        vm: s[1],
        action: s[2]
    });
    setInterval(enum_virsh, 3000);
    setInterval(enum_virsh, 5000);
});

ws.on('vms', function(data) {
    let device = $('#' + data.device + '-table');
    device.html('');
    $.each(data.vms, function(a, b) {
        let status = '' + b[1] + '';
        device.append('
' + b[0] + '	' + status + '	' + buttons(data.device + ':' + b[0], b[1]) + '
');
    });
});

$('.refresh-vms').click(function() {
    enum_virsh();
    message({content: 'Refreshing...', class: 'alert-info'});
});

enum_virsh();
setInterval(enum_virsh, 15000);
<|endoftext|>


<commit_before>/**
 * 产品订购之选择用户
 */
SelectUserWindow = Ext.extend(Ext.Window, {
	userGrid: null,
	store: null,
	constructor: function(){
	    this.store = new Ext.data.GroupingStore({
            reader: new Ext.data.ArrayReader({}, [
       	       {name: 'user_id'},
    	       {name: 'user_type'},
    	       {name: 'device_code'}
    	    ]),
            data: [
                ['000001',"OTT","222222222222"],
    		    ['000001',"OTT","111111111111"],
    		    ['000001',"OTT","111111111111"],
       		    ['000001',"BAND","tommy123"]
       	    ],
            groupField:'user_type'
        });

	    var sm = new Ext.grid.CheckboxSelectionModel();
		this.userGrid = new Ext.grid.GridPanel({
			store: this.store,
	        columns: [sm,
	            {id: 'autoExpandColumn',menuDisabled: true, align: 'left', header: "终端信息", sortable: false, dataIndex: 'device_code'},
	            {menuDisabled: true, hidden: true,width: 20, align: 'left', header: "类型", sortable: false, dataIndex: 'user_type'}
	        ],
	        view: new Ext.grid.GroupingView({
	            forceFit:true,
	            groupTextTpl: 'A产品，共{[values.rs.length]} 个终端，已选 0个'
	        }),
	        sm: sm,
	        width: 700,
	        border: false,
	        autoExpandColumn: 'autoExpandColumn',
	        height: 450,
	        animCollapse: false,
	        tbar: [{
	        	xtype: 'textfield',
	        	emptyText: 'filter..',
	        	enableKeyEvents: true,
	        	id: 'txtFilterInput',
	        	width: 180,
	        	listeners: {
	        		scope: this,
	        		specialKey: function(field, e){
	        			if (e.getKey() == e.ENTER) {
	        				this.doFilterStoreData(field);
	        	        }
	        		}
	        	}
	        },' ',{
	        	iconCls: 'icon-del',
	        	hidden: true,
	        	id: 'btnClearFilter',
	        	text: '清除过滤',
	        	scope: this,
	        	handler: function(){
	        		var field = Ext.getCmp("txtFilterInput");
	        		field.setValue("");
	        		this.doFilterStoreData(field);
	        	}
	        },' ',{
	        	iconCls: 'icon-collapse-all',
	        	scope: this,
	        	handler: function(){
	        		this.userGrid.getView().toggleAllGroups();
	        	}
	        }]
		});

		// Window 构造
		return SelectUserWindow.superclass.constructor.call(this, {
			layout: "fit",
			title: "选择订购的用户",
			width: 300,
			height: 400,
			resizable: false,
			iconCls: 'icon-edit-user',
			maximizable: false,
			closeAction: 'hide',
			minimizable: false,
			items: [this.userGrid]
		});
	},
	doFilterStoreData: function(field){
		var v = field.getValue().trim();
		if(v){
			this.store.filterBy(function(r){
				return new RegExp("^.*" + field.getValue()+".*$").test(r.get("device_code"));
			}, this);
			Ext.getCmp("btnClearFilter").setVisible(true);
		}else{
			this.store.clearFilter();
			Ext.getCmp("btnClearFilter").setVisible(false);
		}
	}
});

/**
 * 转移支付
 */
TransferPayWindow = Ext.extend(Ext.Window, {
	constructor: function(){
		// Window 构造
		return TransferPayWindow.superclass.constructor.call(this, {
			layout: "fit",
			title: "转移支付明细",
			width: 500,
			height: 300,
			resizable: false,
			iconCls: 'icon-pay',
			maximizable: false,
			closeAction: 'hide',
			minimizable: false,
			items: []
		});
	}
});

<commit_msg>a test for git<commit_after>/**
 * 产品订购之选择用户
 */
SelectUserWindow = Ext.extend(Ext.Window, {
	userGrid: null,
	store: null,
	constructor: function(){
	    this.store = new Ext.data.GroupingStore({
            reader: new Ext.data.ArrayReader({}, [
       	       {name: 'user_id'},
    	       {name: 'user_type'},
    	       {name: 'device_code'}
    	    ]),
            data: [
                ['000001',"OTT","222222222222"],
    		    ['000001',"OTT","111111111111"],
    		    ['000001',"OTT","111111111111"],
       		    ['000001',"BAND","tommy123"]
       	    ],
            groupField:'user_type'
        });

	    var sm = new Ext.grid.CheckboxSelectionModel();
		this.userGrid = new Ext.grid.GridPanel({
			store: this.store,
	        columns: [sm,
	            {id: 'autoExpandColumn',menuDisabled: true, align: 'left', header: "终端信息", sortable: false, dataIndex: 'device_code'},
	            {menuDisabled: true, hidden: true,width: 20, align: 'left', header: "类型", sortable: false, dataIndex: 'user_type'}
	        ],
	        view: new Ext.grid.GroupingView({
	            forceFit:true,
	            groupTextTpl: 'A产品，共{[values.rs.length]} 个终端，已选 0个'
	        }),
	        sm: sm,
	        width: 700,
	        border: false,
	        autoExpandColumn: 'autoExpandColumn',
	        height: 450,
	        animCollapse: false,
	        tbar: [{
	        	xtype: 'textfield',
	        	emptyText: 'filter..',
	        	enableKeyEvents: true,
	        	id: 'txtFilterInput',
	        	width: 180,
	        	listeners: {
	        		scope: this,
	        		specialKey: function(field, e){
	        			if (e.getKey() == e.ENTER) {
	        				this.doFilterStoreData(field);
	        	        }
	        		}
	        	}
	        },' ',{
	        	iconCls: 'icon-del',
	        	hidden: true,
	        	id: 'btnClearFilter',
	        	text: '清除过滤',
	        	scope: this,
	        	handler: function(){
	        		var field = Ext.getCmp("txtFilterInput");
	        		field.setValue("");
	        		this.doFilterStoreData(field);
	        	}
	        },' ',{
	        	iconCls: 'icon-collapse-all',
	        	scope: this,
	        	handler: function(){
	        		this.userGrid.getView().toggleAllGroups();
	        	}
	        }]
		});

		// Window 构造
		return SelectUserWindow.superclass.constructor.call(this, {
			layout: "fit",
			title: "选择订购的用户",
			width: 300,
			height: 400,
			resizable: false,
			iconCls: 'icon-edit-user',
			maximizable: false,
			closeAction: 'hide',
			minimizable: false,
			items: [this.userGrid]
		});
	},
	doFilterStoreData: function(field){
		var v = field.getValue().trim();
		if(v){
			this.store.filterBy(function(r){
				return new RegExp("^.*" + field.getValue()+".*$").test(r.get("device_code"));
			}, this);
			Ext.getCmp("btnClearFilter").setVisible(true);
		}else{
			this.store.clearFilter();
			Ext.getCmp("btnClearFilter").setVisible(false);
		}
	}
});

/**
 * 转移支付
 */
TransferPayWindow = Ext.extend(Ext.Window, {
	constructor: function(){
		// Window 构造
		return TransferPayWindow.superclass.constructor.call(this, {
			layout: "fit",
			title: "转移支付明细哈哈哈哈哈哈",
			width: 500,
			height: 300,
			resizable: false,
			iconCls: 'icon-pay',
			maximizable: false,
			closeAction: 'hide',
			minimizable: false,
			items: []
		});
	}
});

<|endoftext|>


<commit_before>/**
 * Project
 * @namespace crowdsource.template.services
 */
(function () {
    'use strict';

    angular
        .module('crowdsource.template.services')
        .factory('Template', Template);

    Template.$inject = ['$cookies', '$http', '$q', '$sce', 'HttpService', '$templateCache'];

    /**
     * @namespace Template
     * @returns {Factory}
     */

    function Template($cookies, $http, $q, $sce, HttpService, $templateCache) {
        /**
         * @name Template
         * @desc The Factory to be returned
         */
        var Template = {
            getCategories: getCategories,
            getTemplateComponents: getTemplateComponents,
            addItem: addItem,
            updateItem: updateItem,
            deleteItem: deleteItem,
            getTemplate: getTemplate
        };

        return Template;

        function getCategories() {
            return $http({
                url: '/api/category/',
                method: 'GET'
            });
        }

        function getTemplate(item_type) {
            var def = $q.defer();
            var template = '';
            template = $templateCache.get(item_type+".html");
            if (typeof template === "undefined") {
                $http.get("/static/templates/template/components/"+item_type+".html")
                    .success(function (data) {
                        $templateCache.put(item_type+".html", data);
                        def.resolve(data);
                    });
            } else {
                def.resolve(template);
            }
            return def.promise;
        }

        function getTemplateComponents(scope) {

            var templateComponents = [
                {
                    name: "Instructions",
                    icon: 'title',
                    type: 'instructions',
                    tooltip: "Instructions",
                    role: 'display',
                    watch_fields: ['aux_attributes', 'position'],
                    aux_attributes: {
                        question: {
                            value: "Instructions",
                            data_source: null
                        }
                    },
                    position: null,
                    required: false
                },
                {
                    name: "Text",
                    icon: 'text_fields',
                    type: 'text',
                    sub_type: 'text',
                    tooltip: "Text Input",
                    role: 'input',
                    watch_fields: ['aux_attributes', 'type', 'sub_type', 'position', 'name', 'required'],
                    aux_attributes: {
                        question: {
                            value: "Untitled Question",
                            data_source: null
                        },
                        pattern: null,
                        max_length: null,
                        min_length: null,
                        placeholder: 'text field'
                    },
                    position: null,
                    required: true

                },
                {
                    name: "Checkbox",
                    icon: 'check_box',
                    type: 'checkbox',
                    tooltip: "Check Box",
                    role: 'input',
                    watch_fields: ['aux_attributes', 'type', 'position', 'name', 'required'],
                    aux_attributes: {
                        question: {
                            value: "Untitled Question",
                            data_source: null
                        },
                        layout: 'column',
                        options: [
                            {
                                value: 'Option 1',
                                data_source: null,
                                position: 1
                            },
                            {
                                value: 'Option 2',
                                data_source: null,
                                position: 2
                            }
                        ],
                        shuffle_options: false
                    },
                    position: null,
                    required: true
                },
                {

                    name: "Radio Button",
                    icon: 'radio_button_checked',
                    type: 'radio',
                    tooltip: "Radio Button",
                    layout: 'column',
                    role: 'input',
                    data_source: null,
                    watch_fields: ['aux_attributes', 'type', 'position', 'name', 'required'],
                    aux_attributes: {
                        question: {
                            value: "Untitled Question",
                            data_source: null
                        },
                        layout: 'column',
                        options: [
                            {
                                value: 'Option 1',
                                data_source: null,
                                position: 1
                            },
                            {
                                value: 'Option 2',
                                data_source: null,
                                position: 2
                            }
                        ],
                        shuffle_options: false
                    },
                    position: null,
                    required: true
                },
                {
                    name: "Select List",
                    icon: 'list',
                    type: 'select_list',
                    tooltip: "Select List",
                    layout: 'column',
                    role: 'input',
                    data_source: null,
                    watch_fields: ['aux_attributes', 'type', 'position', 'name', 'required'],
                    aux_attributes: {
                        question: {
                            value: "Untitled Question",
                            data_source: null
                        },
                        layout: 'column',
                        options: [
                            {
                                value: 'Option 1',
                                data_source: null,
                                position: 1
                            },
                            {
                                value: 'Option 2',
                                data_source: null,
                                position: 2
                            }
                        ],
                        shuffle_options: false
                    },
                    position: null,
                    required: true
                },
                {
                    name: "Image",
                    icon: 'photo',
                    type: 'image',
                    tooltip: "Image Container",
                    role: 'display',
                    watch_fields: ['type', 'aux_attributes', 'position'],
                    aux_attributes: {
                        question: {
                            value: "Untitled Question",
                            data_source: null
                        },
                        src: '',
                        data_source: null
                    },
                    position: null,
                    required: false
                },
                {
                    name: "Audio",
                    icon: 'music_note',
                    type: 'audio',
                    tooltip: "Audio Container",
                    role: 'display',
                    watch_fields: ['type', 'aux_attributes', 'position'],
                    aux_attributes: {
                        question: {
                            value: "Untitled Question",
                            data_source: null
                        },
                        src: 'http://www.noiseaddicts.com/samples_1w72b820/3724.mp3',
                        data_source: null
                    },
                    position: null,
                    required: false
                },
                /*{
                 tooltip: "Video Container",
                 layout: 'column',
                 data_source: null,
                 role: 'display',
                 label: '',
                 name: "Video Container",
                 icon: 'play_circle_outline',
                 type: 'video'
                 },*/
                {
                    name: "Remote Content",
                    icon: 'code',
                    type: 'iframe',
                    tooltip: "Embed content from remote site",
                    role: 'display',
                    watch_fields: ['aux_attributes', 'position', 'name'],
                    position: null,
                    required: false,
                    aux_attributes: {
                        question: {
                            value: "Untitled Form",
                            data_source: null
                        },
                        src: 'http://www.noiseaddicts.com/',
                        data_source: null
                    }
                },
              // TODO: Remove this todo. File field here.
                {
                    name: "File",
                    icon: 'file_upload',
                    type: 'file_upload',
                    tooltip: "File Upload",
                    role: 'input',
                    watch_fields: ['aux_attributes', 'type', 'position', 'name', 'required'],
                    aux_attributes: {
                      url: '',
                      question: {
                          value: "Untitled Question",
                          data_source: null
                      }
                    },
                    position: null,
                    required: true
                },
            ];

            return templateComponents;
        }

        function addItem(data) {
            var settings = {
                url: '/api/template-item/',
                method: 'POST',
                data: data
            };
            return HttpService.doRequest(settings);
        }

        function updateItem(pk, data) {
            var settings = {
                url: '/api/template-item/' + pk + '/',
                method: 'PUT',
                data: data
            };
            return HttpService.doRequest(settings);
        }

        function deleteItem(pk) {
            var settings = {
                url: '/api/template-item/' + pk + '/',
                method: 'DELETE'
            };
            return HttpService.doRequest(settings);
        }
    }
})();
<commit_msg>Update template.service.js<commit_after>/**
 * Project
 * @namespace crowdsource.template.services
 */
(function () {
    'use strict';

    angular
        .module('crowdsource.template.services')
        .factory('Template', Template);

    Template.$inject = ['$cookies', '$http', '$q', '$sce', 'HttpService', '$templateCache'];

    /**
     * @namespace Template
     * @returns {Factory}
     */

    function Template($cookies, $http, $q, $sce, HttpService, $templateCache) {
        /**
         * @name Template
         * @desc The Factory to be returned
         */
        var Template = {
            getCategories: getCategories,
            getTemplateComponents: getTemplateComponents,
            addItem: addItem,
            updateItem: updateItem,
            deleteItem: deleteItem,
            getTemplate: getTemplate
        };

        return Template;

        function getCategories() {
            return $http({
                url: '/api/category/',
                method: 'GET'
            });
        }

        function getTemplate(item_type) {
            var def = $q.defer();
            var template = '';
            template = $templateCache.get(item_type+".html");
            if (typeof template === "undefined") {
                $http.get("/static/templates/template/components/"+item_type+".html")
                    .success(function (data) {
                        $templateCache.put(item_type+".html", data);
                        def.resolve(data);
                    });
            } else {
                def.resolve(template);
            }
            return def.promise;
        }

        function getTemplateComponents(scope) {

            var templateComponents = [
                {
                    name: "Instructions",
                    icon: 'title',
                    type: 'instructions',
                    tooltip: "Instructions",
                    role: 'display',
                    watch_fields: ['aux_attributes', 'position'],
                    aux_attributes: {
                        question: {
                            value: "Instructions",
                            data_source: null
                        }
                    },
                    position: null,
                    required: false
                },
                {
                    name: "Text",
                    icon: 'text_fields',
                    type: 'text',
                    sub_type: 'text',
                    tooltip: "Text Input",
                    role: 'input',
                    watch_fields: ['aux_attributes', 'type', 'sub_type', 'position', 'name', 'required'],
                    aux_attributes: {
                        question: {
                            value: "Untitled Question",
                            data_source: null
                        },
                        pattern: null,
                        max_length: null,
                        min_length: null,
                        placeholder: 'text field'
                    },
                    position: null,
                    required: true

                },
                {
                    name: "Checkbox",
                    icon: 'check_box',
                    type: 'checkbox',
                    tooltip: "Check Box",
                    role: 'input',
                    watch_fields: ['aux_attributes', 'type', 'position', 'name', 'required'],
                    aux_attributes: {
                        question: {
                            value: "Untitled Question",
                            data_source: null
                        },
                        layout: 'column',
                        options: [
                            {
                                value: 'Option 1',
                                data_source: null,
                                position: 1
                            },
                            {
                                value: 'Option 2',
                                data_source: null,
                                position: 2
                            }
                        ],
                        shuffle_options: false
                    },
                    position: null,
                    required: true
                },
                {

                    name: "Radio Button",
                    icon: 'radio_button_checked',
                    type: 'radio',
                    tooltip: "Radio Button",
                    layout: 'column',
                    role: 'input',
                    data_source: null,
                    watch_fields: ['aux_attributes', 'type', 'position', 'name', 'required'],
                    aux_attributes: {
                        question: {
                            value: "Untitled Question",
                            data_source: null
                        },
                        layout: 'column',
                        options: [
                            {
                                value: 'Option 1',
                                data_source: null,
                                position: 1
                            },
                            {
                                value: 'Option 2',
                                data_source: null,
                                position: 2
                            }
                        ],
                        shuffle_options: false
                    },
                    position: null,
                    required: true
                },
                {
                    name: "Select List",
                    icon: 'list',
                    type: 'select_list',
                    tooltip: "Select List",
                    layout: 'column',
                    role: 'input',
                    data_source: null,
                    watch_fields: ['aux_attributes', 'type', 'position', 'name', 'required'],
                    aux_attributes: {
                        question: {
                            value: "Untitled Question",
                            data_source: null
                        },
                        layout: 'column',
                        options: [
                            {
                                value: 'Option 1',
                                data_source: null,
                                position: 1
                            },
                            {
                                value: 'Option 2',
                                data_source: null,
                                position: 2
                            }
                        ],
                        shuffle_options: false
                    },
                    position: null,
                    required: true
                },
                {
                    name: "Image",
                    icon: 'photo',
                    type: 'image',
                    tooltip: "Image Container",
                    role: 'display',
                    watch_fields: ['type', 'aux_attributes', 'position'],
                    aux_attributes: {
                        question: {
                            value: "Untitled Question",
                            data_source: null
                        },
                        src: '',
                        data_source: null
                    },
                    position: null,
                    required: false
                },
                {
                    name: "Audio",
                    icon: 'music_note',
                    type: 'audio',
                    tooltip: "Audio Container",
                    role: 'display',
                    watch_fields: ['type', 'aux_attributes', 'position'],
                    aux_attributes: {
                        question: {
                            value: "Untitled Question",
                            data_source: null
                        },
                        src: 'http://www.noiseaddicts.com/samples_1w72b820/3724.mp3',
                        data_source: null
                    },
                    position: null,
                    required: false
                },
                /*{
                 tooltip: "Video Container",
                 layout: 'column',
                 data_source: null,
                 role: 'display',
                 label: '',
                 name: "Video Container",
                 icon: 'play_circle_outline',
                 type: 'video'
                 },*/
                {
                    name: "Remote Content",
                    icon: 'code',
                    type: 'iframe',
                    tooltip: "Embed content from remote site",
                    role: 'display',
                    watch_fields: ['aux_attributes', 'position', 'name'],
                    position: null,
                    required: false,
                    aux_attributes: {
                        question: {
                            value: "Untitled Form",
                            data_source: null
                        },
                        src: 'http://www.noiseaddicts.com/',
                        data_source: null
                    }
                },
                {
                    name: "File",
                    icon: 'file_upload',
                    type: 'file_upload',
                    tooltip: "File Upload",
                    role: 'input',
                    watch_fields: ['aux_attributes', 'type', 'position', 'name', 'required'],
                    aux_attributes: {
                      url: '',
                      question: {
                          value: "Untitled Question",
                          data_source: null
                      }
                    },
                    position: null,
                    required: true
                },
            ];

            return templateComponents;
        }

        function addItem(data) {
            var settings = {
                url: '/api/template-item/',
                method: 'POST',
                data: data
            };
            return HttpService.doRequest(settings);
        }

        function updateItem(pk, data) {
            var settings = {
                url: '/api/template-item/' + pk + '/',
                method: 'PUT',
                data: data
            };
            return HttpService.doRequest(settings);
        }

        function deleteItem(pk) {
            var settings = {
                url: '/api/template-item/' + pk + '/',
                method: 'DELETE'
            };
            return HttpService.doRequest(settings);
        }
    }
})();
<|endoftext|>


<commit_before>define(
  'ephox.echo.api.AriaRegister',

  [
    'ephox.classify.Type',
    'ephox.compass.Arr',
    'ephox.compass.Obj',
    'ephox.echo.api.Styles',
    'ephox.epithet.Id',
    'ephox.highway.Merger',
    'ephox.peanut.Fun',
    'ephox.sugar.api.Attr',
    'ephox.sugar.api.Class',
    'ephox.sugar.api.Element',
    'ephox.sugar.api.Insert',
    'ephox.sugar.api.InsertAll'
  ],

  function (Type, Arr, Obj, Styles, Id, Merger, Fun, Attr, Class, Element, Insert, InsertAll) {
    var helpStyle = Styles.resolve('aria-help');
    var helpVisibleStyle = Styles.resolve('aria-help-visible');

    var roleDocument = function (element) {
      Attr.set(element, 'role', 'document');
    };

    var presentation = function (element) {
      // Note: aria-hidden=true says this element and all of its descendents are not percievable
      // https://www.w3.org/TR/wai-aria/states_and_properties#aria-hidden
      Attr.setAll(element, {
        'role': 'presentation',
        'aria-hidden': 'true'
      });
    };

    // https://www.w3.org/TR/wai-aria/roles#presentation
    var presentationRole = function (element) {
      Attr.set(element, 'role', 'presentation');
    };

    var editor = function (container, editor, label, ariaHelp, showHelpHint) {
      // Set role=region: https://www.w3.org/TR/wai-aria/roles#region
      // on editor for better user navigation modes, as it is mostly text content.
      // Better than role=application which constrains the reader navigation
      // - https://www.w3.org/TR/wai-aria/roles#application
      Attr.setAll(container, {
        'role': 'region',
        'aria-label': label
      });

      ariaHelp.each(function (helpText) {
        var aria = Element.fromTag('span');
        presentationRole(aria);
        Insert.append(aria, Element.fromText(helpText));
        var labelId = Id.generate('ephox-aria');
        Attr.set(aria, 'id', labelId);
        describedBy(editor, labelId);
        Class.add(aria, helpStyle);
        if (showHelpHint === true) Class.add(aria, helpVisibleStyle);
        Insert.append(container, aria);
      });

      // content attributes - surprisingly helps in both classic and inline
      var attrs = {
        'aria-multiline': 'true',
        'aria-label': label,
        title: label
      };

      Attr.setAll(editor, attrs);

      var destroy = function () {
        var removeFromEditor = Fun.curry(Attr.remove, editor);
        Arr.each(Obj.keys(attrs), removeFromEditor);
        removeFromEditor('aria-describedby');
      };

      return {
        destroy: destroy
      };
    };

    // Set the role 'group'
    var group = function (element) {
      Attr.set(element, 'role', 'group');
    };

    // Sets the role 'group', with a label
    var toolbar = function (element, label) {
      Attr.setAll(element, {
        'role': 'group',
        'aria-label': label
      });
    };

    var menu = function (element, label) {
      Attr.setAll(element, {
        'aria-label': label,
        'role': 'menu'
      });
    };

    var textButton = function (element, contentElement) {
      // Add 'button' roleto a pastry button, and 'presentation' role
      // to the contentElement that contains the button text.
      Attr.set(element, 'role', 'button');
      presentationRole(contentElement);
    };

    // Set the role 'button'
    var toolbarButton = function (element, label, hasPopup, isToggle) {
      Attr.setAll(element, {
        'role': 'button',
        'aria-label': label,
        'aria-haspopup': '' + hasPopup
      });
      if (isToggle) Attr.set(element, 'aria-pressed', 'false');
      if (hasPopup) Attr.set(element, 'aria-expanded', 'false');
    };

    // Set the role 'toolbar' and aria-label if provided
    var toolbarGroup = function (element, label) {
      // TODO: duplicated from 'ephox.polish.alien.Query', consolidate isEmpty();
      var isEmpty = function (val) {
        // TODO: Move to compass Arr and violin Strings
        return (val === null) || (val === undefined) || (val === '') || (Type.isArray(val) && val.length === 0);
      };
      // End TODO

      Attr.set(element, 'role', 'toolbar');

      // customer groups may have empty label, don't use it
      if (!isEmpty(label)) {
        Attr.set(element, 'aria-label', label);
      }
    };

    var menuItem = function (element, label, hasPopup) {
      var labelTxt = label.map(function (txt) {
        return { 'aria-label': txt };
      }).getOr({});

      Attr.setAll(element, Merger.merge(labelTxt, {
        'role': 'menuitem',
        'aria-haspopup': hasPopup.getOr(false)
      }));
    };

    var menuItemCheckbox = function (element) {
      Attr.setAll(element, {
        'role': 'menuitemcheckbox',
        'aria-checked': false
      });
    };

    var checkbox = function (element, label) {
      Attr.setAll(element, {
        'role': 'checkbox',
        'aria-label': label,
        'aria-checked': false
      });
    };

    var dialog = function (element, label) {
      Attr.setAll(element, {
        'role': 'dialog',
        'aria-label': label
      });
    };

    var button = function (element, label) {
      Attr.setAll(element, {
        'aria-label': label,
        'role': 'button'
      });
    };

    // return a container object with methods {element, field} containing an html field and label
    var labelledField = function (field, name, labelText) {
      var container = Element.fromTag('div');
      presentationRole(container);
      var id = name + Id.generate('');
      var label = Element.fromHtml('' + labelText + '');
      Attr.set(label, 'for', id);
      Attr.set(field, 'id', id);
      InsertAll.append(container, [ label, field ]);

      return {
        element: Fun.constant(container),
        field:   Fun.constant(field)
      };
    };

    var textarea = function (element) {
      Attr.setAll(element, {
        'aria-multiline': 'true',
        'role': 'textbox'
      });
    };

    var widget = function (element) {
      Attr.set(element, 'role', 'widget');
    };

    var listBox = function (element) {
      Attr.set(element, 'role', 'listbox');
    };

    var tabList = function (element) {
      Attr.set(element, 'role', 'tablist');
    };

    var tabButton = function (element, label) {
      Attr.setAll(element, {
        'aria-label': label,
        'role': 'tab'
      });
    };

    var tabPanel = function (element) {
      Attr.setAll(element, {
        'role': 'tabpanel'
      });
    };

    var linkTabToPanel = function (tab, panel) {
      var id = Id.generate('ephox-aria');
      Attr.set(panel, 'id', id);
      Attr.setAll(tab, {
        'aria-controls': id
      });
    };

    var describedBy = function (element, id) {
      Attr.set(element, 'aria-describedby', id);
    };

    var labelledBy = function (element, id) {
      Attr.set(element, 'aria-labelledby', id);
    };

    var live = function (element, id, _priority) {
      var priority = _priority ? _priority : 'polite';
      Attr.setAll(element, {
        'aria-live': priority,
        'id': id
      });
    };

    var controls = function (element, id) {
      Attr.set(element, 'aria-controls', id);
    };

    var required = function (element) {
      Attr.set(element, 'aria-required', 'true');
    };

    // TODO: Implement form ARIA support
    // var form = function (element, label) {
    //   throw 'Form ARIA support not implemented yet.';
    // };

    var label = function (element, label) {
      Attr.set(element, 'aria-label', label);
    };

    var option = function (element) {
      Attr.set(element, 'role', 'option');
    };

    // TODO: Implement link ARIA support
    // var link = function (element) {
    //   throw 'Link ARIA support not implemented yet.';
    // };

    // TODO: Implement other ARIA support
    // var other = function () {
    //   throw 'Other ARIA support not implemented yet.';
    // };

    var hidden = function (element, status) {
      Attr.set(element, 'aria-hidden', status);
    };

    return {
      document: roleDocument,
      presentation: presentation,
      presentationRole: presentationRole,
      controls: controls,
      editor: editor,
      group: group,
      toolbar: toolbar,
      toolbarGroup: toolbarGroup,
      toolbarButton: toolbarButton,
      textButton: textButton,
      menu: menu,
      menuItem: menuItem,
      menuItemCheckbox: menuItemCheckbox,
      checkbox: checkbox,
      dialog: dialog,
      button: button,
      labelledField: labelledField,
      textarea: textarea,
      label: label,
      widget: widget,
      option: option,
      listBox: listBox,
      live: live,
      tabList: tabList,
      tabButton: tabButton,
      tabPanel: tabPanel,
      linkTabToPanel: linkTabToPanel,
      describedBy: describedBy,
      labelledBy: labelledBy,
      required: required,
      hidden: hidden
    };
  }
);<commit_msg>TBIO-4293: remove the attribute instead of setting to false (same semantics)<commit_after>define(
  'ephox.echo.api.AriaRegister',

  [
    'ephox.classify.Type',
    'ephox.compass.Arr',
    'ephox.compass.Obj',
    'ephox.echo.api.Styles',
    'ephox.epithet.Id',
    'ephox.highway.Merger',
    'ephox.peanut.Fun',
    'ephox.sugar.api.Attr',
    'ephox.sugar.api.Class',
    'ephox.sugar.api.Element',
    'ephox.sugar.api.Insert',
    'ephox.sugar.api.InsertAll'
  ],

  function (Type, Arr, Obj, Styles, Id, Merger, Fun, Attr, Class, Element, Insert, InsertAll) {
    var helpStyle = Styles.resolve('aria-help');
    var helpVisibleStyle = Styles.resolve('aria-help-visible');

    var roleDocument = function (element) {
      Attr.set(element, 'role', 'document');
    };

    var presentation = function (element) {
      // Note: aria-hidden=true says this element and all of its descendents are not percievable
      // https://www.w3.org/TR/wai-aria/states_and_properties#aria-hidden
      Attr.setAll(element, {
        'role': 'presentation',
        'aria-hidden': 'true'
      });
    };

    // https://www.w3.org/TR/wai-aria/roles#presentation
    var presentationRole = function (element) {
      Attr.set(element, 'role', 'presentation');
    };

    var editor = function (container, editor, label, ariaHelp, showHelpHint) {
      // Set role=region: https://www.w3.org/TR/wai-aria/roles#region
      // on editor for better user navigation modes, as it is mostly text content.
      // Better than role=application which constrains the reader navigation
      // - https://www.w3.org/TR/wai-aria/roles#application
      Attr.setAll(container, {
        'role': 'region',
        'aria-label': label
      });

      ariaHelp.each(function (helpText) {
        var aria = Element.fromTag('span');
        presentationRole(aria);
        Insert.append(aria, Element.fromText(helpText));
        var labelId = Id.generate('ephox-aria');
        Attr.set(aria, 'id', labelId);
        describedBy(editor, labelId);
        Class.add(aria, helpStyle);
        if (showHelpHint === true) Class.add(aria, helpVisibleStyle);
        Insert.append(container, aria);
      });

      // content attributes - surprisingly helps in both classic and inline
      var attrs = {
        'aria-multiline': 'true',
        'aria-label': label,
        title: label
      };

      Attr.setAll(editor, attrs);

      var destroy = function () {
        var removeFromEditor = Fun.curry(Attr.remove, editor);
        Arr.each(Obj.keys(attrs), removeFromEditor);
        removeFromEditor('aria-describedby');
      };

      return {
        destroy: destroy
      };
    };

    // Set the role 'group'
    var group = function (element) {
      Attr.set(element, 'role', 'group');
    };

    // Sets the role 'group', with a label
    var toolbar = function (element, label) {
      Attr.setAll(element, {
        'role': 'group',
        'aria-label': label
      });
    };

    var menu = function (element, label) {
      Attr.setAll(element, {
        'aria-label': label,
        'role': 'menu'
      });
    };

    var textButton = function (element, contentElement) {
      // Add 'button' roleto a pastry button, and 'presentation' role
      // to the contentElement that contains the button text.
      Attr.set(element, 'role', 'button');
      presentationRole(contentElement);
    };

    // Set the role 'button'
    var toolbarButton = function (element, label, hasPopup, isToggle) {
      Attr.setAll(element, {
        'role': 'button',
        'aria-label': label,
        'aria-haspopup': '' + hasPopup
      });
      if (isToggle) Attr.set(element, 'aria-pressed', 'false');
      if (hasPopup) Attr.set(element, 'aria-expanded', 'false');
    };

    // Set the role 'toolbar' and aria-label if provided
    var toolbarGroup = function (element, label) {
      // TODO: duplicated from 'ephox.polish.alien.Query', consolidate isEmpty();
      var isEmpty = function (val) {
        // TODO: Move to compass Arr and violin Strings
        return (val === null) || (val === undefined) || (val === '') || (Type.isArray(val) && val.length === 0);
      };
      // End TODO

      Attr.set(element, 'role', 'toolbar');

      // customer groups may have empty label, don't use it
      if (!isEmpty(label)) {
        Attr.set(element, 'aria-label', label);
      }
    };

    var menuItem = function (element, label, hasPopup) {
      var labelTxt = label.map(function (txt) {
        return { 'aria-label': txt };
      }).getOr({});

      Attr.setAll(element, Merger.merge(labelTxt, {
        'role': 'menuitem',
        'aria-haspopup': hasPopup.getOr(false)
      }));
    };

    var menuItemCheckbox = function (element) {
      Attr.setAll(element, {
        'role': 'menuitemcheckbox',
        'aria-checked': false
      });
    };

    var checkbox = function (element, label) {
      Attr.setAll(element, {
        'role': 'checkbox',
        'aria-label': label,
        'aria-checked': false
      });
    };

    var dialog = function (element, label) {
      Attr.setAll(element, {
        'role': 'dialog',
        'aria-label': label
      });
    };

    var button = function (element, label) {
      Attr.setAll(element, {
        'aria-label': label,
        'role': 'button'
      });
    };

    // return a container object with methods {element, field} containing an html field and label
    var labelledField = function (field, name, labelText) {
      var container = Element.fromTag('div');
      presentationRole(container);
      var id = name + Id.generate('');
      var label = Element.fromHtml('' + labelText + '');
      Attr.set(label, 'for', id);
      Attr.set(field, 'id', id);
      InsertAll.append(container, [ label, field ]);

      return {
        element: Fun.constant(container),
        field:   Fun.constant(field)
      };
    };

    var textarea = function (element) {
      Attr.setAll(element, {
        'aria-multiline': 'true',
        'role': 'textbox'
      });
    };

    var widget = function (element) {
      Attr.set(element, 'role', 'widget');
    };

    var listBox = function (element) {
      Attr.set(element, 'role', 'listbox');
    };

    var tabList = function (element) {
      Attr.set(element, 'role', 'tablist');
    };

    var tabButton = function (element, label) {
      Attr.setAll(element, {
        'aria-label': label,
        'role': 'tab'
      });
    };

    var tabPanel = function (element) {
      Attr.setAll(element, {
        'role': 'tabpanel'
      });
    };

    var linkTabToPanel = function (tab, panel) {
      var id = Id.generate('ephox-aria');
      Attr.set(panel, 'id', id);
      Attr.setAll(tab, {
        'aria-controls': id
      });
    };

    var describedBy = function (element, id) {
      Attr.set(element, 'aria-describedby', id);
    };

    var labelledBy = function (element, id) {
      Attr.set(element, 'aria-labelledby', id);
    };

    var live = function (element, id, _priority) {
      var priority = _priority ? _priority : 'polite';
      Attr.setAll(element, {
        'aria-live': priority,
        'id': id
      });
    };

    var controls = function (element, id) {
      Attr.set(element, 'aria-controls', id);
    };

    var required = function (element) {
      Attr.set(element, 'aria-required', 'true');
    };

    // TODO: Implement form ARIA support
    // var form = function (element, label) {
    //   throw 'Form ARIA support not implemented yet.';
    // };

    var label = function (element, label) {
      Attr.set(element, 'aria-label', label);
    };

    var option = function (element) {
      Attr.set(element, 'role', 'option');
    };

    // TODO: Implement link ARIA support
    // var link = function (element) {
    //   throw 'Link ARIA support not implemented yet.';
    // };

    // TODO: Implement other ARIA support
    // var other = function () {
    //   throw 'Other ARIA support not implemented yet.';
    // };

    var hidden = function (element, status) {
      if (status) {
        Attr.set(element, 'aria-hidden', status);
      } else {
        Attr.remove(element, 'aria-hidden'); // same as setting aria-hidden:false
      }
    };

    return {
      document: roleDocument,
      presentation: presentation,
      presentationRole: presentationRole,
      controls: controls,
      editor: editor,
      group: group,
      toolbar: toolbar,
      toolbarGroup: toolbarGroup,
      toolbarButton: toolbarButton,
      textButton: textButton,
      menu: menu,
      menuItem: menuItem,
      menuItemCheckbox: menuItemCheckbox,
      checkbox: checkbox,
      dialog: dialog,
      button: button,
      labelledField: labelledField,
      textarea: textarea,
      label: label,
      widget: widget,
      option: option,
      listBox: listBox,
      live: live,
      tabList: tabList,
      tabButton: tabButton,
      tabPanel: tabPanel,
      linkTabToPanel: linkTabToPanel,
      describedBy: describedBy,
      labelledBy: labelledBy,
      required: required,
      hidden: hidden
    };
  }
);<|endoftext|>