/*-------------------------------------------------------------------------------
* Copyright (c) 2013, Perforce Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*-------------------------------------------------------------------------------*/
$(function() {
// urls come from the /configuration call
function getSwarmPath() {
return window.uiData.payload.swarmURL;
}
function getCommonsPath() {
return window.uiData.payload.commonsURL;
}
function getP4WebPath() {
return window.uiData.payload.p4webURL;
}
// ready?
$().ready(function() {
$.get("/api/configuration", null, function(resp) {
window.uiData = resp;
});
// remember?
$('#user_username').val($.cookie('username'));
$('#remember').prop('checked', $.cookie('remember') == 'true');
// advanced?
if (window.location.hash == "#advanced")
$('#advancedsearchform').click();
// q=...?
if (!!window.location.search && window.location.search.substr(0,3) == "?q=") {
var query = decodeURI(window.location.search.substr(3));
// make both "search text" inputs agree
$('#advancedsearchtext').val(query);
$('#searchtext').val(query);
startSearch();
}
// check out login status: /userid
$.ajax({
url : "/api/userid",
type : 'get',
error : function(req, status, err) {
showLogin();
},
success : function(resp) {
// getting a status means we are logged in
if (!!resp.status && resp.status.code == "200") {
$('#login').hide();
$('#username').show();
$('#userid').html(resp.payload.userId);
if (isSearching()) {
processPendingSearch();
}
} else {
showLogin();
}
}
});
});
// Setup drop down menu
$('.dropdown-toggle').dropdown();
// Fix input element click problem
$('.dropdown input, .dropdown label').click(function(e) {
e.stopPropagation();
});
$('.clickonenter').keypress(function(e) {
if (e.which == 13) {
$(this).blur();
$(this.getAttribute('enterkey')).click();
e.stopPropagation();
}
});
$('#advancedsearchform').click(function(e) {
// advanced search is active, toggle the input form
$("#advancedsearchform").addClass("active");
$("#searchform").removeClass("active");
$("#search").hide();
$("#advancedsearch").show();
});
$('#searchform').click(function(e) {
// advanced search is active, toggle the input form
$("#advancedsearchform").removeClass("active");
$("#searchform").addClass("active");
$("#advancedsearch").hide();
$("#search").show();
});
function isSearching() {
return $('#loading-indicator').is(':visible');
}
function startSearch() {
$('#loading-indicator').show();
$('#results-div').html("");
$('#search-errors').html("");
}
function endSearch() {
$('#loading-indicator').hide();
}
function getSwarmLink(dp, rev, change) {
return getSwarmPath() + "files" + dp.substr(1) + "?v=" + rev;
}
function getP4WebLink(dp, rev, change) {
return getP4WebPath() + dp + ((!!change) ? "?sr=" + change : "");
}
function getWebLink(dp, rev, change) {
// either p4web or swarm (preferred)
if (!!getSwarmPath())
return getSwarmLink(dp, rev, change);
else
return getP4WebLink(dp, rev, change);
}
function isCommonsPath(dp) {
return !!(dp.match(/^\/\/commons\/spaces\/[0-9]+\/files\//));
}
function getCommonsLink(dp, rev) {
var matches = dp.match(/^\/\/commons\/spaces\/([0-9]+)\/files\//m);
if (dp[dp.length - 1] == '/') {
return getCommonsPath() + "ui/space/" + matches[1]
+ "/files?spaceName=&path="
+ dp.substring(matches[0].length, dp.length - 1)
+ "&pathType=LOCAL";
} else {
return getCommonsPath() + "ui/file-details/space/" + matches[1]
+ "/LOCAL/" + dp.substr(matches[0].length)
+ "?spaceName=&rev=" + rev;
}
}
function makePath(dp, rev, change) {
return isCommonsPath(dp) ? getCommonsLink(dp, rev) : getWebLink(dp,
rev, change);
}
function getWebLinkIcon() {
// either p4web or swarm (preferred)
if (!!getSwarmPath())
return "img/swarm/favicon.ico";
else
return "img/logo.png";
}
function getChangeLink(change) {
if (!!getSwarmPath())
return getSwarmPath() + "changes/" + change;
else
return getP4WebPath() + change + "?ac=10";
}
function parseFiles(data) {
var ret = [];
for (i in data) {
var f = data[i];
ret.push({
filelink : makePath(f.depotFile, f.rev, f.change),
swarmlink : getWebLink(f.depotFile, f.rev, f.change),
swarmicon : getWebLinkIcon(),
commonslink : (isCommonsPath(f.depotFile) ? getCommonsLink(
f.depotFile, f.rev)
: undefined),
commonsicon : "img/commons/favicon.ico",
filename : f.depotFile.substr(f.depotFile
.lastIndexOf('/') + 1), // take the filename
pathlink : makePath(f.depotFile.substr(0, f.depotFile
.lastIndexOf('/') + 1), f.change),
path : f.depotFile.substr(0, f.depotFile
.lastIndexOf('/') + 1),
headAction : f.action,
revision : f.rev,
changelink : getChangeLink(f.change),
changelist : f.change,
date : $.timeago(new Date(f.time * 1000))
});
}
return ret;
}
var template = Handlebars.compile($("#files-template").html());
function addData(data) {
var total = data.length;
if (total >= 100)
total = "100+";
$('#results-count')
.html('Search returned ' + total + ' results.');
$('#results-div').html(template({
filedata : parseFiles(data)
}));
}
function mockSearch() {
addData([ {
depotFile : "//depot/path/to/file.txt",
rev : "1",
change : "1234",
action : "add",
type : "text",
time : "1368657649"
}, {
depotFile : "//commons/spaces/5/files/file.txt",
rev : "1",
change : "1234",
action : "add",
type : "text",
date : "1368657649"
} ]);
}
function reportError(req) {
$('#search-errors').html(req.status + " - " + req.statusText);
endSearch();
}
function doSearch(query, path, pathpartCSV, othertagsCSV, modifiedby, timequery) {
startSearch();
// make both "search text" inputs agree
$('#advancedsearchtext').val(query);
$('#searchtext').val(query);
var paths = [];
if (!!path)
paths.push(path);
var pathparts = [];
if (!!pathpartCSV)
pathparts = pathpartCSV.split(',');
// turn pathparts into field: value pairs, where field is "depotpath"
// and value is the value
var fieldList = [];
for ( var part in pathparts) {
fieldList.push({
"field" : "depotpath",
"value" : pathparts[part].trim()
});
}
var othertags = [];
if (!!othertagsCSV)
othertags = othertagsCSV.split(',');
for ( var i in othertags) {
var pair = othertags[i].split(':');
if (pair.length != 2)
continue;
fieldList.push({
"field" : pair[0].trim(),
"value" : pair[1].trim()
});
}
// append modifiedby and time
if (!!modifiedby) {
if (modifiedby == 'me')
modifiedby = $('#user_username').val();
fieldList.push({
"field" : "modifiedby",
"value" : modifiedby
});
}
if (!!timequery){
fieldList.push({
"field" : "modifiedtime",
"value" : "[" + timequery + "]"
});
}
$.ajax({
url : "/api/auth-search",
data : JSON.stringify({
queryRaw : query,
paths : paths,
searchFields : fieldList
}),
type : 'post',
contentType : "application/json",
error : function(req, status, err) {
reportError(req);
},
success : function(resp) {
if (!resp.status) {
// need to login
showLogin();
} else {
if (resp.status.code == "200") {
addData(resp.payload);
endSearch();
} else {
reportError({
status : resp.status.code,
statusText : resp.status.message
});
}
}
}
});
}
$('#searchbtn').click(function(e) {
// ajax search and handlebars table builder
e.stopPropagation();
doSearch($('#searchtext').val());
});
$('#advancedsearchbtn').click(
function(e) {
// ajax search and handlebars table builder
e.stopPropagation();
// calculate modifiedtime
var timeOption = $('#modifiedtime').children(':selected').attr('id');
var timeQuery='';
switch (timeOption) {
case 'hour':
timeQuery='NOW-1HOUR TO NOW'; // outlier, just do 60 minutes prior
break;
case 'day':
timeQuery='NOW/DAY-1DAY TO NOW';
break;
case 'week':
timeQuery='NOW/DAY-7DAYS TO NOW';
break;
case '6month':
timeQuery='NOW/DAY-6MONTHS TO NOW';
break;
case 'month':
timeQuery='NOW/DAY-1MONTH TO NOW';
break;
case 'year':
timeQuery='NOW/DAY-1YEAR TO NOW';
break;
default:
break;
}
doSearch($('#advancedsearchtext').val(), $(
'#advancedsearchpath').val(), $(
'#advancedsearchpathparts').val(), $(
'#advancedsearchtags').val(), $(
'#modifiedby').val(),
timeQuery);
});
function processPendingSearch() {
((window.location.hash == "#advanced") ? $('#advancedsearchbtn')
: $('#searchbtn')).click();
}
$('#login-div').on(
'shown',
function() {
(($('#user_username').val() == '') ? $('#user_username')
: $('#user_password')).focus();
});
function showLogin() {
$('#login-div').modal("show");
}
$('#login-btn').click(function(e) {
if ($('#remember:checked').val()) {
$.cookie("username", $('#user_username').val());
$.cookie("remember", true);
} else {
$.cookie("username", '');
$.cookie("remember", false);
}
$.ajax({
url : "/j_spring_security_check",
data : {
j_username : $('#user_username').val(),
j_password : $('#user_password').val()
},
type : 'post',
error : function(req, status, err) {
$('#login-error').show();
// $('#login-div').modal("attentionAnimation");
},
success : function(resp) {
if (!!resp.status && resp.status.code == "200") {
$('#login-error').hide();
$('#login').hide();
$('#username').show();
$('#login-div').modal("hide");
$('#userid').html(resp.payload.userId);
if (isSearching()) {
processPendingSearch();
}
} else {
// $('#login-div').modal("attentionAnimation");
$('#login-error').show();
}
}
});
e.stopPropagation();
});
$('#logout').click(function(e) {
$.ajax({
url : "/j_spring_security_logout",
type : 'post',
error : function(req, status, err) {
},
success : function(resp) {
showLogin();
$('#username').hide();
$('#userid').html('');
// clear user/pwd?
}
});
e.stopPropagation();
});
var fieldsTemplate = Handlebars.compile($("#fields-template").html());
$('#indexfields').click(function(e) {
$.ajax({
url : "/api/search-fields",
data : {},
type : 'get',
error : function(req, status, err) {
$('#login-error').show();
// $('#login-div').modal("attentionAnimation");
},
success : function(resp) {
if (!!resp.status && resp.status.code == "200") {
$('#indexfieldstable').html(fieldsTemplate({
fields : resp.payload
}));
$('#indexfieldsdlg').modal("show");
} else {
// $('#login-div').modal("attentionAnimation");
$('#login-error').show();
}
}
});
});
$('#clearbtn-text').click(function(e) {
$('#advancedsearchtext').val("");
});
$('#clearbtn-path').click(function(e) {
$('#advancedsearchpath').val("");
});
$('#clearbtn-parts').click(function(e) {
$('#advancedsearchpathparts').val("");
});
$('#clearbtn-modifiedby').click(function(e) {
$('#modifiedby').val("");
});
$('#clearbtn-tags').click(function(e) {
$('#advancedsearchtags').val("");
});
});