var TYPING_DELAY=6500;function ChatInfo(id){this.id=id;this.name;this.version=0}ChatInfo.prototype.toStatic=function(t){return t>=this.version?undefined:{"id":this.id,"name":this.name}};ChatInfo.prototype.update=function(data,t){if(data["name"]!==undefined)this.name=data["name"];this.version=Math.max(this.version,t)};function Command(data){this.desc=data["desc"];this.name=data["name"];this.type=data["type"];this.usage=data["usage"];this.category=data["category"]} Command.prototype.toStatic=function(t){return{"desc":this.desc,"name":this.name,"type":this.type,"usage":this.usage,"category":this.category}};function SelfPreferences(){this.favoriteEmojis={};this.highlights=[];this.version=0} SelfPreferences.prototype.update=function(prefs,t){if(prefs["emoji_use"])this.favoriteEmojis=JSON.parse(prefs["emoji_use"]);if(prefs["highlight_words"])this.highlights=(prefs["highlight_words"]||"").split(",").filter(function(i){return i.trim()!==""});else if(prefs["highlights"])this.highlights=prefs["highlights"];this.version=Math.max(this.version,t)};SelfPreferences.prototype.toStatic=function(t){return this.version<=t?undefined:{"emoji_use":JSON.stringify(this.favoriteEmojis),"highlights":this.highlights}}; function ChatContext(){this.team=null;this.channels={};this.users={};this.self=null;this.emojis={version:0,data:{}};this.commands={version:0,data:{}};this.typing={};this.capacities={};this.staticV=0;this.liveV=0;this.typingVersion=0}ChatContext.prototype.userFactory=function(userData){return new Chatter(userData["id"])};ChatContext.prototype.roomFactory=function(roomData){return roomData["pv"]?new PrivateMessageRoom(roomData["id"],this.users[roomData["user"]]):new Room(roomData["id"])}; ChatContext.prototype.teamFactory=function(id){return new ChatInfo(id)};ChatContext.prototype.commandFactory=function(data){return new Command(data)}; ChatContext.prototype.updateStatic=function(data,t,idPrefix){idPrefix=idPrefix||"";if(data["team"]){if(!this.team)this.team=this.teamFactory(data["team"]["id"]);this.team.update(data["team"],t)}if(data["users"])for(var i=0,nbUsers=data["users"].length;it?this.emojis.data:undefined};if(this.staticV>t)res["capacities"]=Object.keys(this.capacities);if(this.commands.version>t){res["commands"]={};for(var i in this.commands.data)res["commands"][i]=this.commands.data[i].toStatic(t)}for(var chanId in this.channels){var chan=this.channels[chanId].toStatic(t); if(chan)channels.push(chan)}if(channels.length)res["channels"]=channels;for(var userId in this.users){var user=this.users[userId].toStatic(t);if(user)users.push(user)}if(users.length)res["users"]=users;return res};ChatContext.prototype.getWhoIsTyping=function(version,now){var res;this.cleanTyping(now);if(this.typingVersion>version){res={};for(var typingChan in this.typing){res[typingChan]={};for(var typingUser in this.typing[typingChan])res[typingChan][typingUser]=1}}return res}; ChatContext.prototype.getRoom=function(chanNameOrUserName){var chans=this.getChannelsWithName(chanNameOrUserName);if(chans.length)return chans[0];var users=this.getUsersWithName(chanNameOrUserName);if(users.length)for(var i=0,nbUsers=users.length;i=this.version)return null;var res={"id":this.id,"name":this.name,"created":this.created,"creator":this.creator?this.creator.id:undefined,"is_archived":this.archived,"is_member":this.isMember,"last_read":this.lastRead,"last_msg":this.lastMsg,"is_private":this.isPrivate,"is_starred":this.starred||undefined,"pins":this.exposePins()};if(this.isMember){res["members"]=this.users?Object.keys(this.users):[];res["topic"]={"value":this.topic,"creator":this.topicCreator? this.topicCreator.id:null,"last_set":this.topicTs};res["purpose"]={"value":this.purpose,"creator":this.purposeCreator?this.purposeCreator.id:null,"last_set":this.purposeTs}}return res}; Room.prototype.update=function(chanData,ctx,t,idPrefix){idPrefix=idPrefix||"";if(chanData["name"]!==undefined)this.name=chanData["name"];if(chanData["created"]!==undefined)this.created=chanData["created"];if(chanData["creator"]!==undefined)this.creator=ctx.users[chanData["creator"]];if(chanData["is_archived"]!==undefined)this.archived=chanData["is_archived"];if(chanData["is_member"]!==undefined)this.isMember=chanData["is_member"];if(chanData["last_read"]!==undefined)this.lastRead=Math.max(parseFloat(chanData["last_read"]), this.lastRead);if(chanData["last_msg"]!==undefined)this.lastMsg=parseFloat(chanData["last_msg"]);if(this.lastMsg)this.lastRead=Math.min(this.lastRead,this.lastMsg);if(chanData["is_private"]!==undefined)this.isPrivate=chanData["is_private"];if(chanData["pins"]!==undefined)this.pins=chanData["pins"];this.starred=!!chanData["is_starred"];if(chanData["members"]){this.users={};if(chanData["members"])for(var i=0,nbMembers=chanData["members"].length;i=this.version?null:{"id":this.id,"created":this.created,"user":this.user.id,"last_read":this.lastRead,"last_msg":this.lastMsg,"pv":true,"is_starred":this.starred||undefined,"pins":this.exposePins()}}; (function(){if(typeof module!=="undefined"){module.exports.Room=Room;module.exports.PrivateMessageRoom=PrivateMessageRoom}})();function Message(e,ts){this.userId=e["user"];this.username=e["username"];this.id=e["id"]||e["ts"];this.ts=parseFloat(e["ts"]);this.text="";this.pendingId;this.attachments=[];this.starred=e["is_starred"]||false;this.edited=false;this.removed=false;this.reactions={};this.version=ts;this.update(e,ts)}function MeMessage(e,ts){Message.call(this,e,ts)}function NoticeMessage(e,ts){Message.call(this,e,ts)} Message.prototype.update=function(e,ts){if(e){this.text=e["text"]||"";if(e["attachments"])this.attachments=e["attachments"];this.starred=!!e["is_starred"];this.edited=e["edited"]===undefined?false:e["edited"];this.removed=!!e["removed"];if(e["reactions"]){var reactions={};e["reactions"].forEach(function(r){reactions[r["name"]]=[];r["users"].forEach(function(userId){reactions[r["name"]].push(userId)})});this.reactions=reactions}if(e["pendingId"])this.pendingId=e["pendingId"]}else this.removed=true; this.version=ts}; Message.prototype.toStatic=function(){var reactions=[];for(var reaction in this.reactions)reactions.push({"name":reaction,"users":this.reactions[reaction]});return{"id":this.id,"user":this.userId,"username":this.username,"ts":this.ts,"text":this.text,"pendingId":this.pendingId,"attachments":this.attachments.length?this.attachments:undefined,"is_starred":this.starred||undefined,"edited":this.edited===false?undefined:this.edited,"removed":this.removed||undefined,"reactions":reactions,"isMeMessage":this instanceof MeMessage||undefined,"isNotice":this instanceof NoticeMessage||undefined}};Message.prototype.addReaction=function(reaction,userId,ts){if(!this.reactions[reaction])this.reactions[reaction]=[];if(this.reactions[reaction].indexOf(userId)===-1){this.reactions[reaction].push(userId);this.version=ts;return true}return false}; Message.prototype.removeReaction=function(reaction,userId,ts){var updated=false;if(this.reactions[reaction])if(this.reactions[reaction].length===1&&this.reactions[reaction][0]===userId){delete this.reactions[reaction];updated=true}else this.reactions[reaction]=this.reactions[reaction].filter(function(i){if(i!==userId)return true;updated=true;return false});if(updated)this.version=ts;return updated}; Message.prototype.hasReactionForUser=function(reaction,userId){if(this.reactions[reaction])return this.reactions[reaction].indexOf(userId)!==-1;return false};function RoomHistory(room,keepMessages,maxAge,evts,now){this.id=typeof room==="string"?room:room.id;this.messages=[];this.maxAge=maxAge;this.v=0;this.keepMessages=keepMessages;if(evts)this.pushAll(evts,now)} RoomHistory.prototype.pushAll=function(evts,t){var result=0;evts.forEach(function(e){result=Math.max(this.push(e,t),result)}.bind(this));this.resort();return result};RoomHistory.prototype.messageFactory=function(ev,ts){if(ev["isMeMessage"]===true)return new MeMessage(ev,ts);if(ev["isNotice"]===true)return new NoticeMessage(ev,ts);return new Message(ev,ts)}; RoomHistory.prototype.push=function(e,t){var exists=false,ts;for(var i=0,nbMsg=this.messages.length;ithis.keepMessages)this.messages.shift();if(this.maxAge)for(var i=0;i=this.messages[i].ts;i++)if(this.messages[i].ts===ts)return this.messages[i];return null}; RoomHistory.prototype.getMessageById=function(id){for(var i=0,nbMessages=this.messages.length;i=0;i--)if(this.messages[i].version>knownVersion)result.push(this.messages[i].toStatic());return result};RoomHistory.prototype.resort=function(){this.messages.sort(function(a,b){return a.ts-b.ts})};MeMessage.prototype=Object.create(Message.prototype); MeMessage.prototype.constructor=MeMessage;NoticeMessage.prototype=Object.create(Message.prototype);NoticeMessage.prototype.constructor=NoticeMessage;(function(){if(typeof module!=="undefined")module.exports={Message:Message,MeMessage:MeMessage,NoticeMessage:NoticeMessage,RoomHistory:RoomHistory}})();function Chatter(id){this.id=id;this.name;this.deleted;this.status;this.realName;this.goal;this.phone;this.presence;this.email;this.firstName;this.lastName;this.channels={};this.prefs=null;this.isBot;this.privateRoom=null;this.version=0} Chatter.prototype.toStatic=function(t){return t>=this.version?null:{"id":this.id,"name":this.name,"deleted":this.deleted,"status":this.status,"real_name":this.realName,"isPresent":this.presence,"isBot":this.isBot,"email":this.email,"phone":this.phone,"goal":this.goal,"first_name":this.firstName,"last_name":this.lastName}}; Chatter.prototype.update=function(userData,t){if(userData["name"]!==undefined)this.name=userData["name"];if(userData["deleted"]!==undefined)this.deleted=userData["deleted"];if(userData["status"]!==undefined)this.status=userData["status"];if(userData["goal"]!==undefined)this.goal=userData["goal"];if(userData["phone"]!==undefined)this.phone=userData["phone"];if(userData["email"]!==undefined)this.email=userData["email"];if(userData["first_name"]!==undefined)this.firstName=userData["first_name"];if(userData["last_name"]!== undefined)this.lastName=userData["last_name"];if(userData["real_name"]!==undefined)this.realName=userData["real_name"];if(userData["isPresent"]!==undefined)this.presence=userData["isPresent"];if(userData["isBot"])this.isBot=userData["isBot"];this.version=Math.max(this.version,t)};Chatter.prototype.getSmallIcon=function(){return"api/avatar?user="+encodeURIComponent(this.id)};Chatter.prototype.getLargeIcon=function(){return"api/avatar?size=l&user="+encodeURIComponent(this.id)}; Chatter.prototype.getName=function(){return this.name||this.realName||this.firstName||this.lastName};(function(){if(typeof module!=="undefined")module.exports.Chatter=Chatter})();var POLL_TIMEOUT=55E3;function ChatSystem(){}ChatSystem.prototype.onRequest=function(){};ChatSystem.prototype.getId=function(){};ChatSystem.prototype.getChatContext=function(){};ChatSystem.prototype.sendMeMsg=function(chan,text){};ChatSystem.prototype.sendMsg=function(chan,text,attachments){};ChatSystem.prototype.starMsg=function(chan,msgId){};ChatSystem.prototype.unstarMsg=function(chan,msgId){};ChatSystem.prototype.removeMsg=function(chan,ts){};ChatSystem.prototype.editMsg=function(chan,ts,newText){}; ChatSystem.prototype.addReaction=function(chan,ts,reaction){};ChatSystem.prototype.removeReaction=function(chan,ts,reaction){};ChatSystem.prototype.openUploadFileStream=function(chan,contentType,callback){};ChatSystem.prototype.fetchHistory=function(chan,cb){};ChatSystem.prototype.sendTyping=function(chan){};ChatSystem.prototype.markRead=function(chan,ts){};ChatSystem.prototype.sendCommand=function(chan,cmd,args){};ChatSystem.prototype.poll=function(knownVersion,nowTs,withTyping){}; ChatSystem.prototype.getImage=function(path){};function MultiChatManager(){this.contexts=[]}MultiChatManager.prototype.push=function(chatSystem){this.contexts.push(chatSystem)};MultiChatManager.prototype.getById=function(id){for(var i=0,nbContexts=this.contexts.length;itoday.getTime())return dateObj.toLocaleTimeString();if(dateObj.getTime()>yesterday.getTime())return"hier, "+dateObj.toLocaleTimeString();return dateObj.toLocaleString()},formatDay:function(ts){var today=new Date,yesterday=new Date,dateObj=new Date(ts);today.setHours(0,0,0,0);yesterday.setTime(today.getTime());yesterday.setDate(yesterday.getDate()-1);if(dateObj.getTime()>today.getTime())return"aujourd'hui"; if(dateObj.getTime()>yesterday.getTime())return"hier";return dateObj.toLocaleDateString()},chanName:function(serviceName,chanName){return serviceName+"/"+chanName},dom:{"fileUploadCancel":"Annuler","neterror":"Impossible de se connecter au chat !","ctxMenuSettings":"Configuration","ctxMenuLogout":"D\u00e9connexion","settingTitle":"Configuration","setting-menu-services":"Services","settings-services-title":"Services","setting-menu-display":"Affichage","settings-display-title":"Affichage","setting-menu-privacy":"Vie priv\u00e9e", "settings-privacy-title":"Vie priv\u00e9e","settingCommit":"Appliquer","settings-serviceAddButton":"Ajouter un service","settings-serviceListEmpty":"Vous n'avez pas encore ajout\u00e9 de service. Ajouter un service pour continuer.","settings-serviceAddConfirm":"Suivant","settings-displayEmojiProviderLbl":"Gestionnaire d'emojis","settings-displayDisplayAvatarLbl":"Afficher les avatars","settings-displayColorfulNamesLbl":"Afficher les nomes en couleur","settings-displayScrollAvatarsLbl":"Faire d\u00e9filer les avatars lors de la lecture", "settings-displayAttachmentContentLbl":"Afficher les pieces jointes ?","settings-displayAttachmentContent-never":"Jamais","settings-displayAttachmentContent-always":"Toujours","settings-displayAttachmentContent-notimg":"Si elles ne contiennent pas d'images"}};lang["fr"].pinCount=function(count){if(count===0)return"Pas de message \u00e9pingl\u00e9";return count+(count===1?" message \u00e9pingl\u00e9":" messages \u00e9pingl\u00e9s")}; lang["fr"].userCount=function(count){if(count===0)return"Pas de chatteur";return count+(count===1?" chatteur":" chatteurs")};lang["fr"].edited=function(ts){return"(edité "+lang["fr"].formatDate(ts)+")"};lang["fr"].topicDetail=function(creator,ts){return"par "+creator.getName()+" le "+lang["fr"].formatDate(ts)};lang["en"]={unknownMember:"Unknown member",unknownChannel:"Unknown channel",newMessage:"New message",message:"Message",netErrorShort:"Network",onlyVisible:"(only visible to you)",starred:"Starred",channels:"Channels",members:"Members",privateMessageRoom:"Direct messages",shareYourLocation:"Share your GPS location",ok:"Ok",dissmiss:"Cancel",formatDate:function(ts){if(typeof ts!=="string")ts=parseFloat(ts);var today=new Date,yesterday=new Date,dateObj=new Date(ts);today.setHours(0,0,0,0);yesterday.setTime(today.getTime()); yesterday.setDate(yesterday.getDate()-1);if(dateObj.getTime()>today.getTime())return dateObj.toLocaleTimeString();if(dateObj.getTime()>yesterday.getTime())return"yesterday, "+dateObj.toLocaleTimeString();return dateObj.toLocaleString()},formatDay:function(ts){var today=new Date,yesterday=new Date,dateObj=new Date(ts);today.setHours(0,0,0,0);yesterday.setTime(today.getTime());yesterday.setDate(yesterday.getDate()-1);if(dateObj.getTime()>today.getTime())return"today";if(dateObj.getTime()>yesterday.getTime())return"yesterday"; return dateObj.toLocaleDateString()},chanName:function(serviceName,chanName){return serviceName+"/"+chanName},dom:{"fileUploadCancel":"Cancel","neterror":"Cannot connect to chat !","ctxMenuSettings":"Settings","ctxMenuLogout":"Logout","settingTitle":"Settings","setting-menu-services":"Services","settings-services-title":"Services","setting-menu-display":"Display","settings-display-title":"Display","setting-menu-privacy":"Privacy","settings-privacy-title":"Privacy","settingCommit":"Apply","settings-serviceAddButton":"Add a service", "settings-serviceListEmpty":"You don't have any service yet. Please add a service to continue.","settings-serviceAddConfirm":"Next","settings-displayEmojiProviderLbl":"Emoji provider","settings-displayDisplayAvatarLbl":"Display avatars","settings-displayColorfulNamesLbl":"Colorful names","settings-displayScrollAvatarsLbl":"Scroll avatars","settings-displayAttachmentContentLbl":"Automaticcaly unwrap attachments ?","settings-displayAttachmentContent-never":"Never","settings-displayAttachmentContent-always":"Always", "settings-displayAttachmentContent-notimg":"If they don't contain image"}};lang["en"].pinCount=function(count){if(count===0)return"No pinned messages";return count+(count===1?" pinned message":" pinned messages")};lang["en"].userCount=function(count){if(count===0)return"No users in this room";return count+(count===1?" user":" users")};lang["en"].edited=function(ts){return"(edited "+lang["en"].formatDate(ts)+")"};lang["en"].topicDetail=function(creator,ts){return"by "+creator.getName()+" on "+lang["en"].formatDate(ts)};var formatText=function(){var text;var root;var opts={highlights:[],emojiFormatFunction:identity,textFilter:identity,linkFilter:linkidentity};function MsgTextLeaf(_parent){this.text="";this._parent=_parent}function MsgBranch(_parent,triggerIndex,trigger){this.triggerIndex=triggerIndex;this.lastNode=null;this.subNodes=[];this.trigger=trigger||"";this.isLink=this.trigger==="<";this.isBold=this.trigger==="*";this.isItalic=this.trigger==="_";this.isStrike=this.trigger==="~"||this.trigger==="-";this.isQuote= this.trigger===">"||this.trigger===">";this.isEmoji=this.trigger===":";this.isCode=this.trigger==="`";this.isCodeBlock=this.trigger==="```";this.isEol=this.trigger==="\n";this.isHighlight=trigger!==undefined&&opts.highlights.indexOf(trigger)!==-1;this._parent=_parent;this.prevTwin=null;this.terminated=this.isEol||this.isHighlight?triggerIndex+trigger.length-1:false;if(this.isHighlight){this.lastNode=new MsgTextLeaf(this);this.subNodes.push(this.lastNode);this.lastNode.text=trigger}}MsgBranch.prototype.checkIsBold= function(){return this.isBold&&!!this.terminated||this._parent instanceof MsgBranch&&this._parent.checkIsBold()};MsgBranch.prototype.checkIsItalic=function(){return this.isItalic&&!!this.terminated||this._parent instanceof MsgBranch&&this._parent.checkIsItalic()};MsgBranch.prototype.checkIsStrike=function(){return this.isStrike&&!!this.terminated||this._parent instanceof MsgBranch&&this._parent.checkIsStrike()};MsgBranch.prototype.checkIsQuote=function(){return this.isQuote&&!!this.terminated||this._parent instanceof MsgBranch&&this._parent.checkIsQuote()};MsgBranch.prototype.checkIsEmoji=function(){return this.isEmoji&&!!this.terminated||this._parent instanceof MsgBranch&&this._parent.checkIsEmoji()};MsgBranch.prototype.checkIsHighlight=function(){return this.isHighlight&&!!this.terminated||this._parent instanceof MsgBranch&&this._parent.checkIsHighlight()};MsgBranch.prototype.checkIsCode=function(){return this.isCode&&!!this.terminated||this._parent instanceof MsgBranch&&this._parent.checkIsCode()};MsgBranch.prototype.checkIsCodeBlock= function(){return this.isCodeBlock&&!!this.terminated||this._parent instanceof MsgBranch&&this._parent.checkIsCodeBlock()};MsgBranch.prototype.containsUnterminatedBranch=function(){for(var i=0,nbBranches=this.subNodes.length;i")return true;var prevIsAlphadec=isAlphadec(text[i- 1]);if(!this.isQuote&&text.substr(i,this.trigger.length)===this.trigger){if(!prevIsAlphadec&&(this.isBold||this.isItalic||this.isStrike))return false;if(this.lastNode&&this.containsUnterminatedBranch())return this.lastNode.makeNewBranchFromThis();else if(this.hasContent())return true}if(text[i]==="\n"&&this.isQuote)return true;return false};MsgBranch.prototype.hasContent=function(){var _this=this;while(_this){for(var i=0,nbNodes=_this.subNodes.length;i")return text[i]}if("`"=== text[i]&&!prevIsAlphadec)return text[i];if("\n"===text[i])return text[i];if(["*","~","-","_"].indexOf(text[i])!==-1&&(nextIsAlphadec||text[i+1]===undefined||["*","~","-","_","<","&"].indexOf(text[i+1])!==-1)&&(!prevIsAlphadec||text[i-1]===undefined||["*","~","-","_","<","&"].indexOf(text[i-1])!==-1))return text[i];if([":"].indexOf(text[i])!==-1&&nextIsAlphadec)return text[i];if(["<"].indexOf(text[i])!==-1)return text[i];for(var highlightIndex=0,nbHighlight=opts.highlights.length;highlightIndex=0;i--){var isNewLine=this.subNodes[i].isBeginingOfLine();if(isNewLine!==undefined)return isNewLine}if(this.isEol||this.isQuote)return true;return undefined};function isAlphadec(c){return/[A-Za-z0-9\u00e0\u00e8\u00ec\u00f2\u00f9\u00c0\u00c8\u00cc\u00d2\u00d9\u00e1\u00e9\u00ed\u00f3\u00fa\u00fd\u00c1\u00c9\u00cd\u00d3\u00da\u00dd\u00e2\u00ea\u00ee\u00f4\u00fb\u00c2\u00ca\u00ce\u00d4\u00db\u00e3\u00f1\u00f5\u00c3\u00d1\u00d5\u00e4\u00eb\u00ef\u00f6\u00fc\u00ff\u00c4\u00cb\u00cf\u00d6\u00dc\u0178\u00e7\u00c7\u00df\u00d8\u00f8\u00c5\u00e5\u00c6\u00e6\u0153+]/.test(c)} function isBeginingOfLine(){var isNewLine=root.isBeginingOfLine();return isNewLine===undefined?true:isNewLine}MsgTextLeaf.prototype.addChar=function(i){this.text+=text[i];return 1};MsgBranch.prototype.addChar=function(i){var isFinished=this.lastNode&&!this.lastNode.terminated&&this.lastNode.finishWith?this.lastNode.finishWith(i):null;if(isFinished){var lastTriggerLen=this.lastNode.trigger.length;this.lastNode.terminate(i);if(isFinished instanceof MsgBranch){this.lastNode=isFinished;this.subNodes.push(isFinished)}return lastTriggerLen}else if(!this.lastNode|| this.lastNode.terminated||this.lastNode instanceof MsgTextLeaf||this.lastNode.isAcceptable(i)){var isNewToken=this.isNewToken(i);if(isNewToken){this.lastNode=new MsgBranch(this,i,isNewToken);this.subNodes.push(this.lastNode);return this.lastNode.trigger.length}else{if(!this.lastNode||this.lastNode.terminated){this.lastNode=new MsgTextLeaf(this);this.subNodes.push(this.lastNode)}return this.lastNode.addChar(i)}}else{var revertTo=this.lastNode.triggerIndex+1;root.cancelTerminate(this.lastNode.triggerIndex); this.lastNode=new MsgTextLeaf(this);this.lastNode.addChar(revertTo-1);this.subNodes.pop();this.subNodes.push(this.lastNode);return revertTo-i}};MsgBranch.prototype.terminate=function(terminateAtIndex){var _this=this;while(_this){_this.terminated=terminateAtIndex;_this=_this.prevTwin}};MsgBranch.prototype.cancelTerminate=function(unTerminatedIndex){if(this.terminated&&this.terminated>=unTerminatedIndex)this.terminated=false;this.subNodes.forEach(function(node){if(node instanceof MsgBranch)node.cancelTerminate(unTerminatedIndex)})}; MsgTextLeaf.prototype.innerHTML=function(){if(this._parent.checkIsEmoji()){var _parent=this._parent;while(_parent&&!_parent.isEmoji)_parent=_parent._parent;if(_parent){var fallback=_parent.trigger+this.text+_parent.trigger;var formatted=opts.emojiFormatFunction(fallback);return formatted?formatted:fallback}var _formatted=opts.emojiFormatFunction(this.text);return _formatted?_formatted:this.text}if(this._parent.checkIsCodeBlock()){if(typeof hljs!=="undefined")try{var lang=this.text.match(/^\w+/);hljs.configure({"useBR":true, "tabReplace":"      "});if(lang&&hljs.getLanguage(lang[0]))return hljs.fixMarkup(hljs.highlight(lang[0],this.text.substr(lang[0].length)).value);return hljs.fixMarkup(hljs.highlightAuto(this.text).value)}catch(e){console.error(e)}return this.text.replace(/\n/g,"
")}return opts.textFilter(this.text)};MsgTextLeaf.prototype.outerHTML=function(){var tagName="span",classList=[],innerHTML,params="";if(this._parent.checkIsCodeBlock()){tagName="pre";classList.push("codeblock"); innerHTML=this.innerHTML()}else if(this._parent.checkIsCode()){classList.push("code");innerHTML=this.innerHTML()}else{var link;if(this._parent.isLink&&(link=opts.linkFilter(this.text))){tagName="a";params=' href="'+link.link+'"';if(link.style)params+=' style="'+link.style+'"';if(!link.isInternal)params+=' target="_blank"';if(link.classes)link.classes.forEach(function(i){classList.push(i)});innerHTML=opts.textFilter(link.text)}else innerHTML=this.innerHTML();if(this._parent.checkIsBold())classList.push("bold"); if(this._parent.checkIsItalic())classList.push("italic");if(this._parent.checkIsStrike())classList.push("strike");if(this._parent.checkIsEmoji())classList.push("emoji");if(this._parent.checkIsHighlight())classList.push("highlight")}return"<"+tagName+params+(classList.length?' class="'+classList.join(" ")+'"':"")+">"+innerHTML+""};MsgBranch.prototype.outerHTML=function(){var html="";if(this.isQuote)html+='';if(this.isEol)html+="
";this.subNodes.forEach(function(node){html+= node.outerHTML()});if(this.isQuote)html+="
";return html};function getFirstUnterminated(_root){_root=_root||root;for(var i=0,nbBranches=_root.subNodes.length;i0){if(input[start]=== "#"){var channels=SELECTED_CONTEXT.getChatContext().channels,inputStr=input.substr(start+1,end-start-1);for(var i in channels)if(channels[i].name.length>=inputStr.length&&channels[i].name.substr(0,inputStr.length)===inputStr)commands.push(channels[i])}else if(input[start]==="@"){var users=SELECTED_ROOM instanceof PrivateMessageRoom?SELECTED_CONTEXT.getChatContext().users:SELECTED_ROOM.users,inputStr=input.substr(start+1,end-start-1);for(var i in users){var userName=users[i].getName();if(userName.length>= inputStr.length&&userName.substr(0,inputStr.length)===inputStr)commands.push(users[i])}}else if(input[start]===":"&&window["searchEmojis"]){var inputCmd=input.substr(start+1,end-start-1),emojiList=window["searchEmojis"](inputCmd);for(var emojiCode in emojiList){var domEmoji=window["makeEmoji"](emojiCode,false),domParent=document.createElement("span");domParent.appendChild(domEmoji);domParent.className=R.klass.emoji.small;commands.push({name:":"+emojiCode+":",emojiSpan:domParent,provider:CURRENT_EMOJI_PROVIDER.name})}for(var i in SELECTED_CONTEXT.getChatContext().emojis.data)if(i.length>= inputCmd.length&&i.substr(0,inputCmd.length)===inputCmd){var emojiSpan=document.createElement("span");emojiSpan.className=R.klass.emoji.small;emojiSpan.appendChild(makeEmojiDom(i));commands.push({name:":"+i+":",emojiSpan:emojiSpan,provider:"custom"})}}if(commands.length)slashDom.dataset.cursor=JSON.stringify([start,end])}}if(!commands.length&&input[0]==="/"){var endCmd=input.indexOf(" "),inputFinished=endCmd!==-1;endCmd=endCmd===-1?input.length:endCmd;var inputCmd=input.substr(0,endCmd);if(inputFinished){var currentClientCmd= CLIENT_COMMANDS.getCommand(inputCmd);if(currentClientCmd)commands.push(currentClientCmd)}else{commands=CLIENT_COMMANDS.getCommandsStartingWith(inputCmd);slashDom.dataset.cursor=JSON.stringify([0,inputDom.selectionEnd])}var availableCommands=SELECTED_CONTEXT?SELECTED_CONTEXT.getChatContext().commands.data:{};for(var currentCmdId in availableCommands){var currentCmd=availableCommands[currentCmdId];if(!inputFinished&¤tCmd.name.substr(0,endCmd)===inputCmd||inputFinished&¤tCmd.name===inputCmd)commands.push(currentCmd)}commands.sort(function(a, b){return a.category.localeCompare(b.category)||a.name.localeCompare(b.name)})}slashDom.textContent="";if(commands.length){var slashFrag=document.createDocumentFragment(),prevService;for(var i=0,nbCmd=commands.length;iinput.clientHeight)input.rows++} function initMsgInput(){var lastKeyDown=0,input=document.getElementById(R.id.message.input);input.addEventListener("input",function(){if(SELECTED_ROOM){var now=Date.now();if(lastKeyDown+3E3i.lastRead)hasUnread++});if(hasUnread)title="("+hasUnread+")";setFavicon(0,hasUnread)}if(!title.length&&SELECTED_ROOM)title=SELECTED_ROOM.name;title=title.length?title:"Mimouchat";document.title=title;setNativeTitle(title)} function spawnNotification(){if(!("Notification"in window));else if(Notification.permission==="granted"){var now=Date.now();if(lastNotificationSpawn+NOTIFICATION_COOLDOWN= MSG_GROUPS[currentGroup].messages.length)if(!msg.removed){if(isSameGroup(MSG_GROUPS[currentGroup],msg)){var dom=msg.getDom();if(Math.abs(firstTsCombo-msg.ts)<30&&prevMsg)prevMsg.getDom().classList.add(R.klass.msg.sameTs);firstTsCombo=msg.ts;if((!prevMsg||prevMsg.ts<=SELECTED_ROOM.lastRead)&&msg.ts>SELECTED_ROOM.lastRead)dom.classList.add(R.klass.msg.firstUnread);else dom.classList.remove(R.klass.msg.firstUnread);MSG_GROUPS[currentGroup].content.appendChild(dom);MSG_GROUPS[currentGroup].messages.push(msg.id); ++currentMsgInGroup;prevMsg=msg;return}if(msg.ts0&&msg.tsSELECTED_ROOM.lastRead)dom.classList.add(R.klass.msg.firstUnread);else dom.classList.remove(R.klass.msg.firstUnread);currentMsgInGroup++;prevMsg=msg}else if(!msg.removed){var dom=msg.getDom();MSG_GROUPS[currentGroup].content.insertBefore(dom,MSG_GROUPS[currentGroup].content.children[currentMsgInGroup]);MSG_GROUPS[currentGroup].messages.splice(currentMsgInGroup,0,msg.id);if((!prevMsg||prevMsg.ts<=SELECTED_ROOM.lastRead)&&msg.ts>SELECTED_ROOM.lastRead)dom.classList.add(R.klass.msg.firstUnread); else dom.classList.remove(R.klass.msg.firstUnread);currentMsgInGroup++;prevMsg=msg}return}}if(msg.removed)return;if(MSG_GROUPS[currentGroup]&&!isSameGroup(MSG_GROUPS[currentGroup],msg))MSG_GROUPS.splice(currentGroup,0,null);if(!MSG_GROUPS[currentGroup]){MSG_GROUPS[currentGroup]=createMessageGroupDom(DATA.context.getUser(msg.userId),msg.username,msg instanceof MeMessage,msg.ts);groupDomCreated=true}var dom=msg.getDom();firstTsCombo=msg.ts;if((!prevMsg||prevMsg.ts<=SELECTED_ROOM.lastRead)&&msg.ts>SELECTED_ROOM.lastRead){dom.classList.add(R.klass.msg.firstUnread); dom.insertBefore(UNREAD_INDICATOR_DOM,dom.firstChild)}else dom.classList.remove(R.klass.msg.firstUnread);MSG_GROUPS[currentGroup].content.appendChild(dom);MSG_GROUPS[currentGroup].messages.push(msg.id);prevMsg=msg;if(groupDomCreated){if(MSG_GROUPS[currentGroup+1])chatFrag.insertBefore(MSG_GROUPS[currentGroup],MSG_GROUPS[currentGroup+1]);else chatFrag.appendChild(MSG_GROUPS[currentGroup]);currentMsgInGroup=1}return});if(MSG_GROUPS[currentGroup]){while(MSG_GROUPS[currentGroup].content.children[currentMsgInGroup])MSG_GROUPS[currentGroup].content.children[currentMsgInGroup].remove(); MSG_GROUPS[currentGroup].messages.splice(currentMsgInGroup);if(!MSG_GROUPS[currentGroup].messages.length)--currentGroup;for(var i=currentGroup+1;MSG_GROUPS[i];i++)MSG_GROUPS[i].remove()}for(var i=0,len=MSG_GROUPS.length;i=0){href=href.substr(sepPosition+1);var channelCtx=DATA.context.getChannelContext(href);if(channelCtx){roomInfo.populate(channelCtx,channelCtx.getChatContext().channels[href]).show(t);return}channelCtx=DATA.context.getUserContext(href);if(channelCtx){var room=channelCtx.getChatContext().users[href].privateRoom;if(room){roomInfo.populate(channelCtx, room).show(t);return}}}}t=t.parentElement}roomInfo.hideDelayed()});document.getElementById(R.id.contextButton).addEventListener("click",_toggleMenu);document.getElementById(R.id.currentRoom.starButton).addEventListener("click",function(e){e.preventDefault();if(SELECTED_ROOM)if(SELECTED_ROOM.starred)unstarChannel(SELECTED_ROOM);else starChannel(SELECTED_ROOM);return false});document.getElementById(R.id.message.file.cancel).addEventListener("click",function(e){e.preventDefault();document.getElementById(R.id.message.file.error).classList.add(R.klass.hidden); document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);document.getElementById(R.id.message.file.fileInput).value="";return false});document.getElementById(R.id.settings.logout).addEventListener("click",logout);document.getElementById(R.id.settings.menuButton).addEventListener("click",function(e){e.preventDefault();Settings.display().setClosable(true)});document.getElementById(R.id.message.file.form).addEventListener("submit",function(e){e.preventDefault();var fileInput= document.getElementById(R.id.message.file.fileInput),filename=fileInput.value;if(filename){filename=filename.substr(filename.lastIndexOf("\\")+1);uploadFile(SELECTED_ROOM,filename,fileInput.files[0],function(errorMsg){var error=document.getElementById(R.id.message.file.error);if(errorMsg){error.textContent=errorMsg;error.classList.remove(R.klass.hidden)}else{error.classList.add(R.klass.hidden);document.getElementById(R.id.message.file.fileInput).value="";document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden)}})}return false}); document.getElementById(R.id.message.file.bt).addEventListener("click",function(e){e.preventDefault();if(SELECTED_ROOM)document.getElementById(R.id.message.file.formContainer).classList.remove(R.klass.hidden);return false});document.getElementById(R.id.message.submitButton).addEventListener("click",function(e){e.preventDefault();onMsgFormSubmit();return false});document.getElementById(R.id.message.form).addEventListener("submit",function(e){e.preventDefault();onMsgFormSubmit();return false});window.addEventListener("blur", function(){window.hasFocus=false});window.addEventListener("focus",function(){window.hasFocus=true;lastNotificationSpawn=0;if(SELECTED_ROOM)markRoomAsRead(SELECTED_ROOM);focusInput()});window.hasFocus=true;var emojiButton=document.getElementById(R.id.message.emoji);emojiButton.addEventListener("click",function(){if(SELECTED_CONTEXT)EMOJI_BAR.spawn(document.body,SELECTED_CONTEXT.getChatContext(),function(e){if(e)document.getElementById(R.id.message.input).value+=":"+e+":";focusInput()})});if(isNative()){__native.readSmsPermission(CALLBACK.makeCallback(function(){var response= JSON.parse(__native.getStatic());if(response)DATA.update(response)}));document.body.classList.add(R.klass.native)}if(!IS_LOCAL)startPolling()}); function onMsgFormSubmit(){var input=document.getElementById(R.id.message.input);if(SELECTED_ROOM&&input.value)if(onTextEntered(input.value)){input.value="";if(REPLYING_TO){REPLYING_TO=null;onReplyingToUpdated()}if(EDITING){EDITING=null;onReplyingToUpdated()}document.getElementById(R.id.message.slashComplete).textContent="";updateInputRowCount(input)}focusInput()};var Settings=function(){var displayed=false,currentPage=null,pages={services:"services",display:"display",privacy:"privacy"},spawn=function(){document.getElementById(R.id.settings.wrapper).classList.remove(R.klass.hidden);var serviceFrag=document.createDocumentFragment(),hasServices=false;for(var i in CONFIG.services){var provider=CONFIG.services[i];for(var service in provider){var serviceItem=document.createElement("li"),providerDom=document.createElement("span"),serviceDom=document.createElement("span"); providerDom.textContent=i;serviceDom.textContent=provider[service];serviceItem.className=R.klass.settings.services.item;providerDom.className=R.klass.settings.services.provider;serviceDom.className=R.klass.settings.services.service;serviceItem.appendChild(providerDom);serviceItem.appendChild(serviceDom);serviceFrag.appendChild(serviceItem);hasServices=true}}var serviceListDom=document.getElementById(R.id.settings.services.serviceList);serviceListDom.textContent="";if(hasServices){document.getElementById(R.id.settings.services.serviceListEmpty).classList.remove(R.klass.hidden); serviceListDom.appendChild(serviceFrag)}else document.getElementById(R.id.settings.services.serviceListEmpty).classList.add(R.klass.hidden);var emojiFrag=document.createDocumentFragment(),emojiList=document.getElementById(R.id.settings.display.emojiProvider);for(var i in EmojiProvider){var opt=document.createElement("option");opt.value=i;opt.textContent=EmojiProvider[i].name;if(EmojiProvider[i]===CURRENT_EMOJI_PROVIDER)opt.selected=true;emojiFrag.appendChild(opt)}emojiList.textContent="";emojiList.appendChild(emojiFrag); document.getElementById(R.id.settings.display.displayAvatar).checked=CONFIG.isDisplayAvatars();document.getElementById(R.id.settings.display.colorfulNames).checked=CONFIG.isColorfulNames();document.getElementById(R.id.settings.display.scrollAvatars).checked=CONFIG.isScrollAvatars();document.getElementById(R.id.settings.display.displayAttachments).value=CONFIG.autoExpandAttachments!==undefined?CONFIG.autoExpandAttachments:CONFIG_AUTO_EXPAND.NOT_IMAGE;displayed=true},setVisiblePage=function(page){if(currentPage){document.getElementById(R.id.settings.wrapper).classList.remove("display-"+ currentPage);document.getElementById("setting-menu-"+currentPage).classList.remove(R.klass.selected);document.getElementById(R.id.settings.services.addSection).classList.add(R.klass.hidden)}document.getElementById(R.id.settings.wrapper).classList.add("display-"+page);document.getElementById("setting-menu-"+page).classList.add(R.klass.selected);currentPage=page},close=function(){document.getElementById(R.id.settings.wrapper).classList.add(R.klass.hidden);displayed=false};document.getElementById(R.id.settings.menu.list).addEventListener("click", function(e){for(var target=e.target;e.currentTarget!==target&⌖target=target.parentNode)if(target.dataset&&target.dataset["target"])for(var i in pages)if(pages[i]===target.dataset["target"]){setVisiblePage(pages[i]);return}});document.getElementById(R.id.settings.closeButton).addEventListener("click",close);document.getElementById(R.id.settings.services.addButton).addEventListener("click",function(e){e.preventDefault();document.getElementById(R.id.settings.services.addSection).classList.remove(R.klass.hidden); return false});document.getElementById(R.id.settings.services.serviceAddConfirm).addEventListener("click",function(e){e.preventDefault();document.location.href=document.getElementById(R.id.settings.services.serviceProviderList).value;return false});document.getElementById(R.id.settings.commitBt).addEventListener("click",function(){var newSettings={},emojiProvider=document.getElementById(R.id.settings.display.emojiProvider).value;if(emojiProvider!==CONFIG.getEmojiProvider())newSettings["emojiProvider"]= document.getElementById(R.id.settings.display.emojiProvider).value;var displayAvatar=!!document.getElementById(R.id.settings.display.displayAvatar).checked;if(displayAvatar!==CONFIG.isDisplayAvatars())newSettings["displayAvatar"]=displayAvatar;var isColorfulNames=!!document.getElementById(R.id.settings.display.colorfulNames).checked;if(isColorfulNames!==CONFIG.isColorfulNames())newSettings["colorfulNames"]=isColorfulNames;var isScrollAvatars=!!document.getElementById(R.id.settings.display.scrollAvatars).checked; if(isScrollAvatars!==CONFIG.isScrollAvatars())newSettings["scrollAvatars"]=isScrollAvatars;var displayAttachmentValue=document.getElementById(R.id.settings.display.displayAttachments).value;if(displayAttachmentValue!==CONFIG.autoExpandAttachments)newSettings["autoExpandAttachments"]=displayAttachmentValue;CONFIG.commitNewSettings(newSettings);close()});return{display:function(page){if(!displayed)spawn();setVisiblePage(page||pages.services);return this},setClosable:function(closable){return this}, pages:pages}}();function makeOSMTiles(geo){if(geo["latitude"]!==undefined&&geo["longitude"]!==undefined&&geo["latitude"]>=-90&&geo["latitude"]<=90&&geo["longitude"]>=-180&&geo["longitude"]<=180){var tileServer="https://c.tile.openstreetmap.org",currentVersion=0,getTile=function(zoom,x,y,result){return new Promise(function(resolve,reject){var img=new Image;img.addEventListener("load",function(){result.img=img;resolve(result)});img.addEventListener("error",function(){console.warn("Error loading tile ",{"zoom":zoom, "x":x,"y":y});reject(img)});img.crossOrigin="anonymous";img.src=tileServer+"/"+zoom+"/"+x+"/"+y+".png"})},canvas=document.createElement("canvas"),mapCanvas=document.createElement("canvas");var imgSize=300,tileSize=imgSize/3;canvas.height=canvas.width=mapCanvas.height=mapCanvas.width=imgSize;var ctx=canvas.getContext("2d"),mapCtx=mapCanvas.getContext("2d");var drawPlot=function(centerX,centerY,radius){centerX=tileSize*centerX+tileSize;centerY=tileSize*centerY+tileSize;ctx.putImageData(mapCtx.getImageData(0, 0,imgSize,imgSize),0,0);if(radius!==undefined){ctx.beginPath();ctx.arc(centerX,centerY,Math.max(radius,10),0,2*Math.PI,false);ctx.lineWidth=2;ctx.fillStyle="rgba(244, 146, 66, 0.4)";ctx.strokeStyle="rgba(244, 146, 66, 0.8)";ctx.stroke();ctx.fill()}if(radius===undefined||radius>25){ctx.strokeStyle="rgba(244, 146, 66, 1)";ctx.beginPath();ctx.moveTo(centerX-5,centerY-5);ctx.lineTo(centerX+5,centerY+5);ctx.stroke();ctx.moveTo(centerX+5,centerY-5);ctx.lineTo(centerX-5,centerY+5);ctx.stroke()}},distanceLatlonlon= function(lat,lon0,lon1){lat=lat*Math.PI/180;lon0=lon0*Math.PI/180;lon1=lon1*Math.PI/180;return Math.abs(6371E3*Math.acos(Math.pow(Math.sin(lat),2)+Math.pow(Math.cos(lat),2)*Math.cos(lon1-lon0)))},drawTiles=function(zoom,lat,lon,acc){mapCtx.fillStyle="#808080";mapCtx.fillRect(0,0,imgSize,imgSize);ctx.fillStyle="#808080";ctx.fillRect(0,0,imgSize,imgSize);var nbTiles=Math.pow(2,zoom),px=(lon+180)/360*nbTiles,py=(1-Math.log(Math.tan(lat*Math.PI/180)+1/Math.cos(lat*Math.PI/180))/Math.PI)/2*nbTiles,absoluteX= Math.floor(px),absoluteY=Math.floor(py),accRadiusPx=acc?acc*100/distanceLatlonlon(180/Math.PI*Math.atan(.5*(Math.exp(Math.PI-2*Math.PI*absoluteY/nbTiles)-Math.exp(-(Math.PI-2*Math.PI*absoluteY/nbTiles)))),absoluteX/nbTiles*360-180,(absoluteX+1)/nbTiles*360-180):0,v=currentVersion;for(var i=0;i<3;i++)for(var j=0;j<3;j++)getTile(zoom,absoluteX+i-1,absoluteY+j-1,{i:i,j:j,v:v}).then(function(img){if(img.v===currentVersion){mapCtx.drawImage(img.img,tileSize*img.i,tileSize*img.j,tileSize,tileSize);drawPlot(px- absoluteX,py-absoluteY,accRadiusPx)}}).catch(function(){})},currentZoom,setZoom=function(val){var newZoom=Math.max(4,Math.min(19,val));if(currentZoom!==newZoom){currentVersion++;currentZoom=newZoom;drawTiles(currentZoom,Number(geo["latitude"]),Number(geo["longitude"]),Number(geo["accuracy"]))}};setZoom(12);var canvasWrapper=document.createElement("div"),buttonContainer=document.createElement("div"),zoomP=document.createElement("button"),zoomM=document.createElement("button");canvasWrapper.className= R.klass.map.container;canvas.className=R.klass.map.canvas;buttonContainer.className=R.klass.map.buttonContainer;zoomM.className=R.klass.map.buttonM;zoomP.className=R.klass.map.buttonP;zoomM.addEventListener("click",function(){setZoom(currentZoom-1)});zoomP.addEventListener("click",function(){setZoom(currentZoom+1)});buttonContainer.appendChild(zoomM);buttonContainer.appendChild(zoomP);canvasWrapper.appendChild(canvas);canvasWrapper.appendChild(buttonContainer);return canvasWrapper}};function createTypingDisplay(){var dom=document.createElement("span"),dot1=document.createElement("span"),dot2=document.createElement("span"),dot3=document.createElement("span");dom.className=R.klass.typing.container;dot1.className=R.klass.typing.dot1;dot2.className=R.klass.typing.dot2;dot3.className=R.klass.typing.dot3;dot1.textContent=dot2.textContent=dot3.textContent=".";dom.appendChild(dot1);dom.appendChild(dot2);dom.appendChild(dot3);return dom} function createChanListItem(chan,alternateChanName){var dom=document.createElement("li"),link=document.createElement("a");dom.id="room_"+chan.id;link.href="#"+chan.id;if(chan.isPrivate){dom.className=R.klass.chatList.entry+" "+R.klass.chatList.typePrivate;dom.dataset["count"]=Object.keys(chan.users||{}).length}else dom.className=R.klass.chatList.entry+" "+R.klass.chatList.typeChannel;if(SELECTED_ROOM===chan)dom.classList.add(R.klass.selected);link.textContent=alternateChanName||chan.name;dom.appendChild(createTypingDisplay()); dom.appendChild(link);if(chan.lastMsg!==chan.lastRead&&chan.lastMsg!==undefined){dom.classList.add(R.klass.unread);if(HIGHLIGHTED_CHANS.indexOf(chan)>=0)dom.classList.add(R.klass.unreadHi)}return dom}var createChanListHeader=function(){var cache={};return function(title){var dom=cache[title];if(!dom){dom=cache[title]=document.createElement("header");dom.textContent=title}return dom}}(); function createImsListItem(ims,alternateChanName){var dom=document.createElement("li"),link=document.createElement("a");dom.id="room_"+ims.id;link.href="#"+ims.id;dom.className=R.klass.chatList.entry+" "+R.klass.chatList.typeDirect+" "+R.klass.presenceIndicator;link.textContent=alternateChanName||ims.user.getName();dom.appendChild(createTypingDisplay());dom.appendChild(link);if(!ims.user.presence)dom.classList.add(R.klass.presenceAway);if(SELECTED_ROOM===ims)dom.classList.add(R.klass.selected);if(ims.lastMsg!== ims.lastRead&&ims.lastMsg!==undefined){dom.classList.add(R.klass.unread);dom.classList.add(R.klass.unreadHi)}return dom} function tryGetCustomEmoji(emoji){var loop={},emojiName=emoji;if(SELECTED_CONTEXT){var ctx=SELECTED_CONTEXT.getChatContext();while(!loop[emoji]){var emojisrc=ctx.emojis.data[emoji];if(emojisrc)if(emojisrc.substr(0,6)=="alias:"){loop[emoji]=true;emoji=emojisrc.substr(6)}else{var dom=document.createElement("span");dom.className=R.klass.emoji.custom+" "+R.klass.emoji.emoji;dom.style.backgroundImage="url('"+emojisrc+"')";dom.textContent=":"+emojiName+":";dom.title=emojiName;return dom}else return emoji}}return emojiName} function makeEmojiDom(emojiCode){if("makeEmoji"in window){var emoji=tryGetCustomEmoji(emojiCode);if(typeof emoji==="string")emoji=window["makeEmoji"](emoji);return typeof emoji==="string"?null:emoji}return null} function createReactionDom(chanId,msgId,reaction,users){var emojiDom=makeEmojiDom(reaction);if(emojiDom){var dom=document.createElement("li"),a=document.createElement("a"),emojiContainer=document.createElement("span"),userList=document.createElement("span"),userNames=[];for(var i=0,nbUser=users.length;ibounds.bottom||e.screenXbounds.right)close()});overlay.className=R.klass.emojibar.overlay;dom.className=R.klass.emojibar.container;emojisDom.className=R.klass.emojibar.emojis;unicodeEmojis.className=customEmojis.className=R.klass.emojibar.list;searchBar.className=R.klass.emojibar.search;emojiDetail.className=R.klass.emojibar.detail.container;emojiDetailImg.className=R.klass.emojibar.detail.img;emojiDetailName.className=R.klass.emojibar.detail.name;emojiDetail.appendChild(emojiDetailImg); emojiDetail.appendChild(emojiDetailName);reset();dom.appendChild(emojisDom);dom.appendChild(emojiDetail);dom.appendChild(searchBar);searchBar.addEventListener("keyup",function(){search()});var makeDelegate=function(e,cb){var target=e.target;while(target!==dom&&target&&target.nodeName!=="LI")target=target.parentElement;if(target&&target.nodeName==="LI"&&target.id&&target.id.substr(0,"emojibar-".length)==="emojibar-"){var emojiId=target.id.substr("emojibar-".length);return cb(emojiId)}cb(null)};dom.addEventListener("mousemove", function(e){makeDelegate(e,function(emoji){var emojiCached=emoji?emojiCache.unicode[emoji]||emojiCache.custom[emoji]:null;if(emojiCached){emojiDetailImg.innerHTML=emojiCached.dom.outerHTML;emojiDetailName.textContent=":"+emoji+":"}else{emojiDetailImg.textContent="";emojiDetailName.textContent=""}})});dom.addEventListener("click",function(e){makeDelegate(e,function(emoji){if(emoji)onEmojiSelected(emoji)})});return{isSupported:isSupported,spawn:spawn,search:search,close:close,reset:function(){reset(); search()}}}();var DATA,HIGHLIGHTED_CHANS=[];function SimpleChatSystem(){ChatContext.call(this)}SimpleChatSystem.prototype=Object.create(ChatContext.prototype);SimpleChatSystem.prototype.constructor=SimpleChatSystem;SimpleChatSystem.prototype.getId=function(){return this.team?this.team.id:null};SimpleChatSystem.prototype.getChatContext=function(){return this};SimpleChatSystem.prototype.onRequest=function(){console.error("unimplemented")};SimpleChatSystem.prototype.sendMeMsg=function(chan,text){console.error("unimplemented")}; SimpleChatSystem.prototype.sendMsg=function(chan,text,attachments){console.error("unimplemented")};SimpleChatSystem.prototype.removeMsg=function(chan,ts){console.error("unimplemented")};SimpleChatSystem.prototype.starMsg=function(chan,msgId){console.error("unimplemented")};SimpleChatSystem.prototype.unstarMsg=function(chan,msgId){console.error("unimplemented")};SimpleChatSystem.prototype.pinMsg=function(chan,msgId){console.error("unimplemented")}; SimpleChatSystem.prototype.unpinMsg=function(chan,msgId){console.error("unimplemented")};SimpleChatSystem.prototype.editMsg=function(chan,ts,newText){console.error("unimplemented")};SimpleChatSystem.prototype.addReaction=function(chan,ts,reaction){console.error("unimplemented")};SimpleChatSystem.prototype.removeReaction=function(chan,ts,reaction){console.error("unimplemented")};SimpleChatSystem.prototype.openUploadFileStream=function(chan,contentType,callback){console.error("unimplemented")}; SimpleChatSystem.prototype.fetchHistory=function(chan){console.error("unimplemented")};SimpleChatSystem.prototype.sendTyping=function(chan){console.error("unimplemented")};SimpleChatSystem.prototype.markRead=function(chan,ts){console.error("unimplemented")};SimpleChatSystem.prototype.sendCommand=function(chan,cmd,args){console.error("unimplemented")};SimpleChatSystem.prototype.poll=function(knownVersion,now){console.error("unimplemented");return null}; SimpleChatSystem.prototype.getImage=function(path){console.error("unimplemented");return null};function SlackWrapper(){this.lastServerVersion=0;this.context=new MultiChatManager;this.history={}} SlackWrapper.prototype.update=function(data){var now=Date.now(),i;if(data["v"])this.lastServerVersion=data["v"];if(data["static"])for(i in data["static"]){var ctx=this.context.getById(i);if(!ctx){ctx=new SimpleChatSystem;this.context.push(ctx)}var pins={};if(data["static"][i]["channels"])data["static"][i]["channels"].forEach(function(chanInfo){if(chanInfo["pins"]){pins[chanInfo["id"]]=chanInfo["pins"];chanInfo["pins"]=undefined}});ctx.getChatContext().updateStatic(data["static"][i],now);for(var chanId in pins){var msgs= [],histo=this.history[chanId];if(!histo)histo=this.history[chanId]=new UiRoomHistory(chanId,250,null,now);pins[chanId].forEach(function(msg){msgs.push(histo.messageFactory(msg,now))});ctx.getChatContext().channels[chanId].pins=msgs}}this.context.foreachChannels(function(chan){if(chan.lastMsg===chan.lastRead){var pos=HIGHLIGHTED_CHANS.indexOf(chan);if(pos!==-1)HIGHLIGHTED_CHANS.splice(pos,1)}});if(data["live"]){for(i in data["live"]){var history=this.history[i];if(!history)history=this.history[i]= new UiRoomHistory(i,250,data["live"][i],now);else history.pushAll(data["live"][i],now)}for(var roomId in data["live"]){var liveCtx=this.context.getChannelContext(roomId).getChatContext(),chan=liveCtx.channels[roomId];if(chan){if(this.history[roomId].messages.length)chan.setLastMsg(this.history[roomId].lastMessage().ts,now);if(!chan.archived){onMsgReceived(liveCtx,chan,data["live"][roomId]);if(SELECTED_ROOM&&data["live"][SELECTED_ROOM.id])onRoomUpdated()}}else outOfSync()}}if(data["static"])onContextUpdated(); var typingUpdated=false;if(data["typing"])this.context.contexts.forEach(function(ctx){var chatCtx=ctx.getChatContext();typingUpdated|=chatCtx.updateTyping(data["typing"],now)},this);if(data["static"]||typingUpdated)onTypingUpdated();if(data["config"]){CONFIG=new Config(data["config"]);onConfigUpdated()}if(SELECTED_CONTEXT&&SELECTED_ROOM&&data["static"]&&data["static"][SELECTED_CONTEXT.team.id]&&data["static"][SELECTED_CONTEXT.team.id]["channels"]&&data["static"][SELECTED_CONTEXT.team.id]["channels"]){var arr= data["static"][SELECTED_CONTEXT.team.id]["channels"];i=0;for(var nbChan=arr.length;iroom.lastRead){var history=DATA.history[room.id];if(history){var lastMsg=history.lastMessage();if(lastMsg){sendReadMarker(room,lastMsg.id,lastMsg.ts);room.lastRead=lastMsg.ts}}}if(highlightIndex>=0){HIGHLIGHTED_CHANS.splice(highlightIndex,1);updateTitle()}var roomLi=document.getElementById("room_"+room.id);roomLi.classList.remove(R.klass.unread);roomLi.classList.remove(R.klass.unreadHi)} function invalidateAllMessages(){for(var i in DATA.history)DATA.history[i].invalidateAllMessages();if(SELECTED_ROOM)onRoomUpdated()}DATA=new SlackWrapper;var createContextBackground=function(){var canvas=document.createElement("canvas"),ctx=canvas.getContext("2d"),WIDTH=canvas.width=250,HEIGHT=canvas.height=290,MARGIN=20,NB_ITEM=3,ITEM_SIZE=(WIDTH-2*MARGIN)/NB_ITEM,ITEM_SPACING=.1*ITEM_SIZE,ITEM_INNER_SIZE=Math.floor(ITEM_SIZE-ITEM_SPACING*2),AVATAR_SIZE=ITEM_INNER_SIZE*.5,RESULT={},drawItem=function(background,avatar,x0,y0){var y0Index=Math.floor(y0),y1Index=Math.floor(y0+ITEM_SIZE),topColor=[background.data[y0Index*WIDTH*4+0],background.data[y0Index* WIDTH*4+1],background.data[y0Index*WIDTH*4+2]],botColor=[background.data[y1Index*WIDTH*4+0],background.data[y1Index*WIDTH*4+1],background.data[y1Index*WIDTH*4+2]],targetPcent=1.1,targetColor=(topColor[0]*targetPcent<<16|topColor[1]*targetPcent<<8|topColor[2]*targetPcent).toString(16);ctx.fillStyle="#"+targetColor;ctx.beginPath();ctx.moveTo(x0+ITEM_SIZE/2,y0+ITEM_SPACING);ctx.lineTo(x0-ITEM_SPACING+ITEM_SIZE,y0+ITEM_SIZE/2);ctx.lineTo(x0+ITEM_SIZE/2,y0-ITEM_SPACING+ITEM_SIZE);ctx.lineTo(x0+ITEM_SPACING, y0+ITEM_SIZE/2);ctx.closePath();ctx.fill();ctx.putImageData(blend(ctx.getImageData(x0+ITEM_SPACING,y0+ITEM_SPACING,ITEM_INNER_SIZE,ITEM_INNER_SIZE),avatar),x0+ITEM_SPACING,y0+ITEM_SPACING)},blend=function(img,img2){var margin=(img.height-img2.height)/2;for(var i=0;i'"]}if(!this.isColorfulNames())rules[".chatmsg-authorGroup .chatmsg-item .chatmsg-link-user, .chatsystem-content a.chatmsg-author-name, .chatmsg-author-name"]=["background-color: transparent !important;"];for(var i in rules){css+=i+"{";rules[i].forEach(function(rule){css+=rule+";"});css+="}"}return css};CONFIG=new Config([]);function AbstractRawTCPSocket(){this.onReadyReadHandlers=[]}AbstractRawTCPSocket.prototype.connect=function(){};AbstractRawTCPSocket.prototype.write=function(msg){};AbstractRawTCPSocket.prototype.onReadyRead=function(onReadyRead){this.onReadyReadHandlers.push(onReadyRead)};AbstractRawTCPSocket.prototype.triggerOnReadyRead=function(msg){this.onReadyReadHandlers.forEach(function(handler){handler(msg)})};AbstractRawTCPSocket.prototype.close=function(){}; function NativeRawTCPSocket(address,port){AbstractRawTCPSocket.apply(this);this.socketId=NativeRawTCPSocket.sockCount++;NativeRawTCPSocket.sockets[this.socketId]=this;this.address=address;this.port=port;this.connectPromise}NativeRawTCPSocket.prototype=Object.create(AbstractRawTCPSocket);NativeRawTCPSocket.prototype.constructor=NativeRawTCPSocket; NativeRawTCPSocket.prototype.connect=function(){return new Promise(function(onSuccess,onReject){this.connectPromise={onSuccess:onSuccess,onReject:onReject};__native.TCPConnect(this.socketId,this.address,this.port)})};NativeRawTCPSocket.prototype.onConnected=function(success){if(this.connectPromise){if(success)this.connectPromise.onSuccess();else this.connectPromise.onReject();this.connectPromise=null}};NativeRawTCPSocket.prototype.write=function(msg){__native.TCPWrite(this.socketId,msg)}; NativeRawTCPSocket.prototype.close=function(){__native.TCPClose(this.socketId)};NativeRawTCPSocket.sockCount=0;NativeRawTCPSocket.sockets={};NativeRawTCPSocket.onConnected=function(sockId,success){NativeRawTCPSocket.sockets[sockId].onConnected(success)};NativeRawTCPSocket.onReadyRead=function(sockId,msg){NativeRawTCPSocket.sockets[sockId].triggerOnReadyRead(msg)};function createSocket(address,port){if(isNative())return new NativeRawTCPSocket(address,port);return null};var CALLBACK=function(){var callbacks={},currentCallbackId=0;function makeCallback(fnc,ctx){var cbId=currentCallbackId++;if(ctx)fnc.ctx=ctx;callbacks[""+cbId]=fnc;return cbId}function triggerCallback(){var id=""+Array.prototype.shift.call(arguments);if(callbacks[id]){callbacks[id].apply(callbacks[id].ctx,arguments);delete callbacks[id]}}return{makeCallback:makeCallback,onCallbackResponse:triggerCallback}}();window["__CALLBACK"]={"onResult":CALLBACK.onCallbackResponse}; function isNative(){return!!("__native"in window)};window["displayMenu"]=function(){document.getElementById(R.id.context).classList.add(R.klass.opened)};window["hideMenu"]=function(){document.getElementById(R.id.context).classList.remove(R.klass.opened)};window["toggleMenu"]=function(){_toggleMenu()};window["setChannelFavorite"]=function(chanId,val){var channel=DATA.context.getChannel(chanId);if(channel)if(val)starChannel(channel);else unstarChannel(channel);else console.error("Channel "+chanId+" not found")}; window["onApplicationPaused"]=function(){window.hasFocus=false};window["onApplicationResumed"]=function(){window.hasFocus=true};var CLIENT_COMMANDS=function(){var commands=[];return{getCommand:function(name){for(var i=0,nbCmd=commands.length;i