Esempio n. 1
0
class ClientForm(QtGui.QWidget):
  def __init__(self, host, port, usn):
    super(ClientForm, self).__init__()
    self.ui = Ui_Form()
    self.ui.setupUi(self)
    self.ui.lineEdit.setFocus()
    self.running = 1

    self.dpbar = MProgressBar(self) #download bar
    self.dpbar.setOrientation(QtCore.Qt.Vertical)
    self.dpbar.setGeometry(520, 0, 20, 189)
    self.dpbar.setValue(0)
    self.dpbar.setStyle(True)

    self.dpbar_thread = Update_dpbar()
    self.connect(self.dpbar_thread, QtCore.SIGNAL("set_dpbar"), self.set_dpbar)
    self.dpbar_thread.start() 
    
    self.upbar = MProgressBar(self) #upload bar
    self.upbar.setOrientation(QtCore.Qt.Vertical)
    self.upbar.setGeometry(545, 0, 20, 189)
    self.upbar.setValue(0)
    self.upbar.setStyle(False)
    
    self.upbar_thread = Update_upbar()
    self.connect(self.upbar_thread, QtCore.SIGNAL("set_upbar"), self.set_upbar)
    self.upbar_thread.start()
    
    self.host = host
    self.port = port
    self.size = 1024
    self.socket = None
    self.username = ''

    self.downloadingFromHost = None

    try:
      self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      self.socket.connect((self.host, self.port))
      self.key = int(hash(self.socket)) ^ int(time.time())
      self.key = self.key if self.key > 0 else -self.key
    except socket.error:
      print 'Not accepting connections'
      sys.exit(1)

    try:
      self.socket.send(usn)
      response = self.socket.recv(self.size)
      if response == 'ACCEPT':
        self.username = usn
      else:
        print 'Username already exists, please choose a different username'
        sys.exit(1)
    except socket.error:
      print 'Some socket error'

    self.downloader = Downloader(self.key) #make the downloader listen for incoming download requests
    self.downloader.start()

    self.receiver = Receiver(self.socket, self.key)
    self.connect(self.receiver, QtCore.SIGNAL("update_msg"), self.update_msg)
    self.connect(self.receiver, QtCore.SIGNAL("update_userlist"), self.update_userlist)
    self.receiver.start() #start listening

  def closeEvent(self, event):
    self.dpbar_thread.terminate()
    self.upbar_thread.terminate()

  def on_lineEdit_returnPressed(self):
    if self.ui.lineEdit.displayText() != '':
      stringToSend = str(self.ui.lineEdit.displayText())

      if stringToSend.startswith("\download "):
        fileToDownload = stringToSend.split(' ')[1]
        for host in searchresults.keys():
          for result in searchresults[host]:
            if fileToDownload == result:
              self.downloadingFromHost = host
              stringToSend = "\download "+host+" "+enc(str(self.key))+" "+fileToDownload #host is the hash
              self.socket.send(str(stringToSend))
              self.ui.lineEdit.setText('')
              return
      elif stringToSend.startswith("\pause"): 
        stringToSend = "\pause "+self.downloadingFromHost
        self.update_msg("Download Paused")
      elif stringToSend.startswith(r'\resume'):
        stringToSend = r'\resume '+self.downloadingFromHost
        self.update_msg("Download Resumed")
      
      try:
        if not stringToSend.startswith("\download "):
          self.socket.send(str(stringToSend)) 
        else:
          self.update_msg('This file is not among your search results')
          
      except socket.error:
        self.ui.textEdit.setTextColor(QtCore.Qt.black)
        self.ui.textEdit.setText('The connection with the server has been lost, please restart the client.')
        self.ui.listWidget.clear() #delete the whole thing
              
    self.ui.lineEdit.setText('')

  def update_userlist(self, l):
    self.ui.listWidget.clear()

    for i in l:
      n = QtGui.QListWidgetItem(str(i))
      self.ui.listWidget.addItem(n)

  def update_msg(self, msg):
    self.ui.textEdit.append(msg)
    self.ui.textEdit.ensureCursorVisible()

  def set_dpbar(self, v):
    self.dpbar.setValue(v)

  def set_upbar(self, v):
    self.upbar.setValue(v)
Esempio n. 2
0
class ClientForm(QtGui.QWidget):
  def __init__(self, host, port, usn):
    super(ClientForm, self).__init__()
    self.ui = Ui_Form()
    self.ui.setupUi(self)
    self.ui.lineEdit.setFocus()
    self.running = 1

    self.dpbar = MProgressBar(self) #download bar
    self.dpbar.setOrientation(QtCore.Qt.Vertical)
    self.dpbar.setGeometry(520, 0, 20, 189)
    self.dpbar.setValue(0)
    self.dpbar.setStyle(False)

    self.upbar = MProgressBar(self) #upload bar
    self.upbar.setOrientation(QtCore.Qt.Vertical)
    self.upbar.setGeometry(545, 0, 20, 189)
    self.upbar.setValue(0)
    self.upbar.setStyle(True)

    self.host = host
    self.port = port
    self.size = 1024
    self.socket = None
    self.username = ''

    try:
      self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      self.socket.connect((self.host, self.port))
      self.key = int(hash(self.socket)) ^ int(time.time())
      self.key = self.key if self.key > 0 else -self.key
    except socket.error:
      print 'Not accepting connections'
      sys.exit(1)

    try:
      self.socket.send(usn)
      response = self.socket.recv(self.size)
      if response == 'ACCEPT':
        self.username = usn
      else:
        print 'Username already exists, please choose a different username'
        sys.exit(1)
    except socket.error:
      print 'Some socket error'

    self.downloader = Downloader(self.key) #make the downloader listen for incoming download requests
    #self.connect(self.downloader, QtCore.SIGNAL("update_upload_progressbar"), self.update_upload_progressbar)
    #self.connect(self.downloader, QtCore.SIGNAL("update_download_progressbar"), self.update_download_progressbar)
    self.downloader.start()

    self.receiver = Receiver(self.socket, self.key)
    self.connect(self.receiver, QtCore.SIGNAL("update_msg"), self.update_msg)
    self.connect(self.receiver, QtCore.SIGNAL("update_userlist"), self.update_userlist)
    #self.connect(self.receiver, QtCore.SIGNAL("update_download_progressbar"), self.update_download_progressbar) #tester method. should be connected to a Downloader object
    #self.connect(self.receiver, QtCore.SIGNAL("update_upload_progressbar"), self.update_upload_progressbar)
    #self.connect(self.receiver, QtCore.SIGNAL("update_download_progressbar"), self.update_download_progressbar)
    self.receiver.start() #start listening

  def on_lineEdit_returnPressed(self):
    if self.ui.lineEdit.displayText() != '':
      stringToSend = str(self.ui.lineEdit.displayText())
      #unfortunately, we must intercept a '/download' request client side, as the server does not store search results for the clients

      if stringToSend.startswith("\download "):
        fileToDownload = stringToSend.split(' ')[1]
        for host in searchresults.keys():
          for result in searchresults[host]:
            if fileToDownload == result:
              stringToSend = "\download "+host+" "+str(self.key)+" "+fileToDownload
              self.socket.send(str(stringToSend))
              self.ui.lineEdit.setText('')
              return
      
      try:
        if not stringToSend.startswith("\download "):
          self.socket.send(str(stringToSend)) 
        else:
          self.update_msg('This file is not among your search results')
          
      except socket.error:
        self.ui.textEdit.setTextColor(QtCore.Qt.black)
        self.ui.textEdit.setText('The connection with the server has been lost, please restart the client.')
        self.ui.listWidget.clear() #delete the whole thing
              
    self.ui.lineEdit.setText('')

  def update_userlist(self, l):
    self.ui.listWidget.clear()

    for i in l:
      n = QtGui.QListWidgetItem(str(i))
      self.ui.listWidget.addItem(n)

  def update_msg(self, msg):
    self.ui.textEdit.append(msg)
    self.ui.textEdit.ensureCursorVisible()

  def update_download_progressbar(self):
    #self.dpbar.setValue(value)
    #v = value
    #if not v == 100: #XXX this is ONLY to demonstrate how it would appear. sleeping the thread is NOT a good idea; it defers other GUI events. no idea for a work around right now. its own thread would be overkill.
    #  while not v == 100:
    #    time.sleep(.005)
    #    v += 1
    #    self.dpbar.setValue(v)
    while(1):
      time.sleep(.005)
      self.dpbar.setValue(dprogress[0])
    
  def update_upload_progressbar(self):
    #self.upbar.setValue(value) 
    while(1):
      time.sleep(.005)
      self.upbar.setValue(uprogress[0])
Esempio n. 3
0
class ClientForm(QtGui.QWidget, QtCore.QThread):
  def __init__(self, host, port):
    super(ClientForm, self).__init__()
    self.client = Client(host,port)
    self.ui = Ui_Form()
    self.ui.setupUi(self)
    self.ui.lineEdit.setFocus()
    self.icon = QtGui.QIcon('creeper.tif')
    self.auth = False
    self.colour_list = (QtCore.Qt.red, QtCore.Qt.darkRed, QtCore.Qt.blue, QtCore.Qt.darkGreen, QtCore.Qt.magenta, QtCore.Qt.darkBlue, QtCore.Qt.darkCyan,QtCore.Qt.darkMagenta, QtCore.Qt.darkYellow, QtCore.Qt.darkGray, QtGui.QColor('#00CC99'), QtGui.QColor('#0099FF'), QtGui.QColor('#005555'), QtGui.QColor('#FF6600'), QtGui.QColor('#660033'), QtGui.QColor('#9900FF'))
    self.user_colour_list = {}
    self.running = 1
    if os.path.isfile('client.log'):
      os.remove('client.log')
    self.clientLogger = Logger('client.log')

    self.createActions()
    self.createTrayIcon()
    self.trayIcon.activated.connect(self.iconActivated)
    self.trayIcon.show()
    
  def iconActivated(self, event):
      if event in (QtGui.QSystemTrayIcon.Trigger, QtGui.QSystemTrayIcon.DoubleClick):
          self.showNormal()
          #self.previewWindow.show() #normal, if wanted
    
  def createTrayIcon(self):
      self.trayIconMenu = QtGui.QMenu(self)
      self.trayIconMenu.addAction(self.minimizeAction)
      self.trayIconMenu.addAction(self.maximizeAction)
      self.trayIconMenu.addAction(self.restoreAction)
      self.trayIconMenu.addSeparator()
      self.trayIconMenu.addAction(self.quitAction)
        

      self.trayIcon = QtGui.QSystemTrayIcon(self)
      self.trayIcon.setIcon(QtGui.QIcon('tray.png'))
      self.trayIcon.setContextMenu(self.trayIconMenu)
         
         
  def createActions(self):
    self.minimizeAction = QtGui.QAction("Mi&nimize", self,
            triggered=self.hide)

    self.maximizeAction = QtGui.QAction("Ma&ximize", self,
            triggered=self.showMaximized)

    self.restoreAction = QtGui.QAction("&Restore", self,
            triggered=self.showNormal)

    self.quitAction = QtGui.QAction("&Quit", self,
            triggered=QtGui.qApp.quit)
         
  def closeEvent(self, event):
      if self.trayIcon.isVisible():
          #QtGui.QMessageBox.information(self, "Systray",
              #"Program continues running in tray")
          self.hide()
          event.ignore()


  def parse_msg(self, msg): 
  
    try:
      user,msg = msg.split(': ',1) 
      try:
        if msg.startswith('(l'): #then it is a pickle, if not just display message TODO
          userlist = pickle.loads(msg)

          userlist.sort()

          for i in userlist:
            if not (str(i) in self.user_colour_list):
              self.user_colour_list[str(i)] = self.colour_list[len(self.user_colour_list)%len(self.colour_list)]
          
          self.ui.listWidget.clear() #delete the whole thing

          for user in userlist: 
            n = QtGui.QListWidgetItem(self.icon, str(user))
            n.setTextColor(self.user_colour_list[str(user)])
            self.ui.listWidget.addItem(n)
        elif msg == 'TERMINATE':
          self.running = 0
          self.clientLogger.logger.info("Server Termination")
          return
        else: 
          self.ui.textEdit.setTextColor(self.user_colour_list.get(str(user), QtCore.Qt.black))
          self.ui.textEdit.append(user+': '+msg)
          self.ui.textEdit.ensureCursorVisible() #this will scroll it down

      except EOFError: #if the user sends data that seems like a pickle
        self.ui.textEdit.append(user+': '+msg) #just do this
    except ValueError:
      self.ui.textEdit.setTextColor(QtCore.Qt.black)
      self.ui.textEdit.append(msg)
      self.ui.textEdit.ensureCursorVisible() #whisper

  def request_username(self):
    try:
      self.client.open_socket()
    except socket.error:
      self.ui.textEdit.append("[ERROR] Server is not accepting connections") 
      self.clientLogger.logger.warn("Server is not accepting connections")
      return

    while 1: #loop until accepted
        response = self.client.socket.recv(self.client.size)
        if response == 'REJECT':
          self.ui.textEdit.setTextColor(QtCore.Qt.black)
          self.ui.textEdit.append('Username rejected -- already in use') #TODO server should say this nicely
          self.ui.lineEdit.setText('Enter username') #sometimes it 'skips' over this. no idea why; try not having focus here when settin
          self.client.close_socket()
          self.client.open_socket()
        elif response == 'ACCEPT':
          self.clientLogger.logger.info('Username accepted')
          break #get out
          
    self.auth = True #if accepted
    self.clientLogger.logger.info('Authorized')

  def run(self):       
    self.clientLogger.logger.info('Running')

    self.request_username() #a loop until an acceptable username is given

    while self.running:
      try:
        response = self.client.socket.recv(self.client.size)
      except socket.error:
        self.clientLogger.logger.warn('Response error from server')
        self.client.close_socket()
        self.clientLogger.logger.info("Socket closed")
        return
      try:
        self.parse_msg(response)
      except UnboundLocalError:
        pass  
          
    self.client.close_socket()
    self.clientLogger.logger.info("Socket closed")

  def on_lineEdit_returnPressed(self):
    if self.ui.lineEdit.displayText() != '':
      stringToSend = self.ui.lineEdit.displayText()

      self.clientLogger.logger.info('Would like to send '+stringToSend)
      if not self.auth:
        try:
          self.client.socket.send('request:'+str(stringToSend)) #its a username request
        except socket.error:
          self.ui.textEdit.setText('[ERROR] Server is not accepting connections')
          self.clientLogger.logger.info('Sending request for username '+stringToSend)
      else:
        try:
          self.client.socket.send(str(stringToSend)) #cast qt string
        except socket.error:
          self.ui.textEdit.setTextColor(QtCore.Qt.black)
          self.ui.textEdit.setText('The connection with the server has been lost, please restart the client.')
          self.clientLogger.logger.info('Connection with the server has been lost.')
          self.ui.listWidget.clear() #delete the whole thing
              
    self.ui.lineEdit.setText('')