コード例 #1
0
    def __init__(self, conf, debug=None):
        super().__init__()
        config = yaml.safe_load(open(conf))
        self.sock = None
        self.server = tuple(config["Server"])
        self.username = config["Username"]
        self.realname = config["Real Name"]
        self.mode = config.get("Mode", 0)
        self.ssl = config.get("SSL", False)
        self.password = config.get("Password", None)

        self.nick = None
        self.nicks = config["Nick"]

        self.admins = config["Admins"]
        self.config = config
        self.name = conf.split(".")[0]

        self.connected = False
        self.restart = False

        self.encoding = "utf-8"

        self.printer = MultiPrinter(self)

        if debug is not None:
            self.buff = TimerBuffer(debug, encoding=self.encoding)
        else:
            self.buff = Buffer(encoding=self.encoding)
コード例 #2
0
ファイル: threads.py プロジェクト: svkampen/Karkat
    def __init__(self, conf, debug=None):
        super().__init__()
        config = yaml.safe_load(open(conf))
        self.sock = None
        self.server = tuple(config["Server"])
        self.username = config["Username"]
        self.realname = config["Real Name"]
        self.mode = config.get("Mode", 0)
        self.ssl = config.get("SSL", False)
        self.password = config.get("Password", None)

        self.nick = None
        self.nicks = config["Nick"]

        self.admins = config["Admins"]
        self.config = config
        self.name = conf.split(".")[0]

        self.connected = False
        self.restart = False

        self.encoding = "utf-8"

        self.printer = MultiPrinter(self)

        if debug is not None:
            self.buff = TimerBuffer(debug, encoding=self.encoding)
        else:
            self.buff = Buffer(encoding=self.encoding)
コード例 #3
0
ファイル: threads.py プロジェクト: Mego/Karkat
    def __init__(self, conf):
        super().__init__()
        config = yaml.safe_load(open(conf))
        self.sock = None
        self.server = tuple(config["Server"])
        self.username = config["Username"]
        self.realname = config["Real Name"]
        self.mode = config.get("Mode", 0)
        
        self.nick = None
        self.nicks = config["Nick"]

        self.admins = config["Admins"]
        self.config = config 
        self.name = conf.split(".")[0]

        self.connected = False
        self.restart = False

        # TODO: replace with options
        if "-d" in sys.argv:
            flag = sys.argv.index("-d")
            try:
                thresh = float(sys.argv[flag+1])
            except (IndexError, ValueError):
                thresh = 0.15
            self.buff = TimerBuffer(thresh)
        else:
            self.buff = Buffer()
コード例 #4
0
ファイル: pushbullet.py プロジェクト: svkampen/Karkat
 def __init__(self, token, update_hook):
     self.sock = ssl.wrap_socket(socket.socket())
     self.listening = True
     self.last = time.time()
     self.token = token
     self.update = update_hook
     self.buffer = Buffer()
     self.ws = None
     self.retries = 0
     self.connect()
     self.decapitate()
     super().__init__()
コード例 #5
0
ファイル: pushbullet.py プロジェクト: svkampen/Karkat
class PushListener(threading.Thread):
    def __init__(self, token, update_hook):
        self.sock = ssl.wrap_socket(socket.socket())
        self.listening = True
        self.last = time.time()
        self.token = token
        self.update = update_hook
        self.buffer = Buffer()
        self.ws = None
        self.retries = 0
        self.connect()
        self.decapitate()
        super().__init__()

    def connect(self):
        self.sock.connect(("stream.pushbullet.com", 443))
        self.sock.send((HEADERS % {"key": self.token}).encode("ascii"))

    def decapitate(self):
        while self.buffer.append(self.sock.recv(4096)):
            for line in self.buffer:
                if not line:
                    self.ws = WebSocket(self.sock, self.buffer.buffer)
                    return

    def run(self):
        try:
            for evt in self.ws:
                if not self.listening:
                    break
                self.dispatch(evt)
        except:
            # exponential backoff
            time.sleep(2**self.retries)
            self.retries += 1
            self.sock = ssl.wrap_socket(socket.socket())
            self.connect()
            self.decapitate()
            self.run()

    def dispatch(self, evt):
        if evt["type"] == "tickle":
            self.update()
        self.last = time.time()
コード例 #6
0
class Connection(threading.Thread, object):
    def __init__(self, conf, debug=None):
        super().__init__()
        config = yaml.safe_load(open(conf))
        self.sock = None
        self.server = tuple(config["Server"])
        self.username = config["Username"]
        self.realname = config["Real Name"]
        self.mode = config.get("Mode", 0)
        self.ssl = config.get("SSL", False)
        self.password = config.get("Password", None)

        self.nick = None
        self.nicks = config["Nick"]

        self.admins = config["Admins"]
        self.config = config
        self.name = conf.split(".")[0]

        self.connected = False
        self.restart = False

        self.encoding = "utf-8"

        self.printer = MultiPrinter(self)

        if debug is not None:
            self.buff = TimerBuffer(debug, encoding=self.encoding)
        else:
            self.buff = Buffer(encoding=self.encoding)

    def connect(self):
        self.sock = socket.socket()
        if self.ssl:
            self.sock = ssl.wrap_socket(self.sock)
        print("Connecting...")
        self.sock.connect(self.server)
        # Try our first nickname.
        nicks = collections.deque(self.nicks)
        self.nick = nicks.popleft()
        self.sendline("USER %s %s * :%s\r\n" %
                      (self.username, self.mode, self.realname))
        if self.password is not None:
            self.sendline("PASS %s" % (self.password))
        print("Connected. Trying %s" % self.nick)
        self.sendline("NICK %s" % self.nick)
        # Find a working nickname
        while self.buff.append(self.sock.recv(1)):
            for line in self.buff:
                words = line.split()
                if line.startswith("PING") or words[1] == "001":
                    # We're done here.
                    self.sendline("PONG %s" % line.split()[-1])
                    break
                errdict = {
                    "433": "Invalid nickname, retrying.",
                    "436": "Nickname in use, retrying."
                }
                if words[1] == "432":
                    raise ValueError(
                        "Arguments sent to server are invalid; "
                        "are you sure the configuration file is correct?")
                elif words[1] in errdict:
                    print(errdict[words[1]], file=sys.stderr)
                    self.nick = nicks.popleft()
                    self.sendline("NICK %s" % self.nick)
            else:
                # If we haven't broken out of the loop, our nickname is
                # not valid.
                continue
            break
        self.connected = True
        self.printer.start()
        print("Connected.")

    def sendline(self, line):
        self.sock.send(("%s\r\n" % line).encode(self.encoding))

    def dispatch(self, line):
        """
        Dispatch and process a line of IRC.
        Override me.
        """
        return

    def cleanup(self):
        # TODO: decouple printer and connection.
        self.printer.terminate()
        print("Terminating threads...")

        self.printer.join()
        if "-d" in sys.argv and self.buff.log:
            print("%d high latency events recorded, max=%r, avg=%r" %
                  (len(self.buff.log), max(
                      self.buff.log), util.average(self.buff.log)))

    def run(self):
        try:
            while self.connected and self.buff.append(self.sock.recv(1024)):
                for line in self.buff:
                    self.dispatch(line)

        finally:
            self.sock.close()
            print("Connection closed.")
            self.cleanup()

            self.connected = False

    def message(self, *args, **kwargs):
        return self.printer.message(*args, **kwargs)

    def msg(self, target, message):
        return self.printer.message(message, target)

    def set_encoding(self, encoding):
        try:
            codecs.lookup(encoding)
        except LookupError:
            raise
        else:
            self.encoding = encoding  # output encoding
            self.buff.encoding = encoding  # input encoding
コード例 #7
0
ファイル: threads.py プロジェクト: svkampen/Karkat
class Connection(threading.Thread, object):
    def __init__(self, conf, debug=None):
        super().__init__()
        config = yaml.safe_load(open(conf))
        self.sock = None
        self.server = tuple(config["Server"])
        self.username = config["Username"]
        self.realname = config["Real Name"]
        self.mode = config.get("Mode", 0)
        self.ssl = config.get("SSL", False)
        self.password = config.get("Password", None)

        self.nick = None
        self.nicks = config["Nick"]

        self.admins = config["Admins"]
        self.config = config
        self.name = conf.split(".")[0]

        self.connected = False
        self.restart = False

        self.encoding = "utf-8"

        self.printer = MultiPrinter(self)

        if debug is not None:
            self.buff = TimerBuffer(debug, encoding=self.encoding)
        else:
            self.buff = Buffer(encoding=self.encoding)

    def connect(self):
        self.sock = socket.socket()
        if self.ssl:
            self.sock = ssl.wrap_socket(self.sock)
        print("Connecting...")
        self.sock.connect(self.server)
        # Try our first nickname.
        nicks = collections.deque(self.nicks)
        self.nick = nicks.popleft()
        self.sendline("USER %s %s * :%s\r\n" % (self.username,
                                                self.mode,
                                                self.realname))
        if self.password is not None:
            self.sendline("PASS %s" % (self.password))
        print("Connected. Trying %s" % self.nick)
        self.sendline("NICK %s" % self.nick)
        # Find a working nickname
        while self.buff.append(self.sock.recv(1)):
            for line in self.buff:
                words = line.split()
                if line.startswith("PING") or words[1] == "001":
                    # We're done here.
                    self.sendline("PONG %s" % line.split()[-1])
                    break
                errdict = {"433": "Invalid nickname, retrying.",
                           "436": "Nickname in use, retrying."}
                if words[1] == "432":
                    raise ValueError(
                        "Arguments sent to server are invalid; "
                        "are you sure the configuration file is correct?"
                    )
                elif words[1] in errdict:
                    print(errdict[words[1]], file=sys.stderr)
                    self.nick = nicks.popleft()
                    self.sendline("NICK %s" % self.nick)
            else:
                # If we haven't broken out of the loop, our nickname is
                # not valid.
                continue
            break
        self.connected = True
        self.printer.start()
        print("Connected.")

    def sendline(self, line):
        self.sock.send(("%s\r\n" % line).encode(self.encoding))

    def dispatch(self, line):
        """
        Dispatch and process a line of IRC.
        Override me.
        """
        return

    def cleanup(self):
        # TODO: decouple printer and connection.
        self.printer.terminate()
        print("Terminating threads...")

        self.printer.join()
        if "-d" in sys.argv and self.buff.log:
            print(
                "%d high latency events recorded, max=%r, avg=%r" % (
                    len(self.buff.log),
                    max(self.buff.log),
                    util.average(self.buff.log)
                )
            )

    def run(self):
        try:
            while self.connected and self.buff.append(self.sock.recv(1024)):
                for line in self.buff:
                    self.dispatch(line)

        finally:
            self.sock.close()
            print("Connection closed.")
            self.cleanup()

            self.connected = False

    def message(self, *args, **kwargs):
        return self.printer.message(*args, **kwargs)

    def msg(self, target, message):
        return self.printer.message(message, target)

    def set_encoding(self, encoding):
        try:
            codecs.lookup(encoding)
        except LookupError:
            raise
        else:
            self.encoding = encoding       # output encoding
            self.buff.encoding = encoding  # input encoding
コード例 #8
0
ファイル: threads.py プロジェクト: Mego/Karkat
class Connection(threading.Thread, object):
    def __init__(self, conf):
        super().__init__()
        config = yaml.safe_load(open(conf))
        self.sock = None
        self.server = tuple(config["Server"])
        self.username = config["Username"]
        self.realname = config["Real Name"]
        self.mode = config.get("Mode", 0)
        
        self.nick = None
        self.nicks = config["Nick"]

        self.admins = config["Admins"]
        self.config = config 
        self.name = conf.split(".")[0]

        self.connected = False
        self.restart = False

        # TODO: replace with options
        if "-d" in sys.argv:
            flag = sys.argv.index("-d")
            try:
                thresh = float(sys.argv[flag+1])
            except (IndexError, ValueError):
                thresh = 0.15
            self.buff = TimerBuffer(thresh)
        else:
            self.buff = Buffer()

    def connect(self):
        self.sock = socket.socket()
        print("Connecting...")
        self.sock.connect(self.server)
        # Try our first nickname.
        nicks = collections.deque(self.nicks)
        self.nick = nicks.popleft()
        self.sendline("USER %s %s * :%s\r\n" % (self.username, 
                                                self.mode, 
                                                self.realname))
        print("Connected. Trying %s" % self.nick)
        self.sendline("NICK %s" % self.nick)
        # Find a working nickname
        while self.buff.append(self.sock.recv(1)):
            for line in self.buff:
                if line.startswith("PING"):
                    # We're done here.
                    self.sendline("PONG %s" % line.split()[-1])
                    break
                words = line.split()
                errdict = {"433": "Invalid nickname, retrying.", 
                           "436": "Nickname in use, retrying."}
                if words[1] == "432":
                    raise ValueError("Arguments sent to server are invalid; "\
                            "are you sure the configuration file is correct?")
                elif words[1] in errdict:
                    print(errdict[words[1]], file=sys.stderr)
                    self.nick = nicks.popleft()
                    self.sendline("NICK %s" % self.nick)
            else:
                # If we haven't broken out of the loop, our nickname is 
                # not valid.
                continue
            break
        self.connected = True
        self.printer = ColourPrinter(self)
        self.printer.start()
        print("Connected.")

    def sendline(self, line):
        self.sock.send(("%s\r\n" % line).encode("utf-8"))

    def dispatch(self, line):
        """
        Dispatch and process a line of IRC.
        Override me.
        """
        return

    def cleanup(self):
            # TODO: decouple printer and connection.
            self.printer.terminate()
            print("Terminating threads...")

            self.printer.join()
            if "-d" in sys.argv and self.buff.log:
                print("%d high latency events recorded, max=%r, avg=%r" % (len(self.buff.log), max(self.buff.log), util.average(self.buff.log)))

    def run(self):
        try:
            while self.connected and self.buff.append(self.sock.recv(1024)):
                for line in self.buff:
                    self.dispatch(line)               

        finally:
            self.sock.close()
            print("Connection closed.")
            self.cleanup()            

            self.connected = False