Ejemplo n.º 1
0
class MainWindow(QMainWindow, mainapp_ui.Ui_MainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.db = Helper()
        self.credentials = self.db.get_credentials()
        self.setupUi(self)
        if self.credentials:
            self.form_widget = None
            self.frame_layout = QtWidgets.QVBoxLayout(self.message_frame)
            self.message_frame.setContentsMargins(0, 0, 0, 0)
            self.thread = YowsupThread(self.credentials['phone_number'], self.credentials['password'], debug=False)
            self.thread.interface.success_connection_signal.connect(self.on_success)
            self.thread.interface.message_received_signal.connect(self.on_success)
            self.thread.interface.presence_update_signal.connect(self.on_success)
            self.contact_table.clicked.connect(self.render_page)
            self.thread.render()
        else:
            print("You need to provide authentication credentials")

    def render_page(self, index):
        row = index.row()
        self.form_widget = Messager(index.sibling(row, 1).data(), self.thread)
        self.form_widget.message_received_signal.connect(self.on_success)
        for i in reversed(range(self.frame_layout.count())):
            self.frame_layout.itemAt(i).widget().setParent(None)
        self.frame_layout.addWidget(self.form_widget)
        self.frame_layout.setContentsMargins(0, 0, 0, 0)
        self.message_frame.setLayout(self.frame_layout)
        self.update_contact_table()

    def on_success(self):
        self.update_contact_table(True)
        pass

    def update_contact_table(self, init=False):
        if init:
            self.initialize()
        result = self.db.get_all_contact()
        self.contact_table.setRowCount(result['count'])
        for idx, record in enumerate(result['records']):
            form_widget = ContactRow(record)
            self.contact_table.setItem(idx, 1, QTableWidgetItem(str(record[0])))
            self.contact_table.setCellWidget(idx, 0, form_widget)
        return

    def initialize(self):
        self.contact_table.setColumnCount(2)
        self.contact_table.setColumnHidden(1, True)
        self.contact_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.contact_table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.contact_table.setSelectionBehavior(QTableView.SelectRows)
        self.contact_table.setSelectionMode(QAbstractItemView.SingleSelection)
        self.contact_table.verticalHeader().setVisible(False)
        self.contact_table.horizontalHeader().setVisible(False)
        self.contact_table.verticalHeader().setDefaultSectionSize(68)
Ejemplo n.º 2
0
 def __init__(self, current_id, thread):
     QWidget.__init__(self)
     self.setupUi(self)
     self.thread = thread
     self.db = Helper()
     self.current_id = current_id
     self.toJid = self.db.get_jid_of_id(self.current_id)
     self.send_button.clicked.connect(self.send_message)
     self.message_box.page().mainFrame().contentsSizeChanged.connect(self.scroll_to_bottom)
     self.thread.interface.message_received_signal.connect(self.on_success)
     self.message_text.setFocus()
     self.update_message_table()
     self.message_received_signal.emit()
Ejemplo n.º 3
0
 def __init__(self):
     QMainWindow.__init__(self)
     self.db = Helper()
     self.credentials = self.db.get_credentials()
     self.setupUi(self)
     if self.credentials:
         self.form_widget = None
         self.frame_layout = QtWidgets.QVBoxLayout(self.message_frame)
         self.message_frame.setContentsMargins(0, 0, 0, 0)
         self.thread = YowsupThread(self.credentials['phone_number'], self.credentials['password'], debug=False)
         self.thread.interface.success_connection_signal.connect(self.on_success)
         self.thread.interface.message_received_signal.connect(self.on_success)
         self.thread.interface.presence_update_signal.connect(self.on_success)
         self.contact_table.clicked.connect(self.render_page)
         self.thread.render()
     else:
         print("You need to provide authentication credentials")
Ejemplo n.º 4
0
class Messager(QWidget, message_ui.Ui_Form):
    message_received_signal = pyqtSignal()

    def __init__(self, current_id, thread):
        QWidget.__init__(self)
        self.setupUi(self)
        self.thread = thread
        self.db = Helper()
        self.current_id = current_id
        self.toJid = self.db.get_jid_of_id(self.current_id)
        self.send_button.clicked.connect(self.send_message)
        self.message_box.page().mainFrame().contentsSizeChanged.connect(self.scroll_to_bottom)
        self.thread.interface.message_received_signal.connect(self.on_success)
        self.message_text.setFocus()
        self.update_message_table()
        self.message_received_signal.emit()

    def scroll_to_bottom(self):
        self.message_box.page().mainFrame().scroll(
            self.message_box.page().mainFrame().contentsSize().width(),
            self.message_box.page().mainFrame().contentsSize().height()
        )

    def send_message(self):
        message = self.message_text.toPlainText()
        if self.validate_message(message):
            self.thread.interface.send_message(self.toJid, message)
            self.message_text.setPlainText("")
            self.message_text.setFocus()

    def on_success(self):
        self.update_message_table()

    @staticmethod
    def validate_message(message=''):
        if len(message) > 0:
            return True
        else:
            return False

    def update_message_table(self):
        result = self.db.get_all_messages(self.current_id)
        html_string = '<style type="text/css">' \
                      'p {margin:0px;} p.head-left {color:#990100;text-align: left;margin-bottom: 5px;}' \
                      'p.message {clear:both;padding:5px 20px} p.footer-right {text-align: right;color:#390504;margin-top:10px;font-size: 12px;}' \
                      'div.left, div.right {background-color:#FFFFFF;color:#333333;border:1px solid #E8E8E8;padding:5px;' \
                      'border-radius: 10px;margin-bottom:10px;display:inline-block;}' \
                      'div.right {clear:both;border-top-right-radius: 0px;margin-left:100px;float:right;}' \
                      'div.left {clear:both;margin-right:100px;border-top-left-radius: 0px;float:left;}' \
                      '</style><div style="background-color:#F6F6F6">'
        for idx, record in enumerate(result['records']):
            html_string = html_string + self.generate_message_row(record)
        self.message_box.setHtml(html_string+'</div>')
        self.db.set_read(self.current_id)
        self.message_received_signal.emit()

    @staticmethod
    def generate_message_row(record):
        message_string = '<div class="{}"><p class="head-left">{}</p>' \
                         '<p class="message">{}</p><p class="footer-right">{}</p></div><br />'
        if int(record[7]) == 0:
            orientation = "left"
            name = ""
            status = ""
            if int(record[8]) == 1:
                name = str(record[14])
        else:
            orientation = "right"
            name = ""
            status = "R"
        message = str(record[2]).replace('\n', '<br />')
        return message_string.format(orientation, name, message, status)
Ejemplo n.º 5
0
 def __init__(self):
     super(Interfacer, self).__init__()
     self.ackQueue = []
     self.send_receipts = True
     self.lock = threading.Condition()
     self.services = Helper()
Ejemplo n.º 6
0
class Interfacer(QThread, YowInterfaceLayer):

    # -------------------------- PY QT Signals -------------------------------------------- #
    message_received_signal = pyqtSignal()
    success_connection_signal = pyqtSignal()
    presence_update_signal = pyqtSignal()

    # -------------------------- Class Constructor -------------------------------------------- #
    def __init__(self):
        super(Interfacer, self).__init__()
        self.ackQueue = []
        self.send_receipts = True
        self.lock = threading.Condition()
        self.services = Helper()

    # -------------------------- Forward operations functions -------------------------------------------- #
    def send_message(self, phone, message):
        self.lock.acquire()
        if '@' in phone:
            entity = TextMessageProtocolEntity(message, to=phone)
        elif '-' in phone:
            entity = TextMessageProtocolEntity(message, to="*****@*****.**" % phone)
        else:
            entity = TextMessageProtocolEntity(message, to="*****@*****.**" % phone)
        self.ackQueue.append(entity.getId())
        self.toLower(entity)
        self.services.add_message([
            entity.getId(),
            entity.getBody(),
            self.services.get_contact_id(entity.getTo(), "Unknown", entity.isGroupMessage()),
            entity.getTo(),
            entity.getNotify(),
            self.services.get_contact_id(entity.getParticipant(), "Unknown"),
            entity.isOutgoing(),
            entity.isGroupMessage(),
            '0',
            entity.getTimestamp(),
            '20'
        ])
        self.message_received_signal.emit()
        self.lock.release()
        print(entity)

    def on_text_message(self, entity):
        if entity.isGroupMessage() == 0 and self.services.check_contact_id(entity.getFrom()):
            self.presence_subscribe(entity.getFrom())
        elif entity.isGroupMessage() == 1 and self.services.check_contact_id(entity.getParticipant()):
            self.presence_subscribe(entity.getParticipant())

        self.services.add_message([
            entity.getId(),
            entity.getBody(),
            self.services.get_contact_id(entity.getFrom(), entity.getNotify(), entity.isGroupMessage()),
            entity.getTo(),
            entity.getNotify(),
            self.services.get_contact_id(entity.getParticipant(), entity.getNotify()),
            entity.isOutgoing(),
            entity.isGroupMessage(),
            '0',
            entity.getTimestamp(),
            '10'
        ])
        self.message_received_signal.emit()
        print("Message from %s" % (entity.getFrom(False)))

    def get_group_info(self, group_jid):
        def on_success(success_entity, original_entity):
            print(success_entity)

        def on_error(error_entity, original_entity):
            print(error_entity)
            print(original_entity)
        entity = InfoGroupsIqProtocolEntity(group_jid)
        success = lambda success_entity, original_entity: on_success(success_entity, original_entity)
        error = lambda error_entity, original_entity: on_error(error_entity, original_entity)
        self._sendIq(entity, success, error)

    def contact_picture(self, jid):
        entity = GetPictureIqProtocolEntity(jid, preview=True)
        self._sendIq(entity, self.contact_image_result)

    @staticmethod
    def contact_image_result(success_entity, original_entity):
        success_entity.writeToFile("../tmp/images/%s_%s.jpg" % (
            original_entity.getTo(),
            "preview" if success_entity.isPreview() else "full")
        )

    def groups_list(self):
        def on_success(success_entity, original_entity):
            for group in success_entity.getGroups():
                self.services.update_contact_id(group.getId()+"@g.us", group.getSubject())
                # self.contact_picture(group.getId+"@g.us")
            self.success_connection_signal.emit()

        def on_error(error_entity, original_entity):
            print(error_entity)
            print(original_entity)

        entity = ListGroupsIqProtocolEntity()
        success = lambda success_entity, original_entity: on_success(success_entity, original_entity)
        error = lambda error_entity, original_entity: on_error(error_entity, original_entity)
        self._sendIq(entity, success, error)

    def on_media_message(self, entity):
        """ if messageProtocolEntity.getMediaType() == "image":
            print("Echoing image %s to %s" % (messageProtocolEntity.url, messageProtocolEntity.getFrom(False)))

        elif messageProtocolEntity.getMediaType() == "location":
            print("Echoing location (%s, %s) to %s" %
        ssageProtocolEntity.getLatitude(), messageProtocolEntity.getLongitude(), messageProtocolEntity.getFrom(False)))

        elif messageProtocolEntity.getMediaType() == "vcard":
            print("Echoing vcard (%s, %s) to %s" %
        (messageProtocolEntity.getName(), messageProtocolEntity.getCardData(), messageProtocolEntity.getFrom(False)))
        """
        print(entity)

    def set_presence_available(self):
        entity = AvailablePresenceProtocolEntity()
        self.toLower(entity)

    def presence_name(self, name):
        entity = PresenceProtocolEntity(name=name)
        self.toLower(entity)

    def presence_unavailable(self):
        entity = UnavailablePresenceProtocolEntity()
        self.toLower(entity)

    def presence_subscribe(self, jid):
        entity = SubscribePresenceProtocolEntity(jid)
        self.toLower(entity)

    def contact_lastseen(self, jid):
        def onSuccess(resultIqEntity, originalIqEntity):
            print("%s lastseen %s seconds ago" % (resultIqEntity.getFrom(), resultIqEntity.getSeconds()))

        def onError(errorIqEntity, originalIqEntity):
            print("Error getting lastseen information for %s" % originalIqEntity.getTo())

        entity = LastseenIqProtocolEntity(jid)
        self._sendIq(entity, onSuccess, onError)

    def contacts_sync(self, contacts):
        entity = GetSyncIqProtocolEntity(contacts.split(','))
        self.toLower(entity)

    # -------------------------- Callback functions for each functions -------------------------------------------- #
    @ProtocolEntityCallback("success")
    def on_success(self, entity):
        print("Success Connected")
        self.set_presence_available()
        self.groups_list()

    @ProtocolEntityCallback("ack")
    def on_ack(self, entity):
        self.lock.acquire()
        if entity.getId() in self.ackQueue:
            self.ackQueue.pop(self.ackQueue.index(entity.getId()))
        self.lock.release()

    @ProtocolEntityCallback("chatstate")
    def on_chatstate(self, entity):
        print(entity)

    @ProtocolEntityCallback("iq")
    def on_iq(self, entity):
        print(entity)

    @ProtocolEntityCallback("message")
    def on_message(self, entity):
        print(entity)
        if entity.getType() == 'text':
            self.on_text_message(entity)
        elif entity.getType() == 'media':
            self.on_media_message(entity)
        self.toLower(entity.ack())
        self.toLower(entity.ack(True))

    @ProtocolEntityCallback("receipt")
    def on_receipt(self, entity):
        self.toLower(entity.ack())

    @ProtocolEntityCallback("notification")
    def on_notification(self, notification):
        notification_data = notification.__str__()
        if notification_data:
            print(notification_data)
        else:
            print("From :%s, Type: %s" % (self.jidToAlias(notification.getFrom()), notification.getType()))
        self.toLower(notification.ack())

    @ProtocolEntityCallback("presence")
    def on_presence_update(self, entity):
        self.services.updatePresence(entity.getFrom(), entity.getType(), entity.getLast())
        self.presence_update_signal.emit()