]> git.example.dev Git - binbsis50.git/commitdiff
refactored slash commands system
authorLuigi Pinca <luigipinca@gmail.com>
Fri, 28 Dec 2012 10:17:23 +0000 (11:17 +0100)
committerLuigi Pinca <luigipinca@gmail.com>
Fri, 28 Dec 2012 10:17:23 +0000 (11:17 +0100)
app.js
lib/room.js
package.json
public/js/app.js

diff --git a/app.js b/app.js
index 50c8ddd8903c886a1dacb22fab6f2cd3e1085e09..f950a07470351a3d88ddfe53240f3289ebfa0861 100644 (file)
--- a/app.js
+++ b/app.js
@@ -121,9 +121,9 @@ io.sockets.on('connection', function(socket) {
             rooms[socket.roomname].guess(socket, guess);
         }
     });
-    socket.on('ignore', function(baduser, callback) {
-        if (socket.roomname && typeof baduser === 'string' && typeof callback === 'function') {
-            rooms[socket.roomname].ignore(baduser, socket.nickname, callback);
+    socket.on('ignore', function(who, callback) {
+        if (socket.roomname && typeof who === 'string' && typeof callback === 'function') {
+            rooms[socket.roomname].ignore(who, socket.nickname, callback);
         }
     });
     socket.on('joinanonymously', function(nickname, roomname) {
@@ -142,9 +142,10 @@ io.sockets.on('connection', function(socket) {
             rooms[room].joinRoom(socket);
         }
     });
-    socket.on('kick', function(baduser, callback) {
-        if (socket.roomname && typeof baduser === 'string' && typeof callback === 'function') {
-            rooms[socket.roomname].kick(baduser, socket.nickname, callback);
+    socket.on('kick', function(who, why, callback) {
+        if (socket.roomname && typeof who === 'string' && typeof why === 'string' &&
+            typeof callback === 'function') {
+            rooms[socket.roomname].kick(who, why, socket.nickname, callback);
         }
     });
     socket.on('loggedin', function(callback) {
@@ -158,9 +159,9 @@ io.sockets.on('connection', function(socket) {
             rooms[socket.roomname].sendChatMessage(msg, socket, to);
         }
     });
-    socket.on('unignore', function(baduser) {
-        if (socket.roomname && typeof baduser === 'string') {
-            rooms[socket.roomname].unignore(baduser, socket.nickname);
+    socket.on('unignore', function(who) {
+        if (socket.roomname && typeof who === 'string') {
+            rooms[socket.roomname].unignore(who, socket.nickname);
         }
     });
 });
index ef606a441f34e26eef65338584c082ac17ec1209..3163df203fd608e6c591d5ea360145ff220675ef 100644 (file)
@@ -244,13 +244,13 @@ function Room(roomname) {
         }
     };
 
-    this.ignore = function(baduser, executor, callback) {
+    this.ignore = function(who, executor, callback) {
         // Check if the player to be ignored is in the room
-        if (usersData[baduser]) {
+        if (usersData[who]) {
             // Inform the bad player that he/she is being ignored
-            var recipient = sockets[baduser];
-            recipient.emit('chatmsg', executor+' is ignoring you.', 'binb', baduser);
-            return callback(baduser);
+            var recipient = sockets[who];
+            recipient.emit('chatmsg', executor+' is ignoring you.', 'binb', who);
+            return callback(who);
         }
         callback(false);
     };
@@ -262,13 +262,16 @@ function Room(roomname) {
     };
 
     // Kick a user
-    this.kick = function(baduser, executor, callback) {
+    this.kick = function(who, why, executor, callback) {
         usersdb.hget('user:'+executor, 'role', function (err, role) {
             if (role > 0) { // Check role
-                if (usersData[baduser]) {
-                    var notice = 'you have been kicked by '+executor+'.';
-                    var recipient = sockets[baduser];
-                    recipient.emit('chatmsg', notice, 'binb', baduser);
+                if (usersData[who]) {
+                    if (why) {
+                        why = ' ('+why+')';
+                    }
+                    var notice = 'you have been kicked by '+executor+why+'.';
+                    var recipient = sockets[who];
+                    recipient.emit('chatmsg', notice, 'binb', who);
                     recipient.disconnect();
                 }
                 return;
@@ -448,12 +451,12 @@ function Room(roomname) {
         sendLoadTrack();
     };
 
-    this.unignore = function(baduser, executor) {
-        if (usersData[baduser]) {
+    this.unignore = function(who, executor) {
+        if (usersData[who]) {
             // Inform the bad player that he/she is no longer ignored
             var notice = executor+' has stopped ignoring you.';
-            var recipient = sockets[baduser];
-            recipient.emit('chatmsg', notice, 'binb', baduser);
+            var recipient = sockets[who];
+            recipient.emit('chatmsg', notice, 'binb', who);
         }
     };
 }
index 1d775619dc8fe665e61ae21cf53a1efc681ae07b..f2e491de0985dabc83261e3f3753acd1e3e2e478 100644 (file)
@@ -11,7 +11,8 @@
     "socket.io"
   ],
   "dependencies": {
-    "canvas": "0.13.x"
+    "canvas": "0.13.x",
+    "ws": "0.4.x"
   },
   "engines": {
     "node": "0.8.x"
@@ -21,5 +22,5 @@
     "start": "app.js"
   },
   "subdomain": "binb",
-  "version": "0.3.5-2"
-}
\ No newline at end of file
+  "version": "0.3.5-3"
+}
index 2442b368f28770412607d86a691f58912d2b9e68..252da32de0405462c17c8bb04b9292581ce05a63 100644 (file)
@@ -1,5 +1,5 @@
 (function() {
-    
+
     var elapsedtime = 0
         , DOM = {}
         , historycursor = 0
         loadFromCookie();
     };
 
-    /* Triggered when a logged user tries to join a room from another tab or another browser
-        and he is already in a room */
+    // Called when a registered user already in a room, tries to enter in another room
     var alreadyInARoom = function() {
         var html = '<div class="modal-header"><h3>Already in a room</h3></div>';
         html += '<div class="modal-body"><div class="alert alert-error alert-block">';
     };
 
     // Put a player in the ignore list
-    var ignore = function(baduser, outcome) {
-        socket.emit('ignore', baduser, function(player) {
+    var ignorePlayer = function(args, outcome) {
+        if (ignoredplayers[args[0]]) {
+            outcome.text('(From binb): '+args[0]+' is already ignored.');
+            return addChatEntry(outcome);
+        }
+        socket.emit('ignore', args[0], function(player) {
             if (player) {
                 ignoredplayers[player] = true;
                 outcome.text('(From binb): '+player+' is now ignored.');
         joinAnonymously(feedback+'<br/>Try with another one:');
     };
 
-    // Prompt for name and send it.
+    // Prompt for name and send it
     var joinAnonymously = function(msg) {
         if (/nickname\s*\=/.test(document.cookie) && !msg) {
             var encodednickname = document.cookie.replace(/.*nickname\s*\=\s*([^;]*);?.*/, '$1');
     };
 
     // Kick a player
-    var kick = function(baduser, outcome) {
-        socket.emit('kick', baduser, function() {
-            outcome.append('you are not allowed to kick a player.');
+    var kickPlayer = function(args, outcome) {
+        outcome.append('you are not allowed to kick a player.');
+        if (!subscriber) {
+            return addChatEntry(outcome);
+        }
+        var why = args[1] || '';
+        socket.emit('kick', args[0], why, function() {
             addChatEntry(outcome);
         });
     };
         jplayer.jPlayer('setMedia', {m4a: previewUrl});
     };
 
+    /**
+     * Given a string, parse the string extracting fields separated by whitespace
+     * and optionally enclosed within double quotes (which are stripped off), and
+     * build an array of copies of the string for each field.
+     */
+
+    var parseCommand = function(input) {
+        var inquotes = false
+            , token = ''
+            , tokens = [];
+        for (var i = 0; i < input.length; i++) {
+            if (input[i] === '\\') {
+                if (++i === input.length) {
+                    throw new Error('SyntaxError: Unexpected end of input');
+                }
+                if (input[i] === '\\' || input[i] === '"' || !inquotes) {
+                    token += input[i];
+                    continue;
+                }
+                token += '\\'+input[i];
+                continue;
+            }
+            if (input[i] === '"') {
+                inquotes = !inquotes;
+                var j = i + 1;
+                if (!inquotes && (input[j] === ' ' || j === input.length)) {
+                    tokens.push(token);
+                    token = '';
+                    i = j;
+                }
+                continue;
+            }
+            if (input[i] === ' ') {
+                if (inquotes) {
+                    token += ' ';
+                }
+                else if (token.length) {
+                    tokens.push(token);
+                    token = '';
+                }
+                continue;
+            }
+            token += input[i];
+        }
+        if (inquotes) {
+            throw new Error('SyntaxError: Unexpected end of input');
+        }
+        if (token.length) {
+            tokens.push(token);
+        }
+        return tokens;
+    };
+
     // Play a track
     var playTrack = function(data) {
         if (touchplay) {
     };
 
     var slashCommandHandler = function(line) {
-        var matches = line.match(/^(\/[^ ]+) ?(.*)/)
-            , argument = matches[2]
-            , command = matches[1]
-            , outcome = $('<span class="message private">(From binb): </span>');
-
-        if (/^\/(?:(?:un)?ignore|kick)$/.test(command)) {
-            if (!argument) {
-                outcome.append('usage: '+command+' &lt;player name&gt;');
+        var args;
+        var outcome = $('<span class="message private">(From binb): </span>');
+
+        try {
+            args = parseCommand(line);
+        }
+        catch (err) {
+            outcome.append(err.message);
+            return addChatEntry(outcome);
+        }
+
+        var cmdname = args.shift();
+        var command = slashcommands[cmdname.substr(1)];
+
+        if (command) {
+            if (args.length < command.minargs) {
+                outcome.append(command.usage);
                 return addChatEntry(outcome);
             }
-            if (argument === nickname) {
-                outcome.append('you can\'t '+command.replace(/^\//, '')+' yourself.');
+            if (command.checkrecipient && (!args[0] || args[0] === nickname)) {
+                outcome.append('invalid argument.');
                 return addChatEntry(outcome);
             }
-            switch (command) {
-                case '/ignore':
-                    if (!ignoredplayers[argument]) {
-                        return ignore(argument, outcome);
-                    }
-                    outcome.text('(From binb): '+argument+' is already ignored.');
-                    break;
-                case '/kick':
-                    if (subscriber) {
-                        return kick(argument, outcome);
-                    }
-                    outcome.append('you are not allowed to kick a player.');
-                    break;
-                case '/unignore':
-                    if (ignoredplayers[argument]) {
-                        delete ignoredplayers[argument];
-                        socket.emit('unignore', argument);
-                        outcome.text('(From binb): '+argument+' is no longer ignored.');
-                    }
-                    else {
-                        outcome.text('(From binb): you have not ignored '+argument+'.');
-                    }
-            }
+            return command.fn(args, outcome);
         }
-        else {
-            outcome.text('(From binb): unknown command '+command+'.');
+
+        outcome.text('(From binb): unknown command '+cmdname+'.');
+        addChatEntry(outcome);
+    };
+
+    // Remove a player from the ignore list
+    var unignorePlayer = function(args, outcome) {
+        if (!ignoredplayers[args[0]]) {
+            outcome.text('(From binb): you have not ignored '+args[0]+'.');
+            return addChatEntry(outcome);
         }
+        delete ignoredplayers[args[0]];
+        socket.emit('unignore', args[0]);
+        outcome.text('(From binb): '+args[0]+' is no longer ignored.');
         addChatEntry(outcome);
     };
 
         }
     };
 
-    // Convert any URLs in text into clickable links.
+    // Convert any URLs in text into clickable links
     var urlize = function(text) {
         if (text.match(urlregex)) {
             var html = '';
         updateUsers(usersData);
     };
 
-    // Set up the app.
+    var slashcommands = {
+        ignore: {
+            checkrecipient: true, // Assume that the first argument (argv[0]) is the recipient
+            fn: ignorePlayer,
+            minargs: 1,
+            usage: 'usage: /ignore &lt;player name&gt;'
+        },
+        kick: {
+            checkrecipient: true,
+            fn: kickPlayer,
+            minargs: 1,
+            usage: 'usage: /kick &lt;player name&gt; [message]'
+        },
+        unignore: {
+            checkrecipient: true,
+            fn: unignorePlayer,
+            minargs: 1,
+            usage: 'usage: /unignore &lt;player name&gt;'
+        }
+    };
+
+    // Set up the app
     setVariables();
     DOM.modal.modal({keyboard:false, show:false, backdrop:'static'});
     DOM.togglechat.click(hideChat);
     if ($.browser.mozilla) {
-        // Block ESC button in firefox (breaks socket connections).
+        // Block ESC button in firefox (breaks socket connections)
         $(document).keypress(function(event) {
             if(event.keyCode === 27) {
                 return false;