Skip to content
Browse files

chat history

  • Loading branch information...
1 parent 063e37d commit de9d04df623066946ecb0a0accb524a4aa13526a @k1000 committed
View
55 chatroom/static/chatroom/chat.js
@@ -18,41 +18,12 @@ function updateUsersLink ( ) {
$("#usersLink").text(t);
}
-//handles another person joining chat
-function userJoin(nick, timestamp) {
- //put it in the stream
- addMessage(nick, "joined", timestamp, "join");
- //if we already know about this user, ignore it
- for (var i = 0; i < nicks.length; i++)
- if (nicks[i] == nick) return;
- //otherwise, add the user to the list
- nicks.push(nick);
- //update the UI
- updateUsersLink();
-}
-
-//handles someone leaving
-function userPart(nick, timestamp) {
- //put it in the stream
- addMessage(nick, "left", timestamp, "part");
- //remove the user from the list
- for (var i = 0; i < nicks.length; i++) {
- if (nicks[i] == nick) {
- nicks.splice(i,1)
- break;
- }
- }
- //update the UI
- updateUsersLink();
-}
-
//used to keep the most recent messages visible
function scrollDown () {
var objDiv = document.getElementById("log");
objDiv.scrollTop = objDiv.scrollHeight;
}
-
// utility functions
util = {
@@ -106,7 +77,7 @@ function addMessage (from, text, time, _class) {
time = new Date();
} else if ((time instanceof Date) === false) {
// if it's a timestamp, interpret it
- time = new Date(time);
+ time = new Date(time * 1000);
}
//every message you see is actually a table with 3 cols:
@@ -143,26 +114,10 @@ function addMessage (from, text, time, _class) {
$(messageElement).appendTo( $("#log") )
.animate({ backgroundColor: "#FCFCD8" },1).delay(1000).animate({ backgroundColor: "#EFEAEA" }, 1500);
-
//always view the most recent message when it is added
scrollDown();
}
-//add a list of present chat members to the stream
-function outputUsers () {
- var nick_string = nicks.length > 0 ? nicks.join(", ") : "(none)";
- addMessage("users:", nick_string, new Date(), "info");
- return false;
-}
-
-//get a list of the users presently in the room, and add it to the stream
-function who () {
- jQuery.get(CONFIG.dir +"/who", {room:REPO}, function (data, status) {
- if (status != "success") return;
- nicks = data.nicks;
- outputUsers();
- }, "json");
-}
@@ -181,6 +136,7 @@ $(document).ready(function() {
//userJoin(message.nick, message.timestamp);
};
onmessage = function (msg) {
+
if ( msg.messages){
messages = msg.messages.reverse();
for (var i = messages.length - 1; i >= 0; i--) {
@@ -188,9 +144,12 @@ $(document).ready(function() {
addMessage(ms.nick, ms.text || "", ms.timestamp, ms.type);
};
} else {
- if ( msg ){
+ if ( msg.type == "who"){
+ nicks = msg.who;
+ updateUsersLink()
+ msg.msg = "connected users: " + msg.who.join(" ");
+ }
addMessage(msg.nick, msg.msg, msg.timestamp, msg.type);
- }
}
};
onclose = function(message) {
View
28 chatroom/templates/chatroom/_chat.html
@@ -1,31 +1,9 @@
<div id="log">
- <table class="message"><tr><td class="date">18:58</td><td valign="top" class="nick">TTilus</td>
- <td class="msg-text">x6a616e: i think you can, there was some weird #send trick to do that</td>
- </tr></table>
- <table class="message"><tr><td class="date">18:58</td><td valign="top" class="nick">TTilus</td>
- <td class="msg-text">(or i could just be terribly wrong)</td>
- </tr></table>
- <table class="message"><tr><td class="date">19:02</td><td valign="top" class="nick">x6a616e</td>
- <td class="msg-text">TTilus: with #send you can invoke private methods</td>
- </tr></table>
- <table class="message"><tr><td class="date">19:03</td><td valign="top" class="nick">x6a616e</td>
- <td class="msg-text">dunno how to leverage it to access instance var :-/</td>
- </tr></table>
- <table class="message"><tr><td class="date">19:05</td><td valign="top" class="nick">x6a616e</td>
- <td class="msg-text">i3d: usually I use rspec::mocks</td>
- </tr></table>
- <table class="message"><tr><td class="date">19:05</td><td valign="top" class="nick">dlisboa</td>
- <td class="msg-text">x6a616e: #instance_variable_get ?</td>
- </tr></table>
- <table class="message"><tr><td class="date">19:06</td><td valign="top" class="nick">x6a616e</td>
- <td class="msg-text">dlisboa: phew I forgot that ..</td>
- </tr></table>
+
</div>
<div id="toolbar">
<ul id="status">
- <li><a id="usersLink" href="#">5 users</a></li>
- <li>uptime: <span id="uptime">?</span></li>
- <li>memory: <span id="rss">?</span>mb RSS</li>
+ <li id="usersLink"></li>
</ul>
- <input type="text" id="entry"/>
+ <textarea id="entry"></textarea>
</div>
View
36 chatroom/view.py
@@ -7,6 +7,7 @@
#https://github.com/gabrielfalcao/tornadio-chat/blob/master/app/server.py
#http://djay.posterous.com/how-to-make-a-realtime-chat-app-using-tornado-0
+from stratus.signals import commit
CHANNELS = {}
#
@@ -34,7 +35,6 @@ def query(self, cb, since) :
def size(self) :
return 1024
-
def get_channel(name):
if name not in CHANNELS.keys():
CHANNELS[name]=Channel()
@@ -47,6 +47,10 @@ class ChatConnection(tornadio.SocketConnection):
nick = ""
room = ""
+ def __init__(self, *args, **kwargs) :
+ commit.connect(self.on_signal)
+ return super(ChatConnection, self ).__init__(*args, **kwargs)
+
def on_open(self, *args, **kwargs):
pass
# send participants in the room
@@ -103,15 +107,39 @@ def join( self, msg):
channel = get_channel(self.room)
messages = channel._messages
self.send( {"messages":messages } )
+ self.send(dict(
+ msg ="users "
+ ,type="who"
+ ,who = self.who( self.room )
+ ,nick=self.nick
+ ,room=self.room
+ ))
return msg
def on_close(self):
del self.participants[self.nick]
- self.broadcast( "A user %s has left." % self.nick, self.room )
+ msg = dict(
+ msg ="%s has left." % self.nick
+ ,type="info"
+ ,nick=self.nick
+ ,room=self.room
+ )
+ self.broadcast( msg, self.room )
+
+ def on_signal(sender, **kwargs):
+ print kwargs
+ self.broadcast( **kwargs )
@classmethod
- def who(cls) :
- return [ s.nick for s in self.participants ]
+ def send_msg(cls, msssage, room=None):
+ cls.broadcast( msg, self.room )
+
+ @classmethod
+ def who(cls, room=None) :
+ if room:
+ return [name for name, participant in cls.participants.items() if participant.room == room ]
+ else:
+ return cls.participants.keys()
View
292 django_tornado/management/commands/runtornadosocket.py
@@ -1,146 +1,146 @@
-from os import path as op
-from django.core.management.base import BaseCommand, CommandError
-from django.conf import settings
-from optparse import make_option
-
-import os
-import sys
-import tornado.web
-import tornadio
-import tornadio.router
-import tornadio.server
-
-ROOT = op.normpath(op.dirname(__file__))
-
-from chatroom.view import ChatRouter
-
-class Command(BaseCommand):
- option_list = BaseCommand.option_list + (
- make_option('--reload', action='store_true',
- dest='use_reloader', default=False,
- help="Tells Tornado to use auto-reloader."),
- make_option('--flash_policy_file', action='store_true',
- dest='flash_policy_file', default=False,
- help="Location of 'flash_policy_file' "),
- #make_option('--adminmedia', dest='admin_media_path', default='',
- # help="Specifies the directory from which to serve admin media."),
- make_option('--noxheaders', action='store_false',
- dest='xheaders', default=True,
- help="Tells Tornado to NOT override remote IP with X-Real-IP."),
-
- )
- help = "Starts a Tornado Web Socket Server."
- args = '[optional port number or ipaddr:port] (one or more, will start multiple servers)'
-
- # Validation is called explicitly each time the server is reloaded.
- requires_model_validation = False
-
- def handle(self, *addrport, **options):
- # reopen stdout/stderr file descriptor with write mode
- # and 0 as the buffer size (unbuffered).
- # XXX: why?
- sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
- sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)
-
- if len(addrport) == 0 :
- raise CommandError('Usage is runserver %s' % self.args)
-
- if len(addrport) == 1 :
- self.run_one(addrport[0], **options)
- else :
- from multiprocessing import Process
-
- plist = []
- for ap in addrport :
- p = Process(target=self.run_one, args=(ap,), kwargs=options)
- p.start()
- plist.append(p)
-
- # for p in plist : plist.terminate()
-
- while plist :
- if plist[0].exitcode is None :
- plist.pop(0)
- else :
- plist[0].join()
-
-
- def run_one(self, addrport, **options) :
- import django
- from django.core.handlers.wsgi import WSGIHandler
- from tornado import httpserver, wsgi, ioloop, web
-
- if not addrport:
- addr = ''
- port = '8888'
- else:
- try:
- addr, port = addrport.split(':')
- except ValueError:
- addr, port = '', addrport
- if not addr:
- addr = '127.0.0.1'
-
- if not port.isdigit():
- raise CommandError("%r is not a valid port number." % port)
-
- use_reloader = options.get('use_reloader', False)
-
- flash_policy_file = options.get(
- 'flash_policy_file',
- getattr(settings, "FLASH_POLICY_FILE", op.join(ROOT, 'flashpolicy.xml'))
- )
-
- xheaders = options.get('xheaders', True)
-
- shutdown_message = options.get('shutdown_message', '')
- quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'
-
- if settings.DEBUG :
- import logging
- logger = logging.getLogger()
- logger.setLevel(logging.DEBUG)
-
- def inner_run():
- from django.conf import settings
- from django.utils import translation
- print "Validating models..."
- self.validate(display_num_errors=True)
- print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)
- print "Socket Server is running at http://%s:%s/" % (addr, port)
- print "Quit the server with %s." % quit_command
-
- # django.core.management.base forces the locate to en-us. We
- # should set it up correctly for the first request
- # (particularly important in the not "--reload" case).
- translation.activate(settings.LANGUAGE_CODE)
-
- try:
- # Instance Django's wsgi handler.
- application = web.Application(
- [ ChatRouter.route()],
- enabled_protocols = ['websocket',
- 'flashsocket',
- 'xhr-multipart',
- 'xhr-polling'],
- flash_policy_port = 8843,
- flash_policy_file = flash_policy_file,
- socket_io_port = port
- )
- # start tornado web server in single-threaded mode
- # instead auto pre-fork mode with bind/start.
- tornadio.server.SocketServer(application)
-
- except KeyboardInterrupt:
- if shutdown_message:
- print shutdown_message
- sys.exit(0)
-
- if use_reloader:
- # Use tornado reload to handle IOLoop restarting.
- from tornado import autoreload
- autoreload.start()
-
- inner_run()
-
-
+from os import path as op
+from django.core.management.base import BaseCommand, CommandError
+from django.conf import settings
+from optparse import make_option
+
+import os
+import sys
+import tornado.web
+import tornadio
+import tornadio.router
+import tornadio.server
+
+ROOT = op.normpath(op.dirname(__file__))
+
+from chatroom.view import ChatRouter
+
+class Command(BaseCommand):
+ option_list = BaseCommand.option_list + (
+ make_option('--reload', action='store_true',
+ dest='use_reloader', default=False,
+ help="Tells Tornado to use auto-reloader."),
+ make_option('--flash_policy_file', action='store_true',
+ dest='flash_policy_file', default=False,
+ help="Location of 'flash_policy_file' "),
+ #make_option('--adminmedia', dest='admin_media_path', default='',
+ # help="Specifies the directory from which to serve admin media."),
+ make_option('--noxheaders', action='store_false',
+ dest='xheaders', default=True,
+ help="Tells Tornado to NOT override remote IP with X-Real-IP."),
+
+ )
+ help = "Starts a Tornado Web Socket Server."
+ args = '[optional port number or ipaddr:port] (one or more, will start multiple servers)'
+
+ # Validation is called explicitly each time the server is reloaded.
+ requires_model_validation = False
+
+ def handle(self, *addrport, **options):
+ # reopen stdout/stderr file descriptor with write mode
+ # and 0 as the buffer size (unbuffered).
+ # XXX: why?
+ sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
+ sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)
+
+ if len(addrport) == 0 :
+ raise CommandError('Usage is runserver %s' % self.args)
+
+ if len(addrport) == 1 :
+ self.run_one(addrport[0], **options)
+ else :
+ from multiprocessing import Process
+
+ plist = []
+ for ap in addrport :
+ p = Process(target=self.run_one, args=(ap,), kwargs=options)
+ p.start()
+ plist.append(p)
+
+ # for p in plist : plist.terminate()
+
+ while plist :
+ if plist[0].exitcode is None :
+ plist.pop(0)
+ else :
+ plist[0].join()
+
+
+ def run_one(self, addrport, **options) :
+ import django
+ from django.core.handlers.wsgi import WSGIHandler
+ from tornado import httpserver, wsgi, ioloop, web
+
+ if not addrport:
+ addr = ''
+ port = '8888'
+ else:
+ try:
+ addr, port = addrport.split(':')
+ except ValueError:
+ addr, port = '', addrport
+ if not addr:
+ addr = '127.0.0.1'
+
+ if not port.isdigit():
+ raise CommandError("%r is not a valid port number." % port)
+
+ use_reloader = options.get('use_reloader', False)
+
+ flash_policy_file = options.get(
+ 'flash_policy_file',
+ getattr(settings, "FLASH_POLICY_FILE", op.join(ROOT, 'flashpolicy.xml'))
+ )
+
+ xheaders = options.get('xheaders', True)
+
+ shutdown_message = options.get('shutdown_message', '')
+ quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'
+
+ if settings.DEBUG :
+ import logging
+ logger = logging.getLogger()
+ logger.setLevel(logging.DEBUG)
+
+ def inner_run():
+ from django.conf import settings
+ from django.utils import translation
+ print "Validating models..."
+ self.validate(display_num_errors=True)
+ print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)
+ print "Socket Server is running at http://%s:%s/" % (addr, port)
+ print "Quit the server with %s." % quit_command
+
+ # django.core.management.base forces the locate to en-us. We
+ # should set it up correctly for the first request
+ # (particularly important in the not "--reload" case).
+ translation.activate(settings.LANGUAGE_CODE)
+
+ try:
+ # Instance Django's wsgi handler.
+ application = web.Application(
+ [ ChatRouter.route()],
+ enabled_protocols = ['websocket',
+ 'flashsocket',
+ 'xhr-multipart',
+ 'xhr-polling'],
+ flash_policy_port = 8843,
+ flash_policy_file = flash_policy_file,
+ socket_io_port = port
+ )
+ # start tornado web server in single-threaded mode
+ # instead auto pre-fork mode with bind/start.
+ tornadio.server.SocketServer(application)
+
+ except KeyboardInterrupt:
+ if shutdown_message:
+ print shutdown_message
+ sys.exit(0)
+
+ if use_reloader:
+ # Use tornado reload to handle IOLoop restarting.
+ from tornado import autoreload
+ autoreload.start()
+
+ inner_run()
+
+

0 comments on commit de9d04d

Please sign in to comment.
Something went wrong with that request. Please try again.