Bug 830456 - Code cleanup in /chat/: Use new String methods like startsWith, endsWith, contains, remaining Services.jsm switches and querySelector use instead of NodeList calls. r=florian
authorSebastian Hengst <archaeopteryx@coole-files.de>
Sun, 10 Feb 2013 22:33:09 +0100
changeset 18955 ae97345ea5509f95a2c9e06390a0fb50b18ef5b4
parent 18954 f860f7ade2ee70d47d5835b7966ad23332baf67c
child 18956 7d70e6a10e3d2bee3076f006c828337490c0d536
push id1103
push usermbanner@mozilla.com
push dateTue, 18 Mar 2014 07:44:06 +0000
treeherdercomm-beta@50c6279a0af0 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersflorian
bugs830456
Bug 830456 - Code cleanup in /chat/: Use new String methods like startsWith, endsWith, contains, remaining Services.jsm switches and querySelector use instead of NodeList calls. r=florian
chat/components/src/imAccounts.js
chat/components/src/logger.js
chat/content/convbrowser.xml
chat/modules/imContentSink.jsm
chat/modules/imSmileys.jsm
chat/modules/imThemes.jsm
chat/modules/imXPCOMUtils.jsm
chat/protocols/facebook/facebook.js
chat/protocols/irc/irc.js
chat/protocols/irc/ircBase.jsm
chat/protocols/irc/ircCommands.jsm
chat/protocols/odnoklassniki/odnoklassniki.js
chat/protocols/twitter/twitter.js
chat/protocols/vkontakte/vkontakte.js
chat/protocols/xmpp/xmpp.jsm
--- a/chat/components/src/imAccounts.js
+++ b/chat/components/src/imAccounts.js
@@ -95,17 +95,17 @@ UnknownProtocol.prototype = {
   get usePurpleProxy() false
 };
 
 // aName and aPrplId are provided as parameter only if this is a new
 // account that doesn't exist in the preferences. In this case, these
 // 2 values should be stored.
 function imAccount(aKey, aName, aPrplId)
 {
-  if (aKey.indexOf(kAccountKeyPrefix) != 0)
+  if (!aKey.startsWith(kAccountKeyPrefix))
     throw Cr.NS_ERROR_INVALID_ARG;
 
   this.id = aKey;
   this.numericId = parseInt(aKey.substr(kAccountKeyPrefix.length));
   this.prefBranch = Services.prefs.getBranch(kPrefAccountPrefix + aKey + ".");
 
   if (aName) {
     this.name = aName;
@@ -775,17 +775,17 @@ AccountsService.prototype = {
   _prefObserver: null,
   observe: function(aSubject, aTopic, aData) {
     if (aTopic != "nsPref:changed" || aData != kPrefMessengerAccounts ||
        !this._observingAccountListChange)
       return;
 
     this._accounts =
       this._accountList.split(",").map(String.trim)
-          .filter(function (k) k.indexOf(kAccountKeyPrefix) == 0)
+          .filter(function (k) k.startsWith(kAccountKeyPrefix))
           .map(function (k) parseInt(k.substr(kAccountKeyPrefix.length)))
           .map(this.getAccountByNumericId, this)
           .filter(function (a) a);
 
     Services.obs.notifyObservers(this, "account-list-updated", null);
   },
 
   get _accountList() Services.prefs.getCharPref(kPrefMessengerAccounts),
@@ -916,17 +916,17 @@ AccountsService.prototype = {
 
     this._checkingIfPasswordStillMissing = true;
     for each (let account in this._accounts)
       account._checkIfPasswordStillMissing();
     delete this._checkingIfPasswordStillMissing;
   },
 
   getAccountById: function(aAccountId) {
-    if (aAccountId.indexOf(kAccountKeyPrefix) != 0)
+    if (!aAccountId.startsWith(kAccountKeyPrefix))
       throw Cr.NS_ERROR_INVALID_ARG;
 
     let id = parseInt(aAccountId.substr(kAccountKeyPrefix.length));
     return this.getAccountByNumericId(id);
   },
 
   _keepAccount: function(aAccount) {
     this._accounts.push(aAccount);
--- a/chat/components/src/logger.js
+++ b/chat/components/src/logger.js
@@ -180,18 +180,18 @@ ConversationLog.prototype = {
     let msg = this._serialize(aMessage.originalMessage);
     if (aMessage.system)
       line += msg;
     else {
       let sender = aMessage.alias || aMessage.who;
       if (aMessage.autoResponse)
         line += sender + " <AUTO-REPLY>: " + msg;
       else {
-        if (/^\/me /.test(msg))
-          line += "***" + sender + " " + msg.replace(/^\/me /, "");
+        if (msg.startsWith("/me "))
+          line += "***" + sender + " " + msg.substr(4);
         else
           line += sender + ": " + msg;
       }
     }
     this._log.writeString(line + kLineBreak);
   },
 
   close: function cl_close() {
--- a/chat/content/convbrowser.xml
+++ b/chat/content/convbrowser.xml
@@ -213,17 +213,17 @@
       </method>
 
       <field name="_autoScrollEnabled">true</field>
 
       <method name="_updateAutoScrollEnabled">
         <body>
           <![CDATA[
             // Enable auto-scroll if the scrollbar is at the bottom.
-            let body = this.contentDocument.getElementsByTagName("body")[0];
+            let body = this.contentDocument.querySelector("body");
             this._autoScrollEnabled =
               body.scrollHeight <= body.scrollTop + body.clientHeight + 10;
             return this._autoScrollEnabled;
           ]]>
          </body>
       </method>
 
       <method name="_scrollToElement">
--- a/chat/modules/imContentSink.jsm
+++ b/chat/modules/imContentSink.jsm
@@ -328,12 +328,12 @@ function cleanupNode(aNode, aRules, aTex
 function cleanupImMarkup(aText, aRuleset, aTextModifiers)
 {
   if (!gGlobalRuleset)
     initGlobalRuleset();
 
   let parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
                          .createInstance(Components.interfaces.nsIDOMParser);
   let doc = parser.parseFromString(aText, "text/html");
-  let div = doc.getElementsByTagName("body")[0];
+  let div = doc.querySelector("body");
   cleanupNode(div, aRuleset || gGlobalRuleset, aTextModifiers || []);
   return div.innerHTML;
 }
--- a/chat/modules/imSmileys.jsm
+++ b/chat/modules/imSmileys.jsm
@@ -152,17 +152,17 @@ function smileTextNode(aNode)
    *   data: The URL is not the only content in the link, skip only the one node
    * Check the class name to skip any autolinked nodes from mozTXTToHTMLConv.
    */
   let testNode = aNode;
   while ((testNode = testNode.parentNode)) {
     if (testNode instanceof Components.interfaces.nsIDOMHTMLAnchorElement &&
         (testNode.getAttribute("href") == testNode.textContent.trim() ||
          testNode.getAttribute("href") == aNode.data.trim() ||
-         testNode.className.indexOf("moz-txt-link-") != -1))
+         testNode.className.contains("moz-txt-link-")))
       return 0;
   }
 
   let result = 0;
   let exp = getRegexp();
   if (!exp)
     return result;
 
--- a/chat/modules/imThemes.jsm
+++ b/chat/modules/imThemes.jsm
@@ -282,19 +282,18 @@ function getDirectoryEntries(aDir)
   }
 
   return results;
 }
 
 function getThemeVariants(aTheme)
 {
   let variants = getDirectoryEntries(aTheme.baseURI + "Variants/");
-  let cssRe = /\.css$/;
-  return variants.filter(function(v) cssRe.test(v))
-                 .map(function(v) v.replace(cssRe, ""));
+  return variants.filter(function(v) v.endsWith(".css"))
+                 .map(function(v) v.substring(0, v.length - 4));
 }
 
 /* helper function for replacements in messages */
 function getBuddyFromMessage(aMsg)
 {
   if (aMsg.incoming) {
     let conv = aMsg.conversation;
     if (!conv.isChat)
--- a/chat/modules/imXPCOMUtils.jsm
+++ b/chat/modules/imXPCOMUtils.jsm
@@ -15,16 +15,18 @@ const EXPORTED_SYMBOLS = [
   "initLogModule"
 ];
 
 const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource:///modules/imServices.jsm");
 
+const kLogLevelPref = "purple.debug.loglevel";
+
 /**
  * Creates an nsIScriptError instance and logs it.
  *
  * @param aModule
  *        string identifying the module within which the error occurred.
  * @param aLevel
  *        the error level as defined in imIDebugMessage.
  * @param aMessage
@@ -99,34 +101,33 @@ function initLogModule(aModule, aThis)
 XPCOMUtils.defineLazyGetter(Cu.getGlobalForObject({}), "gLogLevels", function() {
   // This object functions both as an obsever as well as a dict keeping the
   // log levels with prefs; the log levels all start with "level" (i.e. "level"
   // for the global level, "level.irc" for the IRC module).  The dual-purpose
   // is necessary to make sure the observe is left alive while being a weak ref
   // to avoid cycles with the pref service.
   let logLevels = {
     observe: function(aSubject, aTopic, aData) {
-      let module = "level" + aData.replace(/^purple.debug.loglevel/, "");
+      let module = "level" + aData.substr(kLogLevelPref.length);
       if (Services.prefs.getPrefType(aData) == Services.prefs.PREF_INT)
         gLogLevels[module] = Services.prefs.getIntPref(aData);
       else
         delete gLogLevels[module];
     },
     QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
                                            Ci.nsISupportsWeakReference]),
   };
 
   // Add weak pref observer to see log level pref changes.
-  Services.prefs.addObserver("purple.debug.loglevel", logLevels, true /* weak */);
+  Services.prefs.addObserver(kLogLevelPref, logLevels, true /* weak */);
 
   // Initialize with existing log level prefs.
-  for each (let pref in Services.prefs.getChildList("purple.debug.loglevel")) {
+  for each (let pref in Services.prefs.getChildList(kLogLevelPref)) {
     if (Services.prefs.getPrefType(pref) == Services.prefs.PREF_INT)
-      logLevels["level" + pref.replace(/^purple.debug.loglevel/, "")] =
-        Services.prefs.getIntPref(pref);
+      logLevels["level" + pref.substr(kLogLevelPref.length)] = Services.prefs.getIntPref(pref);
   }
 
   // Let environment variables override prefs.
   Cc["@mozilla.org/process/environment;1"]
     .getService(Ci.nsIEnvironment)
     .get("PRPL_LOG")
     .split(/[;,]/)
     .filter(function(n) n != "")
--- a/chat/protocols/facebook/facebook.js
+++ b/chat/protocols/facebook/facebook.js
@@ -15,17 +15,17 @@ XPCOMUtils.defineLazyGetter(this, "_", f
 
 function FacebookAccount(aProtoInstance, aImAccount) {
   this._init(aProtoInstance, aImAccount);
 }
 FacebookAccount.prototype = {
   __proto__: XMPPAccountPrototype,
   get canJoinChat() false,
   connect: function() {
-    if (this.name.indexOf("@") == -1) {
+    if (!this.name.contains("@")) {
       let jid = this.name + "@chat.facebook.com/" + XMPPDefaultResource;
       this._jid = this._parseJID(jid);
     }
     else {
       this._jid = this._parseJID(this.name);
       if (this._jid.domain != "chat.facebook.com") {
         // We can't use this.onError because this._connection doesn't exist.
         this.reportDisconnecting(Ci.prplIAccount.ERROR_INVALID_USERNAME,
--- a/chat/protocols/irc/irc.js
+++ b/chat/protocols/irc/irc.js
@@ -1271,27 +1271,27 @@ ircAccount.prototype = {
       return null;
     }
 
     let message = aCommand;
     // If aParams is empty, then use an empty array. If aParams is not an array,
     // consider it to be a single parameter and put it into an array.
     let params = !aParams ? [] : Array.isArray(aParams) ? aParams : [aParams];
     if (params.length) {
-      if (params.slice(0, -1).some(function(p) p.indexOf(" ") != -1)) {
+      if (params.slice(0, -1).some(function(p) p.contains(" "))) {
         this.ERROR("IRC parameters cannot have spaces: " + params.slice(0, -1));
         return null;
       }
       // Join the parameters with spaces. There are three cases in which the
       // last parameter ("trailing" in RFC 2812) must be prepended with a colon:
       //  1. If the last parameter contains a space.
       //  2. If the first character of the last parameter is a colon.
       //  3. If the last parameter is an empty string.
       let trailing = params.slice(-1)[0];
-      if (!trailing.length || trailing.indexOf(" ") != -1 || trailing[0] == ":")
+      if (!trailing.length || trailing.contains(" ") || trailing.startsWith(":"))
         params.push(":" + params.pop());
       message += " " + params.join(" ");
     }
 
     return message;
   },
 
   // Shortcut method to build & send a message at once. Use aLoggedData to log
--- a/chat/protocols/irc/ircBase.jsm
+++ b/chat/protocols/irc/ircBase.jsm
@@ -309,17 +309,17 @@ var ircBase = {
       // Display message in conversation
       return privmsg(this, aMessage);
     },
     "QUIT": function(aMessage) {
       // QUIT [ < Quit Message> ]
       // Some IRC servers automatically prefix a "Quit: " string. Remove the
       // duplication and use a localized version.
       let quitMsg = aMessage.params[0] || "";
-      if (quitMsg.indexOf("Quit: ") == 0)
+      if (quitMsg.startsWith("Quit: "))
         quitMsg = quitMsg.slice(6); // "Quit: ".length
       // If a quit message was included, show it.
       let msg = _("message.quit", aMessage.nickname,
                   quitMsg.length ? _("message.quit2", quitMsg) : "");
       // Loop over every conversation with the user and display that they quit.
       for each (let conversation in this._conversations) {
         if (conversation.isChat &&
             conversation.hasParticipant(aMessage.nickname)) {
--- a/chat/protocols/irc/ircCommands.jsm
+++ b/chat/protocols/irc/ircCommands.jsm
@@ -202,17 +202,17 @@ var commands = [
     get helpString() _("command.memoserv", "memoserv"),
     run: function(aMsg, aConv) privateMessage(aConv, aMsg, "MemoServ")
   },
   {
     name: "mode",
     get helpString() _("command.modeUser", "mode") + "\n" +
                      _("command.modeChannel", "mode"),
     run: function(aMsg, aConv) {
-      function isMode(aString) "+-".indexOf(aString[0]) != -1;
+      function isMode(aString) "+-".contains(aString[0]);
       let params = splitInput(aMsg);
 
       // Check if we have any params, we can't just check params.length, since
       // that will always be at least 1 (but params[0] would be empty).
       let hasParams = !/^\s*$/.test(aMsg);
       let account = getAccount(aConv);
       // These must be false if we don't have any paramters!
       let isChannelName = hasParams && account.isMUCName(params[0]);
@@ -361,17 +361,17 @@ var commands = [
   },
   {
     name: "whois",
     get helpString() _("command.whois2", "whois"),
     run: function(aMsg, aConv) {
       // Note that this will automatically run whowas if the nick is offline.
       aMsg = aMsg.trim();
       // If multiple parameters are given, this is an error.
-      if (aMsg.indexOf(" ") != -1)
+      if (aMsg.contains(" "))
         return false;
       // If the user does not provide a nick, but is in a private conversation,
       // assume the user is trying to whois the person they are talking to.
       if (!aMsg) {
         if (aConv.isChat)
           return false;
         aMsg = aConv.name;
       }
--- a/chat/protocols/odnoklassniki/odnoklassniki.js
+++ b/chat/protocols/odnoklassniki/odnoklassniki.js
@@ -15,17 +15,17 @@ XPCOMUtils.defineLazyGetter(this, "_", f
 
 function OdnoklassnikiAccount(aProtoInstance, aImAccount) {
   this._init(aProtoInstance, aImAccount);
 }
 OdnoklassnikiAccount.prototype = {
   __proto__: XMPPAccountPrototype,
   get canJoinChat() false,
   connect: function() {
-    if (this.name.indexOf("@") == -1) {
+    if (!this.name.contains("@")) {
       let jid = this.name + "@odnoklassniki.ru/" + XMPPDefaultResource;
       this._jid = this._parseJID(jid);
     }
     else {
       this._jid = this._parseJID(this.name);
       if (this._jid.domain != "odnoklassniki.ru") {
         // We can't use this.onError because this._connection doesn't exist.
         this.reportDisconnecting(Ci.prplIAccount.ERROR_INVALID_USERNAME,
--- a/chat/protocols/twitter/twitter.js
+++ b/chat/protocols/twitter/twitter.js
@@ -312,17 +312,17 @@ Conversation.prototype = {
     let name = aTweet.user.screen_name;
     this._ensureParticipantExists(name);
     let text = this.parseTweet(aTweet);
 
     let flags =
       name == this._account.name ? {outgoing: true} : {incoming: true};
     flags.time = Math.round(new Date(aTweet.created_at) / 1000);
     flags._iconURL = aTweet.user.profile_image_url;
-    if (text.indexOf("@" + this.nick) != -1)
+    if (text.contains("@" + this.nick))
       flags.containsNick = true;
 
     (new Tweet(aTweet, name, text, flags)).conversation = this;
   },
   _ensureParticipantExists: function(aNick) {
     if (hasOwnProperty(this._participants, aNick))
       return;
 
@@ -824,17 +824,17 @@ Account.prototype = {
           QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener,
                                                  Ci.nsISupportsWeakReference]),
           _cleanUp: function() {
             this.webProgress.removeProgressListener(this);
             this.window.close();
             delete this.window;
           },
           _checkForRedirect: function(aURL) {
-            if (aURL.indexOf(this._parent.completionURI) != 0)
+            if (!aURL.startsWith(this._parent.completionURI))
               return;
 
             this._parent.finishAuthorizationRequest();
             this._parent.onAuthorizationReceived(aURL);
           },
           onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) {
             const wpl = Ci.nsIWebProgressListener;
             if (aStateFlags & (wpl.STATE_START | wpl.STATE_IS_NETWORK))
--- a/chat/protocols/vkontakte/vkontakte.js
+++ b/chat/protocols/vkontakte/vkontakte.js
@@ -15,17 +15,17 @@ XPCOMUtils.defineLazyGetter(this, "_", f
 
 function VkontakteAccount(aProtoInstance, aImAccount) {
   this._init(aProtoInstance, aImAccount);
 }
 VkontakteAccount.prototype = {
   __proto__: XMPPAccountPrototype,
   get canJoinChat() false,
   connect: function() {
-    if (this.name.indexOf("@") == -1) {
+    if (!this.name.contains("@")) {
       let jid = this.name + "@vk.com/" + XMPPDefaultResource;
       this._jid = this._parseJID(jid);
     }
     else {
       this._jid = this._parseJID(this.name);
       if (this._jid.domain != "vk.com") {
         // We can't use this.onError because this._connection doesn't exist.
         this.reportDisconnecting(Ci.prplIAccount.ERROR_INVALID_USERNAME,
--- a/chat/protocols/xmpp/xmpp.jsm
+++ b/chat/protocols/xmpp/xmpp.jsm
@@ -744,17 +744,17 @@ const XMPPAccountPrototype = {
     this._disconnect();
   },
 
   addBuddy: function(aTag, aName) {
     if (!this._connection)
       throw "The account isn't connected";
 
     let jid = this._normalizeJID(aName);
-    if (!jid || jid.indexOf("@") == -1)
+    if (!jid || !jid.contains("@"))
       throw "Invalid username";
 
     if (this._buddies.hasOwnProperty(jid)) {
       let subscription = this._buddies[jid].subscription;
       if (subscription && (subscription == "both" || subscription == "to")) {
         this.DEBUG("not re-adding an existing buddy");
         return;
       }