def connect(self): # Open either an SSL or regular NNTP connection. try: if self.ssl: self.connection = NNTP_SSL( self.server, self.port, self.username, self.password, False, True, timeout=15 ) else: self.connection = NNTP(self.server, self.port, self.username, self.password, False, True, timeout=15) except: pass if self.connection: return True return False
class NNTPConnection(mt.threads.Thread): def __init__( self, connection_number, server, port, username, password, ssl, nextSegFunc, onSegComplete=None, onSegFailed=None, onThreadStop=None, ): mt.threads.Thread.__init__(self) # Settings self.connection = None self.connection_number = connection_number self.server = server self.port = port self.username = username self.password = password self.ssl = ssl # Events. self.nextSegFunc = nextSegFunc self.onSegComplete = onSegComplete self.onSegFailed = onSegFailed self.onThreadStop = onThreadStop def connect(self): # Open either an SSL or regular NNTP connection. try: if self.ssl: self.connection = NNTP_SSL( self.server, self.port, self.username, self.password, False, True, timeout=15 ) else: self.connection = NNTP(self.server, self.port, self.username, self.password, False, True, timeout=15) except: pass if self.connection: return True return False def disconnect(self): if self.connection: try: self.connection.quit() except: pass self.connection = None def run(self): connection = None seg = None # Thread has started. mt.log.debug("Thread " + str(self.connection_number) + " started.") start_time = time.time() while self.running: seg = None connected = self.connect() if connected: while self.running: seg = self.nextSegFunc() # Out of segments, sleep for a bit and see if we get anymore. if seg == None: self.sleep(0.1) continue # Download complete, bail. if seg == -1: self.running = False seg = None break # Attempt to grab a segment. try: resp, nr, id, data = self.connection.body("<%s>" % seg.msgid) if resp[0] == "2": seg.data = data if self.onSegComplete: self.onSegComplete(seg) seg = None except ssl.SSLError: break except NNTPError as e: mt.log.error("Error getting segment: " + e.response) pass except: mt.log.error("Error getting segment.") pass if seg and self.onSegFailed: self.onSegFailed(seg) seg = None # Disconnect when we're finished. if seg and self.onSegFailed: self.onSegFailed(seg) self.disconnect() else: mt.log.error("Connection error. Reconnecting in 3 seconds.") self.sleep(3) # Thread has ended. self.disconnect() # just to be safe. end_time = time.time() mt.log.debug( "Thread " + str(self.connection_number) + " stopped after " + str(end_time - start_time) + " seconds." ) if self.onThreadStop: self.onThreadStop(self.connection_number)