window.chat = function() {}; //WORK IN PROGRESS - NOT YET USED!! window.chat.commTabs = [ // channel: the COMM channel ('tab' parameter in server requests) // name: visible name // inputPrompt: string for the input prompt // inputColor: (optional) color for input // sendMessage: (optional) function to send the message (to override the default of sendPlext) // globalBounds: (optional) if true, always use global latLng bounds {channel:'all', name:'All', inputPrompt: 'broadcast:', inputColor:'#f66'}, {channel:'faction', name:'Aaction', inputPrompt: 'tell faction:'}, {channel:'alerts', name:'Alerts', inputPrompt: 'tell Jarvis:', inputColor: '#666', globalBounds: true, sendMessage: function() { alert("Jarvis: A strange game. The only winning move is not to play. How about a nice game of chess?\n(You can't chat to the 'alerts' channel!)"); }}, ]; window.chat.handleTabCompletion = function() { var el = $('#chatinput input'); var curPos = el.get(0).selectionStart; var text = el.val(); var word = text.slice(0, curPos).replace(/.*\b([a-z0-9-_])/, '$1').toLowerCase(); var list = $('#chat > div:visible mark'); list = list.map(function(ind, mark) { return $(mark).text(); } ); list = uniqueArray(list); var nick = null; for(var i = 0; i < list.length; i++) { if(!list[i].toLowerCase().startsWith(word)) continue; if(nick && nick !== list[i]) { console.log('More than one nick matches, aborting. ('+list[i]+' vs '+nick+')'); return; } nick = list[i]; } if(!nick) { console.log('No matches for ' + word); return; } var posStart = curPos - word.length; var newText = text.substring(0, posStart); var atPresent = text.substring(posStart-1, posStart) === '@'; newText += (atPresent ? '' : '@') + nick + ' '; newText += text.substring(curPos); el.val(newText); } // // clear management // window.chat._oldBBox = null; window.chat.genPostData = function(channel, storageHash, getOlderMsgs) { if (typeof channel !== 'string') throw ('API changed: isFaction flag now a channel string - all, faction, alerts'); var b = clampLatLngBounds(map.getBounds()); // set a current bounding box if none set so far if (!chat._oldBBox) chat._oldBBox = b; // to avoid unnecessary chat refreshes, a small difference compared to the previous bounding box // is not considered different var CHAT_BOUNDINGBOX_SAME_FACTOR = 0.1; // if the old and new box contain each other, after expanding by the factor, don't reset chat if (!(b.pad(CHAT_BOUNDINGBOX_SAME_FACTOR).contains(chat._oldBBox) && chat._oldBBox.pad(CHAT_BOUNDINGBOX_SAME_FACTOR).contains(b))) { console.log('Bounding Box changed, chat will be cleared (old: '+chat._oldBBox.toBBoxString()+'; new: '+b.toBBoxString()+')'); $('#chat > div').data('needsClearing', true); // need to reset these flags now because clearing will only occur // after the request is finished – i.e. there would be one almost // useless request. chat._faction.data = {}; chat._faction.oldestTimestamp = -1; chat._faction.newestTimestamp = -1; chat._public.data = {}; chat._public.oldestTimestamp = -1; chat._public.newestTimestamp = -1; chat._alerts.data = {}; chat._alerts.oldestTimestamp = -1; chat._alerts.newestTimestamp = -1; chat._oldBBox = b; } var ne = b.getNorthEast(); var sw = b.getSouthWest(); var data = { // desiredNumItems: isFaction ? CHAT_FACTION_ITEMS : CHAT_PUBLIC_ITEMS , minLatE6: Math.round(sw.lat*1E6), minLngE6: Math.round(sw.lng*1E6), maxLatE6: Math.round(ne.lat*1E6), maxLngE6: Math.round(ne.lng*1E6), minTimestampMs: -1, maxTimestampMs: -1, tab: channel, } if(getOlderMsgs) { // ask for older chat when scrolling up data = $.extend(data, {maxTimestampMs: storageHash.oldestTimestamp}); } else { // ask for newer chat var min = storageHash.newestTimestamp; // the initial request will have both timestamp values set to -1, // thus we receive the newest desiredNumItems. After that, we will // only receive messages with a timestamp greater or equal to min // above. // After resuming from idle, there might be more new messages than // desiredNumItems. So on the first request, we are not really up to // date. We will eventually catch up, as long as there are less new // messages than desiredNumItems per each refresh cycle. // A proper solution would be to query until no more new results are // returned. Another way would be to set desiredNumItems to a very // large number so we really get all new messages since the last // request. Setting desiredNumItems to -1 does unfortunately not // work. // Currently this edge case is not handled. Let’s see if this is a // problem in crowded areas. $.extend(data, {minTimestampMs: min}); // when requesting with an actual minimum timestamp, request oldest rather than newest first. // this matches the stock intel site, and ensures no gaps when continuing after an extended idle period if (min > -1) $.extend(data, {ascendingTimestampOrder: true}); } return data; } // // faction // window.chat._requestFactionRunning = false; window.chat.requestFaction = function(getOlderMsgs, isRetry) { if(chat._requestFactionRunning && !isRetry) return; if(isIdle()) return renderUpdateStatus(); chat._requestFactionRunning = true; $("#chatcontrols a:contains('faction')").addClass('loading'); var d = chat.genPostData('faction', chat._faction, getOlderMsgs); var r = window.postAjax( 'getPlexts', d, function(data, textStatus, jqXHR) { chat.handleFaction(data, getOlderMsgs); }, isRetry ? function() { window.chat._requestFactionRunning = false; } : function() { window.chat.requestFaction(getOlderMsgs, true) } ); } window.chat._faction = {data:{}, oldestTimestamp:-1, newestTimestamp:-1}; window.chat.handleFaction = function(data, olderMsgs) { chat._requestFactionRunning = false; $("#chatcontrols a:contains('faction')").removeClass('loading'); if(!data || !data.result) { window.failedRequestCount++; return console.warn('faction chat error. Waiting for next auto-refresh.'); } if(data.result.length === 0) return; var old = chat._faction.oldestTimestamp; chat.writeDataToHash(data, chat._faction, false, olderMsgs); var oldMsgsWereAdded = old !== chat._faction.oldestTimestamp; runHooks('factionChatDataAvailable', {raw: data, result: data.result, processed: chat._faction.data}); window.chat.renderFaction(oldMsgsWereAdded); } window.chat.renderFaction = function(oldMsgsWereAdded) { chat.renderData(chat._faction.data, 'chatfaction', oldMsgsWereAdded); } // // all // window.chat._requestPublicRunning = false; window.chat.requestPublic = function(getOlderMsgs, isRetry) { if(chat._requestPublicRunning && !isRetry) return; if(isIdle()) return renderUpdateStatus(); chat._requestPublicRunning = true; $("#chatcontrols a:contains('all')").addClass('loading'); var d = chat.genPostData('all', chat._public, getOlderMsgs); var r = window.postAjax( 'getPlexts', d, function(data, textStatus, jqXHR) { chat.handlePublic(data, getOlderMsgs); }, isRetry ? function() { window.chat._requestPublicRunning = false; } : function() { window.chat.requestPublic(getOlderMsgs, true) } ); } window.chat._public = {data:{}, oldestTimestamp:-1, newestTimestamp:-1}; window.chat.handlePublic = function(data, olderMsgs) { chat._requestPublicRunning = false; $("#chatcontrols a:contains('all')").removeClass('loading'); if(!data || !data.result) { window.failedRequestCount++; return console.warn('public chat error. Waiting for next auto-refresh.'); } if(data.result.length === 0) return; var old = chat._public.oldestTimestamp; chat.writeDataToHash(data, chat._public, undefined, olderMsgs); //NOTE: isPublic passed as undefined - this is the 'all' channel, so not really public or private var oldMsgsWereAdded = old !== chat._public.oldestTimestamp; runHooks('publicChatDataAvailable', {raw: data, result: data.result, processed: chat._public.data}); window.chat.renderPublic(oldMsgsWereAdded); } window.chat.renderPublic = function(oldMsgsWereAdded) { chat.renderData(chat._public.data, 'chatall', oldMsgsWereAdded); } // // alerts // window.chat._requestAlertsRunning = false; window.chat.requestAlerts = function(getOlderMsgs, isRetry) { if(chat._requestAlertsRunning && !isRetry) return; if(isIdle()) return renderUpdateStatus(); chat._requestAlertsRunning = true; $("#chatcontrols a:contains('alerts')").addClass('loading'); var d = chat.genPostData('alerts', chat._alerts, getOlderMsgs); var r = window.postAjax( 'getPlexts', d, function(data, textStatus, jqXHR) { chat.handleAlerts(data, getOlderMsgs); }, isRetry ? function() { window.chat._requestAlertsRunning = false; } : function() { window.chat.requestAlerts(getOlderMsgs, true) } ); } window.chat._alerts = {data:{}, oldestTimestamp:-1, newestTimestamp:-1}; window.chat.handleAlerts = function(data, olderMsgs) { chat._requestAlertsRunning = false; $("#chatcontrols a:contains('alerts')").removeClass('loading'); if(!data || !data.result) { window.failedRequestCount++; return console.warn('alerts chat error. Waiting for next auto-refresh.'); } if(data.result.length === 0) return; var old = chat._alerts.oldestTimestamp; chat.writeDataToHash(data, chat._alerts, undefined, olderMsgs); //NOTE: isPublic passed as undefined - it's nether public or private! var oldMsgsWereAdded = old !== chat._alerts.oldestTimestamp; // no hoot for alerts - API change planned here... // runHooks('alertsChatDataAvailable', {raw: data, result: data.result, processed: chat._alerts.data}); window.chat.renderAlerts(oldMsgsWereAdded); } window.chat.renderAlerts = function(oldMsgsWereAdded) { chat.renderData(chat._alerts.data, 'chatalerts', oldMsgsWereAdded); } // // common // window.chat.nicknameClicked = function(event, nickname) { var hookData = { event: event, nickname: nickname }; if (window.runHooks('nicknameClicked', hookData)) { window.chat.addNickname('@' + nickname); } event.preventDefault(); event.stopPropagation(); return false; } window.chat.writeDataToHash = function(newData, storageHash, isPublicChannel, isOlderMsgs) { $.each(newData.result, function(ind, json) { // avoid duplicates if(json[0] in storageHash.data) return true; var isSecureMessage = false; var msgToPlayer = false; var time = json[1]; var team = json[2].plext.team === 'RESISTANCE' ? TEAM_RES : TEAM_ENL; var auto = json[2].plext.plextType !== 'PLAYER_GENERATED'; var systemNarrowcast = json[2].plext.plextType === 'SYSTEM_NARROWCAST'; //track oldest + newest timestamps if (storageHash.oldestTimestamp === -1 || storageHash.oldestTimestamp > time) storageHash.oldestTimestamp = time; if (storageHash.newestTimestamp === -1 || storageHash.newestTimestamp < time) storageHash.newestTimestamp = time; //remove "Your X on Y was destroyed by Z" from the faction channel // if (systemNarrowcast && !isPublicChannel) return true; var msg = '', nick = ''; $.each(json[2].plext.markup, function(ind, markup) { switch(markup[0]) { case 'SENDER': // user generated messages nick = markup[1].plain.slice(0, -2); // cut “: ” at end break; case 'PLAYER': // automatically generated messages nick = markup[1].plain; team = markup[1].team === 'RESISTANCE' ? TEAM_RES : TEAM_ENL; if(ind > 0) msg += nick; // don’t repeat nick directly break; case 'TEXT': msg += $('
').text(markup[1].plain).html().autoLink(); break; case 'AT_PLAYER': var thisToPlayer = (markup[1].plain == ('@'+window.PLAYER.nickname)); var spanClass = thisToPlayer ? "pl_nudge_me" : (markup[1].team + " pl_nudge_player"); var atPlayerName = markup[1].plain.replace(/^@/, ""); msg += $('').html($('') .attr('class', spanClass) .attr('onclick',"window.chat.nicknameClicked(event, '"+atPlayerName+"')") .text(markup[1].plain)).html(); msgToPlayer = msgToPlayer || thisToPlayer; break; case 'PORTAL': var latlng = [markup[1].latE6/1E6, markup[1].lngE6/1E6]; var perma = '/intel?ll='+latlng[0]+','+latlng[1]+'&z=17&pll='+latlng[0]+','+latlng[1]; var js = 'window.selectPortalByLatLng('+latlng[0]+', '+latlng[1]+');return false'; msg += '' + window.chat.getChatPortalName(markup[1]) + ''; break; case 'SECURE': //NOTE: we won't add the '[secure]' string here - it'll be handled below instead isSecureMessage = true; break; default: //handle unknown types by outputting the plain text version, marked with it's type msg += $('').text(markup[0]+':<'+markup[1].plain+'>').html(); break; } }); // //skip secure messages on the public channel // if (isPublicChannel && isSecureMessage) return true; // //skip public messages (e.g. @player mentions) on the secure channel // if ((!isPublicChannel) && (!isSecureMessage)) return true; //NOTE: these two are redundant with the above two tests in place - but things have changed... //from the server, private channel messages are flagged with a SECURE string '[secure] ', and appear in //both the public and private channels //we don't include this '[secure]' text above, as it's redundant in the faction-only channel //let's add it here though if we have a secure message in the public channel, or the reverse if a non-secure in the faction one if (!auto && !(isPublicChannel===false) && isSecureMessage) msg = '[faction] ' + msg; //and, add the reverse - a 'public' marker to messages in the private channel if (!auto && !(isPublicChannel===true) && (!isSecureMessage)) msg = '[public] ' + msg; // format: timestamp, autogenerated, HTML message storageHash.data[json[0]] = [json[1], auto, chat.renderMsg(msg, nick, time, team, msgToPlayer, systemNarrowcast), nick]; }); } // Override portal names that are used over and over, such as 'US Post Office' window.chat.getChatPortalName = function(markup) { var name = markup.name; if(name === 'US Post Office') { var address = markup.address.split(','); name = 'USPS: ' + address[0]; } return name; } // renders data from the data-hash to the element defined by the given // ID. Set 3rd argument to true if it is likely that old data has been // added. Latter is only required for scrolling. window.chat.renderData = function(data, element, likelyWereOldMsgs) { var elm = $('#'+element); if(elm.is(':hidden')) return; // discard guids and sort old to new //TODO? stable sort, to preserve server message ordering? or sort by GUID if timestamps equal? var vals = $.map(data, function(v, k) { return [v]; }); vals = vals.sort(function(a, b) { return a[0]-b[0]; }); // render to string with date separators inserted var msgs = ''; var prevTime = null; $.each(vals, function(ind, msg) { var nextTime = new Date(msg[0]).toLocaleDateString(); if(prevTime && prevTime !== nextTime) msgs += chat.renderDivider(nextTime); msgs += msg[2]; prevTime = nextTime; }); var scrollBefore = scrollBottom(elm); elm.html('