Esempio n. 1
0
    def __init__(self, client, connectivity):
        QObject.__init__(self)
        self._state = GameSessionState.OFF

        # Subscribe to messages targeted at 'game' from the server
        client.subscribe_to('game', self)

        # Connectivity helper
        self.connectivity = connectivity
        self.connectivity.ready.connect(self.ready.emit)
        self.connectivity.peer_bound.connect(self._peer_bound)

        # Keep a parent pointer so we can use it to send
        # relay messages about the game state
        self._client = client  # type: Client
        self.me = client.me

        self.game_port = client.gamePort
        self.player = client.me

        # Use the normal lobby by default
        self.init_mode = 0
        self._joins, self._connects = [], []

        # 'GPGNet' TCP listener
        self._game_listener = QTcpServer(self)
        self._game_listener.newConnection.connect(self._new_game_connection)
        self._game_listener.listen(QHostAddress.LocalHost)

        # We only allow one game connection at a time
        self._game_connection = None

        self._process = game_process_instance  # type: GameProcess
        self._process.started.connect(self._launched)
        self._process.finished.connect(self._exited)
Esempio n. 2
0
 def __init__(self, pidFile):
     """
     Constructor
     
     @param pidFile filename of the PID file used to record some interface
         informations
     """
     addr = QHostAddress()
     addr.setAddress(SAAddress)
     QTcpServer.__init__(self)
     
     self.saFile = os.path.join(Utilities.getConfigDir(), pidFile)
     if self.listen(addr, 0):
         try:
             f = open(self.saFile, "wb")
             
             try:
                 f.write("%s = %d%s" % \
                     (SALckPID, os.getpid(), os.linesep))
             except AttributeError:
                 pass
             
             f.write("%s = %d%s" % \
                 (SALckSocket, self.serverPort(), os.linesep))
             
             f.close()
         except IOError, msg:
             print "Error writing Lockfile: %s\n" % msg
         self.connect(self, SIGNAL("newConnection()"), self.__newConnection)
Esempio n. 3
0
class SocketTcpServer(AbstractSocket):
    """Socket que recebe dados do cliente e envia para o ip desejado via tcp"""
    def __init__(self, portaReceber, parent=None):
        super().__init__(portaReceber, None, parent)
        
        self._clients = {}
        
        self._socketServer = QTcpServer(self)
        self._socketServer.listen(QHostAddress(QHostAddress.Any), portaReceber)

        self._socketServer.newConnection.connect(self._aceitarConexao)
        
    def enviarDados(self, byteArray):
        if self.getPara() in self._clients:
            self._clients[self.getPara()].write(byteArray)

    def ipConexoesClientes(self):
        return list(self._clients.keys())

    def _aceitarConexao(self):
        if self._socketServer.hasPendingConnections():
            client = self._socketServer.nextPendingConnection()
            self._clients[client.localAddress().toString()] = client
            client.readyRead.connect(lambda: self._lerDados(client))

    def _lerDados(self, client):
        if client.bytesAvailable():
            de = client.localAddress().toString()
            data = client.readAll()

            self.dadosRecebidos.emit(de, data)
            
    def meuIP(self):
        return self._socketServer.serverAddress()
class TunnelServer(object):
    """A server for tunnel instances."""

    def __init__(self, cookie):
        """Initialize this tunnel instance."""
        self.tunnels = []
        self.cookie = cookie
        self.server = QTcpServer(QCoreApplication.instance())
        self.server.newConnection.connect(self.new_connection)
        self.server.listen(QHostAddress.LocalHost, 0)
        logger.info("Starting tunnel server at port %d", self.port)

    def new_connection(self):
        """On a new connection create a new tunnel instance."""
        logger.info("New connection made")
        local_socket = self.server.nextPendingConnection()
        tunnel = Tunnel(local_socket, self.cookie)
        self.tunnels.append(tunnel)

    def shutdown(self):
        """Terminate every connection."""
        # TODO: handle this gracefully in an upcoming branch

    @property
    def port(self):
        """The port where this server listens."""
        return self.server.serverPort()
Esempio n. 5
0
 def __init__(self, port, ipFilter='', raiseOnExec=False, raiseHack=False):
     QTcpServer.__init__(self)
     self.enabled = False
     self.ipFilter = ipFilter
     self.raiseOnExec = raiseOnExec
     self.raiseHack = raiseHack
     self.counter = SimuVis4.Misc.Counter()
     self.listen(QHostAddress(QHostAddress.LocalHost), port)
Esempio n. 6
0
 def __init__(self, address=None, port=5000):
     QTcpServer.__init__(self)
     self.tcpSocket = None
     self.trcHeader = None
     self.expectedBytes = 0
     self.expectedDatatype = None
     self.newConnection.connect(self.gotConnection)
     self.listen(port=port)
Esempio n. 7
0
    def __init__(self, parent=None):
        super(HTTPProxy, self).__init__(parent)
        self.proxy_server = QTcpServer(self)
        self.proxy_server.listen(QHostAddress.Any, 8000)
        self.proxy_server.newConnection.connect(self.manage_request)

        if self.debug:
            self.log.write('Proxy server running on 0.0.0.0 port %s\n\n' %
                           self.port())
Esempio n. 8
0
    def __init__(self, iface):
        QTcpServer.__init__(self)
        self.iface = iface

        # timer for interrupting open connections on inactivity
        self.timer = QTimer()
        self.timer.setInterval(3000)  # 3 seconds, worth making configurable?
        self.timer.setSingleShot(True)
        self.timer.timeout.connect(self.timeout)
Esempio n. 9
0
class TCPServer(QObject):
    def __init__(self, port):
        QObject.__init__(self)

        # logging instance
        self.log = logging.getLogger('SMIGOL.TCPServer.{0}'.format(port))

        # TCP server to listen for control commands
        self.tcp_server = QTcpServer()

        # TCP server listenning port
        self.tcp_port = port

        # TCP socket connection
        self.tcp_connection = None

    def start(self):
        self.log.info("Starting TCP server...")
        if self.tcp_server.listen(port=self.tcp_port):
            txt = "Listening at http://localhost:{0} for a connection"
            self.log.info(txt.format(self.tcp_server.serverPort()))
            self.tcp_server.newConnection.connect(self._accept_connection)
        else:
            self.log.critical("Unable to start: {0}".format(
                self.tcp_server.errorString()))

    def disconnect(self):
        if self.tcp_connection and self.tcp_connection.state(
        ) == QTcpSocket.ConnectedState:
            loop = QEventLoop()
            self.tcp_connection.disconnected.connect(loop.quit)
            self.tcp_connection.disconnectFromHost()
            self.log.debug("Entering disconnect state...")
            if self.tcp_connection.state() == QTcpSocket.ConnectedState:
                loop.exec_()
            self.log.debug("Done waiting, closing server...")
        if self.tcp_server.isListening():
            self.tcp_server.close()
        self.log.info("Server closed")

    def _accept_connection(self):
        if not self.tcp_connection:
            self.tcp_connection = self.tcp_server.nextPendingConnection()
            self.tcp_connection.error.connect(self._error_occurred)

            txt = "Accepted connection"
            self.log.debug(txt.format(self.tcp_server.serverPort()))

        else:
            self.log.warning("Received a second connection, ignoring it...")
            self.tcp_server.nextPendingConnection()

    def _error_occurred(self, socket_error):
        if socket_error == QTcpSocket.RemoteHostClosedError:
            self.log.info(self.tcp_connection.errorString())
        else:
            self.log.error(self.tcp_connection.errorString())
Esempio n. 10
0
 def __init__(self, parent = None):
     QTcpServer.__init__(self, parent)
     settings = QSettings()
     self.parent = parent
     # We just assume everything is going fine, gui should do the check here like this:
     # if tcpServer.isListening():
     self.listen(QHostAddress(QHostAddress.Any),
     settings.value("server/port", QVariant(5006)).toInt()[0])
     self.sockets= {}
     QObject.connect(self,SIGNAL("newConnection()"),self.handleIncomingConnection)
Esempio n. 11
0
    def __init__(self):
        QObject.__init__(self)

        # logging instance
        self.log = logging.getLogger('GDAIS.ControlServer')

        # TCP server to listen for control commands
        self.tcp_server = QTcpServer()

        # regexp to check if command is 'set_log_level'
        self.valid_loglevel = re.compile(r"^set_log_level (\d?0)$")
Esempio n. 12
0
    def __init__(self, port):
        QObject.__init__(self)

        # logging instance
        self.log = logging.getLogger('SMIGOL.TCPServer.{0}'.format(port))

        # TCP server to listen for control commands
        self.tcp_server = QTcpServer()

        # TCP server listenning port
        self.tcp_port = port

        # TCP socket connection
        self.tcp_connection = None
Esempio n. 13
0
    def __init__(self, mainWindow):
        QObject.__init__(self)
        self.__mainWindow = mainWindow
        self.__processes = []

        self.__tcpServer = QTcpServer()
        self.connect(self.__tcpServer, SIGNAL("newConnection()"),
                     self.__newConnection)
        self.__tcpServer.listen(QHostAddress.LocalHost)

        self.__waitTimer = QTimer(self)
        self.__waitTimer.setSingleShot(True)
        self.connect(self.__waitTimer, SIGNAL('timeout()'), self.__onWaitImer)
        return
Esempio n. 14
0
    def __init__(self, client, connectivity):
        QObject.__init__(self)
        self._state = GameSessionState.OFF

        # Subscribe to messages targeted at 'game' from the server
        client.subscribe_to('game', self)

        # Connectivity helper
        self.connectivity = connectivity
        self.connectivity.ready.connect(self.ready.emit)
        self.connectivity.peer_bound.connect(self._peer_bound)

        # Keep a parent pointer so we can use it to send
        # relay messages about the game state
        self._client = client  # type: Client
        self.me = client.me

        self.game_port = client.gamePort
        self.player = client.me

        # Use the normal lobby by default
        self.init_mode = 0
        self._joins, self._connects = [], []

        # 'GPGNet' TCP listener
        self._game_listener = QTcpServer(self)
        self._game_listener.newConnection.connect(self._new_game_connection)
        self._game_listener.listen(QHostAddress.LocalHost)

        # We only allow one game connection at a time
        self._game_connection = None

        self._process = game_process_instance  # type: GameProcess
        self._process.started.connect(self._launched)
        self._process.finished.connect(self._exited)
Esempio n. 15
0
    def __init__(self, name, dimensions, port, resource_path):
        QObject.__init__(self)
        self.port = int(port)
        self.server = QTcpServer(self)
        self.connect(self.server, QtCore.SIGNAL("newConnection()"),
                     self.newConnection)
        self.server.listen(Qt.QHostAddress(Qt.QHostAddress.Any), self.port)
        print " --- iVisServer ---  Listening on port: ", str(port)
        self.sockets = {}
        self.buffer = ''

        self.devices = {}

        self.vistrailServer = VistrailServer(resource_path)
        self.summary = None
        self.addDevice(name, dimensions)
        self.userPool = UserPool()
 def __init__(self, cookie):
     """Initialize this tunnel instance."""
     self.tunnels = []
     self.cookie = cookie
     self.server = QTcpServer(QCoreApplication.instance())
     self.server.newConnection.connect(self.new_connection)
     self.server.listen(QHostAddress.LocalHost, 0)
     logger.info("Starting tunnel server at port %d", self.port)
Esempio n. 17
0
File: main.py Progetto: xiaq/chat
 def createServer(self):
     self.server = QTcpServer()
     if not self.server.listen(port=PEER_PORT):
         QMessageBox.critical(
             self, "Server Error",
             "Cannot start server. Port %d seems in use." % PEER_PORT)
         sys.exit(1)
     self.server.newConnection.connect(self.onNewConnection)
Esempio n. 18
0
    def __init__(self, parent=None):
        super(HTTPProxy, self).__init__(parent)
        self.proxy_server = QTcpServer(self)
        self.proxy_server.listen(QHostAddress.Any, 8000)
        self.proxy_server.newConnection.connect(self.manage_request)

        if self.debug:
            self.log.write('Proxy server running on 0.0.0.0 port %s\n\n' %
                self.port())
Esempio n. 19
0
    def __init__(self, portaReceber, parent=None):
        super().__init__(portaReceber, None, parent)
        
        self._clients = {}
        
        self._socketServer = QTcpServer(self)
        self._socketServer.listen(QHostAddress(QHostAddress.Any), portaReceber)

        self._socketServer.newConnection.connect(self._aceitarConexao)
Esempio n. 20
0
    def StartServer(self):
        self.host = "localhost"
        self.port = int(self.ui.port_Edit.text())
        self.ui.inbuffer_Edit.append("ServerStart on port:" + str(self.port))

        self.timestamp = datetime.datetime.now()
        self.tcpServer = QTcpServer(self)
        self.tcpServer.listen(QHostAddress(self.host), self.port)
        curtime = datetime.datetime.now()
        delta = curtime - self.timestamp
        self.time_delta = delta.total_seconds()

        self.scanman.ui.fitGroupBox.fittedsignal.connect(self.GetCurrent)

        self.connections = []
        self.connect(self.tcpServer, qtCore.SIGNAL("newConnection()"),
                     self.addConnection)
        self.ui.status_Edit.setText("On")

        True
Esempio n. 21
0
 def __init__(self, boardName, board, parent = None):
    QTcpServer.__init__(self, parent)
    self.boardName = boardName
    self.connections = []
    SM.next = _smDebug(SM.next)
    self.sm = SM(board)
    self.sm.stateChanged.connect(self.sendStateChange)
    self.sm.turnChanged.connect(self.sendTurnChange)
    self.sm.territoryUpdated.connect(self.sendTerritoryUpdate)
    self.sm.remainingTroopsChanged.connect(self.sendRemainingTroopsChange)
    self.sm.attacked.connect(self.sendAttack)
    self.sm.cardAwarded.connect(self.sendCardAward)
    self.sm.cardsExchanged.connect(self.sendCardsExchanged)
    self.sm.mustExchangeCards.connect(self.sendMustExchangeCards)
    self.sm.playerEliminated.connect(self.sendPlayerEliminated)
    self.chatHistory = []
    self.colors = self.predefinedColors
    parent = os.path.dirname(__file__)
    with open(os.path.join(parent, "words")) as f:
        self.words = f.read().split("\n")
    timer = QTimer(self)
    timer.setInterval(3000)
    timer.timeout.connect(self.sendPing)
    timer.start()
Esempio n. 22
0
    def __init__(self, listen_port, parent = None):
        QTcpServer.__init__(self, parent)   
        
        # define verbose variable
        self.verbose = True
        
        # Starts listening on selected port.
        try:
            port = int(listen_port)
        except:
            print ('[*] Error, port is not a number.')
				
        started = self.listen(address = QHostAddress.Any, port = port)
        
        # It is possible that such port is not available.
        if started:
            print ('[*] Listening on port %s' % port)
            
        else:
            print ('[*] Could not bind port %s' % port)
        
        # This dictionary will always contains a reference to all 
        #current sockets.
        self.sockets = {}
Esempio n. 23
0
    def __init__( self, mainWindow ):
        QObject.__init__( self )
        self.__mainWindow = mainWindow
        self.__processes = []

        self.__tcpServer = QTcpServer()
        self.connect( self.__tcpServer, SIGNAL( "newConnection()" ),
                      self.__newConnection )
        self.__tcpServer.listen( QHostAddress.LocalHost )

        self.__waitTimer = QTimer( self )
        self.__waitTimer.setSingleShot( True )
        self.connect( self.__waitTimer, SIGNAL( 'timeout()' ),
                      self.__onWaitImer )
        return
Esempio n. 24
0
    def __init__( self, name, dimensions, port, resource_path ):
        QObject.__init__(self)
        self.port = int(port)
        self.server = QTcpServer(self)
        self.connect(self.server, QtCore.SIGNAL("newConnection()"), self.newConnection)
        self.server.listen(Qt.QHostAddress(Qt.QHostAddress.Any), self.port )
        print " --- iVisServer ---  Listening on port: ", str( port )
        self.sockets = {}
        self.buffer = ''

        self.devices = {}

        self.vistrailServer = VistrailServer( resource_path )
        self.summary = None
        self.addDevice( name, dimensions )
        self.userPool = UserPool()
Esempio n. 25
0
    def __init__(self):
        FreeseerApp.__init__(self)
        self.resize(400, 300)
        
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/freeseer/logo.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(icon)
        
        configdir = os.path.abspath(os.path.expanduser('~/.freeseer/'))
        self.logger = Logger(configdir)
        logging.info("Logger initialized")
        
        self.server = QTcpServer(self)
        logging.info("Starting Freeseer Server")
        
        # Setup Widget
        self.mainWidget = ControllerServerWidget()
        self.setCentralWidget(self.mainWidget)
        
        self.mainWidget.hostCombo.addItem(QtCore.QString("0.0.0.0"))
                
        #Connections
        self.connect(self.server, QtCore.SIGNAL('newConnection()'), self.acceptConnection)  
        self.connect(self.mainWidget.startButton, QtCore.SIGNAL('pressed()'), self.startServer)
        self.connect(self.mainWidget.hostCombo, QtCore.SIGNAL('currentIndexChanged(int)'), self.ipComboBoxHandler)
        self.connect(self.mainWidget.passEdit, QtCore.SIGNAL('textChanged(QString)'), self.onPassChanged)
        
        # Initialize Passphrase Field
        self.mainWidget.passEdit.setPlaceholderText("Passphrase required to start server")
        self.mainWidget.startButton.setEnabled(False)

        # Client Control
        self.connect(self.mainWidget.clientStartButton, QtCore.SIGNAL('pressed()'), self.sendRecordCommand)
        self.connect(self.mainWidget.clientStopButton, QtCore.SIGNAL('pressed()'), self.sendStopCommand)
        self.connect(self.mainWidget.clientDisconnectButton, QtCore.SIGNAL('pressed()'), self.disconnectClients)
        self.connect(self.mainWidget.clientList, QtCore.SIGNAL('itemSelectionChanged()'), self.updateClientButtons)
    
        self.load_settings()
        self.updateStatus(self.status)
Esempio n. 26
0
    def __init__(self):
        FreeseerApp.__init__(self)
        self.resize(400, 300)

        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/freeseer/logo.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(icon)

        self.server = QTcpServer(self)
        log.info("Starting Freeseer Server")

        # Setup Widget
        self.mainWidget = ControllerServerWidget()
        self.setCentralWidget(self.mainWidget)

        self.mainWidget.hostCombo.addItem(QtCore.QString("0.0.0.0"))
        addresses = QNetworkInterface().allAddresses()
        for address in addresses:
            self.mainWidget.hostCombo.addItem(address.toString())

        # Connections
        self.connect(self.server, QtCore.SIGNAL("newConnection()"), self.acceptConnection)
        self.connect(self.mainWidget.startButton, QtCore.SIGNAL("pressed()"), self.startServer)
        self.connect(self.mainWidget.hostCombo, QtCore.SIGNAL("currentIndexChanged(int)"), self.ipComboBoxHandler)
        self.connect(self.mainWidget.passEdit, QtCore.SIGNAL("textChanged(QString)"), self.onPassChanged)

        # Initialize Passphrase Field
        self.mainWidget.passEdit.setPlaceholderText("Passphrase required to start server")
        self.mainWidget.startButton.setEnabled(False)

        # Client Control
        self.connect(self.mainWidget.clientStartButton, QtCore.SIGNAL("pressed()"), self.sendRecordCommand)
        self.connect(self.mainWidget.clientStopButton, QtCore.SIGNAL("pressed()"), self.sendStopCommand)
        self.connect(self.mainWidget.clientDisconnectButton, QtCore.SIGNAL("pressed()"), self.disconnectClients)
        self.connect(self.mainWidget.clientList, QtCore.SIGNAL("itemSelectionChanged()"), self.updateClientButtons)

        self.load_settings()
        self.updateStatus(self.status)
Esempio n. 27
0
 def __init__(self, port=Globals.config.getint('main', 'help_server_port')):
     QTcpServer.__init__(self)
     self.enabled = True
     self.listen(QHostAddress(QHostAddress.LocalHost), port)
Esempio n. 28
0
 def incomingConnection(self, socketDescriptor):
     # this is called when someone tries to connect
     QTcpServer.incomingConnection(self,socketDescriptor)
Esempio n. 29
0
class Dialog(QDialog):
    TotalBytes = 50 * 1024 * 1024
    PayloadSize = 65536

    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.settings = QSettings('settings.ini', QSettings.IniFormat)
        self.tcpServer = QTcpServer()

        self.chBox = QCheckBox("Print log to window")
        self.text = QPlainTextEdit()
        self.serverStatusLabel = QLabel("Server ready")

        self.lblFileName = QLabel("Choose file before start!")
        self.saveButton = QPushButton("&Choose file...")
        self.startButton = QPushButton("&Start")
        self.stopButton = QPushButton("S&top")
        self.quitButton = QPushButton("&Quit")

        self.file = None
        self.tcpServerConnection = None

        self._lineCounter = 0
        self._lineBuf = ''

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.startButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(self.stopButton, QDialogButtonBox.RejectRole)
        buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole)

        clearButon = QPushButton('&Clear')

        self.saveButton.clicked.connect(self.savedlg)
        self.startButton.clicked.connect(self.start)
        self.stopButton.clicked.connect(self.stopClicked)
        self.quitButton.clicked.connect(self.close)
        clearButon.clicked.connect(self.text.clear)
        self.tcpServer.newConnection.connect(self.acceptConnection)

        saveLayout = QHBoxLayout()
        saveLayout.addWidget(self.lblFileName)
        saveLayout.addStretch(1)
        saveLayout.addWidget(self.saveButton)

        topTextLayout = QHBoxLayout()
        topTextLayout.addWidget(self.chBox)
        topTextLayout.addStretch(1)
        topTextLayout.addWidget(clearButon)

        mainLayout = QVBoxLayout()
        mainLayout.addLayout(saveLayout)
        mainLayout.addLayout(topTextLayout)
        mainLayout.addWidget(self.text)
        mainLayout.addWidget(self.serverStatusLabel)
        #        mainLayout.addStretch(1)
        mainLayout.addSpacing(10)
        mainLayout.addWidget(buttonBox)
        self.setLayout(mainLayout)

        self.title = "Simple Logger"
        self.ver = '1.0'

        self.setWindowIcon(QIcon('./icon.png'))
        self.setWindowTitle("{} {}".format(self.title, self.ver))

    def start(self):
        if self.file is None:
            QMessageBox.critical(
                self, self.title,
                "Unable open log file.\nPlease, select another file.")
            return
        self.startButton.setEnabled(False)

        while not self.tcpServer.isListening() and not self.tcpServer.listen(
                port=9112):
            ret = QMessageBox.critical(
                self, self.title,
                "Unable to start the test: %s." % self.tcpServer.errorString(),
                QMessageBox.Retry | QMessageBox.Cancel)
            if ret == QMessageBox.Cancel:
                return

        self.serverStatusLabel.setText("Waiting connection ...")

    def acceptConnection(self):
        self.tcpServerConnection = self.tcpServer.nextPendingConnection()
        self.tcpServerConnection.readyRead.connect(self.updateLog)
        self.tcpServerConnection.error.connect(self.displayError)

        self.file = QFile(self.filename)
        if not self.file.open(QFile.Append):
            QMessageBox.warning(
                self, self.title, "Unable to write file {}:\n{}.".format(
                    self.filename, self.file.errorString()))
            self.file = None
            return
        self.textStream = QTextStream(self.file)
        self.textStream.setCodec('UTF-8')

        self.serverStatusLabel.setText("Logging ...")
        self.tcpServer.close()

    def savedlg(self):
        self.filename = QFileDialog.getSaveFileName(
            self, "Log Filename",
            self.settings.value('directories/dir_save', QDir.currentPath()),
            "Text (*.log *.txt);;All (*)")
        if not self.filename:
            return

        self.file = QFile(self.filename)
        self.lblFileName.setText(self.filename)
        if not self.file.open(QFile.WriteOnly):
            QMessageBox.warning(
                self, self.title, "Unable to write file {}:\n{}.".format(
                    self.filename, self.file.errorString()))
            self.file = None
            return
        self.textStream = QTextStream(self.file)
        self.textStream.setCodec('UTF-8')

        self.settings.setValue('directories/dir_save',
                               QFileInfo(self.file).path())
        self.file.close()

    def updateLog(self):
        if self.tcpServerConnection.bytesAvailable():
            data = self.tcpServerConnection.readAll()
            line = "{}".format(str(data.data().decode()))
            if self.chBox.isChecked():
                self._lineCounter += 1
                self._lineBuf += line
                if self._lineCounter > 10:
                    self.text.appendPlainText(self._lineBuf)
                    self._lineCounter = 0
                    self._lineBuf = ''
            self.textStream << line
            self.file.flush()


#            self.serverStatusLabel.setText(line)

    def closeEvent(self, event):
        if self.file is not None:
            self.file.flush()
            self.file.close()

    def stopClicked(self):
        if self.tcpServerConnection is not None:
            self.tcpServerConnection.close()
        self.file.close()
        self.startButton.setEnabled(True)
        self.serverStatusLabel.setText("Logger ready")

    def displayError(self, socketError):
        if socketError == QTcpSocket.RemoteHostClosedError:
            return

        QMessageBox.information(
            self, "Network error",
            "The following error occured: %s." % self.tcpServer.errorString())

        self.tcpServer.close()
        self.file.close()
        self.serverStatusLabel.setText("Logger ready")
        self.startButton.setEnabled(True)
Esempio n. 30
0
class QiVisServer(QObject):
    def __init__(self, name, dimensions, port, resource_path):
        QObject.__init__(self)
        self.port = int(port)
        self.server = QTcpServer(self)
        self.connect(self.server, QtCore.SIGNAL("newConnection()"),
                     self.newConnection)
        self.server.listen(Qt.QHostAddress(Qt.QHostAddress.Any), self.port)
        print " --- iVisServer ---  Listening on port: ", str(port)
        self.sockets = {}
        self.buffer = ''

        self.devices = {}

        self.vistrailServer = VistrailServer(resource_path)
        self.summary = None
        self.addDevice(name, dimensions)
        self.userPool = UserPool()

#    def __del__( self ):
#        self.shutdownClients()

    def shutdownClients(self):
        for device in self.devices.values():
            device.shutdown()
        self.devices.clear()

    def addDevice(self, name, dimensions):
        device = Device(name, dimensions)
        self.devices[device.name] = device

    def readDevicesFromFile(self, filename):
        import os.path
        if os.path.isfile(filename):
            f = file(filename, 'r')
        else:
            f = None

        if not f is None:
            lines = f.readlines()
            name = ""
            dimensions = None
            for i in range(len(lines)):
                tokens = lines[i].split()
                if tokens:
                    if tokens[0] == "device":
                        pass
                    elif tokens[0] == "name":
                        name = ''.join([x + " " for x in tokens[1:]])[:-1]
                    elif tokens[0] == "dimensions":
                        dimensions = (int(tokens[1]), int(tokens[2]))
                    elif tokens[0] == "end_device":
                        device = Device(name, dimensions)
                        self.devices[device.name] = device
        f.close()

    def newConnection(self):
        while self.server.hasPendingConnections():
            print " ~~~~~~~~~~~~~~~~~~~~~~Received Connection~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
            socket = self.server.nextPendingConnection()

            print socket.peerAddress().toString()
            self.sockets[str(socket.peerAddress().toString())] = socket

            self.connect(self.sockets[str(socket.peerAddress().toString())],
                         QtCore.SIGNAL("readyRead()"), self.readDataFromSocket)
            self.connect(self.sockets[str(socket.peerAddress().toString())],
                         QtCore.SIGNAL("disconnected()"), self.disconnected)

    def disconnected(self):
        print "Disconnected"

    def readDataFromSocket(self):
        socket = None
        for s in self.sockets:
            if self.sockets[s].bytesAvailable() != 0:
                socket = self.sockets[s]
                break

        if socket is None:
            return

        incoming = str(socket.readAll().data())
        while incoming != "":
            self.buffer += incoming
            while (self.buffer != ""):
                tokens = self.buffer.split(":")
                header = tokens[0]
                rest = ""
                for piece in tokens[1:]:
                    rest += piece + ":"
                rest = rest[:-1]
                tmp = header.split("-")
                if len(tmp) == 3:
                    (sender, receiver, size) = header.split("-")
                else:
                    break

                if int(size) > len(rest):
                    break

                tokens = rest[:int(size)]
                self.buffer = rest[int(size):]

                reply = ("", "", "")
                if (receiver == "server"):
                    reply = self.processMessage((sender, tokens), socket)
                elif (receiver == "vistrailServer"):
                    reply = self.vistrailServer.processMessage(
                        (sender, tokens), socket)

                if reply != ("", "", ""):
                    reply = reply[0] + "-" + reply[1] + "-" + str(len(
                        reply[2])) + ":" + reply[2]
                    socket.write(reply)

            incoming = str(socket.readAll().data())

    def executePipeline(self, pipeline, deviceName, vistrailName, versionName,
                        moduleId, dimensions):
        cellID = self.devices[deviceName].dispatchPipeline(
            pipeline, vistrailName, versionName, moduleId, dimensions)

#        replyTokens = "localID,"+deviceName+","+str(cellID)+","+tokens[5]+","+tokens[6]+","+tokens[7]+","+tokens[8]

#        broadcastTokens = "addCell,"
#        broadcastTokens += deviceName +","+vistrailName+","+str(versionName)+","+str(moduleId)+","+str(cellID)+","
#        broadcastTokens += str(dimensions[0]) + ","+str(dimensions[1])+","+str(dimensions[2])+","+str(dimensions[3])
#        self.broadcastMessage(("server", sender, broadcastTokens), [self.sockets[x] for x in self.sockets if self.sockets[x] != socket])
#
#        summaryMessageTokens = 'attach,blank_user,'+str(dimensions[1])+','+str(dimensions[3])+','+str(dimensions[0])+','+str(dimensions[2])
#        summaryMessage = 'server-summary-'+str(len(summaryMessageTokens))+':'+summaryMessageTokens
#        if not self.summary is None:
#            self.summary.write(summaryMessage)

#       return ("server", sender, replyTokens)

    def processMessage(self, message, socket=None):
        (sender, tokens) = message
        #        print " -- Server process message: %s " % tokens
        tokens = tokens.split(MessageTokenSep)
        if len(tokens) == 0: return

        ### connection attempt
        if tokens[0] == "tryConnect":
            #elif sender == "summary":
            #    print "SummarY!!!"
            #    self.summary = socket

            return ("server", sender, "acceptConnect")

        ### disconnection warning
        if tokens[0] == "willDisconnect":
            print "Disconnecting iPhone"
            key = socket.peerAddress().toString()
            if (self.sockets.has_key(key)):
                del self.sockets[key]

        if tokens[0] == "logout":
            print "Logging out"
            key = socket.peerAddress().toString()
            if (self.sockets.has_key(key)):
                del self.sockets[key]
            summaryMessageTokens = "logout," + tokens[1]
            summaryMessage = 'server-summary-' + str(
                len(summaryMessageTokens)) + ':' + summaryMessageTokens
            if not self.summary is None:
                self.summary.write(summaryMessage)

        ### querying for an existing user
        elif tokens[0] == "usernameQuery":
            if self.userPool.queryUser(tokens[1]):
                summaryMessageTokens = 'login,'+str(tokens[1])+','\
                    +str(self.userPool.users[tokens[1]].color[0])+","\
                    +str(self.userPool.users[tokens[1]].color[1])+","\
                    +str(self.userPool.users[tokens[1]].color[2])

                summaryMessage = 'server-summary-' + str(
                    len(summaryMessageTokens)) + ':' + summaryMessageTokens
                if not self.summary is None:
                    self.summary.write(summaryMessage)

                return ("server",sender,"username,true,"\
                    +str(self.userPool.users[tokens[1]].color[0])+","\
                    +str(self.userPool.users[tokens[1]].color[1])+","\
                    +str(self.userPool.users[tokens[1]].color[2]))
            else:
                return ("server", sender, "username,false")

        ### sender asked to create a new user
        elif tokens[0] == "createUser":
            username = tokens[1]
            color = (float(tokens[2]), float(tokens[3]), float(tokens[4]))
            self.userPool.addUser(User(username, color))

            summaryMessageTokens = 'login,'+str(tokens[1])+','\
                +str(self.userPool.users[tokens[1]].color[0])+","\
                +str(self.userPool.users[tokens[1]].color[1])+","\
                +str(self.userPool.users[tokens[1]].color[2])

            summaryMessage = 'server-summary-' + str(
                len(summaryMessageTokens)) + ':' + summaryMessageTokens
            if not self.summary is None:
                self.summary.write(summaryMessage)

        ### querying the available devices
        elif tokens[0] == "queryDevices":
            replyTokens = "availableDevices,"
            for device in self.devices.values():
                replyTokens += device.name + "," + str(
                    device.dimensions[0]) + "," + str(
                        device.dimensions[1]) + ","
            replyTokens = replyTokens[:-1]
            return ("server", sender, replyTokens)

        ### querying the pipeline properties
        elif tokens[0] == "queryProperties":
            deviceName = tokens[1]
            reply = "availableProperties," + self.devices[
                deviceName].queryProperties(tokens[2])
            return ("server", sender, reply)

        ### querying the pipeline properties
        elif tokens[0] == "updatePipeline":
            deviceName = tokens[1]
            #tokens: 2. LocalID, 3. MedleyXML
            reply = "updatePipeline," + tokens[2] + "," + self.devices[
                deviceName].updatePipeline(tokens[2], tokens[3])
            return ("server", sender, reply)

        ### saving the visualization layout
        elif tokens[0] == "saveLayout":
            deviceName = tokens[1]
            reply = "layoutSaved,"
            #deviceName, vistrailName, versionName, moduleId, dimensions, pipeline
            #pickle doesnt work. Have to write the file by myself
            #
            #devices amount
            #info, pipeline
            if tokens[2] != "":
                pickle.dump(
                    self.devices,
                    open(
                        self.vistrailServer.resource_path + tokens[2] + ".lay",
                        "w"))
            print "Save Layout"
            return ("server", sender, reply)

        ### querying the visualization layout available
        elif tokens[0] == "queryLayouts":
            reply = "availableLayouts,"
            for n in self.vistrailServer.querySavedLayouts():
                reply += n + ","
            reply = reply[:-1]
            return ("server", sender, reply)

        ### open the saved layout available
        elif tokens[0] == "openLayout":
            reply = "appliedLayout,"
            print tokens[1]
            return ("server", sender, reply)

        ### sender is a display client advertising its dimensions
        elif tokens[0] == "dimensions":
            deviceName = tokens[1]
            dimensions = (int(tokens[2]), int(tokens[3]), int(tokens[4]),
                          int(tokens[5]))
            print "Dimensions!", deviceName, dimensions
            print self.devices.keys()
            if self.devices.has_key(deviceName):
                self.devices[deviceName].addClient(dimensions, socket)

        ### sender is an iPhone asking to execute a pipeline
        elif tokens[0] == "executePipeline":
            deviceName = tokens[1]
            vistrailName = tokens[2]
            versionName = tokens[3]
            moduleId = int(tokens[4])
            dimensions = (int(tokens[5]), int(tokens[6]), int(tokens[7]),
                          int(tokens[8]))

            pipeline = self.vistrailServer.getPipeline(vistrailName,
                                                       versionName)
            print " Executing message executePipeline!!! "

            cellID = self.devices[deviceName].dispatchPipeline(
                pipeline, vistrailName, versionName, moduleId, dimensions)
            replyTokens = "localID," + deviceName + "," + str(
                cellID) + "," + tokens[5] + "," + tokens[6] + "," + tokens[
                    7] + "," + tokens[8]

            broadcastTokens = "addCell,"
            broadcastTokens += deviceName + "," + vistrailName + "," + versionName + "," + str(
                moduleId) + "," + str(cellID) + ","
            broadcastTokens += str(dimensions[0]) + "," + str(
                dimensions[1]) + "," + str(dimensions[2]) + "," + str(
                    dimensions[3])
            self.broadcastMessage(("server", sender, broadcastTokens), [
                self.sockets[x]
                for x in self.sockets if self.sockets[x] != socket
            ])

            summaryMessageTokens = 'attach,blank_user,' + str(
                dimensions[1]) + ',' + str(dimensions[3]) + ',' + str(
                    dimensions[0]) + ',' + str(dimensions[2])
            summaryMessage = 'server-summary-' + str(
                len(summaryMessageTokens)) + ':' + summaryMessageTokens
            if not self.summary is None:
                self.summary.write(summaryMessage)

            return ("server", sender, replyTokens)

        ### sender is a device sending an interaction event
        elif tokens[0] == "interaction":
            deviceName = tokens[1]
            self.devices[deviceName].processInteractionMessage(tokens[1:])

        ### sender is an iPhone asking for device occupation on a certain device
        elif tokens[0] == "deviceOccupation":
            deviceName = tokens[1]
            reply = self.devices[deviceName].queryOccupation()
            return ("server", sender, reply)

        ### sender is asking to delete a certain cell
        elif tokens[0] == "deleteCell":
            deviceName = tokens[1]
            reply = self.devices[deviceName].deleteCell(tokens[2:])
            broadcastTokens = "deleteCell," + deviceName + "," + str(tokens[2])
            self.broadcastMessage(("server", sender, broadcastTokens), [
                self.sockets[x]
                for x in self.sockets if self.sockets[x] != socket
            ])
            return ("server", sender, reply)

        ### sender is asking to lock a certain cell for interaction
        elif tokens[0] == "lockCell":
            deviceName = tokens[1]
            reply = self.devices[deviceName].lockCell(tokens[2:])
            reply = ("server", sender, reply)
            self.broadcastMessage(reply, self.sockets.values())

        elif tokens[0] == "unlockCell":
            deviceName = tokens[1]
            reply = self.devices[deviceName].unlockCell(tokens[2:])
            reply = ("server", sender, reply)
            self.broadcastMessage(reply, self.sockets.values())
        return ("", "", "")

    def broadcastMessage(self, message, receivers):
        message = message[0] + "-" + message[1] + "-" + str(len(
            message[2])) + ":" + message[2]
        for receiver in receivers:
            receiver.write(message)

    def processGuiCommand(self, deviceName, command, selected_cells):
        self.devices[deviceName].processInteractionMessage(
            command, selected_cells, "command")

    def processInteractionState(self, deviceName, selected_cells,
                                interactionState, altMode):
        print " Process Interaction State Event %s" % (interactionState)
        tokens = ["interactionState"]
        if interactionState:
            tokens.append(interactionState)
            if altMode: tokens.append(altMode)
        self.devices[deviceName].processInteractionMessage(
            tokens, selected_cells)

    def processInteractionEvent(self, deviceName, event, screen_dims,
                                selected_cells, camera_pos):
        etype = event.type()
        event_type = "none"
        tokens = ""
        if etype == QtCore.QEvent.MouseMove: event_type = "mouseMove"
        elif etype == QtCore.QEvent.MouseButtonPress:
            event_type = "singleClick"
        elif etype == QtCore.QEvent.MouseButtonRelease:
            event_type = "mouseRelease"
        elif etype == QtCore.QEvent.KeyPress:
            event_type = "keyPress"
        elif etype == QtCore.QEvent.KeyRelease:
            event_type = "keyRelease"
        mod = event.modifiers()
        if mod:
            if (mod & QtCore.Qt.ShiftModifier): mod = "shift"
            elif (mod & QtCore.Qt.ControlModifier): mod = "ctrl"
            elif (mod & QtCore.Qt.AltModifier): mod = "alt"
            else: mod = "none"

        if (etype == QtCore.QEvent.KeyRelease) or (etype
                                                   == QtCore.QEvent.KeyPress):
            key = event.key()
            tokens = [event_type, key, mod]
#            print ' >>----------iVisServer--> process Key Event:  %s '   % str( ( event_type, key, mod, event.text() ) )
        else:
            fullSpec = True  # ( etype == QtCore.QEvent.MouseButtonPress )
            x = event.x()
            y = event.y()
            xf = '%.4f' % (float(x) / screen_dims[0])
            yf = '%.4f' % (float(y) / screen_dims[1])
            b = event.button()
            button = "none"
            if b == QtCore.Qt.LeftButton: button = "left"
            if b == QtCore.Qt.RightButton: button = "right"
            if fullSpec:
                cpos = camera_pos[0]
                cfol = camera_pos[1]
                cup = camera_pos[2]
                tokens = [
                    event_type, button, xf, yf, mod, cpos[0], cpos[1], cpos[2],
                    cfol[0], cfol[1], cfol[2], cup[0], cup[1], cup[2]
                ]
            else:
                tokens = [event_type, button, xf, yf, mod]
#            print ' >>----------iVisServer--> process Mouse Event:  %s '   % str( ( event_type, xf, yf, button, mod, screen_dims, tokens ) )

        self.devices[deviceName].processInteractionMessage(
            tokens, selected_cells)
Esempio n. 31
0
class SicsDEF(QGroupBox):
    def __init__(self, ScanmanMain=""):
        QGroupBox.__init__(self)
        self.name = "Sics"
        self.ui = Ui_Sics()
        self.ui.setupUi(self)
        self.scanman = ScanmanMain
        self.ui.inbuffer_Edit.setText("Hello\n")
        self.prm = DeviceParams()

        self.cmplist = []
        self.cmplist.append(CmpItem("inten2bgnd", 0))
        self.cmplist.append(CmpItem("inten", 1))
        self.cmplist.append(CmpItem("rho_inten", 2))
        self.cmplist.append(CmpItem("rho_pos", 3))
        self.cmplist.append(CmpItem("rho_fwhm", 4))
        self.cmplist.append(CmpItem("rho_bgnd", 5))

        self.compareprms = {}
        self.compareprms["inten2bgnd"] = CmpItem(
            "Minimum Intensity to Background", 2.0, 0, "greater")
        self.compareprms["inten"] = CmpItem("Minimum Intensity", 20.0, 1,
                                            "greater")
        self.compareprms["rho_inten"] = CmpItem("Maximum %Rel StDev Intensity",
                                                2.0, 2, "less")
        self.compareprms["rho_pos"] = CmpItem("Maximum %Rel StDev Position",
                                              2.0, 3, "less")
        self.compareprms["rho_fwhm"] = CmpItem("Maximum %Rel StDev FWHM", 2.0,
                                               4, "less")
        self.compareprms["rho_bgnd"] = CmpItem("Maximum %Rel StDev Background",
                                               2.0, 5, "less")
        self.compareprms["err_ustrain"] = CmpItem("Maximum error in u-strain",
                                                  50.0, 6, "less")

        self.reqcol = 0
        self.curcol = 1
        self.prevevents = float(0)
        self.prevstatus = ""
        self.worstpercent = float(0)

        cmptbl = self.ui.compare_tbl
        #for i in range(cmptbl.rowCount()):
        #    someitem = qt.QTableWidgetItem()
        #    someitem.setFlags(someitem.flags()  & ~qtCore.Qt.ItemIsEditable)
        #    someitem.setTextAlignment(qtCore.Qt.AlignRight)
        #    someitem.setText("0")
        #    cmptbl.setItem(i,self.curcol,someitem)

        cmptbl.setRowCount(len(self.compareprms))
        cmptbl.setColumnCount(2)
        #for item in self.compareprms.itervalues():    CDM itervalues depricated
        for item in self.compareprms.values():
            cmptbl.setItem(item.row, self.curcol, item.tblitem_cur)
            cmptbl.setItem(item.row, self.reqcol, item.tblitem_req)
            cmptbl.setVerticalHeaderItem(item.row, item.tblitem_header)

            True
        True

        self.compare_tbl = mylib.Table(self.ui.compare_tbl)

    #**************************************************************************************
    def ClearValues(self):
        self.prm.counter_value = float(0)
        self.prm.counter_rate = float(0)
        self.prm.accumulated_time = float(0)
        self.prm.time_delta = float(0)
        self.worstpercent = float(0)
        #for item in self.cmplist:
        #    item.percent = float(0)
        #    item.cur = float(0)
        for item in self.compareprms.itervalues():
            item.percent = float(0)
            item.cur = float(0)

    #**************************************************************************************
    def UpdateValues(self):
        #paramdict = copy.deepcopy(self.scanman.ui.sourceGroupBox.paramdict)
        paramdict = self.scanman.ui.sourceGroupBox.paramdict
        try:
            status = paramdict["DAQ_Status"]
        except:
            return False
        if status == "Started":
            if self.prevstatus != "Started":
                self.ClearValues()
                #self.prevstatus = status
                #return True

            #self.prevevents = float(paramdict["events"])
            curtime = datetime.datetime.now()
            delta = curtime - self.prm.timestamp
            self.prm.time_delta = delta.total_seconds()
            self.prm.accumulated_time += delta.total_seconds()
            self.prm.timestamp = curtime

            self.prm.count_delta = float(1.0)

            #if paramdict.has_key("COUNT_METHOD"):
            if "COUNT_METHOD" in paramdict.keys():
                if paramdict[
                        "COUNT_METHOD"][:
                                        -2] == "MONITOR" and self.worstpercent >= 100.0:  #Required precision reached
                    self.prm.counter_value = float(
                        paramdict["COUNT_SIZE"]
                    )  #So stop count by setting time as the preset time
                else:
                    self.prm.counter_value = float(paramdict["time"])
            else:
                self.prm.counter_value = self.prm.accumulated_time

            self.prm.counter_rate = self.worstpercent

            if (self.prm.accumulated_time != 0):
                self.average_rate = self.prm.counter_value / self.prm.accumulated_time

            self.prevstatus = status
            return True

        elif (status == "Stopped" or status == 'Paused'):
            self.ClearValues()
            self.prevstatus = status
            return False

    #**************************************************************************************
    def GetCurrent(self):
        if "DAQ_Status" in self.scanman.ui.sourceGroupBox.paramdict:  #This is data comming in from Histogram Server
            if (self.UpdateValues() == False): return
        cmptbl = self.ui.compare_tbl

        rngList = self.scanman.ui.fitGroupBox.rangeList
        rng = rngList[0]
        if (rng.intensity == 0 or rng.fwhm == 0):
            #self.ClearValues()
            self.ui.worstprm_label.setText("N/A")
            self.ui.worstval_edit.setText("%.4f" % (self.worstpercent))
            return

        for item in self.compareprms.itervalues():
            item.req = float(cmptbl.item(item.row, self.reqcol).text())

        self.compareprms["inten2bgnd"].Compare(rng.intensity / rng.background)
        self.compareprms["inten"].Compare(rng.intensity)
        self.compareprms["rho_inten"].Compare(rng.intensity_stdev /
                                              rng.intensity * 100)
        self.compareprms["rho_pos"].Compare(rng.position_stdev / rng.position *
                                            100)
        self.compareprms["rho_fwhm"].Compare(rng.fwhm_stdev / rng.fwhm * 100)
        self.compareprms["rho_bgnd"].Compare(rng.background_stdev /
                                             rng.background * 100)
        self.compareprms["err_ustrain"].Compare(rng.errustrain)

        itemkey = "inten2bgnd"
        self.worstpercent = self.compareprms[itemkey].percent
        worstitem = itemkey
        #for itemkey in self.compareprms.iterkeys():
        for itemkey in self.compareprms.keys():
            item = self.compareprms[itemkey]
            if item.percent < self.worstpercent:
                self.worstpercent = item.percent
                worstitem = itemkey
        if self.worstpercent < 0: self.worstpercent = float(0)
        self.ui.worstprm_label.setText(worstitem)
        self.ui.worstval_edit.setText("%.4f" % (self.worstpercent))

        True

    #**************************************************************************************
    def Device_print(self):
        outstring = "Time: %s, Count: %10d, Delta: %6d, Time: %8.6f, Rate: %8.2f, Ave: %8.2f\r\n" % (
            str(self.prm.timestamp.time()), self.prm.counter_value,
            self.prm.count_delta, self.prm.time_delta, self.prm.counter_rate,
            self.prm.average_rate)
        return outstring

    #**************************************************************************************
    def Device_read(self):
        outstring = "READ %c%c%c%c %s %.6f %10d %8.2f\r\n" % (
            self.prm.state, self.prm.terminal_due, self.prm.range_error,
            self.prm.range_gated, str(
                self.prm.timestamp.time()), self.prm.accumulated_time,
            self.prm.counter_value, self.prm.counter_rate)
        paramdict = self.scanman.ui.sourceGroupBox.paramdict
        if self.prm.counter_value >= float(
                paramdict["COUNT_SIZE"]
        ) and paramdict["COUNT_METHOD"].find(
                "MONITOR"
        ) > -1:  #Only do a quick clear when performing a scan with the monitor.
            self.prm.counter_value = float(0)
            self.worstpercent = float(0)
            True
        return outstring

    #**************************************************************************************

    def ReadFromServer(self):
        True

    #**************************************************************************************
    def StartServer(self):
        self.host = "localhost"
        self.port = int(self.ui.port_Edit.text())
        self.ui.inbuffer_Edit.append("ServerStart on port:" + str(self.port))

        self.timestamp = datetime.datetime.now()
        self.tcpServer = QTcpServer(self)
        self.tcpServer.listen(QHostAddress(self.host), self.port)
        curtime = datetime.datetime.now()
        delta = curtime - self.timestamp
        self.time_delta = delta.total_seconds()

        self.scanman.ui.fitGroupBox.fittedsignal.connect(self.GetCurrent)

        self.connections = []
        self.connect(self.tcpServer, qtCore.SIGNAL("newConnection()"),
                     self.addConnection)
        self.ui.status_Edit.setText("On")

        True

    #**************************************************************************************
    def addConnection(self):
        try:
            clientConnection = self.tcpServer.nextPendingConnection()
            clientConnection.nextBlockSize = 0
            self.connections.append(clientConnection)

            self.connect(clientConnection, qtCore.SIGNAL("readyRead()"),
                         self.receiveMessage)
            self.connect(clientConnection, qtCore.SIGNAL("disconnected()"),
                         self.removeConnection)
            self.connect(clientConnection, qtCore.SIGNAL("error()"),
                         self.socketError)
        except:
            self.ui.inbuffer_Edit.append("Failed to add connection")
            True

    #**************************************************************************************
    def receiveMessage(self):
        try:
            s = self.sender()
            reply = ""
            #self.disconnect(s, qtCore.SIGNAL("readyRead()"), self.receiveMessage)       #Histogram server polls very quickly, rather let a request be completed before starting another one
            if s.bytesAvailable() > 0:
                textFromClient = s.readAll()
                textFromClient = textFromClient.toLower()
                #outstring = "%s - %s:%d -> %s" % (datetime.datetime.now().time(), s.peerAddress().toString(), s.peerPort(), textFromClient)
                #self.ui.inbuffer_Edit.append(outstring)

                if textFromClient.contains("pause"):
                    self.prm.state = 'P'
                    reply = "OK\r\n"
                elif textFromClient.contains("continue"):
                    self.prm.state = 'R'
                    reply = "OK\r\n"
                elif textFromClient.contains("resume"):
                    self.prm.state = 'R'
                    reply = "OK\r\n"
                elif textFromClient.contains("start"):
                    self.prm.state = 'R'
                    reply = "OK\r\n"
                elif textFromClient.contains("stop"):
                    self.prm.state = 'S'
                    #self.ClearValues()
                    reply = "OK\r\n"
                elif textFromClient.contains("read"):
                    time.sleep(0.0001)
                    reply = self.Device_read()
                elif textFromClient.contains("test"):
                    True
                else:
                    reply = self.Device_print()
                self.sendMessage(reply, s.socketDescriptor())

            #self.connect(s, qtCore.SIGNAL("readyRead()"), self.receiveMessage)
        except:
            self.ui.inbuffer_Edit.append(
                "Failed read message and send response")
            True

    #**************************************************************************************
    def sendMessage(self, text, socketId):
        try:
            for s in self.connections:
                if s.socketDescriptor() == socketId:
                    s.write(text)
        except:
            self.ui.inbuffer_Edit.append("Failed send response")
            True

    #**************************************************************************************
    def removeConnection(self):
        s = self.sender()
        self.connections.remove(s)
        True

    #**************************************************************************************
    def socketError(self):
        self.ui.inbuffer_Edit.append("Socket Error...\n")
        True

    #**************************************************************************************
    def StopServer(self):
        for i in range(len(self.connections)):
            self.connections[0].close(
            )  #Once removed, all will shift forward in the array
        self.tcpServer.close()
        self.scanman.ui.fitGroupBox.fittedsignal.disconnect(self.GetCurrent)
        self.ui.status_Edit.setText("Off")

    def DoIt(self, astr=""):
        self.ui.inbuffer_Edit.setText(astr)
Esempio n. 32
0
class ServerApp(FreeseerApp):
    
    STATUS = ["Offline",
              "Online"]

    status = STATUS[0]
    clients = []
    passPhrase = ''
    ipAddress = None
    
    def __init__(self):
        FreeseerApp.__init__(self)
        self.resize(400, 300)
        
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/freeseer/logo.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(icon)
        
        configdir = os.path.abspath(os.path.expanduser('~/.freeseer/'))
        self.logger = Logger(configdir)
        logging.info("Logger initialized")
        
        self.server = QTcpServer(self)
        logging.info("Starting Freeseer Server")
        
        # Setup Widget
        self.mainWidget = ControllerServerWidget()
        self.setCentralWidget(self.mainWidget)
        
        self.mainWidget.hostCombo.addItem(QtCore.QString("0.0.0.0"))
                
        #Connections
        self.connect(self.server, QtCore.SIGNAL('newConnection()'), self.acceptConnection)  
        self.connect(self.mainWidget.startButton, QtCore.SIGNAL('pressed()'), self.startServer)
        self.connect(self.mainWidget.hostCombo, QtCore.SIGNAL('currentIndexChanged(int)'), self.ipComboBoxHandler)
        self.connect(self.mainWidget.passEdit, QtCore.SIGNAL('textChanged(QString)'), self.onPassChanged)
        
        # Initialize Passphrase Field
        self.mainWidget.passEdit.setPlaceholderText("Passphrase required to start server")
        self.mainWidget.startButton.setEnabled(False)

        # Client Control
        self.connect(self.mainWidget.clientStartButton, QtCore.SIGNAL('pressed()'), self.sendRecordCommand)
        self.connect(self.mainWidget.clientStopButton, QtCore.SIGNAL('pressed()'), self.sendStopCommand)
        self.connect(self.mainWidget.clientDisconnectButton, QtCore.SIGNAL('pressed()'), self.disconnectClients)
        self.connect(self.mainWidget.clientList, QtCore.SIGNAL('itemSelectionChanged()'), self.updateClientButtons)
    
        self.load_settings()
        self.updateStatus(self.status)
        
    ###
    ### Translation Related
    ###
    def retranslate(self):
        self.setWindowTitle(self.uiTranslator.translate("ControllerServerApp", "Controller Server"))
        
        #
        # Reusuable Strings
        #
        self.serverStatusString = self.uiTranslator.translate("ControllerServerApp", "Server status")
        self.startServerString = self.uiTranslator.translate("ControllerServerApp", "Start Server")
        self.stopServerString = self.uiTranslator.translate("ControllerServerApp", "Stop Server")
        self.startRecordingString = self.uiTranslator.translate("ControllerServerApp", "Start Recording")
        self.stopRecordingString = self.uiTranslator.translate("ControllerServerApp", "Stop Recording")
        self.pauseRecordingString = self.uiTranslator.translate("ControllerServerApp", "Pause Recording")
        self.resumeRecordingString = self.uiTranslator.translate("ControllerServerApp", "Resume Recording")
        # --- End Reusable Strings
        
        #
        # Server Settings
        #
        self.mainWidget.toolBox.setItemText(0, self.uiTranslator.translate("ControllerServerApp", "Server Settings"))
        self.mainWidget.hostLabel.setText(self.uiTranslator.translate("ControllerServerApp", "IP Address"))
        self.mainWidget.portLabel.setText(self.uiTranslator.translate("ControllerServerApp", "Port"))
        self.mainWidget.passLabel.setText(self.uiTranslator.translate("ControllerServerApp", "Passphrase"))
        
        # Button
        if self.status == self.STATUS[0]:
            self.mainWidget.startButton.setText(self.startServerString)
        else:
            self.mainWidget.startButton.setText(self.stopServerString)
        # --- End Server Settings
        
        #
        # Control Clients
        #
        self.mainWidget.toolBox.setItemText(1, self.uiTranslator.translate("ControllerServerApp", "Control Clients"))
        self.updateClientButtons()
        self.mainWidget.clientDisconnectButton.setText(self.uiTranslator.translate("ControllerServerApp", "Disconnect"))
        # --- End Control Clients
        
    ###
    ### Server Methods
    ###
    def load_settings(self): 
        logging.info('Loading settings...')
        configdir = os.path.abspath(os.path.expanduser('~/.freeseer/'))
        self.config = Config(configdir)
        
        # Load default language.
        actions = self.menuLanguage.actions()
        for action in actions:
            if action.data().toString() == self.config.default_language:
                action.setChecked(True)
                self.translate(action)
                break
    
    def startServer(self):    
        if self.status == self.STATUS[0]:   # Check if status is Offline
            if self.ipAddress is None:
                self.ipAddress = QHostAddress(self.mainWidget.hostCombo.currentText())
            self.server.listen(self.ipAddress, PORT)    
            self.status = self.STATUS[1]    # Set Running            
            self.mainWidget.hostCombo.setEnabled(False)
            logging.info("Started server %s: %s", self.server.serverAddress().toString(), str(self.server.serverPort()))
            
        elif self.status == self.STATUS[1]:      # Check if status is Online
            self.server.close()
            self.status = self.STATUS[0]         # Set status Offline
            self.disconnectAllClients()
            self.mainWidget.hostCombo.setEnabled(True)
            self.ipAddress = None
            
        self.updateStatus(self.status)
        self.setPassPhrase()
        self.setConnectionLabel()
        self.retranslate()
        
    def updateStatus(self, status):
        self.mainWidget.statusLabel.setText("%s: %s" % (self.serverStatusString, status))
        
    def setConnectionLabel(self):
        text = "%s:%s" % (self.mainWidget.hostCombo.currentText(),
                          self.mainWidget.portEdit.text())
        self.mainWidget.settingsEdit.setText(text)

        if self.mainWidget.passEdit.text():
            self.mainWidget.settingsEdit.setText("%s@%s" % (self.mainWidget.passEdit.text(),
                                                            text))
        
    '''
    This function is for changing the passphrase. It saves the new passphrase in the self.passPhrase after encoding it.
    '''
    def setPassPhrase(self):
        self.passphrase = self.mainWidget.passEdit.text()
        logging.info ("Passphrase set to %s", self.passphrase)
        #self.passPhrase = base64.b64encode(self.passPhrase)
        self.passphrase = str(self.passphrase)
        self.passphrase = pwd_context.encrypt(self.passphrase)
        
    '''
    This function reads the passphrase sent from the client. It decodes the saved passphrase and the one that client sent and compares.
    Client is accepted if the passphrases match. Otherwise client is rejected
    '''  
    def readPassPhrase(self):
        client = QtCore.QObject.sender(self)
        message = client.read(client.bytesAvailable())   
        logging.info("Client said: %s", message)
        if pwd_context.verify(message, self.passphrase) is False:
            client.disconnectFromHost()
            logging.info("Client rejected")
        else:
            self.clients.append(client)
            self.updateList()
            logging.info("Client accepted")
            self.disconnect(client, QtCore.SIGNAL('readyRead()'), self.readPassPhrase)
            self.connect(client, QtCore.SIGNAL('readyRead()'), self.startRead)
    
    def onPassChanged(self):
        """Disable 'Start' button only when the passphrase field is empty."""
        if self.mainWidget.passEdit.text():
            self.mainWidget.startButton.setEnabled(True)
        else:
            self.mainWidget.startButton.setEnabled(False)
            
    def ipComboBoxHandler(self):
        self.ipAddress = QHostAddress(self.ipComboBox.itemText(self.ipComboBox.currentIndex()))
        logging.info("Server IP changed to: %s", self.ipAddress.toString())
    
    ###
    ### Messaging
    ###
    
    def startRead(self):
        client = QtCore.QObject.sender(self)
        message = client.read(client.bytesAvailable())   
        logging.info("Client said: %s", message)
        return message
    
    def sendMessage(self, client, message):
        block = QtCore.QByteArray()
        block.append(message)
        client.write(block)
            
    ###
    ### Client List Methods
    ###
            
    '''
    This is the function to handle a new connection.
    '''
    def acceptConnection(self):
        client = self.server.nextPendingConnection()
        self.connect(client, QtCore.SIGNAL("disconnected()"), self.clientDisconnected)
        self.connect(client, QtCore.SIGNAL('readyRead()'), self.readPassPhrase)
    
    def clientDisconnected(self):
        client = QtCore.QObject.sender(self)
        logging.info("Client disconnected")
        self.clients.remove(client)
        self.updateList()
        self.updateClientButtons()
    
    '''
    This method is to update the list
    '''
    def updateList(self):
        self.mainWidget.clientList.clear()
        for i in range(0, len(self.clients)):
            client = self.clients[i]
            listItem = ClientListItem(client)
            self.mainWidget.clientList.addItem(listItem)
            clientLabel = QtGui.QLabel('F1', self)
            clientLabel.move(5 + (i * 20), 150)
    
    def addClientToList(self, client):
        self.clients.append(object)
        listItem = ClientListItem(client)
        self.mainWidget.clientList.addItem(listItem)
    
    def removeClientFromTheList(self, client):
        self.clients.remove(client)
        self.updateList()

    '''
    Sends a record command to the selected clients
    '''     
    def sendRecordCommand (self):
        buttonText = self.mainWidget.clientStartButton.text()
        
        # Find out what command to send
        if buttonText == self.startRecordingString or buttonText == self.resumeRecordingString:
            command = COMMANDS[1]   # Set Record
        elif buttonText == self.pauseRecordingString:
            command = COMMANDS[2]   # Set Pause
        
        # Send command
        for i in range(0, len(self.mainWidget.clientList.selectedItems())):
            c_item = self.mainWidget.clientList.selectedItems()[i]
            client = c_item.client
            self.sendMessage(client, command)
            
            if command == COMMANDS[1]:                # Check if command is Record
                c_item.changeStatus(CLIENT_STATUS[1]) # Set Recording
            elif command == COMMANDS[2]:              # Check if command is Pause
                c_item.changeStatus(CLIENT_STATUS[2]) # Set Paused
                
            logging.info("Sent  %s  command to %s" % (command, c_item.address))
                
        self.updateClientButtons()
    
    '''
    Sends a stop command to selected clients
    '''
    def sendStopCommand (self):
        command = COMMANDS[0]   # Set Stop command
        
        for i in range(0, len(self.mainWidget.clientList.selectedItems())):
            c_item = self.mainWidget.clientList.selectedItems()[i]
            client = c_item.client
            self.sendMessage(client, command)
            c_item.changeStatus(CLIENT_STATUS[3])  # Set Idle
            
            logging.info("Sent  %s  command to %s" % (command, c_item.address))
            
        self.updateClientButtons()
        
    '''
    Method to disconnect all clients selected from the list
    '''
    def disconnectClients(self):
        for i in range(0, len(self.mainWidget.clientList.selectedItems())):
            client = self.mainWidget.clientList.selectedItems()[i].client
            client.disconnectFromHost()  
    
    '''
    Method to disconnect all clients that are connected
    '''
    def disconnectAllClients(self):
        for i in range(0, self.mainWidget.clientList.count()):
            client = self.mainWidget.clientList.item(i).client
            client.disconnectFromHost()
            
    def updateClientButtons(self):
        if len(self.mainWidget.clientList.selectedItems()) > 0:
            self.mainWidget.clientDisconnectButton.setEnabled(True)
            self.mainWidget.clientStartButton.setEnabled(True)
            
            for i in range(0, len(self.mainWidget.clientList.selectedItems())):
                clientStatus = self.mainWidget.clientList.selectedItems()[i].status
                logging.debug("Client status: %s", clientStatus)
                
                if clientStatus == CLIENT_STATUS[1]:    # Client is Recording
                    self.mainWidget.clientStartButton.setText(self.pauseRecordingString)
                    self.mainWidget.clientStopButton.setEnabled(True)
                    
                elif clientStatus == CLIENT_STATUS[3]:  # Client is Idle
                    self.mainWidget.clientStartButton.setText(self.startRecordingString)
                    self.mainWidget.clientStopButton.setEnabled(False)
                    
                elif clientStatus == CLIENT_STATUS[2]:  # Client is Paused
                    self.mainWidget.clientStartButton.setText(self.resumeRecordingString)
                    self.mainWidget.clientStopButton.setEnabled(True)
                    
        else:
            self.mainWidget.clientDisconnectButton.setEnabled(False)
            self.mainWidget.clientStartButton.setEnabled(False)
            self.mainWidget.clientStartButton.setText(self.startRecordingString)
            self.mainWidget.clientStopButton.setEnabled(False) 
            self.mainWidget.clientStopButton.setText(self.stopRecordingString)
Esempio n. 33
0
class RunManager( QObject ):
    " Manages the external running processes "

    def __init__( self, mainWindow ):
        QObject.__init__( self )
        self.__mainWindow = mainWindow
        self.__processes = []

        self.__tcpServer = QTcpServer()
        self.connect( self.__tcpServer, SIGNAL( "newConnection()" ),
                      self.__newConnection )
        self.__tcpServer.listen( QHostAddress.LocalHost )

        self.__waitTimer = QTimer( self )
        self.__waitTimer.setSingleShot( True )
        self.connect( self.__waitTimer, SIGNAL( 'timeout()' ),
                      self.__onWaitImer )
        return

    def __newConnection( self ):
        " Handles new incoming connections "
        clientSocket = self.__tcpServer.nextPendingConnection()
        clientSocket.setSocketOption( QAbstractSocket.KeepAliveOption, 1 )
        clientSocket.setSocketOption( QAbstractSocket.LowDelayOption, 1 )
        QApplication.setOverrideCursor( QCursor( Qt.WaitCursor ) )
        self.__waitForHandshake( clientSocket )
        QApplication.restoreOverrideCursor()
        return

    def __waitForHandshake( self, clientSocket ):
        " Waits for the message with the proc ID "
        if clientSocket.waitForReadyRead( 1000 ):
            qs = clientSocket.readAll()
            us = str( CODEC.fromUnicode( str( qs ) ) )
            if not us.endswith( EOT ):
                return

            line = us[ 0 : -len( EOT ) ]
            if not line.startswith( '>' ):
                return

            cmdIndex = line.find( '<' )
            if cmdIndex == -1:
                return

            cmd = line[ 0 : cmdIndex + 1 ]
            content = line[ cmdIndex + 1 : ]
            if cmd != ResponseProcID:
                return

            # It could only be a redirected process
            procID = int( content )
            procIndex = self.__getProcessIndex( procID )
            if procIndex is not None:
                self.__onProcessStarted( procID )
                self.__processes[ procIndex ].procWrapper.setSocket(
                                                            clientSocket )
        return

    def run( self, path, needDialog ):
        " Runs the given script with redirected IO "
        if needDialog:
            params = GlobalData().getRunParameters( path )
            termType = Settings().terminalType
            profilerParams = Settings().getProfilerSettings()
            debuggerParams = Settings().getDebuggerSettings()
            dlg = RunDialog( path, params, termType,
                             profilerParams, debuggerParams, "Run" )
            if dlg.exec_() != QDialog.Accepted:
                return
            GlobalData().addRunParams( path, dlg.runParams )
            if dlg.termType != termType:
                Settings().terminalType = dlg.termType

        # The parameters for the run are ready.
        # Start the run business.
        remoteProc = RemoteProcess()
        remoteProc.isProfiling = False
        remoteProc.procWrapper = RemoteProcessWrapper( path,
                                        self.__tcpServer.serverPort() )
        if Settings().terminalType == TERM_REDIRECT:
            remoteProc.widget = RunConsoleTabWidget(
                                        remoteProc.procWrapper.procID() )
            self.connect( remoteProc.procWrapper, SIGNAL( 'ClientStdout' ),
                          remoteProc.widget.appendStdoutMessage )
            self.connect( remoteProc.procWrapper, SIGNAL( 'ClientStderr' ),
                          remoteProc.widget.appendStderrMessage )
            self.connect( remoteProc.procWrapper, SIGNAL( 'ClientRawInput' ),
                          remoteProc.widget.rawInput )
            self.connect( remoteProc.widget, SIGNAL( 'UserInput' ),
                          self.__onUserInput )
        else:
            remoteProc.widget = None

        self.connect( remoteProc.procWrapper, SIGNAL( 'Finished' ),
                      self.__onProcessFinished )
        self.__processes.append( remoteProc )
        if remoteProc.procWrapper.start() == False:
            # Failed to start - the fact is logged, just remove from the list
            procIndex = self.__getProcessIndex( remoteProc.procWrapper.procID() )
            if procIndex is not None:
                del self.__processes[ procIndex ]
        else:
            if Settings().terminalType != TERM_REDIRECT:
                if not self.__waitTimer.isActive():
                    self.__waitTimer.start( 1000 )
        return

    def profile( self, path ):
        " Profiles the given script with redirected IO "
        return

    def killAll( self ):
        " Kills all the processes if needed "
        index = len( self.__processes ) - 1
        while index >= 0:
            item = self.__processes[ index ]
            if item.procWrapper.needRedirection():
                item.procWrapper.stop()
            index -= 1

        # Wait till all the processes stopped
        count = self.__getDetachedCount()
        while count > 0:
            time.sleep( 0.01 )
            QApplication.processEvents()
            count = self.__getDetachedCount()
        return

    def __getDetachedCount( self ):
        " Return the number of detached processes still running "
        count = 0
        index = len( self.__processes ) - 1
        while index >= 0:
            if self.__processes[ index ].procWrapper.needRedirection():
                count += 1
            index -= 1
        return count

    def kill( self, procID ):
        " Kills a single process "
        index = self.__getProcessIndex( procID )
        if index is None:
            return
        item = self.__processes[ index ]
        if not item.procWrapper.needRedirection():
            return

        item.procWrapper.stop()
        return

    def __getProcessIndex( self, procID ):
        " Returns a process index in the list "
        for index, item in enumerate( self.__processes ):
            if item.procWrapper.procID() == procID:
                return index
        return None

    def __onProcessFinished( self, procID, retCode ):
        " Triggered when a process has finished "
        index = self.__getProcessIndex( procID )
        if index is not None:
            item = self.__processes[ index ]
            if item.procWrapper.needRedirection():
                if item.widget:
                    item.widget.scriptFinished()
                    if retCode == KILLED:
                        msg  = "Script killed"
                        tooltip = "killed"
                    elif retCode == DISCONNECTED:
                        msg = "Connection lost to the script process"
                        tooltip = "connection lost"
                    else:
                        msg = "Script finished with exit code " + str( retCode )
                        tooltip = "finished, exit code " + str( retCode )
                        item.procWrapper.wait()
                    item.widget.appendIDEMessage( msg )
                    self.__mainWindow.updateIOConsoleTooltip( procID, tooltip )
            del self.__processes[ index ]
        return

    def __onProcessStarted( self, procID ):
        " Triggered when a process has started "
        index = self.__getProcessIndex( procID )
        if index is not None:
            item = self.__processes[ index ]
            if item.widget:
                self.__mainWindow.installIOConsole( item.widget )
                item.widget.appendIDEMessage( "Script " +
                                              item.procWrapper.path() +
                                              " started" )
        return

    def __onUserInput( self, procID, userInput ):
        " Triggered when the user input is collected "
        index = self.__getProcessIndex( procID )
        if index is not None:
            item = self.__processes[ index ]
            if item.procWrapper.needRedirection():
                item.procWrapper.userInput( userInput )
        return

    def __onWaitImer( self ):
        " Triggered when the timer fired "
        needNewTimer = False
        index = len( self.__processes ) - 1
        while index >= 0:
            item = self.__processes[ index ]
            if item.procWrapper.needRedirection() == False:
                if item.procWrapper.waitDetached() == True:
                    del self.__processes[ index ]
                else:
                    needNewTimer = True
            index -= 1
        if needNewTimer:
            self.__waitTimer.start( 1000 )
        return
Esempio n. 34
0
    def __init__(self, parent=None):
        QTcpServer.__init__(self)

        self.newConnection.connect(self.handler)
        self.listen(QHostAddress(argv[1]), int(argv[2]))
Esempio n. 35
0
class GameSession(QObject):
    ready = pyqtSignal()

    def __init__(self, client, connectivity):
        QObject.__init__(self)
        self._state = GameSessionState.OFF

        # Subscribe to messages targeted at 'game' from the server
        client.subscribe_to('game', self)

        # Connectivity helper
        self.connectivity = connectivity
        self.connectivity.ready.connect(self.ready.emit)
        self.connectivity.peer_bound.connect(self._peer_bound)

        # Keep a parent pointer so we can use it to send
        # relay messages about the game state
        self._client = client  # type: Client
        self.me = client.me

        self.game_port = client.gamePort
        self.player = client.me

        # Use the normal lobby by default
        self.init_mode = 0
        self._joins, self._connects = [], []

        # 'GPGNet' TCP listener
        self._game_listener = QTcpServer(self)
        self._game_listener.newConnection.connect(self._new_game_connection)
        self._game_listener.listen(QHostAddress.LocalHost)

        # We only allow one game connection at a time
        self._game_connection = None

        self._process = game_process_instance  # type: GameProcess
        self._process.started.connect(self._launched)
        self._process.finished.connect(self._exited)

    @property
    def relay_port(self):
        return self._game_listener.serverPort()

    @property
    def state(self):
        return self._state

    @state.setter
    def state(self, val):
        self._state = val

    def listen(self):
        """
        Start listening for remote commands

        Call this in good time before hosting a game,
        e.g. when the host game dialog is being shown.
        """
        assert self.state == GameSessionState.OFF
        self.state = GameSessionState.LISTENING
        if self.connectivity.is_ready:
            self.ready.emit()
        else:
            self.connectivity.prepare()

    def handle_message(self, message):
        command, args = message.get('command'), message.get('args', [])
        if command == 'SendNatPacket':
            addr_and_port, message = args
            host, port = addr_and_port.split(':')
            self.connectivity.send(message, (host, port))
        elif command == 'CreatePermission':
            addr_and_port = args[0]
            host, port = addr_and_port.split(':')
            self.connectivity.permit((host, port))
        elif command == 'JoinGame':
            addr, login, peer_id = args
            self._joins.append(peer_id)
            self.connectivity.bind(addr, login, peer_id)
        elif command == 'ConnectToPeer':
            addr, login, peer_id = args
            self._connects.append(peer_id)
            self.connectivity.bind(addr, login, peer_id)
        else:
            self._game_connection.send(command, *args)

    def send(self, command_id, args):
        self._logger.info("Outgoing relay message {} {}".format(
            command_id, args))
        self._client.send({
            'command': command_id,
            'target': 'game',
            'args': args or []
        })

    def _peer_bound(self, login, peer_id, port):
        self._logger.info("Bound peer {}/{} to {}".format(
            login, peer_id, port))
        if peer_id in self._connects:
            self._game_connection.send('ConnectToPeer',
                                       '127.0.0.1:{}'.format(port), login,
                                       peer_id)
            self._connects.remove(peer_id)
        elif peer_id in self._joins:
            self._game_connection.send('JoinGame', '127.0.0.1:{}'.format(port),
                                       login, peer_id)
            self._joins.remove(peer_id)

    def _new_game_connection(self):
        self._logger.info("Game connected through GPGNet")
        assert not self._game_connection
        self._game_connection = GPGNetConnection(
            self._game_listener.nextPendingConnection())
        self._game_connection.messageReceived.connect(self._on_game_message)
        self.state = GameSessionState.RUNNING

    def _on_game_message(self, command, args):
        self._logger.info("Incoming GPGNet: {} {}".format(command, args))
        if command == "GameState":
            if args[0] == 'Idle':
                # autolobby, port, nickname, uid, hasSupcom
                self._game_connection.send("CreateLobby", self.init_mode,
                                           self.game_port + 1, self.me.login,
                                           self.me.id, 1)
            elif args[0] == 'Lobby':
                # TODO: Eagerly initialize the game by hosting/joining early
                pass
        self.send(command, args)

    def _turn_state_changed(self, val):
        if val == TURNState.BOUND:
            self.ready.emit()

    def _launched(self):
        self._logger.info("Game has started")

    def _exited(self, status):
        self._game_connection = None
        self.state = GameSessionState.OFF
        self._logger.info(
            "Game has exited with status code: {}".format(status))
        self.send('GameState', ['Ended'])
Esempio n. 36
0
class QiVisServer(QObject):
    def __init__( self, name, dimensions, port, resource_path ):
        QObject.__init__(self)
        self.port = int(port)
        self.server = QTcpServer(self)
        self.connect(self.server, QtCore.SIGNAL("newConnection()"), self.newConnection)
        self.server.listen(Qt.QHostAddress(Qt.QHostAddress.Any), self.port )
        print " --- iVisServer ---  Listening on port: ", str( port )
        self.sockets = {}
        self.buffer = ''

        self.devices = {}

        self.vistrailServer = VistrailServer( resource_path )
        self.summary = None
        self.addDevice( name, dimensions )
        self.userPool = UserPool()
    
#    def __del__( self ): 
#        self.shutdownClients()
        
    def shutdownClients(self):
        for device in self.devices.values(): 
            device.shutdown()
        self.devices.clear()
        
    def addDevice(self, name, dimensions ):
        device = Device(name, dimensions)
        self.devices[device.name] = device

    def readDevicesFromFile(self, filename):
        import os.path
        if os.path.isfile(filename):
            f = file(filename, 'r')
        else:
            f = None

        if not f is None:
            lines = f.readlines()
            name = ""
            dimensions = None
            for i in range(len(lines)):
                tokens = lines[i].split()
                if tokens:
                    if tokens[0] == "device":
                        pass
                    elif tokens[0] == "name":
                        name = ''.join([x+" " for x in tokens[1:]])[:-1]
                    elif tokens[0] == "dimensions":
                        dimensions = (int(tokens[1]), int(tokens[2]))
                    elif tokens[0] == "end_device":
                        device = Device(name, dimensions)
                        self.devices[device.name] = device
        f.close()

    def newConnection(self):
        while self.server.hasPendingConnections():
            print " ~~~~~~~~~~~~~~~~~~~~~~Received Connection~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
            socket = self.server.nextPendingConnection()

            print socket.peerAddress().toString()
            self.sockets[str(socket.peerAddress().toString())] = socket

            self.connect(self.sockets[str(socket.peerAddress().toString())], QtCore.SIGNAL("readyRead()"), self.readDataFromSocket)
            self.connect(self.sockets[str(socket.peerAddress().toString())], QtCore.SIGNAL("disconnected()"), self.disconnected)

    def disconnected(self):
        print "Disconnected"

    def readDataFromSocket(self):
        socket = None
        for s in self.sockets:
            if self.sockets[s].bytesAvailable() != 0:
                socket = self.sockets[s]
                break

        if socket is None:
            return

        incoming = str(socket.readAll().data())
        while incoming != "":
            self.buffer += incoming
            while (self.buffer != ""):
                tokens = self.buffer.split(":")
                header = tokens[0]
                rest = ""
                for piece in tokens[1:]:
                    rest += piece+":"
                rest = rest[:-1]
                tmp = header.split("-")
                if len(tmp) == 3:
                    (sender, receiver, size) = header.split("-")
                else:
                    break

                if int(size) > len(rest):
                    break

                tokens = rest[:int(size)]
                self.buffer = rest[int(size):]

                reply = ("", "", "")
                if (receiver == "server"):
                    reply = self.processMessage((sender,tokens), socket)
                elif (receiver == "vistrailServer"):
                    reply = self.vistrailServer.processMessage((sender, tokens), socket)

                if reply != ("","",""):
                    reply = reply[0] + "-" + reply[1] + "-" + str(len(reply[2])) + ":" + reply[2]
                    socket.write(reply)

            incoming = str(socket.readAll().data())

    def executePipeline( self, pipeline, deviceName, vistrailName, versionName, moduleId, dimensions ):
        cellID = self.devices[deviceName].dispatchPipeline( pipeline, vistrailName, versionName, moduleId, dimensions)
        
#        replyTokens = "localID,"+deviceName+","+str(cellID)+","+tokens[5]+","+tokens[6]+","+tokens[7]+","+tokens[8]

#        broadcastTokens = "addCell,"
#        broadcastTokens += deviceName +","+vistrailName+","+str(versionName)+","+str(moduleId)+","+str(cellID)+","
#        broadcastTokens += str(dimensions[0]) + ","+str(dimensions[1])+","+str(dimensions[2])+","+str(dimensions[3])
#        self.broadcastMessage(("server", sender, broadcastTokens), [self.sockets[x] for x in self.sockets if self.sockets[x] != socket])
#
#        summaryMessageTokens = 'attach,blank_user,'+str(dimensions[1])+','+str(dimensions[3])+','+str(dimensions[0])+','+str(dimensions[2])
#        summaryMessage = 'server-summary-'+str(len(summaryMessageTokens))+':'+summaryMessageTokens
#        if not self.summary is None:
#            self.summary.write(summaryMessage)

 #       return ("server", sender, replyTokens)


    def processMessage(self, message, socket=None):
        (sender, tokens) = message
#        print " -- Server process message: %s " % tokens
        tokens = tokens.split( MessageTokenSep )
        if len(tokens) == 0: return

        ### connection attempt
        if tokens[0] == "tryConnect":
            #elif sender == "summary":
            #    print "SummarY!!!"
            #    self.summary = socket

            return ("server",sender,"acceptConnect")

        ### disconnection warning
        if tokens[0] == "willDisconnect":
            print "Disconnecting iPhone"
            key = socket.peerAddress().toString()
            if (self.sockets.has_key(key)):
                del self.sockets[key]

        if tokens[0] == "logout":
            print "Logging out"
            key = socket.peerAddress().toString()
            if (self.sockets.has_key(key)):
                del self.sockets[key]
            summaryMessageTokens = "logout,"+tokens[1]
            summaryMessage = 'server-summary-'+str(len(summaryMessageTokens))+':'+summaryMessageTokens
            if not self.summary is None:
                self.summary.write(summaryMessage)

        ### querying for an existing user
        elif tokens[0] == "usernameQuery":
            if self.userPool.queryUser(tokens[1]):
                summaryMessageTokens = 'login,'+str(tokens[1])+','\
                    +str(self.userPool.users[tokens[1]].color[0])+","\
                    +str(self.userPool.users[tokens[1]].color[1])+","\
                    +str(self.userPool.users[tokens[1]].color[2])

                summaryMessage = 'server-summary-'+str(len(summaryMessageTokens))+':'+summaryMessageTokens
                if not self.summary is None:
                    self.summary.write(summaryMessage)

                return ("server",sender,"username,true,"\
                    +str(self.userPool.users[tokens[1]].color[0])+","\
                    +str(self.userPool.users[tokens[1]].color[1])+","\
                    +str(self.userPool.users[tokens[1]].color[2]))
            else:
                return ("server", sender, "username,false")

        ### sender asked to create a new user
        elif tokens[0] == "createUser":
            username = tokens[1]
            color = (float(tokens[2]), float(tokens[3]), float(tokens[4]))
            self.userPool.addUser(User(username, color))

            summaryMessageTokens = 'login,'+str(tokens[1])+','\
                +str(self.userPool.users[tokens[1]].color[0])+","\
                +str(self.userPool.users[tokens[1]].color[1])+","\
                +str(self.userPool.users[tokens[1]].color[2])
            
            summaryMessage = 'server-summary-'+str(len(summaryMessageTokens))+':'+summaryMessageTokens
            if not self.summary is None:
                self.summary.write(summaryMessage)

        ### querying the available devices
        elif tokens[0] == "queryDevices":
            replyTokens = "availableDevices,"
            for device in self.devices.values():
                replyTokens += device.name+","+str(device.dimensions[0])+","+str(device.dimensions[1])+","
            replyTokens = replyTokens[:-1]
            return ("server", sender, replyTokens)

        ### querying the pipeline properties
        elif tokens[0] == "queryProperties":
            deviceName = tokens[1]
            reply = "availableProperties," + self.devices[deviceName].queryProperties(tokens[2])
            return ("server", sender, reply)

        ### querying the pipeline properties
        elif tokens[0] == "updatePipeline":
            deviceName = tokens[1]
            #tokens: 2. LocalID, 3. MedleyXML
            reply = "updatePipeline," + tokens[2] + "," + self.devices[deviceName].updatePipeline(tokens[2], tokens[3])
            return ("server", sender, reply)

        ### saving the visualization layout
        elif tokens[0] == "saveLayout":
            deviceName = tokens[1]
            reply = "layoutSaved,"
            #deviceName, vistrailName, versionName, moduleId, dimensions, pipeline
            #pickle doesnt work. Have to write the file by myself
            #
            #devices amount
            #info, pipeline
            if tokens[2] != "":
                pickle.dump( self.devices, open(self.vistrailServer.resource_path +tokens[2]+".lay","w"))
            print "Save Layout"
            return ("server", sender, reply)

        ### querying the visualization layout available
        elif tokens[0] == "queryLayouts":
            reply = "availableLayouts,"
            for n in self.vistrailServer.querySavedLayouts():
                reply += n + ","
            reply = reply[:-1]
            return ("server", sender, reply)

        ### open the saved layout available
        elif tokens[0] == "openLayout":
            reply = "appliedLayout,"
            print tokens[1]
            return ("server", sender, reply)

        ### sender is a display client advertising its dimensions
        elif tokens[0] == "dimensions":
            deviceName = tokens[1]
            dimensions = (int(tokens[2]), int(tokens[3]), int(tokens[4]), int(tokens[5]))
            print "Dimensions!", deviceName, dimensions
            print self.devices.keys()
            if self.devices.has_key(deviceName):
                self.devices[deviceName].addClient(dimensions, socket)

        ### sender is an iPhone asking to execute a pipeline
        elif tokens[0] == "executePipeline":
            deviceName = tokens[1]
            vistrailName = tokens[2]
            versionName = tokens[3]
            moduleId = int(tokens[4])
            dimensions = (int(tokens[5]), int(tokens[6]), int(tokens[7]), int(tokens[8]))

            pipeline = self.vistrailServer.getPipeline(vistrailName, versionName)
            print " Executing message executePipeline!!! "

            cellID = self.devices[deviceName].dispatchPipeline(pipeline, vistrailName, versionName, moduleId, dimensions)
            replyTokens = "localID,"+deviceName+","+str(cellID)+","+tokens[5]+","+tokens[6]+","+tokens[7]+","+tokens[8]

            broadcastTokens = "addCell,"
            broadcastTokens += deviceName +","+vistrailName+","+versionName+","+str(moduleId)+","+str(cellID)+","
            broadcastTokens += str(dimensions[0]) + ","+str(dimensions[1])+","+str(dimensions[2])+","+str(dimensions[3])
            self.broadcastMessage(("server", sender, broadcastTokens), [self.sockets[x] for x in self.sockets if self.sockets[x] != socket])

            summaryMessageTokens = 'attach,blank_user,'+str(dimensions[1])+','+str(dimensions[3])+','+str(dimensions[0])+','+str(dimensions[2])
            summaryMessage = 'server-summary-'+str(len(summaryMessageTokens))+':'+summaryMessageTokens
            if not self.summary is None:
                self.summary.write(summaryMessage)

            return ("server", sender, replyTokens)

        ### sender is a device sending an interaction event
        elif tokens[0] == "interaction":
            deviceName = tokens[1]
            self.devices[deviceName].processInteractionMessage(tokens[1:])

        ### sender is an iPhone asking for device occupation on a certain device
        elif tokens[0] == "deviceOccupation":
            deviceName = tokens[1]
            reply = self.devices[deviceName].queryOccupation()
            return ("server", sender, reply)

        ### sender is asking to delete a certain cell
        elif tokens[0] == "deleteCell":
            deviceName = tokens[1]            
            reply = self.devices[deviceName].deleteCell(tokens[2:])
            broadcastTokens = "deleteCell,"+deviceName+","+str(tokens[2])
            self.broadcastMessage(("server", sender, broadcastTokens), [self.sockets[x] for x in self.sockets if self.sockets[x] != socket])
            return ("server", sender, reply)

        ### sender is asking to lock a certain cell for interaction
        elif tokens[0] == "lockCell":
            deviceName = tokens[1]
            reply = self.devices[deviceName].lockCell(tokens[2:])
            reply = ("server", sender, reply)
            self.broadcastMessage(reply, self.sockets.values())

        elif tokens[0] == "unlockCell":
            deviceName = tokens[1]
            reply = self.devices[deviceName].unlockCell(tokens[2:])
            reply = ("server", sender, reply)
            self.broadcastMessage(reply, self.sockets.values())
        return ("", "", "")

    def broadcastMessage(self, message, receivers):
        message = message[0] + "-" + message[1] + "-" + str(len(message[2])) + ":" + message[2]
        for receiver in receivers:
            receiver.write(message)

    def processGuiCommand( self, deviceName, command, selected_cells ):
        self.devices[deviceName].processInteractionMessage( command, selected_cells, "command" )

    def processInteractionState( self, deviceName, selected_cells, interactionState, altMode  ):
        print " Process Interaction State Event %s" % ( interactionState ) 
        tokens = [ "interactionState" ]
        if interactionState: 
            tokens.append( interactionState )
            if altMode: tokens.append( altMode )
        self.devices[deviceName].processInteractionMessage( tokens, selected_cells  )

    def processInteractionEvent( self, deviceName, event, screen_dims, selected_cells, camera_pos   ):
        etype = event.type()
        event_type = "none"
        tokens = ""
        if   etype == QtCore.QEvent.MouseMove:          event_type = "mouseMove" 
        elif etype == QtCore.QEvent.MouseButtonPress:   event_type = "singleClick" 
        elif etype == QtCore.QEvent.MouseButtonRelease: event_type = "mouseRelease" 
        elif etype == QtCore.QEvent.KeyPress:           event_type = "keyPress" 
        elif etype == QtCore.QEvent.KeyRelease:         event_type = "keyRelease" 
        mod = event.modifiers() 
        if mod:
           if   ( mod & QtCore.Qt.ShiftModifier    ): mod = "shift" 
           elif ( mod & QtCore.Qt.ControlModifier  ): mod = "ctrl" 
           elif ( mod & QtCore.Qt.AltModifier      ): mod = "alt" 
           else:                                      mod = "none"
        
        if (etype== QtCore.QEvent.KeyRelease) or (etype== QtCore.QEvent.KeyPress):   
            key = event.key() 
            tokens = [ event_type, key, mod ]
#            print ' >>----------iVisServer--> process Key Event:  %s '   % str( ( event_type, key, mod, event.text() ) )
        else: 
            fullSpec = True # ( etype == QtCore.QEvent.MouseButtonPress )            
            x = event.x()
            y = event.y()
            xf = '%.4f' % (float(x)/screen_dims[0])
            yf = '%.4f' % (float(y)/screen_dims[1])
            b = event.button() 
            button = "none"       
            if b == QtCore.Qt.LeftButton: button = "left"
            if b == QtCore.Qt.RightButton: button = "right" 
            if fullSpec:
                cpos = camera_pos[0]  
                cfol = camera_pos[1]  
                cup = camera_pos[2]         
                tokens = [ event_type, button, xf, yf, mod, cpos[0], cpos[1], cpos[2], cfol[0], cfol[1], cfol[2], cup[0], cup[1], cup[2]  ]
            else:
                tokens = [ event_type, button, xf, yf, mod ]
#            print ' >>----------iVisServer--> process Mouse Event:  %s '   % str( ( event_type, xf, yf, button, mod, screen_dims, tokens ) )  
                      
        self.devices[deviceName].processInteractionMessage( tokens, selected_cells  )
Esempio n. 37
0
class RunManager(QObject):
    " Manages the external running processes "

    def __init__(self, mainWindow):
        QObject.__init__(self)
        self.__mainWindow = mainWindow
        self.__processes = []

        self.__tcpServer = QTcpServer()
        self.connect(self.__tcpServer, SIGNAL("newConnection()"),
                     self.__newConnection)
        self.__tcpServer.listen(QHostAddress.LocalHost)

        self.__waitTimer = QTimer(self)
        self.__waitTimer.setSingleShot(True)
        self.connect(self.__waitTimer, SIGNAL('timeout()'), self.__onWaitImer)
        return

    def __newConnection(self):
        " Handles new incoming connections "
        clientSocket = self.__tcpServer.nextPendingConnection()
        clientSocket.setSocketOption(QAbstractSocket.KeepAliveOption, 1)
        clientSocket.setSocketOption(QAbstractSocket.LowDelayOption, 1)
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.__waitForHandshake(clientSocket)
        QApplication.restoreOverrideCursor()
        return

    def __waitForHandshake(self, clientSocket):
        " Waits for the message with the proc ID "
        if clientSocket.waitForReadyRead(1000):
            qs = clientSocket.readAll()
            us = str(CODEC.fromUnicode(str(qs)))
            if not us.endswith(EOT):
                return

            line = us[0:-len(EOT)]
            if not line.startswith('>'):
                return

            cmdIndex = line.find('<')
            if cmdIndex == -1:
                return

            cmd = line[0:cmdIndex + 1]
            content = line[cmdIndex + 1:]
            if cmd != ResponseProcID:
                return

            # It could only be a redirected process
            procID = int(content)
            procIndex = self.__getProcessIndex(procID)
            if procIndex is not None:
                self.__onProcessStarted(procID)
                self.__processes[procIndex].procWrapper.setSocket(clientSocket)
        return

    def run(self, path, needDialog):
        " Runs the given script with redirected IO "
        if needDialog:
            params = GlobalData().getRunParameters(path)
            termType = Settings().terminalType
            profilerParams = Settings().getProfilerSettings()
            debuggerParams = Settings().getDebuggerSettings()
            dlg = RunDialog(path, params, termType, profilerParams,
                            debuggerParams, "Run", self.__mainWindow)
            if dlg.exec_() != QDialog.Accepted:
                return
            GlobalData().addRunParams(path, dlg.runParams)
            if dlg.termType != termType:
                Settings().terminalType = dlg.termType

        # The parameters for the run are ready.
        # Start the run business.
        remoteProc = RemoteProcess()
        remoteProc.isProfiling = False
        remoteProc.procWrapper = RemoteProcessWrapper(
            path, self.__tcpServer.serverPort())
        if Settings().terminalType == TERM_REDIRECT:
            remoteProc.widget = RunConsoleTabWidget(
                remoteProc.procWrapper.procID())
            self.connect(remoteProc.procWrapper, SIGNAL('ClientStdout'),
                         remoteProc.widget.appendStdoutMessage)
            self.connect(remoteProc.procWrapper, SIGNAL('ClientStderr'),
                         remoteProc.widget.appendStderrMessage)
            self.connect(remoteProc.procWrapper, SIGNAL('ClientRawInput'),
                         remoteProc.widget.rawInput)
            self.connect(remoteProc.widget, SIGNAL('UserInput'),
                         self.__onUserInput)
        else:
            remoteProc.widget = None

        self.connect(remoteProc.procWrapper, SIGNAL('Finished'),
                     self.__onProcessFinished)
        self.__processes.append(remoteProc)
        if remoteProc.procWrapper.start() == False:
            # Failed to start - the fact is logged, just remove from the list
            procIndex = self.__getProcessIndex(remoteProc.procWrapper.procID())
            if procIndex is not None:
                del self.__processes[procIndex]
        else:
            if Settings().terminalType != TERM_REDIRECT:
                if not self.__waitTimer.isActive():
                    self.__waitTimer.start(1000)
        return

    def profile(self, path):
        " Profiles the given script with redirected IO "
        return

    def killAll(self):
        " Kills all the processes if needed "
        index = len(self.__processes) - 1
        while index >= 0:
            item = self.__processes[index]
            if item.procWrapper.needRedirection():
                item.procWrapper.stop()
            index -= 1

        # Wait till all the processes stopped
        count = self.__getDetachedCount()
        while count > 0:
            time.sleep(0.01)
            QApplication.processEvents()
            count = self.__getDetachedCount()
        return

    def __getDetachedCount(self):
        " Return the number of detached processes still running "
        count = 0
        index = len(self.__processes) - 1
        while index >= 0:
            if self.__processes[index].procWrapper.needRedirection():
                count += 1
            index -= 1
        return count

    def kill(self, procID):
        " Kills a single process "
        index = self.__getProcessIndex(procID)
        if index is None:
            return
        item = self.__processes[index]
        if not item.procWrapper.needRedirection():
            return

        item.procWrapper.stop()
        return

    def __getProcessIndex(self, procID):
        " Returns a process index in the list "
        for index, item in enumerate(self.__processes):
            if item.procWrapper.procID() == procID:
                return index
        return None

    def __onProcessFinished(self, procID, retCode):
        " Triggered when a process has finished "
        index = self.__getProcessIndex(procID)
        if index is not None:
            item = self.__processes[index]
            if item.procWrapper.needRedirection():
                if item.widget:
                    item.widget.scriptFinished()
                    if retCode == KILLED:
                        msg = "Script killed"
                        tooltip = "killed"
                    elif retCode == DISCONNECTED:
                        msg = "Connection lost to the script process"
                        tooltip = "connection lost"
                    else:
                        msg = "Script finished with exit code " + str(retCode)
                        tooltip = "finished, exit code " + str(retCode)
                        item.procWrapper.wait()
                    item.widget.appendIDEMessage(msg)
                    self.__mainWindow.updateIOConsoleTooltip(procID, tooltip)
            del self.__processes[index]
        return

    def __onProcessStarted(self, procID):
        " Triggered when a process has started "
        index = self.__getProcessIndex(procID)
        if index is not None:
            item = self.__processes[index]
            if item.widget:
                self.__mainWindow.installIOConsole(item.widget)
                item.widget.appendIDEMessage("Script " +
                                             item.procWrapper.path() +
                                             " started")
        return

    def __onUserInput(self, procID, userInput):
        " Triggered when the user input is collected "
        index = self.__getProcessIndex(procID)
        if index is not None:
            item = self.__processes[index]
            if item.procWrapper.needRedirection():
                item.procWrapper.userInput(userInput)
        return

    def __onWaitImer(self):
        " Triggered when the timer fired "
        needNewTimer = False
        index = len(self.__processes) - 1
        while index >= 0:
            item = self.__processes[index]
            if item.procWrapper.needRedirection() == False:
                if item.procWrapper.waitDetached() == True:
                    del self.__processes[index]
                else:
                    needNewTimer = True
            index -= 1
        if needNewTimer:
            self.__waitTimer.start(1000)
        return
Esempio n. 38
0
class ControlServer(QObject):

    # Signal to inform that the set logging level command has been received
    logging_command_received = pyqtSignal(int)

    # Signal to inform that the quit command has been received and the system should exit
    quit_command_received = pyqtSignal()

    def __init__(self):
        QObject.__init__(self)

        # logging instance
        self.log = logging.getLogger('GDAIS.ControlServer')

        # TCP server to listen for control commands
        self.tcp_server = QTcpServer()

        # regexp to check if command is 'set_log_level'
        self.valid_loglevel = re.compile(r"^set_log_level (\d?0)$")

    def start(self):
        self.log.info("Starting TCP server...")
        if self.tcp_server.listen(port=12345):
            txt = "Listening at http://localhost:{0} for commands"
            self.log.info(txt.format(self.tcp_server.serverPort()))
            self.tcp_server.newConnection.connect(self._accept_connection)
        else:
            self.log.warn("Unable to start: {0}".format(
                self.tcp_server.errorString()))

            # define a timer to auto-quit the app after 10 sec
            timeout = 10  # seconds
            self.log.warn(
                "GDAIS will run for {0} seconds and then die".format(timeout))
            self.timer = QTimer()
            self.timer.timeout.connect(self.quit)
            self.timer.start(timeout * 1000)  # msec

    def quit(self):
        if self.tcp_connection and self.tcp_connection.state(
        ) == QTcpSocket.ConnectedState:
            loop = QEventLoop()
            self.tcp_connection.disconnected.connect(loop.quit)
            self.tcp_connection.disconnectFromHost()
            self.log.debug("Entering disconnect state...")
            if self.tcp_connection.state() == QTcpSocket.ConnectedState:
                loop.exec_()
            self.log.debug("Done waiting, closing server...")
        if self.tcp_server.isListening():
            self.tcp_server.close()
        self.quit_command_received.emit()

    def _accept_connection(self):
        self.tcp_connection = self.tcp_server.nextPendingConnection()
        self.tcp_connection.readyRead.connect(self._read_data)
        self.tcp_connection.error.connect(self._error_ocurred)

        self.log.debug("Accepted connection")

    def _read_data(self):
        tcp_data = self.tcp_connection.readAll()
        if tcp_data == 'quit':
            self.log.info("Received 'quit' command")
            self.quit()
        elif self.valid_loglevel.match(tcp_data):
            self.log.info("Received 'set_log_level' command")
            try:
                new_level = int(self.valid_loglevel.match(tcp_data).group(1))
            except ValueError:
                self.log.exception("Level has to be an integer value")
            else:
                self.logging_command_received.emit(new_level)
        else:
            self.log.error("Received unknown command: {0}".format(tcp_data))

    def _error_ocurred(self, socket_error):
        if socket_error == QTcpSocket.RemoteHostClosedError:
            self.log.info(self.tcp_connection.errorString())
        else:
            self.log.error(self.tcp_connection.errorString())
Esempio n. 39
0
File: main.py Progetto: xiaq/chat
class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.createServer()
        self.configureWindow()
        self.createUi()
        self.readConfig()
        self.loginName = ''

        for cmd in self.config['autorun']:
            self.evalCmd(cmd)

    def configureWindow(self):
        self.setWindowTitle('Simple Chat Program')
        self.resize(700, 600)
        self.center()

    def readConfig(self):
        self.config = {
            'friends': [],
            'autorun': [],
            'receiveDirectory': 'received',
        }
        path = os.path.join(mydir, 'config.json')
        try:
            with open(path, 'r') as f:
                self.config.update(json.load(f))
        except IOError:
            self.buf.error('Cannot read configuration file %s.' % path)
        except ValueError:
            self.buf.error('Configuration file %s contains errors.' % path)

        rdir = self.config['receiveDirectory']
        if os.path.isabs(rdir):
            self.receiveDirectory = rdir
        else:
            self.receiveDirectory = os.path.join(mydir, rdir)

    def createUi(self):
        main = QHBoxLayout()

        console = QVBoxLayout()
        self.buf = TextBrowser()
        self.buf.setFontFamily('monospace')
        self.buf.setFocusPolicy(Qt.NoFocus)
        console.addWidget(self.buf)
        self.command_line = QLineEdit()
        console.addWidget(self.command_line)

        main.addLayout(console, 1)
        self.tab = QTabWidget()
        self.tab.setTabsClosable(True)
        self.peers = {}
        main.addWidget(self.tab, 3)

        self.setLayout(main)

        self.command_line.returnPressed.connect(self.onCommand)
        self.tab.tabCloseRequested.connect(self.onTabCloseRequested)

    def createServer(self):
        self.server = QTcpServer()
        if not self.server.listen(port=PEER_PORT):
            QMessageBox.critical(
                self, "Server Error",
                "Cannot start server. Port %d seems in use." % PEER_PORT)
            sys.exit(1)
        self.server.newConnection.connect(self.onNewConnection)

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def addPage(self, socket):
        addr = socket.peerAddress()
        page = ChatWindow(socket, addr)
        self.peers[addr] = page
        self.tab.addTab(page, addr.toString())

    def newActive(self, peer, resolve=True):
        if resolve and peer in self.config['friends']:
            self.buf.info('%s is in friends list, querying...' % peer)

            def cb(res):
                if res == 'n':
                    self.buf.error('%s is offline' % peer)
                elif res[0].isdigit():
                    self.buf.info('%s has IP address %s' % (peer, res))
                    self.newActive(res, False)
                else:
                    self.buf.error('status of %s is unknown' % peer)
            self.talkToCentral('q%s' % peer, u'query', r'', cb, False)
            return

        socket = QTcpSocket()
        socket.connectToHost(peer, PEER_PORT)

        def onConnected():
            self.buf.info('Connected to %s' % peer)
            self.addPage(socket)

        def onError():
            self.buf.error('Error communicating with %s: %s' % (
                peer, socket.errorString()))
        socket.connected.connect(onConnected)
        socket.error.connect(onError)

        self.buf.info('Reaching out to %s...' % peer)

    def talkToCentral(self, msg, name, pattern, cb=None, successMsg=True):
        Name = name.title()
        socket = QTcpSocket()
        socket.connectToHost(CENTRAL_ADDR, CENTRAL_PORT)

        def onConnected():
            socket.write(msg)

            def onReadyRead():
                response = str(socket.readAll())
                if re.match(pattern, response):
                    if successMsg:
                        self.buf.info(u'%s successful.' % Name)
                    if cb:
                        cb(response)
                else:
                    self.buf.error(u'%s failed, server said %s.' %
                        (Name, repr(response)))
                socket.close()
            socket.readyRead.connect(onReadyRead)

        def onError():
            self.buf.error(u'Error %s: %s' %
                (name, urepr(socket.errorString())))

        socket.connected.connect(onConnected)
        socket.error.connect(onError)

    def login(self, obj):
        name, sep, passwd = obj.partition(' ')

        def cb(res):
            self.loginName = name
        self.talkToCentral('%s_%s' % (name, passwd), u'login', r'^lol$', cb)

    def logout(self):
        if not self.loginName:
            self.buf.error(u'Not logged in')
            return

        def cb(res):
            self.loginName = ''

        self.talkToCentral('logout%s' % self.loginName,
                           u'logout', r'^loo$', cb)

    def queryOne(self, p):
        def cb(res):
            if res == 'n':
                self.buf.info('%s: offline' % p)
            elif res[0].isdigit():
                self.buf.info('%s: online, %s' % (p, res))
            else:
                self.buf.info('%s: unknown' % p)
        self.talkToCentral('q%s' % p, u'query', r'', cb, False)

    def query(self, obj):
        if obj:
            self.queryOne(obj)
        else:
            for p in self.config['friends']:
                self.queryOne(p)

    def evalCmd(self, command):
        if len(command) == 0:
            return

        if command[0] != u'/':
            self.buf.info(u"%s taken as implicit /talk" % urepr(command))
            command = u'/talk ' + command

        verb, sep, obj = command[1:].partition(' ')
        if verb in (u't', u'talk'):
            self.newActive(obj)
        elif verb in (u'h', u'help'):
            self.buf.info(COMMANDS_HELP)
        elif verb == u'login':
            self.login(obj)
        elif verb == u'logout':
            self.logout()
        elif verb in (u'q', u'query'):
            self.query(obj)
        else:
            self.buf.error(u'Unknown command %s.' % urepr(verb))

    def onCommand(self):
        self.evalCmd(unicode(self.command_line.text()))
        self.command_line.clear()

    readBufSize = 1024
    text_msg_pattern = re.compile(r'^T(\d+) (.*)$', re.S)
    file_msg_pattern = re.compile(r'^F(\d+) ([^/]+)/(.*)$', re.S)

    def onNewConnection(self):
        socket = self.server.nextPendingConnection()

        def onReadyRead():
            addr = socket.peerAddress()
            if addr not in self.peers:
                self.addPage(socket)

            addr_s = addr.toString()
            payload = str(socket.read(self.readBufSize))

            if payload[0] == 'T':
                payload_m = re.match(self.text_msg_pattern, payload)
                if not payload_m:
                    self.buf.error('Bad text message from %s' % addr_s)
                    return

                size = int(payload_m.group(1))
                segments = [payload_m.group(2)]

                remain = size - len(segments[0])
                while remain > 0:
                    payload = str(socket.read(remain))
                    if len(payload) <= 0:
                        self.buf.error('Incomplete text message from %s'
                                       ' - need %d more bytes' %
                                       (addr_s, remain))
                        break
                    segments.append(payload)
                    remain -= len(payload)
                self.peers[addr].buf.feed(''.join(segments))

            elif payload[0] == 'F':
                payload_m = re.match(self.file_msg_pattern, payload)
                if not payload_m:
                    self.buf.error('Bad file message from %s: %s' % (addr_s,
                        repr(payload)))
                    return

                size = int(payload_m.group(1))
                bname = payload_m.group(2)
                rdir = self.receiveDirectory
                path = os.path.join(rdir, bname)

                with open(path, 'wb') as f:
                    segment = payload_m.group(3)
                    f.write(segment)
                    remain = size - len(segment)
                    while remain > 0:
                        segment = str(socket.read(
                            min(remain, self.readBufSize)))
                        if len(segment) <= 0:
                            self.buf.error('Incomplete file message from %s'
                                           ' - need %d more bytes' %
                                           (addr_s, remain))
                            break
                        f.write(segment)
                        remain -= len(segment)
                self.buf.info('File %s from %s saved at %s' %
                    (repr(bname), addr_s, rdir))

            else:
                self.buf.error('Bad message from %s: unknown type '
                               '"%s"' % (addr.toString(), payload[0]))

        socket.readyRead.connect(onReadyRead)

    def onTabCloseRequested(self, idx):
        page = self.tab.widget(idx)
        self.tab.removeTab(idx)
        page.close()
        page.deleteLater()
Esempio n. 40
0
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.settings = QSettings('settings.ini', QSettings.IniFormat)
        self.tcpServer = QTcpServer()

        self.chBox = QCheckBox("Print log to window")
        self.text = QPlainTextEdit()
        self.serverStatusLabel = QLabel("Server ready")

        self.lblFileName = QLabel("Choose file before start!")
        self.saveButton = QPushButton("&Choose file...")
        self.startButton = QPushButton("&Start")
        self.stopButton = QPushButton("S&top")
        self.quitButton = QPushButton("&Quit")

        self.file = None
        self.tcpServerConnection = None

        self._lineCounter = 0
        self._lineBuf = ''

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.startButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(self.stopButton, QDialogButtonBox.RejectRole)
        buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole)

        clearButon = QPushButton('&Clear')

        self.saveButton.clicked.connect(self.savedlg)
        self.startButton.clicked.connect(self.start)
        self.stopButton.clicked.connect(self.stopClicked)
        self.quitButton.clicked.connect(self.close)
        clearButon.clicked.connect(self.text.clear)
        self.tcpServer.newConnection.connect(self.acceptConnection)

        saveLayout = QHBoxLayout()
        saveLayout.addWidget(self.lblFileName)
        saveLayout.addStretch(1)
        saveLayout.addWidget(self.saveButton)

        topTextLayout = QHBoxLayout()
        topTextLayout.addWidget(self.chBox)
        topTextLayout.addStretch(1)
        topTextLayout.addWidget(clearButon)

        mainLayout = QVBoxLayout()
        mainLayout.addLayout(saveLayout)
        mainLayout.addLayout(topTextLayout)
        mainLayout.addWidget(self.text)
        mainLayout.addWidget(self.serverStatusLabel)
        #        mainLayout.addStretch(1)
        mainLayout.addSpacing(10)
        mainLayout.addWidget(buttonBox)
        self.setLayout(mainLayout)

        self.title = "Simple Logger"
        self.ver = '1.0'

        self.setWindowIcon(QIcon('./icon.png'))
        self.setWindowTitle("{} {}".format(self.title, self.ver))
Esempio n. 41
0
    def __init__(self, parent=None):
        QTcpServer.__init__(self)

        self.newConnection.connect(self.handler)
        self.listen(QHostAddress(argv[1]), int(argv[2]))
Esempio n. 42
0
class Dialog(QDialog):
    TotalBytes = 50 * 1024 * 1024
    PayloadSize = 65536

    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.settings = QSettings('settings.ini', QSettings.IniFormat)
        self.tcpServer = QTcpServer()

        self.chBox = QCheckBox("Print log to window")
        self.text = QPlainTextEdit()
        self.serverStatusLabel = QLabel("Server ready")

        self.lblFileName = QLabel("Choose file before start!")
        self.saveButton = QPushButton("&Choose file...")
        self.startButton = QPushButton("&Start")
        self.stopButton = QPushButton("S&top")
        self.quitButton = QPushButton("&Quit")
        
        self.file = None
        self.tcpServerConnection = None

        self._lineCounter = 0
        self._lineBuf = ''

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.startButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(self.stopButton, QDialogButtonBox.RejectRole)
        buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole)

        clearButon = QPushButton('&Clear')

        self.saveButton.clicked.connect(self.savedlg)
        self.startButton.clicked.connect(self.start)
        self.stopButton.clicked.connect(self.stopClicked)
        self.quitButton.clicked.connect(self.close)
        clearButon.clicked.connect(self.text.clear)
        self.tcpServer.newConnection.connect(self.acceptConnection)

        saveLayout = QHBoxLayout()
        saveLayout.addWidget(self.lblFileName)
        saveLayout.addStretch(1)
        saveLayout.addWidget(self.saveButton)

        topTextLayout = QHBoxLayout()
        topTextLayout.addWidget(self.chBox)
        topTextLayout.addStretch(1)
        topTextLayout.addWidget(clearButon)

        mainLayout = QVBoxLayout()
        mainLayout.addLayout(saveLayout)
        mainLayout.addLayout(topTextLayout)
        mainLayout.addWidget(self.text)
        mainLayout.addWidget(self.serverStatusLabel)
#        mainLayout.addStretch(1)
        mainLayout.addSpacing(10)
        mainLayout.addWidget(buttonBox)
        self.setLayout(mainLayout)

        self.title = "Simple Logger"
        self.ver = '1.0'

        self.setWindowIcon(QIcon('./icon.png'))
        self.setWindowTitle("{} {}".format(self.title, self.ver))

    def start(self):
        if self.file is None:
            QMessageBox.critical(self, self.title, "Unable open log file.\nPlease, select another file.")
            return
        self.startButton.setEnabled(False)

        while not self.tcpServer.isListening() and not self.tcpServer.listen(port=9112):
            ret = QMessageBox.critical(self, self.title,
                    "Unable to start the test: %s." % self.tcpServer.errorString(),
                    QMessageBox.Retry | QMessageBox.Cancel)
            if ret == QMessageBox.Cancel:
                return

        self.serverStatusLabel.setText("Waiting connection ...")

    def acceptConnection(self):
        self.tcpServerConnection = self.tcpServer.nextPendingConnection()
        self.tcpServerConnection.readyRead.connect(self.updateLog)
        self.tcpServerConnection.error.connect(self.displayError)

        self.file = QFile(self.filename)
        if not self.file.open(QFile.Append):
            QMessageBox.warning(self, self.title, "Unable to write file {}:\n{}.".format(self.filename, self.file.errorString()))
            self.file = None
            return
        self.textStream = QTextStream(self.file)
        self.textStream.setCodec('UTF-8')

        self.serverStatusLabel.setText("Logging ...")
        self.tcpServer.close()

    def savedlg(self):
        self.filename = QFileDialog.getSaveFileName(self, "Log Filename", self.settings.value('directories/dir_save', QDir.currentPath()), "Text (*.log *.txt);;All (*)")
        if not self.filename:
            return

        self.file = QFile(self.filename)
        self.lblFileName.setText(self.filename)
        if not self.file.open(QFile.WriteOnly):
            QMessageBox.warning(self, self.title, "Unable to write file {}:\n{}.".format(self.filename, self.file.errorString()))
            self.file = None
            return
        self.textStream = QTextStream(self.file)
        self.textStream.setCodec('UTF-8')

        self.settings.setValue('directories/dir_save', QFileInfo(self.file).path())
        self.file.close()

    def updateLog(self):
        if self.tcpServerConnection.bytesAvailable():
            data = self.tcpServerConnection.readAll()
            line = "{}".format(str(data.data().decode()))
            if self.chBox.isChecked():
                self._lineCounter += 1
                self._lineBuf += line
                if self._lineCounter > 10:
                    self.text.appendPlainText(self._lineBuf)
                    self._lineCounter = 0
                    self._lineBuf = ''
            self.textStream << line
            self.file.flush()
#            self.serverStatusLabel.setText(line)

    def closeEvent(self, event):
        if self.file is not None:
            self.file.flush()
            self.file.close()

    def stopClicked(self):
        if self.tcpServerConnection is not None:
            self.tcpServerConnection.close()
        self.file.close()
        self.startButton.setEnabled(True)
        self.serverStatusLabel.setText("Logger ready")


    def displayError(self, socketError):
        if socketError == QTcpSocket.RemoteHostClosedError:
            return

        QMessageBox.information(self, "Network error",
                "The following error occured: %s." % self.tcpServer.errorString())

        self.tcpServer.close()
        self.file.close()
        self.serverStatusLabel.setText("Logger ready")
        self.startButton.setEnabled(True)
Esempio n. 43
0
class GameSession(QObject):
    ready = pyqtSignal()

    def __init__(self, client, connectivity):
        QObject.__init__(self)
        self._state = GameSessionState.OFF

        # Subscribe to messages targeted at 'game' from the server
        client.subscribe_to('game', self)

        # Connectivity helper
        self.connectivity = connectivity
        self.connectivity.ready.connect(self.ready.emit)
        self.connectivity.peer_bound.connect(self._peer_bound)

        # Keep a parent pointer so we can use it to send
        # relay messages about the game state
        self._client = client  # type: Client
        self.me = client.me

        self.game_port = client.gamePort
        self.player = client.me

        # Use the normal lobby by default
        self.init_mode = 0
        self._joins, self._connects = [], []

        # 'GPGNet' TCP listener
        self._game_listener = QTcpServer(self)
        self._game_listener.newConnection.connect(self._new_game_connection)
        self._game_listener.listen(QHostAddress.LocalHost)

        # We only allow one game connection at a time
        self._game_connection = None

        self._process = game_process_instance  # type: GameProcess
        self._process.started.connect(self._launched)
        self._process.finished.connect(self._exited)

    @property
    def relay_port(self):
        return self._game_listener.serverPort()

    @property
    def state(self):
        return self._state

    @state.setter
    def state(self, val):
        self._state = val

    def listen(self):
        """
        Start listening for remote commands

        Call this in good time before hosting a game,
        e.g. when the host game dialog is being shown.
        """
        assert self.state == GameSessionState.OFF
        self.state = GameSessionState.LISTENING
        if self.connectivity.is_ready:
            self.ready.emit()
        else:
            self.connectivity.prepare()

    def handle_message(self, message):
        command, args = message.get('command'), message.get('args', [])
        if command == 'SendNatPacket':
            addr_and_port, message = args
            host, port = addr_and_port.split(':')
            self.connectivity.send(message, (host, port))
        elif command == 'CreatePermission':
            addr_and_port = args[0]
            host, port = addr_and_port.split(':')
            self.connectivity.permit((host, port))
        elif command == 'JoinGame':
            addr, login, peer_id = args
            self._joins.append(peer_id)
            self.connectivity.bind(addr, login, peer_id)
        elif command == 'ConnectToPeer':
            addr, login, peer_id = args
            self._connects.append(peer_id)
            self.connectivity.bind(addr, login, peer_id)
        else:
            self._game_connection.send(command, *args)

    def send(self, command_id, args):
        self._logger.info("Outgoing relay message {} {}".format(command_id, args))
        self._client.send({
            'command': command_id,
            'target': 'game',
            'args': args or []
        })

    def _peer_bound(self, login, peer_id, port):
        self._logger.info("Bound peer {}/{} to {}".format(login, peer_id, port))
        if peer_id in self._connects:
            self._game_connection.send('ConnectToPeer', '127.0.0.1:{}'.format(port), login, peer_id)
            self._connects.remove(peer_id)
        elif peer_id in self._joins:
            self._game_connection.send('JoinGame', '127.0.0.1:{}'.format(port), login, peer_id)
            self._joins.remove(peer_id)

    def _new_game_connection(self):
        self._logger.info("Game connected through GPGNet")
        assert not self._game_connection
        self._game_connection = GPGNetConnection(self._game_listener.nextPendingConnection())
        self._game_connection.messageReceived.connect(self._on_game_message)
        self.state = GameSessionState.RUNNING

    def _on_game_message(self, command, args):
        self._logger.info("Incoming GPGNet: {} {}".format(command, args))
        if command == "GameState":
            if args[0] == 'Idle':
                # autolobby, port, nickname, uid, hasSupcom
                self._game_connection.send("CreateLobby",
                                           self.init_mode,
                                           self.game_port + 1,
                                           self.me.login,
                                           self.me.id,
                                           1)
            elif args[0] == 'Lobby':
                # TODO: Eagerly initialize the game by hosting/joining early
                pass
        self.send(command, args)

    def _turn_state_changed(self, val):
        if val == TURNState.BOUND:
            self.ready.emit()

    def _launched(self):
        self._logger.info("Game has started")

    def _exited(self, status):
        self._game_connection = None
        self.state = GameSessionState.OFF
        self._logger.info("Game has exited with status code: {}".format(status))
        self.send('GameState', ['Ended'])
Esempio n. 44
0
class HTTPProxy(QObject):

    debug = True
    log = sys.stderr
    username = '******'
    password = '******'
    stopServing = pyqtSlot()

    def __init__(self, parent=None):
        super(HTTPProxy, self).__init__(parent)
        self.proxy_server = QTcpServer(self)
        self.proxy_server.listen(QHostAddress.Any, 8000)
        self.proxy_server.newConnection.connect(self.manage_request)

        if self.debug:
            self.log.write('Proxy server running on 0.0.0.0 port %s\n\n' %
                           self.port())

    def port(self):
        return self.proxy_server.serverPort()

    def addr(self):
        return self.proxy_server.serverAddress().toString()

    def stopServing(self):
        if self.debug:
            self.log.write('Service is stopping...\n\n')

        # does not "close" the server, just stop listening...
        self.proxy_server.close()

        if self.proxy_server.hasPendingConnections():
            socket = self.proxy_server.nextPendingConnection()
            while socket:
                socket.abort()
                socket = self.proxy_server.nextPendingConnection()

    def manage_request(self):
        proxy_server = self.sender()
        # Qt docs says that the caller of nextPendingConnection()
        # is the parent of the socket
        socket = proxy_server.nextPendingConnection()
        socket.readyRead.connect(self.process_request)
        socket.disconnected.connect(socket.deleteLater)

    def authorize_request(self, request_data):
        return True
        header = QHttpRequestHeader(QString(request_data))
        if self.debug:
            self.log.write(header.toString())

        auth = header.value('Proxy-Authorization')
        if not auth:
            return False

        challenge = base64.b64encode(self.username + ':' + self.password)
        return challenge == str(auth).split()[1]

    def process_request(self):
        socket = self.sender()
        request_data = socket.readAll()

        if not self.authorize_request(request_data):
            socket.write('HTTP/1.1 407 Proxy Authentication Required\r\n')
            if self.debug:
                self.log.write('407 Proxy Authentication Required\n\n')
            socket.write('Proxy-Authenticate: Basic realm="test"\r\n')
            socket.write('\r\n')
            socket.disconnectFromHost()
            return
        else:
            # remove Proxy-Authorization header
            start = request_data.indexOf('Proxy-Authorization:')
            end = request_data.lastIndexOf('\r\n')
            request_data.remove(start, end)
            request_data.append('\r\n')

        pos = request_data.indexOf('\r\n')
        request_line = request_data.left(pos)
        request_data.remove(0, pos + 2)

        entries = request_line.split(' ')
        method = entries[0]
        address = entries[1]
        version = entries[2]
        port = '80'

        if address.count(':') > 1:
            protocol, host, port = address.split(':')
        else:
            protocol, host = address.split(':')

        print 'address', address

        #url = QUrl( protocol + host )
        url = QUrl.fromEncoded(address)
        #url.setHost( host )
        #url.setPort( int(port) )

        if not url.isValid():
            if self.debug:
                self.log.write('Invalid URL: %s\n\n', url)
            socket.disconnectFromHost()
            return

        host = url.host()
        port = 80 if (url.port() < 0) else url.port()
        req = url.encodedPath()
        if url.hasQuery():
            req.append('?').append(url.encodedQuery())
        request_line = method + ' ' + req + ' ' + version + '\r\n'
        request_data.prepend(request_line)

        if self.debug:
            self.log.write(method + ' ' + address + ' ' + version + '\n\n')

        key = host + ':' + QString.number(port)
        proxy_socket = socket.findChild(QTcpSocket, key)
        if proxy_socket:
            proxy_socket.setObjectName(key)
            proxy_socket.setProperty('url', url)
            proxy_socket.setProperty('request_data', request_data)
            proxy_socket.write(request_data)
        else:
            proxy_socket = QTcpSocket(socket)
            proxy_socket.setObjectName(key)
            proxy_socket.setProperty('url', url)
            proxy_socket.setProperty('request_data', request_data)
            proxy_socket.connected.connect(self.send_request)
            proxy_socket.readyRead.connect(self.transfer_data)
            proxy_socket.disconnected.connect(self.close_connection)
            proxy_socket.error.connect(self.close_connection)
            proxy_socket.connectToHost(host, port)

    def send_request(self):
        proxy_socket = self.sender()
        request_data = proxy_socket.property('request_data').toByteArray()
        proxy_socket.write(request_data)

    def transfer_data(self):
        proxy_socket = self.sender()
        socket = proxy_socket.parent()
        socket.write(proxy_socket.readAll())

    def close_connection(self):
        proxy_socket = self.sender()
        if proxy_socket:
            socket = proxy_socket.parent()
            if isinstance(socket, QTcpSocket) and socket:
                socket.disconnectFromHost()
            if proxy_socket.error() != QTcpSocket.RemoteHostClosedError:
                url = proxy_socket.property('url').toUrl()
                error_string = proxy_socket.errorString()

                if self.debug:
                    self.log.write('Error for %s %s\n\n' % (url, error_string))

            proxy_socket.deleteLater()
Esempio n. 45
0
class HTTPProxy(QObject):

    debug = True
    log = sys.stderr
    username = '******'
    password = '******'
    stopServing = pyqtSlot()

    def __init__(self, parent=None):
        super(HTTPProxy, self).__init__(parent)
        self.proxy_server = QTcpServer(self)
        self.proxy_server.listen(QHostAddress.Any, 8000)
        self.proxy_server.newConnection.connect(self.manage_request)

        if self.debug:
            self.log.write('Proxy server running on 0.0.0.0 port %s\n\n' %
                self.port())

    def port(self):
        return self.proxy_server.serverPort()

    def addr(self):
        return self.proxy_server.serverAddress().toString()

    def stopServing(self):
        if self.debug:
            self.log.write('Service is stopping...\n\n')

        # does not "close" the server, just stop listening...
        self.proxy_server.close()

        if self.proxy_server.hasPendingConnections():
            socket = self.proxy_server.nextPendingConnection()
            while socket:
                socket.abort()
                socket = self.proxy_server.nextPendingConnection()

    def manage_request(self):
        proxy_server = self.sender()
        # Qt docs says that the caller of nextPendingConnection()
        # is the parent of the socket
        socket = proxy_server.nextPendingConnection()
        socket.readyRead.connect(self.process_request)
        socket.disconnected.connect(socket.deleteLater)

    def authorize_request(self, request_data):
        return True
        header = QHttpRequestHeader(QString(request_data))
        if self.debug:
            self.log.write(header.toString())

        auth = header.value('Proxy-Authorization')
        if not auth:
            return False

        challenge = base64.b64encode(self.username+':'+self.password)
        return challenge == str(auth).split()[1]

    def process_request(self):
        socket = self.sender()
        request_data = socket.readAll()

        if not self.authorize_request(request_data):
            socket.write('HTTP/1.1 407 Proxy Authentication Required\r\n')
            if self.debug:
                self.log.write('407 Proxy Authentication Required\n\n')
            socket.write('Proxy-Authenticate: Basic realm="test"\r\n')
            socket.write('\r\n')
            socket.disconnectFromHost()
            return
        else:
            # remove Proxy-Authorization header
            start = request_data.indexOf('Proxy-Authorization:')
            end = request_data.lastIndexOf('\r\n')
            request_data.remove(start, end)
            request_data.append('\r\n')

        pos = request_data.indexOf('\r\n')
        request_line = request_data.left(pos)
        request_data.remove(0, pos + 2)

        entries = request_line.split(' ')
        method = entries[0]
        address = entries[1]
        version = entries[2]
        port = '80'
        
        if address.count(':') > 1:
            protocol, host, port = address.split(':')
        else:
            protocol, host = address.split(':')
           
        print 'address', address
        
        #url = QUrl( protocol + host )
        url = QUrl.fromEncoded(address)
        #url.setHost( host )
        #url.setPort( int(port) )
        
        if not url.isValid():
            if self.debug:
                self.log.write('Invalid URL: %s\n\n', url)
            socket.disconnectFromHost()
            return

        host = url.host()
        port = 80 if (url.port() < 0) else url.port()
        req = url.encodedPath()
        if url.hasQuery():
            req.append('?').append(url.encodedQuery())
        request_line = method + ' ' + req + ' ' + version + '\r\n'
        request_data.prepend(request_line)

        if self.debug:
            self.log.write(method + ' ' + address + ' ' + version + '\n\n')

        key = host + ':' + QString.number(port)
        proxy_socket = socket.findChild(QTcpSocket, key)
        if proxy_socket:
            proxy_socket.setObjectName(key)
            proxy_socket.setProperty('url', url)
            proxy_socket.setProperty('request_data', request_data)
            proxy_socket.write(request_data)
        else:
            proxy_socket = QTcpSocket(socket)
            proxy_socket.setObjectName(key)
            proxy_socket.setProperty('url', url)
            proxy_socket.setProperty('request_data', request_data)
            proxy_socket.connected.connect(self.send_request)
            proxy_socket.readyRead.connect(self.transfer_data)
            proxy_socket.disconnected.connect(self.close_connection)
            proxy_socket.error.connect(self.close_connection)
            proxy_socket.connectToHost(host, port)

    def send_request(self):
        proxy_socket = self.sender()
        request_data = proxy_socket.property('request_data').toByteArray()
        proxy_socket.write(request_data)

    def transfer_data(self):
        proxy_socket = self.sender()
        socket = proxy_socket.parent()
        socket.write(proxy_socket.readAll())

    def close_connection(self):
        proxy_socket = self.sender()
        if proxy_socket:
            socket = proxy_socket.parent()
            if isinstance(socket, QTcpSocket) and socket:
                socket.disconnectFromHost()
            if proxy_socket.error() != QTcpSocket.RemoteHostClosedError:
                url = proxy_socket.property('url').toUrl()
                error_string = proxy_socket.errorString()

                if self.debug:
                    self.log.write('Error for %s %s\n\n' % (url, error_string))

            proxy_socket.deleteLater()
Esempio n. 46
0
def isAvailable(port):
    server = QTcpServer()
    result = server.listen(QHostAddress("127.0.0.1"), port)
    server.close()
    return result
Esempio n. 47
0
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.settings = QSettings('settings.ini', QSettings.IniFormat)
        self.tcpServer = QTcpServer()

        self.chBox = QCheckBox("Print log to window")
        self.text = QPlainTextEdit()
        self.serverStatusLabel = QLabel("Server ready")

        self.lblFileName = QLabel("Choose file before start!")
        self.saveButton = QPushButton("&Choose file...")
        self.startButton = QPushButton("&Start")
        self.stopButton = QPushButton("S&top")
        self.quitButton = QPushButton("&Quit")
        
        self.file = None
        self.tcpServerConnection = None

        self._lineCounter = 0
        self._lineBuf = ''

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.startButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(self.stopButton, QDialogButtonBox.RejectRole)
        buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole)

        clearButon = QPushButton('&Clear')

        self.saveButton.clicked.connect(self.savedlg)
        self.startButton.clicked.connect(self.start)
        self.stopButton.clicked.connect(self.stopClicked)
        self.quitButton.clicked.connect(self.close)
        clearButon.clicked.connect(self.text.clear)
        self.tcpServer.newConnection.connect(self.acceptConnection)

        saveLayout = QHBoxLayout()
        saveLayout.addWidget(self.lblFileName)
        saveLayout.addStretch(1)
        saveLayout.addWidget(self.saveButton)

        topTextLayout = QHBoxLayout()
        topTextLayout.addWidget(self.chBox)
        topTextLayout.addStretch(1)
        topTextLayout.addWidget(clearButon)

        mainLayout = QVBoxLayout()
        mainLayout.addLayout(saveLayout)
        mainLayout.addLayout(topTextLayout)
        mainLayout.addWidget(self.text)
        mainLayout.addWidget(self.serverStatusLabel)
#        mainLayout.addStretch(1)
        mainLayout.addSpacing(10)
        mainLayout.addWidget(buttonBox)
        self.setLayout(mainLayout)

        self.title = "Simple Logger"
        self.ver = '1.0'

        self.setWindowIcon(QIcon('./icon.png'))
        self.setWindowTitle("{} {}".format(self.title, self.ver))