Example #1
0
    def __init__(self, session, parent=None):
        super(MainWinGui, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.session = session
        self.setWindowTitle("Secure messaging: " + self.session.username)
        self.messages = {"MESSAGES": [], "CURSOR": None, "MORE": False}

        self.ui.refresh.clicked.connect(self.refresh)
        self.ui.send.clicked.connect(self.send)
        self.ui.logout.triggered.connect(self.logout)
        self.ui.scrollBar = self.ui.display.verticalScrollBar()
        self.ui.scrollBar.valueChanged.connect(self.drag)

        self.refreshShortcut = QtGui.QShortcut(QtGui.QKeySequence("F5"), self)
        self.refreshShortcut.activated.connect(self.refresh)

        self.setPeerShortcut = QtGui.QShortcut(QtGui.QKeySequence("Return"), self)
        self.setPeerShortcut.activated.connect(self.refresh)
        self.setPeerShortcut.setEnabled(False)

        self.ui.peer.focusInEvent = self.peerFieldFocused
        self.ui.peer.focusOutEvent = self.peerFieldUnfocused

        self.refreshing = False
Example #2
0
    def __init__(self, session, peerName, parent=None):
        super(MainWinGui, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.session = session
        self.peerName = peerName
        if peerName == "":
            self.ui.peerName.setVisible(False)
            self.ui.peer.setVisible(True)
            self.ui.peer.setText("")
            self.ui.peer.setFocus()
        else:
            self.ui.peerName.setVisible(True)
            self.ui.peer.setVisible(False)
            self.ui.peer.setText(peerName)
            self.ui.peerName.setText(peerName)
            self.ui.message.setFocus()

        self.ui.refresh.clicked.connect(self.refresh)
        self.ui.send.clicked.connect(self.send)
        self.ui.scrollBar = self.ui.display.verticalScrollBar()
        self.ui.display.setOpenLinks(False)
        self.ui.display.anchorClicked.connect(self.linkClicked)
        self.ui.display.anchorClicked.emit(QtCore.QUrl("UP"))

        self.refreshShortcut = QtGui.QShortcut(QtGui.QKeySequence("F5"), self)
        self.refreshShortcut.activated.connect(self.refresh)

        self.enterShortcut = QtGui.QShortcut(QtGui.QKeySequence("Enter"), self)
        self.returnShortcut = QtGui.QShortcut(QtGui.QKeySequence("Return"), self)
        self.enterShortcut.activated.connect(self.enterPressed)
        self.returnShortcut.activated.connect(self.enterPressed)
        self.ui.message.keyPressEvent = types.MethodType(keyPressEventReplacement, self.ui.message)

        self.ui.uploadFile.triggered.connect(self.uploadFile)

        self.ui.deleteMessages.triggered.connect(self.clearMessages)

        self.ui.stopSigning.triggered.connect(self.clearSigningSecret)

        self.ui.signMessages.triggered.connect(self.askForSigningSecret)

        self.ui.message.parentWindow = self

        self.refreshDisplay.connect(self.refreshDisplaySlot)
        self.sendCompleted.connect(self.sendCompletedSlot)
        self.fileDownloadCompleted.connect(self.fileDownloadCompletedSlot)

        self.progressIndicator = QProgressBar(self.ui.statusBar)
        self.progressIndicator.setMinimumHeight(5)
        self.progressIndicator.setVisible(False)
        self.progressIndicator.setMaximum(0)
        self.progressIndicator.setMinimum(0)

        self.signatureIndicator = QLabel(self.ui.statusBar)

        self.ui.statusBar.addWidget(self.progressIndicator)
        self.ui.statusBar.addPermanentWidget(self.signatureIndicator)

        self.signingSecret = None

        self.uiTranslate()

        self.refresh()
Example #3
0
class MainWinGui(BaseWindow, QtGui.QMainWindow):
    refreshDisplay = QtCore.pyqtSignal()
    sendCompleted = QtCore.pyqtSignal(Message)
    fileDownloadCompleted = QtCore.pyqtSignal(bytes, str)
    onClose = QtCore.pyqtSignal(str)

    def __init__(self, session, peerName, parent=None):
        super(MainWinGui, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.session = session
        self.peerName = peerName
        if peerName == "":
            self.ui.peerName.setVisible(False)
            self.ui.peer.setVisible(True)
            self.ui.peer.setText("")
            self.ui.peer.setFocus()
        else:
            self.ui.peerName.setVisible(True)
            self.ui.peer.setVisible(False)
            self.ui.peer.setText(peerName)
            self.ui.peerName.setText(peerName)
            self.ui.message.setFocus()

        self.ui.refresh.clicked.connect(self.refresh)
        self.ui.send.clicked.connect(self.send)
        self.ui.scrollBar = self.ui.display.verticalScrollBar()
        self.ui.display.setOpenLinks(False)
        self.ui.display.anchorClicked.connect(self.linkClicked)
        self.ui.display.anchorClicked.emit(QtCore.QUrl("UP"))

        self.refreshShortcut = QtGui.QShortcut(QtGui.QKeySequence("F5"), self)
        self.refreshShortcut.activated.connect(self.refresh)

        self.enterShortcut = QtGui.QShortcut(QtGui.QKeySequence("Enter"), self)
        self.returnShortcut = QtGui.QShortcut(QtGui.QKeySequence("Return"), self)
        self.enterShortcut.activated.connect(self.enterPressed)
        self.returnShortcut.activated.connect(self.enterPressed)
        self.ui.message.keyPressEvent = types.MethodType(keyPressEventReplacement, self.ui.message)

        self.ui.uploadFile.triggered.connect(self.uploadFile)

        self.ui.deleteMessages.triggered.connect(self.clearMessages)

        self.ui.stopSigning.triggered.connect(self.clearSigningSecret)

        self.ui.signMessages.triggered.connect(self.askForSigningSecret)

        self.ui.message.parentWindow = self

        self.refreshDisplay.connect(self.refreshDisplaySlot)
        self.sendCompleted.connect(self.sendCompletedSlot)
        self.fileDownloadCompleted.connect(self.fileDownloadCompletedSlot)

        self.progressIndicator = QProgressBar(self.ui.statusBar)
        self.progressIndicator.setMinimumHeight(5)
        self.progressIndicator.setVisible(False)
        self.progressIndicator.setMaximum(0)
        self.progressIndicator.setMinimum(0)

        self.signatureIndicator = QLabel(self.ui.statusBar)

        self.ui.statusBar.addWidget(self.progressIndicator)
        self.ui.statusBar.addPermanentWidget(self.signatureIndicator)

        self.signingSecret = None

        self.uiTranslate()

        self.refresh()

    def uiTranslate(self):
        self.ui.peer.setPlaceholderText(strings["peerBoxHint"])
        self.ui.refresh.setText(strings["refreshButtonText"])
        self.ui.send.setText(strings["sendMessageButtonText"])
        self.ui.deleteMessages.setText(strings["deleteConversationButtonText"])
        self.setWindowTitle(strings["conversationWindowTitle"] + ": " + self.peerName)
        self.ui.menuTools.setTitle(strings["toolsMenuText"])
        self.ui.uploadFile.setText(strings["uploadFileButtonText"])
        self.ui.stopSigning.setText(strings["stopSigningButtonText"])
        self.ui.signMessages.setText(strings["signMessagesButtonText"])
        self.signatureIndicator.setText(strings["signatureIndicatorOffText"])

    def enterPressed(self):
        if self.ui.peer.hasFocus():
            self.ui.message.setFocus()

    def progressStart(self):
        self.progressIndicator.setVisible(True)

    def askForConfirmation(self, message):
        confirmationBox = QtGui.QMessageBox(parent=self, text=message)
        confirmationBox.setStandardButtons(QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        confirmationBox.setWindowTitle(strings["appName"])
        return confirmationBox.exec() == QtGui.QMessageBox.Yes

    def askForSigningSecret(self):
        response = QInputDialog.getText(
            self, strings["signatureSecretInputTitle"], strings["signatureSecretInputLabel"]
        )
        if response[1]:
            self.signingSecret = response[0].encode("utf-8")
            self.signatureIndicator.setText(strings["signatureIndicatorOnText"])

    def clearSigningSecret(self):
        self.signingSecret = None
        self.signatureIndicator.setText(strings["signatureIndicatorOffText"])

    def progressStop(self):
        self.progressIndicator.setVisible(False)

    def fileDownloadCompletedSlot(self, contents, fileName):
        self.progressStop()
        try:
            with open(fileName, mode="wb") as file:
                file.write(contents)
        except (SecureMessagingException, IOError) as error:
            self.showMessageBox.emit(strings["errorText"] + responseTranslations[str(error)])
            return

    def sendCompletedSlot(self, message):
        sharedData.messages += [message]
        self.ui.message.clear()
        self.ui.peerName.setText(self.ui.peer.text())
        self.ui.peer.setVisible(False)
        self.ui.peerName.setVisible(True)
        self.peerName = self.ui.peer.text()
        self.setWindowTitle(strings["conversationWindowTitle"] + ": " + self.peerName)
        self.refresh()

    def show(self):
        super(MainWinGui, self).show()
        self.refreshDisplay.emit()

    def linkClicked(self, url):
        url = url.toString()
        if url == "UP":
            return
        if url.startswith("FILE"):
            messageId = url[len("FILE") :]
            messageId = int(messageId)
            message = sharedData.messages[messageId]
            fileName = QtGui.QFileDialog.getSaveFileName(directory=message.fileName)
            if fileName:
                self.progressStart()

                def fileDownloaderThread():
                    try:
                        fileContents = self.session.downloadFile(message)
                        self.fileDownloadCompleted.emit(fileContents, fileName)
                    except (SecureMessagingException, IOError) as error:
                        self.showMessageBox.emit(strings["errorText"] + responseTranslations[str(error)])
                        return

                Thread(target=fileDownloaderThread).start()
        elif url.startswith("DEL_"):
            messageId = int(url[len("DEL_") :])
            if self.askForConfirmation(strings["confirmDeleteMessageText"]):
                sharedData.messages.pop(messageId)
                storeMessages(self.session.username, sharedData.messages)
                self.refreshDisplay.emit()
        elif url.startswith("SGN_"):
            messageId = int(url[len("SGN_") :])
            message = sharedData.messages[messageId]
            response = QInputDialog.getText(
                self, strings["signatureSecretInputTitle"], strings["signatureSecretInputLabel"]
            )
            if response[1]:
                if message.verifySignature(response[0].encode("utf-8")):
                    self.showMessageBox.emit(strings["signatureOkMessageText"])
                else:
                    self.showMessageBox.emit(strings["signatureBadMessageText"])

    def refreshDisplaySlot(self):
        outputText = '<table width="100%" cellpadding="5" border="" style="padding:15px;width:100%;">'
        peer = self.ui.peer.text()
        msgCount = -1
        for message in sharedData.messages:
            msgCount += 1
            if message.messagePeer != peer:
                continue
            contents = message.contents
            contents = escape(contents)
            if message.isFile:
                contents = (
                    '<a href ="FILE' + str(sharedData.messages.index(message)) + '">File: ' + message.fileName + "</a>"
                )
            if message.sender == self.session.username:
                outputText += '<tr style="background-color:#cadced;color:#000000"><td>'
            else:
                outputText += '<tr style="background-color:#FFFFFF;color:#000000"><td>'
            outputText += "<b>" + message.sender + "</b>&#10153;<b>" + message.receiver + "</b>"
            outputText += "<pre style='word-break:break-all;white-space:pre-wrap;font-family:Arial'>"
            outputText += contents
            outputText += "</pre>"
            outputText += (
                "<a style='text-decoration:none;color:#000000' href='"
                + "DEL_"
                + str(msgCount)
                + "'><font size='1'>&#9003;</font></a>"
            )
            if message.isSigned():
                outputText += (
                    "&emsp;<a style='text-decoration:none;color:#000000' href='"
                    + "SGN_"
                    + str(msgCount)
                    + "'><font size='1'>&#10004;</font></a>"
                )
            outputText += "<div style='font-size:small;' align='right'>" + message.getTimeStamp() + "</div>"
            outputText += "</td></tr>"
        outputText += "</table>"
        self.ui.display.setHtml(outputText)
        self.ui.display.verticalScrollBar().setValue(self.ui.display.verticalScrollBar().maximum())
        self.progressStop()

    def refresh(self):
        self.progressStart()

        def refreshThread():
            try:
                sharedData.messages += self.session.getMessages()
            except SecureMessagingException as error:
                self.showMessageBox.emit(strings["errorText"] + responseTranslations[str(error)])
                return
            sharedData.messages = sorted(sharedData.messages, key=messageSort)
            sharedData.markAsRead(self.ui.peer.text())
            storeMessages(self.session.username, sharedData.messages)
            self.refreshDisplay.emit()

        Thread(target=refreshThread).start()

    def send(self):
        self.progressStart()

        def senderThread():
            peer = self.ui.peer.text()
            contents = self.ui.message.toPlainText()
            if peer == "" or contents == "":
                self.showMessageBox.emit(strings["missingPeerOrMessageErrorText"])
                return
            if peer == self.session.username:
                self.showMessageBox.emit(strings["cantSendMessageToSelfText"])
                return
            sharedData.messages = sorted(sharedData.messages, key=messageSort)
            try:
                self.session.sendMessage(contents, peer, signatureSecret=self.signingSecret)
            except SecureMessagingException as error:
                self.showMessageBox.emit(strings["errorText"] + responseTranslations[str(error)])
                return
            self.sendCompleted.emit(Message(contents, self.session.username, peer, peer, self.session.timeDiff))

        Thread(target=senderThread).start()

    def uploadFile(self):
        peer = self.ui.peer.text()
        if peer == "":
            self.showMessageBox.emit(strings["missingPeerErrorText"])
            return
        if peer == self.session.username:
            self.showMessageBox.emit(strings["cantSendMessageToSelfText"])
            return
        fileName = QtGui.QFileDialog.getOpenFileName()
        if fileName:
            self.progressStart()

            def uploaderThread():
                try:
                    fileContents = open(fileName, "rb").read()
                    basename = os.path.basename(fileName)
                    fileType = mimetypes.guess_type("file://" + fileName)[0] or "application/octet-stream"
                    fileType = fileType.encode("ascii")
                    self.session.sendFile(basename, fileContents, peer, fileType)
                    self.sendCompleted.emit(Message(basename, self.session.username, peer, peer, self.session.timeDiff))
                except (SecureMessagingException, IOError) as error:
                    self.showMessageBox.emit(strings["errorText"] + responseTranslations[str(error)])
                    return

            Thread(target=uploaderThread).start()

    def clearMessages(self):
        if self.peerName and self.askForConfirmation(strings["confirmDeleteConversationText"]):
            numberOfMessages = len(sharedData.messages)
            deletedMessages = 0
            for i in range(numberOfMessages):
                if sharedData.messages[i - deletedMessages].messagePeer == self.peerName:
                    sharedData.messages.pop(i - deletedMessages)
                    deletedMessages += 1
            storeMessages(self.session.username, sharedData.messages)
            self.refreshDisplay.emit()

    def closeEvent(self, event):
        self.onClose.emit(self.ui.peer.text())
        super(MainWinGui, self).closeEvent(event)
Example #4
0
class MainWinGui(QtGui.QMainWindow):
    def __init__(self, session, parent=None):
        super(MainWinGui, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.session = session
        self.setWindowTitle("Secure messaging: " + self.session.username)
        self.messages = {"MESSAGES": [], "CURSOR": None, "MORE": False}

        self.ui.refresh.clicked.connect(self.refresh)
        self.ui.send.clicked.connect(self.send)
        self.ui.logout.triggered.connect(self.logout)
        self.ui.scrollBar = self.ui.display.verticalScrollBar()
        self.ui.scrollBar.valueChanged.connect(self.drag)

        self.refreshShortcut = QtGui.QShortcut(QtGui.QKeySequence("F5"), self)
        self.refreshShortcut.activated.connect(self.refresh)

        self.setPeerShortcut = QtGui.QShortcut(QtGui.QKeySequence("Return"), self)
        self.setPeerShortcut.activated.connect(self.refresh)
        self.setPeerShortcut.setEnabled(False)

        self.ui.peer.focusInEvent = self.peerFieldFocused
        self.ui.peer.focusOutEvent = self.peerFieldUnfocused

        self.refreshing = False

    def drag(self, e):
        if (not self.refreshing) and self.messages["MORE"] and e == 0:
            self.refreshing = True
            peer = self.ui.peer.text()
            try:
                if peer == "":
                    newData = self.session.getMessages(count=10, cursor=self.messages["CURSOR"])
                else:
                    newData = self.session.getMessages(peer, count=5, cursor=self.messages["CURSOR"])
            except HTTPError as error:
                messageBox = QtGui.QMessageBox(parent=self, text="Error: " + str(error))
                messageBox.show()
                return
            if newData["MESSAGES"]:
                newData["MESSAGES"].reverse()
                self.messages["MESSAGES"] = newData["MESSAGES"] + self.messages["MESSAGES"]
                self.messages["CURSOR"] = newData["CURSOR"]
                self.messages["MORE"] = newData["MORE"]
            self.refreshDisplay()
            self.ui.scrollBar.setValue(0)
            self.refreshing = False

    def peerFieldFocused(self, e):
        self.setPeerShortcut.setEnabled(True)

    def peerFieldUnfocused(self, e):
        self.setPeerShortcut.setEnabled(False)

    def refreshDisplay(self):
        outputText = '<table width="100%" cellpadding="5" border="" style="padding:15px;width:100%;">'
        for message in self.messages["MESSAGES"]:
            contents = message.contents
            contents = escape(contents)
            contents = contents.replace('\n', "<br/>")
            if message.sender == self.session.username:
                outputText += '<tr style="background-color:#cadced;color:#000000"><td>'
            else:
                outputText += '<tr style="background-color:#FFFFFF;color:#000000"><td>'
            outputText += "<b>" + message.sender + "</b><br/>"
            outputText += contents
            outputText += "<br/> <div style='font-size:small 'align='right'><i>" + message.getTimeStamp() + \
                          "</i></div>"
            outputText += "</td></tr>"
        outputText += "</table>"
        opr = self.refreshing
        self.refreshing = True
        self.ui.display.setHtml(outputText)
        self.refreshing = opr

    def refresh(self):
        peer = self.ui.peer.text()
        try:
            if peer == "":
                self.messages = self.session.getMessages(count=10)
            else:
                self.messages = self.session.getMessages(peer, count=5)
        except HTTPError as error:
            messageBox = QtGui.QMessageBox(parent=self, text="Error: " + str(error))
            messageBox.show()
            return
        self.messages["MESSAGES"].reverse()
        self.refreshDisplay()
        self.ui.scrollBar.setValue(self.ui.scrollBar.maximum())

    def send(self):
        sagovornik = self.ui.peer.text()
        sadrzaj = self.ui.message.toPlainText()
        if sagovornik == "" or sadrzaj == "":
            messageBox = QtGui.QMessageBox(parent=self, text="Please choose peer")
            messageBox.show()
            return
        self.session.sendMessage(sadrzaj, sagovornik)
        self.refreshing = True
        self.refresh()
        self.refreshing = False

    def logout(self):
        self.session.logout()
        loginWin = LoginWinGui(parent=self)
        loginWin.show()
        self.hide()