Esempio n. 1
0
def onClientOpen(clientHandler):
    global numClients, names

    # Increment the client count.
    numClients += 1

    # Give the client a random name.
    rname = names.randomName()
    while rname in clientNames:
        rname = names.randomName()
    clientHandler.name = rname
    clientNames[rname] = clientHandler
    
    # Give the client an empty subreddit list.
    clientHandler.subreddits = {}
Esempio n. 2
0
	def __init__(self, size, bankroll=100.0):
		if size<1:
			print "Erro to instatiate Player"
			return
	  
		self.bankroll = bankroll
		self.name=randomName()
		self.probabilities = [0] * size
		for i in range(size):
			self.probabilities[i] = random()
Esempio n. 3
0
def onClientMessage(clientHandler):

    # Get all incoming messages.
    messages = clientHandler.get()
    
    # Handle messages.
    for msg in messages:
    
        # Decode the message.
        try:
            jmsg = loads(msg)    
        except:
            logerr()
            continue
        
        # Check that the message type exists.
        if not 'y' in jmsg:
            logging.debug("malformed message: %s" % str(jmsg))
            continue

        # Handle a subreddit entrance message.
        ########################################################################
        if jmsg['y'] == 'u':
            addClientToSubreddit(clientHandler, jmsg['u'])            

            continue
                    

        # Handle a subreddit exit message:
        ########################################################################
        if jmsg['y'] == 'x':
            
            # Make sure it has the subreddit we're exiting.
            if not 'x' in jmsg:
                continue
            
            # Remove the clientHandler from the shard.
            removeClientFromSubreddit(clientHandler, jmsg['x'])
            
            continue


        # Handle a chat-type message.
        ########################################################################
        if jmsg['y'] == 'c':
        
            # Set the timestamp.
            jmsg['t'] = int(time.time() * 1000)
            
            # Make sure the client is in a shard and get it.
            try:
                subreddit = jmsg['s']
                if not subreddit in clientHandler.subreddits:
                    addClientToSubreddit(clientHandler, subreddit)
                shard = clientHandler.subreddits[subreddit]
            except:
                logerr()
                continue
            
            # Broadcast.
            if jmsg['c'].startswith("/broadcast"):
                if clientHandler.name != "adminUsername":
                    clientHandler.put(jdicto(y = 'w', w = "What?"))
                    continue
                line = jmsg['c'].replace("/broadcast", '').strip()
                for ch in clientHandler.server.clientHandlers.values():
                    try:
                        ch.put(jdicto(y = 'f', f = line))
                    except:
                        logerr()
                continue

            # If it starts with a '/', reject.
            if jmsg['c'].startswith("/"):
                clientHandler.put(jdicto(y = 'w', w = "What?"))
                continue
            
            # Make sure it's of the right length.
            if len(jmsg['c']) > 512:
                clientHandler.put(jdicto(y = 'w', w = "Too long of a message."))
                continue
            if len(jmsg['c'].strip()) < 1:
                clientHandler.put(jdicto(y = 'w', w = "That's not really a message at all."))
                continue
            
            # Apply the user name.
            try:
                jmsg['n'] = clientHandler.name
            except:
                logerr()
                continue
                
            # Attach the addrHash to the message.
            try:
                jmsg['h'] = clientHandler.getAddrHash()
            except:
                logerr()
                continue
            
            # Handle a link type message.
            try:
                jmsg['c'] = sanitize(strip(jmsg['c']))
                r = re.compile(r"(http&#58;&#47;&#47;[^ ]+)")
                jmsg['c'] = r.sub(r'<a href="\1" target="_blank">\1</a>', jmsg['c'])            
                r = re.compile(r"(https&#58;&#47;&#47;[^ ]+)")
                jmsg['c'] = r.sub(r'<a href="\1" target="_blank">\1</a>', jmsg['c'])            
            except:
                logerr()
                continue
                
            # Handle bold and italics.
            try:
                jmsg['c'] = ib(jmsg['c'])
            except:
                logerr()
                continue
            
                
            # Recompile the message.
            try:
                msg = dumps(jmsg)
            except:
                logerr()
                continue
            
            # Send the message to the clients in this shard, or the target recipient if there is one.
            try:
                if 'a' in jmsg:
                    if jmsg['a'] in clientHandler.server.addrs:
                        b = clientHandler.server.addrs[jmsg['a']]
                        b.clientHandler.put(msg)
                        clientHandler.put(msg)
                else:
                    for client in shard:
                        client.put(msg)
                    # Push this one onto the lastTen list.
                    lastTen = subreddits[subreddit]["lastTen"]
                    lastTen.insert(0, msg)
                    subreddits[subreddit]["lastTen"] = lastTen[:32]
            except:
                logerr()
                continue
        
            
            continue
            
                
        # Handle a name-type message.
        ########################################################################
        if jmsg['y'] == 'n':
            
            # Make sure it has the name component.
            if 'n' not in jmsg:
                logging.debug("malformed message: %s" % str(jmsg))
                continue

            # Get the name in a handy variable.
            desire = jmsg['n'].strip()
            desire = desire.replace(" ", '')
            
            # Use my name.
            if desire == "adminPassword":
                clientNames["adminUsername"] = clientHandler
                del clientNames[clientHandler.name]
                clientHandler.name = "adminUsername"
                clientHandler.put(jdicto(y = 'f', f = "Hello, Dave."))
                continue

            # Handle random name request.
            if desire == "/random":
                rname = names.randomName()
                while rname in clientNames:
                    rname = names.randomName()
                del clientNames[clientHandler.name]
                clientHandler.name = rname
                clientNames[rname] = clientHandler
                clientHandler.put(jdicto(y = 'f', f = "You are now %s." % rname))
                continue

            # Make sure it's not too long.
            if len(desire) > 21:
                clientHandler.put(jdicto(y = 'w', w = "Name too long (21 character maximum)."))
                continue

            desire = strip(desire)
            
            # Make sure it's not too short.
            if len(desire) < 3 and len(desire) > 0:
                clientHandler.put(jdicto(y = 'w', w = "Name too short (3 character minimum)."))
                continue
                
            desire = sanitize(desire)

            # Make sure it's not too short.
            if len(desire) < 3 and len(desire) > 0:
                clientHandler.put(jdicto(y = 'w', w = "Name too short (3 character minimum)."))
                continue
                
            # Make sure this name does not already exist.
            if desire in clientNames:
                if clientNames[desire] == clientHandler:
                    clientHandler.put(jdicto(y = 'f', f = "You are already %s." % desire))
                else:
                    clientHandler.put(jdicto(y = 'w', w = "Name already in use."))
                continue
                
            # Can't use my name.
            if desire.lower() == "adminUsername":
                clientHandler.put(jdicto(y = 'w', w = "Don't be silly."))
                continue

            # Tell me my name!
            if desire == "":
                clientHandler.put(jdicto(y = 'f', f = "You are %s." % clientHandler.name))
                continue
            
            # This name appears to be okay. Delete the old name and use this one.
            del clientNames[clientHandler.name]
            clientHandler.name = desire
            clientNames[desire] = clientHandler
            clientHandler.put(jdicto(y = 'f', f = "You are now %s." % desire))
        
            continue
        
                
        # Handle a top ten request.
        ########################################################################
        if jmsg['y'] == 't':
        
            trs = {}
            for tr in topSubreddits:
                trs[tr] = subreddits[tr]['population']
            clientHandler.put(jdicto(y='t', t=trs))
                            
                
        # Handle an emote message:
        ########################################################################
        if jmsg['y'] == 'e':
        
            # Check form.
            if 'e' not in jmsg:
                logging.debug(" malformed message: %s" % str(jmsg))
                continue
        
            # Sanitize it.
            try:
                emote = sanitize(strip(jmsg['e'][:512]))
            except:
                logerr()
                continue

            # Create the emote.
            try:
                msg = jdicto(y = 'e', e = emote, n = clientHandler.name, h = clientHandler.getAddrHash(), s = jmsg['s'])
            except:
                logerr()
                continue

            # Send the message to the clients in this shard.
            for client in clientHandler.subreddits[jmsg['s']]:
                client.put(msg)
                
            # Push this one onto the lastTen list.
            try:
                lastTen = subreddits[jmsg['s']]["lastTen"]
                lastTen.insert(0, msg)
                subreddits[jmsg['s']]["lastTen"] = lastTen[:32]
            except:
                logerr()
                continue
 def __init__(self, constraints=None):
     self.name = randomName()
     self.dna=[]
     if constraints is not None:
         self.dna = constraints.getInitialSolution()
         self.weight = constraints.f(self.dna)